lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | bsd-3-clause | bd217b586d585b1936ceb7e6dae0ebf2ca686ecd | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.ui.submit;
/**
* This class sets up input form for size characterization.
*
* @author pansu
*/
/* CVS $Id: NanoparticleFunctionAction.java,v 1.13 2007-08-08 18:56:01 pansu Exp $ */
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.dto.function.AgentBean;
import gov.nih.nci.calab.dto.function.AgentTargetBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.dto.function.LinkageBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class NanoparticleFunctionAction extends AbstractDispatchAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
FunctionBean function = (FunctionBean) theForm.get("function");
if (function.getId() == null || function.getId() == "") {
function.setId((String) theForm.get("functionId"));
}
// validate agent target
for (LinkageBean linkageBean : function.getLinkages()) {
for (AgentTargetBean agentTargetBean : linkageBean.getAgent()
.getAgentTargets()) {
if (agentTargetBean.getName().length() == 0
&& agentTargetBean.getDescription().length() == 0
&& agentTargetBean.getType().length() == 0) {
throw new RuntimeException("Agent target type can not be empty.");
}
}
}
request.getSession().setAttribute("newFunctionCreated", "true");
request.getSession().setAttribute("newBondTypeCreated", "true");
request.getSession().setAttribute("newContrastAgentTypeCreated", "true");
// TODO save in database
SubmitNanoparticleService service = new SubmitNanoparticleService();
service.addParticleFunction(particleType, particleName, function);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addparticle.function");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return forward;
}
/**
* Set up the input forms for adding data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
private void clearMap(HttpSession session, DynaValidatorForm theForm,
ActionMapping mapping) throws Exception {
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
// clear session data from the input forms
theForm.getMap().clear();
theForm.set("particleName", particleName);
theForm.set("particleType", particleType);
theForm.set("function", new FunctionBean());
}
private void initSetup(HttpServletRequest request, DynaValidatorForm theForm)
throws Exception {
HttpSession session = request.getSession();
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
InitSessionSetup.getInstance().setStaticDropdowns(session);
InitSessionSetup.getInstance().setAllFunctionDropdowns(session);
}
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
String functionId = (String) theForm.get("functionId");
SearchNanoparticleService service = new SearchNanoparticleService();
Function aFunc = service.getFunctionBy(functionId);
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
FunctionBean function = new FunctionBean(aFunc);
theForm.set("function", function);
return mapping.findForward("setup");
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
public ActionForward addLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add((LinkageBean) origLinkages.get(i));
}
// add a new one
linkages.add(new LinkageBean());
function.setLinkages(linkages);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add(origLinkages.get(i));
}
// remove the one at the index
if (origNum > 0) {
linkages.remove(ind);
}
function.setLinkages(linkages);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward addTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// add a new one
targets.add(new AgentTargetBean());
agent.setAgentTargets(targets);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
String targetIndex = (String) request.getParameter("targetInd");
int tInd = Integer.parseInt(targetIndex);
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// remove the one at the index
if (origNum > 0) {
targets.remove(tInd);
}
agent.setAgentTargets(targets);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
// update editable dropdowns
FunctionBean function = (FunctionBean) theForm.get("function");
HttpSession session = request.getSession();
updateEditables(session, function);
return mapping.findForward("setup");
}
private void updateEditables(HttpSession session, FunctionBean function)
throws Exception {
// update bondType editable dropdowns
for (LinkageBean linkage : function.getLinkages()) {
if (linkage.getType() != null
&& linkage.getType().equals(CaNanoLabConstants.ATTACHMENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getBondType(), "allBondTypes");
}
if (linkage.getAgent() != null
&& linkage.getAgent().getType() != null
&& linkage.getAgent().getType().equals(
CaNanoLabConstants.IMAGE_CONTRAST_AGENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getAgent().getImageContrastAgent().getType(),
"allImageContrastAgentTypes");
}
}
}
public boolean loginRequired() {
return true;
}
}
| src/gov/nih/nci/calab/ui/submit/NanoparticleFunctionAction.java | package gov.nih.nci.calab.ui.submit;
/**
* This class sets up input form for size characterization.
*
* @author pansu
*/
/* CVS $Id: NanoparticleFunctionAction.java,v 1.12 2007-08-02 20:31:41 pansu Exp $ */
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.dto.function.AgentBean;
import gov.nih.nci.calab.dto.function.AgentTargetBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.dto.function.ImageContrastAgentBean;
import gov.nih.nci.calab.dto.function.LinkageBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class NanoparticleFunctionAction extends AbstractDispatchAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
FunctionBean function = (FunctionBean) theForm.get("function");
if (function.getId() == null || function.getId() == "") {
function.setId((String) theForm.get("functionId"));
}
// validate agent target
for (LinkageBean linkageBean : function.getLinkages()) {
for (AgentTargetBean agentTargetBean : linkageBean.getAgent()
.getAgentTargets()) {
if (agentTargetBean.getName().length() == 0
&& agentTargetBean.getDescription().length() == 0
&& agentTargetBean.getType().length() == 0) {
throw new RuntimeException("Agent target type can not be empty.");
}
}
}
request.getSession().setAttribute("newFunctionCreated", "true");
request.getSession().setAttribute("newBondTypeCreated", "true");
request.getSession().setAttribute("newContrastAgentTypeCreated", "true");
// TODO save in database
SubmitNanoparticleService service = new SubmitNanoparticleService();
service.addParticleFunction(particleType, particleName, function);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addparticle.function");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return forward;
}
/**
* Set up the input forms for adding data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
private void clearMap(HttpSession session, DynaValidatorForm theForm,
ActionMapping mapping) throws Exception {
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
// clear session data from the input forms
theForm.getMap().clear();
theForm.set("particleName", particleName);
theForm.set("particleType", particleType);
theForm.set("function", new FunctionBean());
}
private void initSetup(HttpServletRequest request, DynaValidatorForm theForm)
throws Exception {
HttpSession session = request.getSession();
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
InitSessionSetup.getInstance().setStaticDropdowns(session);
InitSessionSetup.getInstance().setAllFunctionDropdowns(session);
}
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
String functionId = (String) theForm.get("functionId");
SearchNanoparticleService service = new SearchNanoparticleService();
Function aFunc = service.getFunctionBy(functionId);
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
FunctionBean function = new FunctionBean(aFunc);
theForm.set("function", function);
return mapping.findForward("setup");
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
public ActionForward addLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add((LinkageBean) origLinkages.get(i));
}
// add a new one
linkages.add(new LinkageBean());
function.setLinkages(linkages);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add(origLinkages.get(i));
}
// remove the one at the index
if (origNum > 0) {
linkages.remove(ind);
}
function.setLinkages(linkages);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward addTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// add a new one
targets.add(new AgentTargetBean());
agent.setAgentTargets(targets);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String linkageIndex = (String) request.getParameter("linkageInd");
int ind = Integer.parseInt(linkageIndex);
String targetIndex = (String) request.getParameter("targetInd");
int tInd = Integer.parseInt(targetIndex);
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// remove the one at the index
if (origNum > 0) {
targets.remove(tInd);
}
agent.setAgentTargets(targets);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
// update editable dropdowns
FunctionBean function = (FunctionBean) theForm.get("function");
HttpSession session = request.getSession();
updateEditables(session, function);
return mapping.findForward("setup");
}
private void updateEditables(HttpSession session, FunctionBean function)
throws Exception {
// update bondType editable dropdowns
for (LinkageBean linkage : function.getLinkages()) {
if (linkage.getType() != null
&& linkage.getType().equals(CaNanoLabConstants.ATTACHMENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getBondType(), "allBondTypes");
}
if (linkage.getAgent() != null
&& linkage.getAgent().getType() != null
&& linkage.getAgent().getType().equals(
CaNanoLabConstants.IMAGE_CONTRAST_AGENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getImageContrastAgent().getType(),
"allImageContrastAgentTypes");
}
}
}
public boolean loginRequired() {
return true;
}
}
| updated updateEditables
SVN-Revision: 10485
| src/gov/nih/nci/calab/ui/submit/NanoparticleFunctionAction.java | updated updateEditables | <ide><path>rc/gov/nih/nci/calab/ui/submit/NanoparticleFunctionAction.java
<ide> * @author pansu
<ide> */
<ide>
<del>/* CVS $Id: NanoparticleFunctionAction.java,v 1.12 2007-08-02 20:31:41 pansu Exp $ */
<add>/* CVS $Id: NanoparticleFunctionAction.java,v 1.13 2007-08-08 18:56:01 pansu Exp $ */
<ide>
<ide> import gov.nih.nci.calab.domain.nano.function.Function;
<ide> import gov.nih.nci.calab.dto.function.AgentBean;
<ide> import gov.nih.nci.calab.dto.function.AgentTargetBean;
<ide> import gov.nih.nci.calab.dto.function.FunctionBean;
<del>import gov.nih.nci.calab.dto.function.ImageContrastAgentBean;
<ide> import gov.nih.nci.calab.dto.function.LinkageBean;
<ide> import gov.nih.nci.calab.service.search.SearchNanoparticleService;
<ide> import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
<ide> && linkage.getAgent().getType().equals(
<ide> CaNanoLabConstants.IMAGE_CONTRAST_AGENT)) {
<ide> InitSessionSetup.getInstance().updateEditableDropdown(session,
<del> linkage.getImageContrastAgent().getType(),
<add> linkage.getAgent().getImageContrastAgent().getType(),
<ide> "allImageContrastAgentTypes");
<ide> }
<ide> } |
|
JavaScript | mit | 024188b180a45be46d9ba7d48c2a2a5cece50909 | 0 | flock-together/flock-fee,flock-together/flock-fee | ;(function(){
angular.module('flockTogether')
.controller('detailCtrl', function($scope, $http, $location) {
var id = $location.path().split('/')[2]-1;//pulls event_id out of path for reference
$http.get("api/event.json")
.then(function(response){
$scope.thisEvent = response.data[id];
$scope.directions = $scope.thisEvent.location.split(" ").join("+");
})//END get event.json
})//END eventDetail controller
})();
| src/js/event_detail.js | ;(function(){
angular.module('flockTogether')
.controller('detailCtrl', function($scope, $http, $location) {
var id = $location.path().split('/')[2]-1;//pulls event_id out of path for reference
$http.get("api/event.json")
.then(function(response){
$scope.thisEvent = response.data[id];
console.log($scope.thisEvent);
$scope.directions = $scope.thisEvent.location.split(" ").join("+");
})//END get event.json
})//END eventDetail controller
})();
| Remove console.log
| src/js/event_detail.js | Remove console.log | <ide><path>rc/js/event_detail.js
<ide> $http.get("api/event.json")
<ide> .then(function(response){
<ide> $scope.thisEvent = response.data[id];
<del> console.log($scope.thisEvent);
<ide> $scope.directions = $scope.thisEvent.location.split(" ").join("+");
<ide> })//END get event.json
<ide> })//END eventDetail controller |
|
JavaScript | mit | 9b5880d7f6f0b22ef821ac46891c0b61cc2d2501 | 0 | dalejung/nbx,dalejung/nbx,dalejung/nbx,dalejung/nbx | /*
Add this file to $(ipython locate)/nbextensions/vim.js
And load it with:
require(["nbextensions/vim"], function (vim_extension) {
console.log('vim extension loaded');
vim_extension.load_extension();
});
*/
define(function() {
var token_name = "vim_github_token";
var load_extension = function() {
$([IPython.events]).on("notebook_loaded.Notebook", function() {
console.log("notebook loaded event");
});
};
return {
load_extension: load_extension,
};
});
// plug in so :w saves
CodeMirror.commands.save = function(cm) {
IPython.notebook.save_notebook();
}
// Monkey patch: KeyboardManager.handle_keydown
// Diff: disable this handler
IPython.KeyboardManager.prototype.handle_keydown = function(event) {
var cell = IPython.notebook.get_selected_cell();
var vim_mode = cell.code_mirror.getOption('keyMap');
if (cell instanceof IPython.TextCell) {
// when cell is rendered, we get no key events, so we capture here
if (cell.rendered && event.type == 'keydown') {
// switch IPython.notebook to this.notebook if Cells get notebook reference
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
}
return;
}
// Monkey patch: KeyboardManager.register_events
// Diff: disable this handler
IPython.KeyboardManager.prototype.register_events = function(e) {
return;
}
// Monkey patch insert_cell_below
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_below = function(type, index) {
index = this.index_or_selected(index);
var cell = this.insert_cell_at_index(type, index + 1);
this.select(this.find_cell_index(cell));
return cell;
};
// Monkey patch insert_cell_above
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_above = function(type, index) {
index = this.index_or_selected(index);
var cell = this.insert_cell_at_index(type, index);
this.select(this.find_cell_index(cell));
return cell;
};
// Monkey patch: execute_cell
// Diff: don't switch to command mode
IPython.Notebook.prototype.execute_cell = function() {
var cell = this.get_selected_cell();
var cell_index = this.find_cell_index(cell);
cell.execute();
this.set_dirty(true);
};
IPython.Notebook.prototype.command_mode = function () {
return;
}
IPython.Notebook.prototype.edit_mode = function () {
return;
}
// Focus editor on select
IPython.CodeCell.prototype.select = function() {
var cont = IPython.Cell.prototype.select.apply(this);
if (cont) {
this.code_mirror.refresh();
this.focus_editor();
this.auto_highlight();
}
return cont;
};
// Focus editor on select
IPython.TextCell.prototype.select = function() {
var cont = IPython.Cell.prototype.select.apply(this);
if (cont) {
if (this.mode === 'edit') {
this.code_mirror.refresh();
}
this.element.focus();
}
return cont;
};
IPython.TextCell.prototype.execute = function () {
this.render();
this.command_mode();
};
IPython.CodeCell.prototype.handle_keyevent = function(editor, event) {
// console.log('CM', this.mode, event.which, event.type)
var ret = this.handle_codemirror_keyevent(editor, event);
if (ret) {
return ret;
}
if (event.type == 'keydown') {
// switch IPython.notebook to this.notebook if Cells get notebook reference
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
return false;
};
// Override TextCell keydown
// Really just here to handle the render/editing of text cells
// Might need to consider also using codemirror keyevent
IPython.TextCell.prototype.handle_keyevent = function(editor, event) {
var ret = this.handle_codemirror_keyevent(editor, event);
if (ret) {
return ret;
}
if (event.type == 'keydown') {
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
return false;
}
IPython.Notebook.prototype.setVIMode = function(mode) {
var cell = this.get_selected_cell();
cm = cell.code_mirror;
if (cm) {
if (mode == 'INSERT') {
CodeMirror.keyMap.vim.I(cm);
}
}
}
var IPython = (function(IPython) {
var NormalMode = {};
var InsertMode = {};
var VIM = function() {;
};
VIM.prototype.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var vim_mode = cell.code_mirror.getOption('keyMap');
ret = false;
if (vim_mode == 'vim') {
ret = NormalMode.keyDown(that, event);
}
if (vim_mode == 'vim-insert') {
ret = InsertMode.keyDown(that, event);
}
if (ret) {
event.preventDefault();
return true;
}
return false;
};
NormalMode.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var cell_type = cell.cell_type;
var textcell = cell instanceof IPython.TextCell;
// ` : enable console
if (event.which === 192) {
$(IPython.console_book.element).toggle();
IPython.console_book.focus_selected();
return true;
}
// Meta S: save_notebook
if ((event.ctrlKey || event.metaKey) && event.keyCode == 83) {
that.save_notebook();
event.preventDefault();
return false;
}
// K: up cell
if (event.which === 75 && (event.shiftKey || event.metaKey)) {
that.select_prev();
return true;
}
// k: up
if (event.which === 75 && !event.shiftKey) {
// textcell. Treat as one line item when not rendered
if (textcell && cell.rendered) {
that.select_prev();
return true;
}
var cursor = cell.code_mirror.getCursor();
if (cursor.line === 0) {
that.select_prev();
var new_cell = that.get_selected_cell();
if (new_cell.code_mirror) { // bottom line, same ch position
var last_line = new_cell.code_mirror.lastLine();
// NOTE: a current code_mirror bug doesn't respect the new cursor opsition
// https://github.com/marijnh/CodeMirror/issues/2289
if (new_cell.code_mirror.state.vim) {
new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
}
new_cell.code_mirror.setCursor(last_line, cursor.ch);
}
// right now textcell is handled via Document handler prevent the double call
event.preventDefault();
event.stopPropagation();
return true;
}
}
// J: down cell
if (event.which === 74 && (event.shiftKey || event.metaKey)) {
that.select_next();
return true;
}
// j: down
if (event.which === 74 && !event.shiftKey) {
// textcell. Treat as one line item when not rendered
if (textcell && cell.rendered) {
that.select_next();
return true;
}
var cursor = cell.code_mirror.getCursor();
var ch = cursor.ch;
if (cursor.line === (cell.code_mirror.lineCount() - 1)) {
that.select_next();
var new_cell = that.get_selected_cell();
if (new_cell.code_mirror) { // bottom line, same ch position
// NOTE: a current code_mirror bug doesn't respect the new cursor opsition
// https://github.com/marijnh/CodeMirror/issues/2289
new_cell.code_mirror.setCursor(0, cursor.ch);
if (new_cell.code_mirror.state.vim) {
new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
}
}
// right now textcell is handled via Document handler prevent the double call
event.preventDefault();
event.stopPropagation();
return true;
};
}
// Y: copy cell
if (event.which === 89 && event.shiftKey) {
that.copy_cell();
return true;
}
// D: delete cell / cut
if (event.which === 68 && event.shiftKey) {
that.cut_cell();
return true;
}
// P: paste cell
if (event.which === 80 && event.shiftKey) {
that.paste_cell();
return true;
}
// B: open new cell below
if (event.which === 66 && event.shiftKey) {
that.insert_cell_below('code');
that.setVIMode('INSERT');
return true;
}
// shift+O or apple + O: open new cell below
// I know this is wrong but i hate hitting A
if (event.which === 79 && (event.metaKey || event.shiftKey)) {
that.insert_cell_below('code');
that.setVIMode('INSERT');
return true;
}
// A: open new cell above
if (event.which === 65 && event.shiftKey) {
that.insert_cell_above('code');
that.setVIMode('INSERT');
return true;
}
// control/apple E: execute (apple - E is easier than shift E)
if ((event.ctrlKey || event.metaKey) && event.keyCode == 69) {
that.execute_cell();
return true;
}
// E: execute
if (event.which === 69 && event.shiftKey) {
that.execute_cell();
return true;
}
// F: toggle output
if (event.which === 70 && event.shiftKey) {
that.toggle_output();
return true;
}
// M: markdown
if (event.which === 77 && event.shiftKey) {
that.to_markdown();
return true;
}
// C: codecell
if (event.which === 77 && event.shiftKey) {
that.to_code();
return true;
}
// i: insert. only relevant on textcell
var rendered = cell.rendered;
if (textcell && rendered && event.which === 73 && !event.shiftKey) {
cell.edit_mode();
return false;
}
// esc: get out of insert and render textcell
if (textcell && !rendered && event.which === 27 && !event.shiftKey) {
cell.render();
return false;
}
};
InsertMode.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var cell_type = cell.cell_type;
var textcell = cell instanceof IPython.TextCell;
// control/apple E: execute (apple - E is easier than shift E)
if ((event.ctrlKey || event.metaKey) && event.keyCode == 69) {
that.execute_cell();
return true;
}
if (event.which === 74 && (event.metaKey)) {
that.select_next();
return true;
}
if (event.which === 75 && (event.metaKey)) {
that.select_prev();
return true;
}
// Meta S: save_notebook
if ((event.ctrlKey || event.metaKey) && event.keyCode == 83) {
that.save_notebook();
event.preventDefault();
return false;
}
};
IPython.VIM = new VIM();
return IPython;
}(IPython));
| nbextensions/vim.js | /*
Add this file to $(ipython locate)/nbextensions/vim.js
And load it with:
require(["nbextensions/vim"], function (vim_extension) {
console.log('vim extension loaded');
vim_extension.load_extension();
});
*/
define(function() {
var token_name = "vim_github_token";
var load_extension = function() {
$([IPython.events]).on("notebook_loaded.Notebook", function() {
console.log("notebook loaded event");
});
};
return {
load_extension: load_extension,
};
});
// plug in so :w saves
CodeMirror.commands.save = function(cm) {
IPython.notebook.save_notebook();
}
// Monkey patch: KeyboardManager.handle_keydown
// Diff: disable this handler
IPython.KeyboardManager.prototype.handle_keydown = function(event) {
var cell = IPython.notebook.get_selected_cell();
if (cell instanceof IPython.TextCell) {
if (cell.mode == 'command' && event.type == 'keydown') {
// switch IPython.notebook to this.notebook if Cells get notebook reference
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
}
return;
}
// Monkey patch: KeyboardManager.register_events
// Diff: disable this handler
IPython.KeyboardManager.prototype.register_events = function(e) {
return;
}
// Monkey patch insert_cell_below
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_below = function(type, index) {
index = this.index_or_selected(index);
var cell = this.insert_cell_at_index(type, index + 1);
this.select(this.find_cell_index(cell));
return cell;
};
// Monkey patch insert_cell_above
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_above = function(type, index) {
index = this.index_or_selected(index);
var cell = this.insert_cell_at_index(type, index);
this.select(this.find_cell_index(cell));
return cell;
};
// Monkey patch: execute_cell
// Diff: don't switch to command mode
IPython.Notebook.prototype.execute_cell = function() {
var cell = this.get_selected_cell();
var cell_index = this.find_cell_index(cell);
cell.execute();
this.set_dirty(true);
};
// Focus editor on select
IPython.CodeCell.prototype.select = function() {
var cont = IPython.Cell.prototype.select.apply(this);
if (cont) {
this.code_mirror.refresh();
this.focus_editor();
this.auto_highlight();
}
return cont;
};
IPython.CodeCell.prototype.handle_keyevent = function(editor, event) {
// console.log('CM', this.mode, event.which, event.type)
var ret = this.handle_codemirror_keyevent(editor, event);
if (ret) {
return ret;
}
if (event.type == 'keydown') {
// switch IPython.notebook to this.notebook if Cells get notebook reference
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
return false;
};
// Override TextCell keydown
// Really just here to handle the render/editing of text cells
// Might need to consider also using codemirror keyevent
IPython.TextCell.prototype.handle_keyevent = function(editor, event) {
var ret = this.handle_codemirror_keyevent(editor, event);
if (ret) {
return ret;
}
if (event.type == 'keydown') {
ret = IPython.VIM.keyDown(IPython.notebook, event);
return ret;
}
return false;
}
IPython.Notebook.prototype.setVIMode = function(mode) {
var cell = this.get_selected_cell();
cm = cell.code_mirror;
if (cm) {
if (mode == 'INSERT') {
CodeMirror.keyMap.vim.I(cm);
}
}
}
var IPython = (function(IPython) {
var NormalMode = {};
var InsertMode = {};
var VIM = function() {;
};
VIM.prototype.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var vim_mode = cell.code_mirror.getOption('keyMap');
ret = false;
if (vim_mode == 'vim') {
ret = NormalMode.keyDown(that, event);
}
if (vim_mode == 'vim-insert') {
ret = InsertMode.keyDown(that, event);
}
if (ret) {
event.preventDefault();
return true;
}
return false;
};
NormalMode.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var cell_type = cell.cell_type;
var textcell = cell instanceof IPython.TextCell;
// ` : enable console
if (event.which === 192) {
$(IPython.console_book.element).toggle();
IPython.console_book.focus_selected();
return true;
}
// Meta S: save_notebook
if ((event.ctrlKey || event.metaKey) && event.keyCode == 83) {
that.save_notebook();
event.preventDefault();
return false;
}
// K: up cell
if (event.which === 75 && (event.shiftKey || event.metaKey)) {
that.select_prev();
return true;
}
// k: up
if (event.which === 75 && !event.shiftKey) {
// textcell. Treat as one line item when not rendered
if (textcell && cell.rendered) {
that.select_prev();
return true;
}
var cursor = cell.code_mirror.getCursor();
if (cursor.line === 0) {
that.select_prev();
var new_cell = that.get_selected_cell();
if (new_cell.code_mirror) { // bottom line, same ch position
var last_line = new_cell.code_mirror.lastLine();
// NOTE: a current code_mirror bug doesn't respect the new cursor opsition
// https://github.com/marijnh/CodeMirror/issues/2289
if (new_cell.code_mirror.state.vim) {
new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
}
new_cell.code_mirror.setCursor(last_line, cursor.ch);
}
}
// right now textcell is handled via Document handler prevent the double call
event.preventDefault();
event.stopPropagation();
return true;
}
// J: down cell
if (event.which === 74 && (event.shiftKey || event.metaKey)) {
that.select_next();
return true;
}
// j: down
if (event.which === 74 && !event.shiftKey) {
// textcell. Treat as one line item when not rendered
if (textcell && cell.rendered) {
that.select_next();
return true;
}
var cursor = cell.code_mirror.getCursor();
var ch = cursor.ch;
if (cursor.line === (cell.code_mirror.lineCount() - 1)) {
that.select_next();
var new_cell = that.get_selected_cell();
if (new_cell.code_mirror) { // bottom line, same ch position
// NOTE: a current code_mirror bug doesn't respect the new cursor opsition
// https://github.com/marijnh/CodeMirror/issues/2289
new_cell.code_mirror.setCursor(0, cursor.ch);
if (new_cell.code_mirror.state.vim) {
new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
}
}
// right now textcell is handled via Document handler prevent the double call
event.preventDefault();
event.stopPropagation();
return true;
};
}
// Y: copy cell
if (event.which === 89 && event.shiftKey) {
that.copy_cell();
return true;
}
// D: delete cell / cut
if (event.which === 68 && event.shiftKey) {
that.cut_cell();
return true;
}
// P: paste cell
if (event.which === 80 && event.shiftKey) {
that.paste_cell();
return true;
}
// B: open new cell below
if (event.which === 66 && event.shiftKey) {
that.insert_cell_below('code');
that.setVIMode('INSERT');
return true;
}
// shift+O or apple + O: open new cell below
// I know this is wrong but i hate hitting A
if (event.which === 79 && (event.metaKey || event.shiftKey)) {
that.insert_cell_below('code');
that.setVIMode('INSERT');
return true;
}
// A: open new cell above
if (event.which === 65 && event.shiftKey) {
that.insert_cell_above('code');
that.setVIMode('INSERT');
return true;
}
// control/apple E: execute (apple - E is easier than shift E)
if ((event.ctrlKey || event.metaKey) && event.keyCode == 69) {
that.execute_cell();
return true;
}
// E: execute
if (event.which === 69 && event.shiftKey) {
that.execute_cell();
return true;
}
// F: toggle output
if (event.which === 70 && event.shiftKey) {
that.toggle_output();
return true;
}
// M: markdown
if (event.which === 77 && event.shiftKey) {
that.to_markdown();
return true;
}
// C: codecell
if (event.which === 77 && event.shiftKey) {
that.to_code();
return true;
}
// i: insert. only relevant on textcell
var rendered = cell.rendered;
if (textcell && rendered && event.which === 73 && !event.shiftKey) {
cell.edit_mode();
return false;
}
// esc: get out of insert and render textcell
if (textcell && !rendered && event.which === 27 && !event.shiftKey) {
cell.render();
return false;
}
};
InsertMode.keyDown = function(that, event) {
var cell = that.get_selected_cell();
var cell_type = cell.cell_type;
var textcell = cell instanceof IPython.TextCell;
// control/apple E: execute (apple - E is easier than shift E)
if ((event.ctrlKey || event.metaKey) && event.keyCode == 69) {
that.execute_cell();
return true;
}
if (event.which === 74 && (event.metaKey)) {
that.select_next();
return true;
}
if (event.which === 75 && (event.metaKey)) {
that.select_prev();
return true;
}
// Meta S: save_notebook
if ((event.ctrlKey || event.metaKey) && event.keyCode == 83) {
that.save_notebook();
event.preventDefault();
return false;
}
};
IPython.VIM = new VIM();
return IPython;
}(IPython));
| fixes for TextCell, basically routing around dual mode
| nbextensions/vim.js | fixes for TextCell, basically routing around dual mode | <ide><path>bextensions/vim.js
<ide>
<ide> IPython.KeyboardManager.prototype.handle_keydown = function(event) {
<ide> var cell = IPython.notebook.get_selected_cell();
<add> var vim_mode = cell.code_mirror.getOption('keyMap');
<ide> if (cell instanceof IPython.TextCell) {
<del> if (cell.mode == 'command' && event.type == 'keydown') {
<add> // when cell is rendered, we get no key events, so we capture here
<add> if (cell.rendered && event.type == 'keydown') {
<ide> // switch IPython.notebook to this.notebook if Cells get notebook reference
<ide> ret = IPython.VIM.keyDown(IPython.notebook, event);
<ide> return ret;
<ide> this.set_dirty(true);
<ide> };
<ide>
<add>IPython.Notebook.prototype.command_mode = function () {
<add> return;
<add>}
<add>
<add>IPython.Notebook.prototype.edit_mode = function () {
<add> return;
<add>}
<add>
<ide> // Focus editor on select
<ide> IPython.CodeCell.prototype.select = function() {
<ide> var cont = IPython.Cell.prototype.select.apply(this);
<ide> this.auto_highlight();
<ide> }
<ide> return cont;
<add>};
<add>
<add>// Focus editor on select
<add>IPython.TextCell.prototype.select = function() {
<add> var cont = IPython.Cell.prototype.select.apply(this);
<add> if (cont) {
<add> if (this.mode === 'edit') {
<add> this.code_mirror.refresh();
<add> }
<add> this.element.focus();
<add> }
<add> return cont;
<add>};
<add>
<add>IPython.TextCell.prototype.execute = function () {
<add> this.render();
<add> this.command_mode();
<ide> };
<ide>
<ide> IPython.CodeCell.prototype.handle_keyevent = function(editor, event) {
<ide> }
<ide> new_cell.code_mirror.setCursor(last_line, cursor.ch);
<ide> }
<add> // right now textcell is handled via Document handler prevent the double call
<add> event.preventDefault();
<add> event.stopPropagation();
<add> return true;
<ide> }
<del> // right now textcell is handled via Document handler prevent the double call
<del> event.preventDefault();
<del> event.stopPropagation();
<del> return true;
<ide> }
<ide> // J: down cell
<ide> if (event.which === 74 && (event.shiftKey || event.metaKey)) { |
|
Java | apache-2.0 | 80d6899472fb437a2807f7100a07cccc16b50b7d | 0 | gcoders/gerrit,anminhsu/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,supriyantomaftuh/gerrit,qtproject/qtqa-gerrit,Distrotech/gerrit,dwhipstock/gerrit,jackminicloud/test,Seinlin/gerrit,gerrit-review/gerrit,dwhipstock/gerrit,gcoders/gerrit,gcoders/gerrit,supriyantomaftuh/gerrit,GerritCodeReview/gerrit,bpollack/gerrit,thinkernel/gerrit,netroby/gerrit,quyixia/gerrit,bpollack/gerrit,Overruler/gerrit,gerrit-review/gerrit,jackminicloud/test,bootstraponline-archive/gerrit-mirror,GerritCodeReview/gerrit,midnightradio/gerrit,thesamet/gerrit,supriyantomaftuh/gerrit,jackminicloud/test,TonyChai24/test,pkdevbox/gerrit,Overruler/gerrit,renchaorevee/gerrit,Distrotech/gerrit,hdost/gerrit,netroby/gerrit,bootstraponline-archive/gerrit-mirror,Team-OctOS/host_gerrit,netroby/gerrit,WANdisco/gerrit,joshuawilson/merrit,WANdisco/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,Saulis/gerrit,supriyantomaftuh/gerrit,dwhipstock/gerrit,gerrit-review/gerrit,supriyantomaftuh/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,Distrotech/gerrit,netroby/gerrit,Team-OctOS/host_gerrit,WANdisco/gerrit,WANdisco/gerrit,thesamet/gerrit,gcoders/gerrit,joshuawilson/merrit,jackminicloud/test,qtproject/qtqa-gerrit,hdost/gerrit,thinkernel/gerrit,bootstraponline-archive/gerrit-mirror,hdost/gerrit,renchaorevee/gerrit,Team-OctOS/host_gerrit,pkdevbox/gerrit,anminhsu/gerrit,joshuawilson/merrit,qtproject/qtqa-gerrit,renchaorevee/gerrit,bootstraponline-archive/gerrit-mirror,MerritCR/merrit,Seinlin/gerrit,thinkernel/gerrit,Saulis/gerrit,dwhipstock/gerrit,Seinlin/gerrit,renchaorevee/gerrit,TonyChai24/test,WANdisco/gerrit,gerrit-review/gerrit,jackminicloud/test,TonyChai24/test,bootstraponline-archive/gerrit-mirror,quyixia/gerrit,jackminicloud/test,TonyChai24/test,midnightradio/gerrit,bpollack/gerrit,qtproject/qtqa-gerrit,bootstraponline-archive/gerrit-mirror,Saulis/gerrit,GerritCodeReview/gerrit,hdost/gerrit,joshuawilson/merrit,gerrit-review/gerrit,renchaorevee/gerrit,quyixia/gerrit,quyixia/gerrit,midnightradio/gerrit,midnightradio/gerrit,supriyantomaftuh/gerrit,hdost/gerrit,netroby/gerrit,Team-OctOS/host_gerrit,renchaorevee/gerrit,thinkernel/gerrit,GerritCodeReview/gerrit,Distrotech/gerrit,qtproject/qtqa-gerrit,Distrotech/gerrit,thesamet/gerrit,Seinlin/gerrit,Saulis/gerrit,Seinlin/gerrit,gerrit-review/gerrit,netroby/gerrit,MerritCR/merrit,Saulis/gerrit,anminhsu/gerrit,gcoders/gerrit,thesamet/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,jackminicloud/test,Saulis/gerrit,Overruler/gerrit,pkdevbox/gerrit,thesamet/gerrit,TonyChai24/test,supriyantomaftuh/gerrit,thinkernel/gerrit,Team-OctOS/host_gerrit,thinkernel/gerrit,MerritCR/merrit,Seinlin/gerrit,WANdisco/gerrit,dwhipstock/gerrit,Seinlin/gerrit,MerritCR/merrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,joshuawilson/merrit,thesamet/gerrit,qtproject/qtqa-gerrit,Overruler/gerrit,MerritCR/merrit,bpollack/gerrit,Overruler/gerrit,quyixia/gerrit,midnightradio/gerrit,bpollack/gerrit,midnightradio/gerrit,thinkernel/gerrit,TonyChai24/test,pkdevbox/gerrit,anminhsu/gerrit,quyixia/gerrit,joshuawilson/merrit,Distrotech/gerrit,gcoders/gerrit,TonyChai24/test,netroby/gerrit,renchaorevee/gerrit,dwhipstock/gerrit,quyixia/gerrit,WANdisco/gerrit,MerritCR/merrit,Distrotech/gerrit,gcoders/gerrit,dwhipstock/gerrit,Overruler/gerrit,joshuawilson/merrit,thesamet/gerrit,bpollack/gerrit,anminhsu/gerrit,hdost/gerrit,anminhsu/gerrit,joshuawilson/merrit,hdost/gerrit,pkdevbox/gerrit,GerritCodeReview/gerrit | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project.SubmitType;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.changedetail.RebaseChange;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/** Factory to create a {@link SubmitStrategy} for a {@link SubmitType}. */
public class SubmitStrategyFactory {
private static final Logger log = LoggerFactory
.getLogger(SubmitStrategyFactory.class);
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final PersonIdent myIdent;
private final PatchSetInfoFactory patchSetInfoFactory;
private final GitReferenceUpdated gitRefUpdated;
private final RebaseChange rebaseChange;
private final ProjectCache projectCache;
private final ApprovalsUtil approvalsUtil;
private final MergeUtil.Factory mergeUtilFactory;
private final ChangeIndexer indexer;
@Inject
SubmitStrategyFactory(
final IdentifiedUser.GenericFactory identifiedUserFactory,
@GerritPersonIdent final PersonIdent myIdent,
final PatchSetInfoFactory patchSetInfoFactory,
final GitReferenceUpdated gitRefUpdated, final RebaseChange rebaseChange,
final ProjectCache projectCache,
final ApprovalsUtil approvalsUtil,
final MergeUtil.Factory mergeUtilFactory,
final ChangeIndexer indexer) {
this.identifiedUserFactory = identifiedUserFactory;
this.myIdent = myIdent;
this.patchSetInfoFactory = patchSetInfoFactory;
this.gitRefUpdated = gitRefUpdated;
this.rebaseChange = rebaseChange;
this.projectCache = projectCache;
this.approvalsUtil = approvalsUtil;
this.mergeUtilFactory = mergeUtilFactory;
this.indexer = indexer;
}
public SubmitStrategy create(final SubmitType submitType, final ReviewDb db,
final Repository repo, final RevWalk rw, final ObjectInserter inserter,
final RevFlag canMergeFlag, final Set<RevCommit> alreadyAccepted,
final Branch.NameKey destBranch)
throws MergeException, NoSuchProjectException {
ProjectState project = getProject(destBranch);
final SubmitStrategy.Arguments args =
new SubmitStrategy.Arguments(identifiedUserFactory, myIdent, db, repo,
rw, inserter, canMergeFlag, alreadyAccepted, destBranch,
approvalsUtil, mergeUtilFactory.create(project), indexer);
switch (submitType) {
case CHERRY_PICK:
return new CherryPick(args, patchSetInfoFactory, gitRefUpdated);
case FAST_FORWARD_ONLY:
return new FastForwardOnly(args);
case MERGE_ALWAYS:
return new MergeAlways(args);
case MERGE_IF_NECESSARY:
return new MergeIfNecessary(args);
case REBASE_IF_NECESSARY:
return new RebaseIfNecessary(args, rebaseChange, myIdent);
default:
final String errorMsg = "No submit strategy for: " + submitType;
log.error(errorMsg);
throw new MergeException(errorMsg);
}
}
private ProjectState getProject(Branch.NameKey branch)
throws NoSuchProjectException {
final ProjectState p = projectCache.get(branch.getParentKey());
if (p == null) {
throw new NoSuchProjectException(branch.getParentKey());
}
return p;
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/git/SubmitStrategyFactory.java | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project.SubmitType;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.changedetail.RebaseChange;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/** Factory to create a {@link SubmitStrategy} for a {@link SubmitType}. */
public class SubmitStrategyFactory {
private static final Logger log = LoggerFactory
.getLogger(SubmitStrategyFactory.class);
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final PersonIdent myIdent;
private final PatchSetInfoFactory patchSetInfoFactory;
private final GitReferenceUpdated gitRefUpdated;
private final RebaseChange rebaseChange;
private final ProjectCache projectCache;
private final ApprovalsUtil approvalsUtil;
private final MergeUtil.Factory mergeUtilFactory;
private final ChangeIndexer indexer;
@Inject
SubmitStrategyFactory(
final IdentifiedUser.GenericFactory identifiedUserFactory,
@GerritPersonIdent final PersonIdent myIdent,
final PatchSetInfoFactory patchSetInfoFactory,
@CanonicalWebUrl @Nullable final Provider<String> urlProvider,
final GitReferenceUpdated gitRefUpdated, final RebaseChange rebaseChange,
final ProjectCache projectCache,
final ApprovalsUtil approvalsUtil,
final MergeUtil.Factory mergeUtilFactory,
final ChangeIndexer indexer) {
this.identifiedUserFactory = identifiedUserFactory;
this.myIdent = myIdent;
this.patchSetInfoFactory = patchSetInfoFactory;
this.gitRefUpdated = gitRefUpdated;
this.rebaseChange = rebaseChange;
this.projectCache = projectCache;
this.approvalsUtil = approvalsUtil;
this.mergeUtilFactory = mergeUtilFactory;
this.indexer = indexer;
}
public SubmitStrategy create(final SubmitType submitType, final ReviewDb db,
final Repository repo, final RevWalk rw, final ObjectInserter inserter,
final RevFlag canMergeFlag, final Set<RevCommit> alreadyAccepted,
final Branch.NameKey destBranch)
throws MergeException, NoSuchProjectException {
ProjectState project = getProject(destBranch);
final SubmitStrategy.Arguments args =
new SubmitStrategy.Arguments(identifiedUserFactory, myIdent, db, repo,
rw, inserter, canMergeFlag, alreadyAccepted, destBranch,
approvalsUtil, mergeUtilFactory.create(project), indexer);
switch (submitType) {
case CHERRY_PICK:
return new CherryPick(args, patchSetInfoFactory, gitRefUpdated);
case FAST_FORWARD_ONLY:
return new FastForwardOnly(args);
case MERGE_ALWAYS:
return new MergeAlways(args);
case MERGE_IF_NECESSARY:
return new MergeIfNecessary(args);
case REBASE_IF_NECESSARY:
return new RebaseIfNecessary(args, rebaseChange, myIdent);
default:
final String errorMsg = "No submit strategy for: " + submitType;
log.error(errorMsg);
throw new MergeException(errorMsg);
}
}
private ProjectState getProject(Branch.NameKey branch)
throws NoSuchProjectException {
final ProjectState p = projectCache.get(branch.getParentKey());
if (p == null) {
throw new NoSuchProjectException(branch.getParentKey());
}
return p;
}
}
| Remove unused injection of URL provider from SubmitStrategyFactory
Change-Id: I39a5c83886b4d5a1e6590740e5808fca28207dd1
Signed-off-by: Edwin Kempin <[email protected]>
| gerrit-server/src/main/java/com/google/gerrit/server/git/SubmitStrategyFactory.java | Remove unused injection of URL provider from SubmitStrategyFactory | <ide><path>errit-server/src/main/java/com/google/gerrit/server/git/SubmitStrategyFactory.java
<ide>
<ide> package com.google.gerrit.server.git;
<ide>
<del>import com.google.gerrit.common.Nullable;
<ide> import com.google.gerrit.reviewdb.client.Branch;
<ide> import com.google.gerrit.reviewdb.client.Project.SubmitType;
<ide> import com.google.gerrit.reviewdb.server.ReviewDb;
<ide> import com.google.gerrit.server.GerritPersonIdent;
<ide> import com.google.gerrit.server.IdentifiedUser;
<ide> import com.google.gerrit.server.changedetail.RebaseChange;
<del>import com.google.gerrit.server.config.CanonicalWebUrl;
<ide> import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
<ide> import com.google.gerrit.server.index.ChangeIndexer;
<ide> import com.google.gerrit.server.patch.PatchSetInfoFactory;
<ide> import com.google.gerrit.server.project.ProjectCache;
<ide> import com.google.gerrit.server.project.ProjectState;
<ide> import com.google.inject.Inject;
<del>import com.google.inject.Provider;
<ide>
<ide> import org.eclipse.jgit.lib.ObjectInserter;
<ide> import org.eclipse.jgit.lib.PersonIdent;
<ide> final IdentifiedUser.GenericFactory identifiedUserFactory,
<ide> @GerritPersonIdent final PersonIdent myIdent,
<ide> final PatchSetInfoFactory patchSetInfoFactory,
<del> @CanonicalWebUrl @Nullable final Provider<String> urlProvider,
<ide> final GitReferenceUpdated gitRefUpdated, final RebaseChange rebaseChange,
<ide> final ProjectCache projectCache,
<ide> final ApprovalsUtil approvalsUtil, |
|
Java | apache-2.0 | 81d357b31a3f03b1fc20a3daf50e227146360580 | 0 | mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.segment;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.addAll;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Lists.newArrayListWithExpectedSize;
import static com.google.common.collect.Lists.partition;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.io.ByteStreams.read;
import static java.lang.Integer.getInteger;
import static java.lang.System.nanoTime;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.nCopies;
import static org.apache.jackrabbit.oak.api.Type.BINARIES;
import static org.apache.jackrabbit.oak.api.Type.BINARY;
import static org.apache.jackrabbit.oak.api.Type.NAME;
import static org.apache.jackrabbit.oak.api.Type.NAMES;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.segment.MapRecord.BUCKETS_PER_LEVEL;
import static org.apache.jackrabbit.oak.segment.RecordWriters.newNodeStateWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.PropertyType;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.io.Closeables;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
import org.apache.jackrabbit.oak.api.Blob;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.api.jmx.CacheStatsMBean;
import org.apache.jackrabbit.oak.plugins.memory.ModifiedNodeState;
import org.apache.jackrabbit.oak.segment.WriteOperationHandler.WriteOperation;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.DefaultNodeStateDiff;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@code SegmentWriter} converts nodes, properties, values, etc. to records and
* persists them with the help of a {@link WriteOperationHandler}.
* All public methods of this class are thread safe if and only if the
* {@link WriteOperationHandler} passed to the constructor is thread safe.
*/
public class SegmentWriter {
private static final Logger LOG = LoggerFactory.getLogger(SegmentWriter.class);
/**
* Size of the window for collecting statistics about the time it takes to
* write / compact nodes.
* @see DescriptiveStatistics#setWindowSize(int)
*/
private static final int NODE_WRITER_STATS_WINDOW = getInteger(
"oak.tar.nodeWriterStatsWindow", 10000);
static final int BLOCK_SIZE = 1 << 12; // 4kB
@Nonnull
private final WriterCacheManager cacheManager;
@Nonnull
private final SegmentStore store;
@Nonnull
private final SegmentReader reader;
@CheckForNull
private final BlobStore blobStore;
@Nonnull
private final WriteOperationHandler writeOperationHandler;
@Nonnull
private final BinaryReferenceConsumer binaryReferenceConsumer;
@Nonnull
private final SynchronizedDescriptiveStatistics nodeCompactTimeStats =
new SynchronizedDescriptiveStatistics(NODE_WRITER_STATS_WINDOW);
@Nonnull
private final SynchronizedDescriptiveStatistics nodeWriteTimeStats =
new SynchronizedDescriptiveStatistics(NODE_WRITER_STATS_WINDOW);
/**
* Create a new instance of a {@code SegmentWriter}. Note the thread safety properties
* pointed out in the class comment.
*
* @param store store to write to
* @param reader segment reader for the {@code store}
* @param blobStore the blog store or {@code null} for inlined blobs
* @param cacheManager cache manager instance for the de-duplication caches used by this writer
* @param writeOperationHandler handler for write operations.
*/
public SegmentWriter(@Nonnull SegmentStore store,
@Nonnull SegmentReader reader,
@Nullable BlobStore blobStore,
@Nonnull WriterCacheManager cacheManager,
@Nonnull WriteOperationHandler writeOperationHandler,
@Nonnull BinaryReferenceConsumer binaryReferenceConsumer
) {
this.store = checkNotNull(store);
this.reader = checkNotNull(reader);
this.blobStore = blobStore;
this.cacheManager = checkNotNull(cacheManager);
this.writeOperationHandler = checkNotNull(writeOperationHandler);
this.binaryReferenceConsumer = checkNotNull(binaryReferenceConsumer);
}
/**
* @return Statistics for node compaction times (in ns). These statistics
* include explicit compactions triggered by the file store and implicit
* compactions triggered by references to older generations.
* The statistics are collected with a window size defined by {@link #NODE_WRITER_STATS_WINDOW}
* @see #getNodeWriteTimeStats()
*/
@Nonnull
public DescriptiveStatistics getNodeCompactTimeStats() {
return nodeCompactTimeStats;
}
/**
* @return Statistics for node write times (in ns).
* The statistics are collected with a window size defined by {@link #NODE_WRITER_STATS_WINDOW}
* @see #getNodeCompactTimeStats()
*/
@Nonnull
public DescriptiveStatistics getNodeWriteTimeStats() {
return nodeWriteTimeStats;
}
public void flush() throws IOException {
writeOperationHandler.flush();
}
/**
* @return Statistics for the string deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getStringCacheStats() {
return cacheManager.getStringCacheStats();
}
/**
* @return Statistics for the template deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getTemplateCacheStats() {
return cacheManager.getTemplateCacheStats();
}
/**
* @return Statistics for the node deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getNodeCacheStats() {
return cacheManager.getNodeCacheStats();
}
/**
* Write a map record.
* @param base base map relative to which the {@code changes} are applied ot
* {@code null} for the empty map.
* @param changes the changed mapping to apply to the {@code base} map.
* @return the map record written
* @throws IOException
*/
@Nonnull
public MapRecord writeMap(@Nullable final MapRecord base,
@Nonnull final Map<String, RecordId> changes)
throws IOException {
RecordId mapId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeMap(base, changes);
}
});
return new MapRecord(reader, mapId);
}
/**
* Write a list record.
* @param list the list to write.
* @return the record id of the list written
* @throws IOException
*/
@Nonnull
public RecordId writeList(@Nonnull final List<RecordId> list) throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeList(list);
}
});
}
/**
* Write a string record.
* @param string the string to write.
* @return the record id of the string written.
* @throws IOException
*/
@Nonnull
public RecordId writeString(@Nonnull final String string) throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeString(string);
}
});
}
/**
* Write a blob (as list of block records)
* @param blob blob to write
* @return The segment blob written
* @throws IOException
*/
@Nonnull
public SegmentBlob writeBlob(@Nonnull final Blob blob) throws IOException {
RecordId blobId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeBlob(blob);
}
});
return new SegmentBlob(blobStore, blobId);
}
/**
* Writes a block record containing the given block of bytes.
*
* @param bytes source buffer
* @param offset offset within the source buffer
* @param length number of bytes to write
* @return block record identifier
*/
@Nonnull
public RecordId writeBlock(@Nonnull final byte[] bytes, final int offset, final int length)
throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeBlock(bytes, offset, length);
}
});
}
/**
* Writes a stream value record. The given stream is consumed <em>and closed</em> by
* this method.
*
* @param stream stream to be written
* @return blob for the passed {@code stream}
* @throws IOException if the input stream could not be read or the output could not be written
*/
@Nonnull
public SegmentBlob writeStream(@Nonnull final InputStream stream) throws IOException {
RecordId blobId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeStream(stream);
}
});
return new SegmentBlob(blobStore, blobId);
}
/**
* Write a property.
* @param state the property to write
* @return the property state written
* @throws IOException
*/
@Nonnull
public SegmentPropertyState writeProperty(@Nonnull final PropertyState state)
throws IOException {
RecordId id = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeProperty(state);
}
});
return new SegmentPropertyState(reader, id, state.getName(), state.getType());
}
/**
* Write a node state
* @param state node state to write
* @return segment node state equal to {@code state}
* @throws IOException
*/
@Nonnull
public SegmentNodeState writeNode(@Nonnull final NodeState state) throws IOException {
RecordId nodeId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeNode(state);
}
});
return new SegmentNodeState(reader, this, nodeId);
}
/**
* Write a node state, unless cancelled using a dedicated write operation handler.
* The write operation handler is automatically {@link WriteOperationHandler#flush() flushed}
* once the node has been written successfully.
* @param state node state to write
* @param writeOperationHandler the write operation handler through which all write calls
* induced by by this call are routed.
* @param cancel supplier to signal cancellation of this write operation
* @return segment node state equal to {@code state} or {@code null} if cancelled.
* @throws IOException
*/
@CheckForNull
public SegmentNodeState writeNode(@Nonnull final NodeState state,
@Nonnull WriteOperationHandler writeOperationHandler,
@Nonnull Supplier<Boolean> cancel)
throws IOException {
try {
RecordId nodeId = writeOperationHandler.execute(new SegmentWriteOperation(cancel) {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeNode(state);
}
});
writeOperationHandler.flush();
return new SegmentNodeState(reader, this, nodeId);
} catch (SegmentWriteOperation.CancelledWriteException ignore) {
return null;
}
}
/**
* This {@code WriteOperation} implementation is used internally to provide
* context to a recursive chain of calls without having pass the context
* as a separate argument (a poor mans monad). As such it is entirely
* <em>not thread safe</em>.
*/
private abstract class SegmentWriteOperation implements WriteOperation {
private class NodeWriteStats {
private final long startTime = nanoTime();
/*
* Total number of nodes in the subtree rooted at the node passed
* to {@link #writeNode(SegmentWriteOperation, SegmentBufferWriter, NodeState)}
*/
public int nodeCount;
/*
* Number of cache hits for a deferred compacted node
*/
public int cacheHits;
/*
* Number of cache misses for a deferred compacted node
*/
public int cacheMiss;
/*
* Number of nodes that where de-duplicated as the store already contained
* them.
*/
public int deDupNodes;
/*
* Number of nodes that actually had to be written as there was no de-duplication
* and a cache miss (in case of a deferred compaction).
*/
public int writesOps;
/*
* {@code true} for if the node written was a compaction operation, false otherwise
*/
boolean isCompactOp;
@Override
public String toString() {
return "NodeStats{" +
"op=" + (isCompactOp ? "compact" : "write") +
", nodeCount=" + nodeCount +
", writeOps=" + writesOps +
", deDupNodes=" + deDupNodes +
", cacheHits=" + cacheHits +
", cacheMiss=" + cacheMiss +
", hitRate=" + (100*(double) cacheHits / ((double) cacheHits + (double) cacheMiss)) +
'}';
}
}
/**
* This exception is used internally to signal cancellation of a (recursive)
* write node operation.
*/
private class CancelledWriteException extends IOException {
public CancelledWriteException() {
super("Cancelled write operation");
}
}
@Nonnull
private final Supplier<Boolean> cancel;
@CheckForNull
private NodeWriteStats nodeWriteStats;
private SegmentBufferWriter writer;
private RecordCache<String> stringCache;
private RecordCache<Template> templateCache;
private NodeCache nodeCache;
protected SegmentWriteOperation(@Nonnull Supplier<Boolean> cancel) {
this.cancel = cancel;
}
protected SegmentWriteOperation() {
this(Suppliers.ofInstance(false));
}
@Override
public abstract RecordId execute(SegmentBufferWriter writer) throws IOException;
@Nonnull
SegmentWriteOperation with(@Nonnull SegmentBufferWriter writer) {
checkState(this.writer == null);
this.writer = writer;
int generation = writer.getGeneration();
this.stringCache = cacheManager.getStringCache(generation);
this.templateCache = cacheManager.getTemplateCache(generation);
this.nodeCache = cacheManager.getNodeCache(generation);
return this;
}
private RecordId writeMap(@Nullable MapRecord base,
@Nonnull Map<String, RecordId> changes)
throws IOException {
if (base != null && base.isDiff()) {
Segment segment = base.getSegment();
RecordId key = segment.readRecordId(base.getOffset(8));
String name = reader.readString(key);
if (!changes.containsKey(name)) {
changes.put(name, segment.readRecordId(base.getOffset(8, 1)));
}
base = new MapRecord(reader, segment.readRecordId(base.getOffset(8, 2)));
}
if (base != null && changes.size() == 1) {
Map.Entry<String, RecordId> change =
changes.entrySet().iterator().next();
RecordId value = change.getValue();
if (value != null) {
MapEntry entry = base.getEntry(change.getKey());
if (entry != null) {
if (value.equals(entry.getValue())) {
return base.getRecordId();
} else {
return RecordWriters.newMapBranchWriter(entry.getHash(), asList(entry.getKey(),
value, base.getRecordId())).write(writer);
}
}
}
}
List<MapEntry> entries = newArrayList();
for (Map.Entry<String, RecordId> entry : changes.entrySet()) {
String key = entry.getKey();
RecordId keyId = null;
if (base != null) {
MapEntry e = base.getEntry(key);
if (e != null) {
keyId = e.getKey();
}
}
if (keyId == null && entry.getValue() != null) {
keyId = writeString(key);
}
if (keyId != null) {
entries.add(new MapEntry(reader, key, keyId, entry.getValue()));
}
}
return writeMapBucket(base, entries, 0);
}
private RecordId writeMapLeaf(int level, Collection<MapEntry> entries) throws IOException {
checkNotNull(entries);
int size = entries.size();
checkElementIndex(size, MapRecord.MAX_SIZE);
checkPositionIndex(level, MapRecord.MAX_NUMBER_OF_LEVELS);
checkArgument(size != 0 || level == MapRecord.MAX_NUMBER_OF_LEVELS);
return RecordWriters.newMapLeafWriter(level, entries).write(writer);
}
private RecordId writeMapBranch(int level, int size, MapRecord... buckets) throws IOException {
int bitmap = 0;
List<RecordId> bucketIds = newArrayListWithCapacity(buckets.length);
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] != null) {
bitmap |= 1L << i;
bucketIds.add(buckets[i].getRecordId());
}
}
return RecordWriters.newMapBranchWriter(level, size, bitmap, bucketIds).write(writer);
}
private RecordId writeMapBucket(MapRecord base, Collection<MapEntry> entries, int level)
throws IOException {
// when no changed entries, return the base map (if any) as-is
if (entries == null || entries.isEmpty()) {
if (base != null) {
return base.getRecordId();
} else if (level == 0) {
return RecordWriters.newMapLeafWriter().write(writer);
} else {
return null;
}
}
// when no base map was given, write a fresh new map
if (base == null) {
// use leaf records for small maps or the last map level
if (entries.size() <= BUCKETS_PER_LEVEL
|| level == MapRecord.MAX_NUMBER_OF_LEVELS) {
return writeMapLeaf(level, entries);
}
// write a large map by dividing the entries into buckets
MapRecord[] buckets = new MapRecord[BUCKETS_PER_LEVEL];
List<List<MapEntry>> changes = splitToBuckets(entries, level);
for (int i = 0; i < BUCKETS_PER_LEVEL; i++) {
buckets[i] = mapRecordOrNull(writeMapBucket(null, changes.get(i), level + 1));
}
// combine the buckets into one big map
return writeMapBranch(level, entries.size(), buckets);
}
// if the base map is small, update in memory and write as a new map
if (base.isLeaf()) {
Map<String, MapEntry> map = newHashMap();
for (MapEntry entry : base.getEntries()) {
map.put(entry.getName(), entry);
}
for (MapEntry entry : entries) {
if (entry.getValue() != null) {
map.put(entry.getName(), entry);
} else {
map.remove(entry.getName());
}
}
return writeMapBucket(null, map.values(), level);
}
// finally, the if the base map is large, handle updates per bucket
int newSize = 0;
int newCount = 0;
MapRecord[] buckets = base.getBuckets();
List<List<MapEntry>> changes = splitToBuckets(entries, level);
for (int i = 0; i < BUCKETS_PER_LEVEL; i++) {
buckets[i] = mapRecordOrNull(writeMapBucket(buckets[i], changes.get(i), level + 1));
if (buckets[i] != null) {
newSize += buckets[i].size();
newCount++;
}
}
// OAK-654: what if the updated map is smaller?
if (newSize > BUCKETS_PER_LEVEL) {
return writeMapBranch(level, newSize, buckets);
} else if (newCount <= 1) {
// up to one bucket contains entries, so return that as the new map
for (MapRecord bucket : buckets) {
if (bucket != null) {
return bucket.getRecordId();
}
}
// no buckets remaining, return empty map
return writeMapBucket(null, null, level);
} else {
// combine all remaining entries into a leaf record
List<MapEntry> list = newArrayList();
for (MapRecord bucket : buckets) {
if (bucket != null) {
addAll(list, bucket.getEntries());
}
}
return writeMapLeaf(level, list);
}
}
private MapRecord mapRecordOrNull(RecordId id) {
return id == null ? null : new MapRecord(reader, id);
}
/**
* Writes a list record containing the given list of record identifiers.
*
* @param list list of record identifiers
* @return list record identifier
*/
private RecordId writeList(@Nonnull List<RecordId> list) throws IOException {
checkNotNull(list);
checkArgument(!list.isEmpty());
List<RecordId> thisLevel = list;
while (thisLevel.size() > 1) {
List<RecordId> nextLevel = newArrayList();
for (List<RecordId> bucket :
partition(thisLevel, ListRecord.LEVEL_SIZE)) {
if (bucket.size() > 1) {
nextLevel.add(writeListBucket(bucket));
} else {
nextLevel.add(bucket.get(0));
}
}
thisLevel = nextLevel;
}
return thisLevel.iterator().next();
}
private RecordId writeListBucket(List<RecordId> bucket) throws IOException {
checkArgument(bucket.size() > 1);
return RecordWriters.newListBucketWriter(bucket).write(writer);
}
private List<List<MapEntry>> splitToBuckets(Collection<MapEntry> entries, int level) {
int mask = (1 << MapRecord.BITS_PER_LEVEL) - 1;
int shift = 32 - (level + 1) * MapRecord.BITS_PER_LEVEL;
List<List<MapEntry>> buckets =
newArrayList(nCopies(MapRecord.BUCKETS_PER_LEVEL, (List<MapEntry>) null));
for (MapEntry entry : entries) {
int index = (entry.getHash() >> shift) & mask;
List<MapEntry> bucket = buckets.get(index);
if (bucket == null) {
bucket = newArrayList();
buckets.set(index, bucket);
}
bucket.add(entry);
}
return buckets;
}
private RecordId writeValueRecord(long length, RecordId blocks) throws IOException {
long len = (length - Segment.MEDIUM_LIMIT) | (0x3L << 62);
return RecordWriters.newValueWriter(blocks, len).write(writer);
}
private RecordId writeValueRecord(int length, byte... data) throws IOException {
checkArgument(length < Segment.MEDIUM_LIMIT);
return RecordWriters.newValueWriter(length, data).write(writer);
}
/**
* Writes a string value record.
*
* @param string string to be written
* @return value record identifier
*/
private RecordId writeString(@Nonnull String string) throws IOException {
RecordId id = stringCache.get(string);
if (id != null) {
return id; // shortcut if the same string was recently stored
}
byte[] data = string.getBytes(UTF_8);
if (data.length < Segment.MEDIUM_LIMIT) {
// only cache short strings to avoid excessive memory use
id = writeValueRecord(data.length, data);
stringCache.put(string, id);
return id;
}
int pos = 0;
List<RecordId> blockIds = newArrayListWithExpectedSize(
data.length / BLOCK_SIZE + 1);
// write as many full bulk segments as possible
while (pos + Segment.MAX_SEGMENT_SIZE <= data.length) {
SegmentId bulkId = store.newBulkSegmentId();
store.writeSegment(bulkId, data, pos, Segment.MAX_SEGMENT_SIZE);
for (int i = 0; i < Segment.MAX_SEGMENT_SIZE; i += BLOCK_SIZE) {
blockIds.add(new RecordId(bulkId, i));
}
pos += Segment.MAX_SEGMENT_SIZE;
}
// inline the remaining data as block records
while (pos < data.length) {
int len = Math.min(BLOCK_SIZE, data.length - pos);
blockIds.add(writeBlock(data, pos, len));
pos += len;
}
return writeValueRecord(data.length, writeList(blockIds));
}
private boolean sameStore(SegmentId id) {
return id.sameStore(store);
}
/**
* @param blob
* @return {@code true} iff {@code blob} is a {@code SegmentBlob}
* and originates from the same segment store.
*/
private boolean sameStore(Blob blob) {
return (blob instanceof SegmentBlob)
&& sameStore(((Record) blob).getRecordId().getSegmentId());
}
private RecordId writeBlob(@Nonnull Blob blob) throws IOException {
if (sameStore(blob)) {
SegmentBlob segmentBlob = (SegmentBlob) blob;
if (!isOldGeneration(segmentBlob.getRecordId())) {
return segmentBlob.getRecordId();
}
if (segmentBlob.isExternal()) {
return writeBlobId(segmentBlob.getBlobId());
}
}
String reference = blob.getReference();
if (reference != null && blobStore != null) {
String blobId = blobStore.getBlobId(reference);
if (blobId != null) {
return writeBlobId(blobId);
} else {
LOG.debug("No blob found for reference {}, inlining...", reference);
}
}
return writeStream(blob.getNewStream());
}
/**
* Write a reference to an external blob. This method handles blob IDs of
* every length, but behaves differently for small and large blob IDs.
*
* @param blobId Blob ID.
* @return Record ID pointing to the written blob ID.
* @see Segment#BLOB_ID_SMALL_LIMIT
*/
private RecordId writeBlobId(String blobId) throws IOException {
byte[] data = blobId.getBytes(UTF_8);
RecordId recordId;
if (data.length < Segment.BLOB_ID_SMALL_LIMIT) {
recordId = RecordWriters.newBlobIdWriter(data).write(writer);
} else {
recordId = RecordWriters.newBlobIdWriter(writeString(blobId)).write(writer);
}
binaryReferenceConsumer.consume(writer.getGeneration(), recordId.asUUID(), blobId);
return recordId;
}
private RecordId writeBlock(@Nonnull byte[] bytes, int offset, int length)
throws IOException {
checkNotNull(bytes);
checkPositionIndexes(offset, offset + length, bytes.length);
return RecordWriters.newBlockWriter(bytes, offset, length).write(writer);
}
private RecordId writeStream(@Nonnull InputStream stream) throws IOException {
boolean threw = true;
try {
RecordId id = SegmentStream.getRecordIdIfAvailable(stream, store);
if (id == null) {
// This is either not a segment stream or a one from another store:
// fully serialise the stream.
id = internalWriteStream(stream);
} else if (isOldGeneration(id)) {
// This is a segment stream from this store but from an old generation:
// try to link to the blocks if there are any.
SegmentStream segmentStream = (SegmentStream) stream;
List<RecordId> blockIds = segmentStream.getBlockIds();
if (blockIds == null) {
return internalWriteStream(stream);
} else {
return writeValueRecord(segmentStream.getLength(), writeList(blockIds));
}
}
threw = false;
return id;
} finally {
Closeables.close(stream, threw);
}
}
private RecordId internalWriteStream(@Nonnull InputStream stream) throws IOException {
// Special case for short binaries (up to about 16kB):
// store them directly as small- or medium-sized value records
byte[] data = new byte[Segment.MEDIUM_LIMIT];
int n = read(stream, data, 0, data.length);
if (n < Segment.MEDIUM_LIMIT) {
return writeValueRecord(n, data);
}
if (blobStore != null) {
String blobId = blobStore.writeBlob(new SequenceInputStream(
new ByteArrayInputStream(data, 0, n), stream));
return writeBlobId(blobId);
}
data = Arrays.copyOf(data, Segment.MAX_SEGMENT_SIZE);
n += read(stream, data, n, Segment.MAX_SEGMENT_SIZE - n);
long length = n;
List<RecordId> blockIds =
newArrayListWithExpectedSize(2 * n / BLOCK_SIZE);
// Write the data to bulk segments and collect the list of block ids
while (n != 0) {
SegmentId bulkId = store.newBulkSegmentId();
int len = Segment.align(n, 1 << Segment.RECORD_ALIGN_BITS);
LOG.debug("Writing bulk segment {} ({} bytes)", bulkId, n);
store.writeSegment(bulkId, data, 0, len);
for (int i = 0; i < n; i += BLOCK_SIZE) {
blockIds.add(new RecordId(bulkId, data.length - len + i));
}
n = read(stream, data, 0, data.length);
length += n;
}
return writeValueRecord(length, writeList(blockIds));
}
private RecordId writeProperty(@Nonnull PropertyState state) throws IOException {
Map<String, RecordId> previousValues = emptyMap();
return writeProperty(state, previousValues);
}
private RecordId writeProperty(@Nonnull PropertyState state,
@Nonnull Map<String, RecordId> previousValues)
throws IOException {
Type<?> type = state.getType();
int count = state.count();
List<RecordId> valueIds = newArrayList();
for (int i = 0; i < count; i++) {
if (type.tag() == PropertyType.BINARY) {
try {
valueIds.add(writeBlob(state.getValue(BINARY, i)));
} catch (IOException e) {
throw new IllegalStateException("Unexpected IOException", e);
}
} else {
String value = state.getValue(STRING, i);
RecordId valueId = previousValues.get(value);
if (valueId == null) {
valueId = writeString(value);
}
valueIds.add(valueId);
}
}
if (!type.isArray()) {
return valueIds.iterator().next();
} else if (count == 0) {
return RecordWriters.newListWriter().write(writer);
} else {
return RecordWriters.newListWriter(count, writeList(valueIds)).write(writer);
}
}
private RecordId writeTemplate(Template template) throws IOException {
checkNotNull(template);
RecordId id = templateCache.get(template);
if (id != null) {
return id; // shortcut if the same template was recently stored
}
Collection<RecordId> ids = newArrayList();
int head = 0;
RecordId primaryId = null;
PropertyState primaryType = template.getPrimaryType();
if (primaryType != null) {
head |= 1 << 31;
primaryId = writeString(primaryType.getValue(NAME));
ids.add(primaryId);
}
List<RecordId> mixinIds = null;
PropertyState mixinTypes = template.getMixinTypes();
if (mixinTypes != null) {
head |= 1 << 30;
mixinIds = newArrayList();
for (String mixin : mixinTypes.getValue(NAMES)) {
mixinIds.add(writeString(mixin));
}
ids.addAll(mixinIds);
checkState(mixinIds.size() < (1 << 10));
head |= mixinIds.size() << 18;
}
RecordId childNameId = null;
String childName = template.getChildName();
if (childName == Template.ZERO_CHILD_NODES) {
head |= 1 << 29;
} else if (childName == Template.MANY_CHILD_NODES) {
head |= 1 << 28;
} else {
childNameId = writeString(childName);
ids.add(childNameId);
}
PropertyTemplate[] properties = template.getPropertyTemplates();
RecordId[] propertyNames = new RecordId[properties.length];
byte[] propertyTypes = new byte[properties.length];
for (int i = 0; i < properties.length; i++) {
// Note: if the property names are stored in more than 255 separate
// segments, this will not work.
propertyNames[i] = writeString(properties[i].getName());
Type<?> type = properties[i].getType();
if (type.isArray()) {
propertyTypes[i] = (byte) -type.tag();
} else {
propertyTypes[i] = (byte) type.tag();
}
}
RecordId propNamesId = null;
if (propertyNames.length > 0) {
propNamesId = writeList(asList(propertyNames));
ids.add(propNamesId);
}
checkState(propertyNames.length < (1 << 18));
head |= propertyNames.length;
RecordId tid = RecordWriters.newTemplateWriter(ids, propertyNames,
propertyTypes, head, primaryId, mixinIds, childNameId,
propNamesId).write(writer);
templateCache.put(template, tid);
return tid;
}
private RecordId writeNode(@Nonnull NodeState state) throws IOException {
this.nodeWriteStats = new NodeWriteStats();
try {
return writeNode(state, 0);
} finally {
if (nodeWriteStats.isCompactOp) {
nodeCompactTimeStats.addValue(nanoTime() - nodeWriteStats.startTime);
LOG.info(nodeWriteStats.toString());
} else {
nodeWriteTimeStats.addValue(nanoTime() - nodeWriteStats.startTime);
}
}
}
private RecordId writeNode(@Nonnull NodeState state, int depth) throws IOException {
if (cancel.get()) {
// Poor man's Either Monad
throw new CancelledWriteException();
}
checkState(nodeWriteStats != null);
nodeWriteStats.nodeCount++;
RecordId compactedId = deduplicateNode(state, nodeWriteStats);
if (compactedId != null) {
return compactedId;
}
nodeWriteStats.writesOps++;
RecordId recordId = writeNodeUncached(state, depth);
if (state instanceof SegmentNodeState) {
// This node state has been rewritten because it is from an older
// generation (e.g. due to compaction). Put it into the cache for
// deduplication of hard links to it (e.g. checkpoints).
SegmentNodeState sns = (SegmentNodeState) state;
nodeCache.put(sns.getStableId(), recordId, depth);
nodeWriteStats.isCompactOp = true;
}
return recordId;
}
private RecordId writeNodeUncached(@Nonnull NodeState state, int depth) throws IOException {
ModifiedNodeState after = null;
if (state instanceof ModifiedNodeState) {
after = (ModifiedNodeState) state;
}
RecordId beforeId = null;
if (after != null) {
// Pass null to indicate we don't want to update the node write statistics
// when deduplicating the base state
beforeId = deduplicateNode(after.getBaseState(), null);
}
SegmentNodeState before = null;
Template beforeTemplate = null;
if (beforeId != null) {
before = reader.readNode(beforeId);
beforeTemplate = before.getTemplate();
}
List<RecordId> ids = newArrayList();
Template template = new Template(reader, state);
if (template.equals(beforeTemplate)) {
ids.add(before.getTemplateId());
} else {
ids.add(writeTemplate(template));
}
String childName = template.getChildName();
if (childName == Template.MANY_CHILD_NODES) {
MapRecord base;
Map<String, RecordId> childNodes;
if (before != null
&& before.getChildNodeCount(2) > 1
&& after.getChildNodeCount(2) > 1) {
base = before.getChildNodeMap();
childNodes = new ChildNodeCollectorDiff(depth).diff(before, after);
} else {
base = null;
childNodes = newHashMap();
for (ChildNodeEntry entry : state.getChildNodeEntries()) {
childNodes.put(
entry.getName(),
writeNode(entry.getNodeState(), depth + 1));
}
}
ids.add(writeMap(base, childNodes));
} else if (childName != Template.ZERO_CHILD_NODES) {
ids.add(writeNode(state.getChildNode(template.getChildName()), depth + 1));
}
List<RecordId> pIds = newArrayList();
for (PropertyTemplate pt : template.getPropertyTemplates()) {
String name = pt.getName();
PropertyState property = state.getProperty(name);
assert property != null;
if (before != null) {
// If this property is already present in before (the base state)
// and it hasn't been modified use that one. This will result
// in an already compacted property to be reused given before
// has been already compacted.
PropertyState beforeProperty = before.getProperty(name);
if (property.equals(beforeProperty)) {
property = beforeProperty;
}
}
if (sameStore(property)) {
RecordId pid = ((Record) property).getRecordId();
if (isOldGeneration(pid)) {
pIds.add(writeProperty(property));
} else {
pIds.add(pid);
}
} else if (before == null || !sameStore(before)) {
pIds.add(writeProperty(property));
} else {
// reuse previously stored property, if possible
PropertyTemplate bt = beforeTemplate.getPropertyTemplate(name);
if (bt == null) {
pIds.add(writeProperty(property)); // new property
} else {
SegmentPropertyState bp = beforeTemplate.getProperty(before.getRecordId(), bt.getIndex());
if (property.equals(bp)) {
pIds.add(bp.getRecordId()); // no changes
} else if (bp.isArray() && bp.getType() != BINARIES) {
// reuse entries from the previous list
pIds.add(writeProperty(property, bp.getValueRecords()));
} else {
pIds.add(writeProperty(property));
}
}
}
}
if (!pIds.isEmpty()) {
ids.add(writeList(pIds));
}
RecordId stableId = null;
if (state instanceof SegmentNodeState) {
byte[] id = ((SegmentNodeState) state).getStableIdBytes();
stableId = writeBlock(id, 0, id.length);
}
return newNodeStateWriter(stableId, ids).write(writer);
}
/**
* Try to deduplicate the passed {@code node}. This succeeds if
* the passed node state has already been persisted to this store and
* either it has the same generation or it has been already compacted
* and is still in the de-duplication cache for nodes.
*
* @param node The node states to de-duplicate.
* @param nodeWriteStats write statistics to update if not {@code null}.
* @return the id of the de-duplicated node or {@code null} if none.
*/
private RecordId deduplicateNode(
@Nonnull NodeState node,
@CheckForNull NodeWriteStats nodeWriteStats) {
if (!(node instanceof SegmentNodeState)) {
// De-duplication only for persisted node states
return null;
}
SegmentNodeState sns = (SegmentNodeState) node;
if (!sameStore(sns)) {
// De-duplication only within same store
return null;
}
if (!isOldGeneration(sns.getRecordId())) {
// This segment node state is already in this store, no need to
// write it again
if (nodeWriteStats != null) {
nodeWriteStats.deDupNodes++;
}
return sns.getRecordId();
}
// This is a segment node state from an old generation. Check
// whether an equivalent one of the current generation is in the
// cache
RecordId compacted = nodeCache.get(sns.getStableId());
if (nodeWriteStats != null) {
if (compacted == null) {
nodeWriteStats.cacheMiss++;
} else {
nodeWriteStats.cacheHits++;
}
}
return compacted;
}
/**
* @param node
* @return {@code true} iff {@code node} originates from the same segment store.
*/
private boolean sameStore(SegmentNodeState node) {
return sameStore(node.getRecordId().getSegmentId());
}
/**
* @param property
* @return {@code true} iff {@code property} is a {@code SegmentPropertyState}
* and originates from the same segment store.
*/
private boolean sameStore(PropertyState property) {
return (property instanceof SegmentPropertyState)
&& sameStore(((Record) property).getRecordId().getSegmentId());
}
private boolean isOldGeneration(RecordId id) {
try {
int thatGen = id.getSegmentId().getGcGeneration();
int thisGen = writer.getGeneration();
return thatGen < thisGen;
} catch (SegmentNotFoundException snfe) {
// This SNFE means a defer compacted node state is too far
// in the past. It has been gc'ed already and cannot be
// compacted.
// Consider increasing SegmentGCOptions.getRetainedGenerations()
throw new SegmentNotFoundException(
"Cannot copy record from a generation that has been gc'ed already", snfe);
}
}
private class ChildNodeCollectorDiff extends DefaultNodeStateDiff {
private final int depth;
private final Map<String, RecordId> childNodes = newHashMap();
private IOException exception;
private ChildNodeCollectorDiff(int depth) {
this.depth = depth;
}
public Map<String, RecordId> diff(SegmentNodeState before, ModifiedNodeState after) throws IOException {
after.compareAgainstBaseState(before, this);
if (exception != null) {
throw new IOException(exception);
} else {
return childNodes;
}
}
@Override
public boolean childNodeAdded(String name, NodeState after) {
try {
childNodes.put(name, writeNode(after, depth + 1));
} catch (IOException e) {
exception = e;
return false;
}
return true;
}
@Override
public boolean childNodeChanged(
String name, NodeState before, NodeState after) {
try {
childNodes.put(name, writeNode(after, depth + 1));
} catch (IOException e) {
exception = e;
return false;
}
return true;
}
@Override
public boolean childNodeDeleted(String name, NodeState before) {
childNodes.put(name, null);
return true;
}
}
}
}
| oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.segment;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.addAll;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Lists.newArrayListWithExpectedSize;
import static com.google.common.collect.Lists.partition;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.io.ByteStreams.read;
import static java.lang.Integer.getInteger;
import static java.lang.System.nanoTime;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.nCopies;
import static org.apache.jackrabbit.oak.api.Type.BINARIES;
import static org.apache.jackrabbit.oak.api.Type.BINARY;
import static org.apache.jackrabbit.oak.api.Type.NAME;
import static org.apache.jackrabbit.oak.api.Type.NAMES;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.segment.MapRecord.BUCKETS_PER_LEVEL;
import static org.apache.jackrabbit.oak.segment.RecordWriters.newNodeStateWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.PropertyType;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.io.Closeables;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
import org.apache.jackrabbit.oak.api.Blob;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.api.jmx.CacheStatsMBean;
import org.apache.jackrabbit.oak.plugins.memory.ModifiedNodeState;
import org.apache.jackrabbit.oak.segment.WriteOperationHandler.WriteOperation;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.DefaultNodeStateDiff;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@code SegmentWriter} converts nodes, properties, values, etc. to records and
* persists them with the help of a {@link WriteOperationHandler}.
* All public methods of this class are thread safe if and only if the
* {@link WriteOperationHandler} passed to the constructor is thread safe.
*/
public class SegmentWriter {
private static final Logger LOG = LoggerFactory.getLogger(SegmentWriter.class);
/**
* Size of the window for collecting statistics about the time it takes to
* write / compact nodes.
* @see DescriptiveStatistics#setWindowSize(int)
*/
private static final int NODE_WRITER_STATS_WINDOW = getInteger(
"oak.tar.nodeWriterStatsWindow", 10000);
static final int BLOCK_SIZE = 1 << 12; // 4kB
@Nonnull
private final WriterCacheManager cacheManager;
@Nonnull
private final SegmentStore store;
@Nonnull
private final SegmentReader reader;
@CheckForNull
private final BlobStore blobStore;
@Nonnull
private final WriteOperationHandler writeOperationHandler;
@Nonnull
private final BinaryReferenceConsumer binaryReferenceConsumer;
@Nonnull
private final SynchronizedDescriptiveStatistics nodeCompactTimeStats =
new SynchronizedDescriptiveStatistics(NODE_WRITER_STATS_WINDOW);
@Nonnull
private final SynchronizedDescriptiveStatistics nodeWriteTimeStats =
new SynchronizedDescriptiveStatistics(NODE_WRITER_STATS_WINDOW);
/**
* Create a new instance of a {@code SegmentWriter}. Note the thread safety properties
* pointed out in the class comment.
*
* @param store store to write to
* @param reader segment reader for the {@code store}
* @param blobStore the blog store or {@code null} for inlined blobs
* @param cacheManager cache manager instance for the de-duplication caches used by this writer
* @param writeOperationHandler handler for write operations.
*/
public SegmentWriter(@Nonnull SegmentStore store,
@Nonnull SegmentReader reader,
@Nullable BlobStore blobStore,
@Nonnull WriterCacheManager cacheManager,
@Nonnull WriteOperationHandler writeOperationHandler,
@Nonnull BinaryReferenceConsumer binaryReferenceConsumer
) {
this.store = checkNotNull(store);
this.reader = checkNotNull(reader);
this.blobStore = blobStore;
this.cacheManager = checkNotNull(cacheManager);
this.writeOperationHandler = checkNotNull(writeOperationHandler);
this.binaryReferenceConsumer = checkNotNull(binaryReferenceConsumer);
}
/**
* @return Statistics for node compaction times (in ns). These statistics
* include explicit compactions triggered by the file store and implicit
* compactions triggered by references to older generations.
* The statistics are collected with a window size defined by {@link #NODE_WRITER_STATS_WINDOW}
* @see #getNodeWriteTimeStats()
*/
@Nonnull
public DescriptiveStatistics getNodeCompactTimeStats() {
return nodeCompactTimeStats;
}
/**
* @return Statistics for node write times (in ns).
* The statistics are collected with a window size defined by {@link #NODE_WRITER_STATS_WINDOW}
* @see #getNodeCompactTimeStats()
*/
@Nonnull
public DescriptiveStatistics getNodeWriteTimeStats() {
return nodeWriteTimeStats;
}
public void flush() throws IOException {
writeOperationHandler.flush();
}
/**
* @return Statistics for the string deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getStringCacheStats() {
return cacheManager.getStringCacheStats();
}
/**
* @return Statistics for the template deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getTemplateCacheStats() {
return cacheManager.getTemplateCacheStats();
}
/**
* @return Statistics for the node deduplication cache or {@code null} if not available.
*/
@CheckForNull
public CacheStatsMBean getNodeCacheStats() {
return cacheManager.getNodeCacheStats();
}
/**
* Write a map record.
* @param base base map relative to which the {@code changes} are applied ot
* {@code null} for the empty map.
* @param changes the changed mapping to apply to the {@code base} map.
* @return the map record written
* @throws IOException
*/
@Nonnull
public MapRecord writeMap(@Nullable final MapRecord base,
@Nonnull final Map<String, RecordId> changes)
throws IOException {
RecordId mapId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeMap(base, changes);
}
});
return new MapRecord(reader, mapId);
}
/**
* Write a list record.
* @param list the list to write.
* @return the record id of the list written
* @throws IOException
*/
@Nonnull
public RecordId writeList(@Nonnull final List<RecordId> list) throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeList(list);
}
});
}
/**
* Write a string record.
* @param string the string to write.
* @return the record id of the string written.
* @throws IOException
*/
@Nonnull
public RecordId writeString(@Nonnull final String string) throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeString(string);
}
});
}
/**
* Write a blob (as list of block records)
* @param blob blob to write
* @return The segment blob written
* @throws IOException
*/
@Nonnull
public SegmentBlob writeBlob(@Nonnull final Blob blob) throws IOException {
RecordId blobId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeBlob(blob);
}
});
return new SegmentBlob(blobStore, blobId);
}
/**
* Writes a block record containing the given block of bytes.
*
* @param bytes source buffer
* @param offset offset within the source buffer
* @param length number of bytes to write
* @return block record identifier
*/
@Nonnull
public RecordId writeBlock(@Nonnull final byte[] bytes, final int offset, final int length)
throws IOException {
return writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeBlock(bytes, offset, length);
}
});
}
/**
* Writes a stream value record. The given stream is consumed <em>and closed</em> by
* this method.
*
* @param stream stream to be written
* @return blob for the passed {@code stream}
* @throws IOException if the input stream could not be read or the output could not be written
*/
@Nonnull
public SegmentBlob writeStream(@Nonnull final InputStream stream) throws IOException {
RecordId blobId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeStream(stream);
}
});
return new SegmentBlob(blobStore, blobId);
}
/**
* Write a property.
* @param state the property to write
* @return the property state written
* @throws IOException
*/
@Nonnull
public SegmentPropertyState writeProperty(@Nonnull final PropertyState state)
throws IOException {
RecordId id = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeProperty(state);
}
});
return new SegmentPropertyState(reader, id, state.getName(), state.getType());
}
/**
* Write a node state
* @param state node state to write
* @return segment node state equal to {@code state}
* @throws IOException
*/
@Nonnull
public SegmentNodeState writeNode(@Nonnull final NodeState state) throws IOException {
RecordId nodeId = writeOperationHandler.execute(new SegmentWriteOperation() {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeNode(state);
}
});
return new SegmentNodeState(reader, this, nodeId);
}
/**
* Write a node state, unless cancelled using a dedicated write operation handler.
* The write operation handler is automatically {@link WriteOperationHandler#flush() flushed}
* once the node has been written successfully.
* @param state node state to write
* @param writeOperationHandler the write operation handler through which all write calls
* induced by by this call are routed.
* @param cancel supplier to signal cancellation of this write operation
* @return segment node state equal to {@code state} or {@code null} if cancelled.
* @throws IOException
*/
@CheckForNull
public SegmentNodeState writeNode(@Nonnull final NodeState state,
@Nonnull WriteOperationHandler writeOperationHandler,
@Nonnull Supplier<Boolean> cancel)
throws IOException {
try {
RecordId nodeId = writeOperationHandler.execute(new SegmentWriteOperation(cancel) {
@Override
public RecordId execute(SegmentBufferWriter writer) throws IOException {
return with(writer).writeNode(state);
}
});
writeOperationHandler.flush();
return new SegmentNodeState(reader, this, nodeId);
} catch (SegmentWriteOperation.CancelledWriteException ignore) {
return null;
}
}
/**
* This {@code WriteOperation} implementation is used internally to provide
* context to a recursive chain of calls without having pass the context
* as a separate argument (a poor mans monad). As such it is entirely
* <em>not thread safe</em>.
*/
private abstract class SegmentWriteOperation implements WriteOperation {
private class NodeWriteStats {
private final long startTime = nanoTime();
/*
* Total number of nodes in the subtree rooted at the node passed
* to {@link #writeNode(SegmentWriteOperation, SegmentBufferWriter, NodeState)}
*/
public int nodeCount;
/*
* Number of cache hits for a deferred compacted node
*/
public int cacheHits;
/*
* Number of cache misses for a deferred compacted node
*/
public int cacheMiss;
/*
* Number of nodes that where de-duplicated as the store already contained
* them.
*/
public int deDupNodes;
/*
* Number of nodes that actually had to be written as there was no de-duplication
* and a cache miss (in case of a deferred compaction).
*/
public int writesOps;
/*
* {@code true} for if the node written was a compaction operation, false otherwise
*/
boolean isCompactOp;
@Override
public String toString() {
return "NodeStats{" +
"op=" + (isCompactOp ? "compact" : "write") +
", nodeCount=" + nodeCount +
", writeOps=" + writesOps +
", deDupNodes=" + deDupNodes +
", cacheHits=" + cacheHits +
", cacheMiss=" + cacheMiss +
", hitRate=" + (100*(double) cacheHits / ((double) cacheHits + (double) cacheMiss)) +
'}';
}
}
/**
* This exception is used internally to signal cancellation of a (recursive)
* write node operation.
*/
private class CancelledWriteException extends IOException {
public CancelledWriteException() {
super("Cancelled write operation");
}
}
@Nonnull
private final Supplier<Boolean> cancel;
@CheckForNull
private NodeWriteStats nodeWriteStats;
private SegmentBufferWriter writer;
private RecordCache<String> stringCache;
private RecordCache<Template> templateCache;
private NodeCache nodeCache;
protected SegmentWriteOperation(@Nonnull Supplier<Boolean> cancel) {
this.cancel = cancel;
}
protected SegmentWriteOperation() {
this(Suppliers.ofInstance(false));
}
@Override
public abstract RecordId execute(SegmentBufferWriter writer) throws IOException;
@Nonnull
SegmentWriteOperation with(@Nonnull SegmentBufferWriter writer) {
checkState(this.writer == null);
this.writer = writer;
int generation = writer.getGeneration();
this.stringCache = cacheManager.getStringCache(generation);
this.templateCache = cacheManager.getTemplateCache(generation);
this.nodeCache = cacheManager.getNodeCache(generation);
return this;
}
private RecordId writeMap(@Nullable MapRecord base,
@Nonnull Map<String, RecordId> changes)
throws IOException {
if (base != null && base.isDiff()) {
Segment segment = base.getSegment();
RecordId key = segment.readRecordId(base.getOffset(8));
String name = reader.readString(key);
if (!changes.containsKey(name)) {
changes.put(name, segment.readRecordId(base.getOffset(8, 1)));
}
base = new MapRecord(reader, segment.readRecordId(base.getOffset(8, 2)));
}
if (base != null && changes.size() == 1) {
Map.Entry<String, RecordId> change =
changes.entrySet().iterator().next();
RecordId value = change.getValue();
if (value != null) {
MapEntry entry = base.getEntry(change.getKey());
if (entry != null) {
if (value.equals(entry.getValue())) {
return base.getRecordId();
} else {
return RecordWriters.newMapBranchWriter(entry.getHash(), asList(entry.getKey(),
value, base.getRecordId())).write(writer);
}
}
}
}
List<MapEntry> entries = newArrayList();
for (Map.Entry<String, RecordId> entry : changes.entrySet()) {
String key = entry.getKey();
RecordId keyId = null;
if (base != null) {
MapEntry e = base.getEntry(key);
if (e != null) {
keyId = e.getKey();
}
}
if (keyId == null && entry.getValue() != null) {
keyId = writeString(key);
}
if (keyId != null) {
entries.add(new MapEntry(reader, key, keyId, entry.getValue()));
}
}
return writeMapBucket(base, entries, 0);
}
private RecordId writeMapLeaf(int level, Collection<MapEntry> entries) throws IOException {
checkNotNull(entries);
int size = entries.size();
checkElementIndex(size, MapRecord.MAX_SIZE);
checkPositionIndex(level, MapRecord.MAX_NUMBER_OF_LEVELS);
checkArgument(size != 0 || level == MapRecord.MAX_NUMBER_OF_LEVELS);
return RecordWriters.newMapLeafWriter(level, entries).write(writer);
}
private RecordId writeMapBranch(int level, int size, MapRecord... buckets) throws IOException {
int bitmap = 0;
List<RecordId> bucketIds = newArrayListWithCapacity(buckets.length);
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] != null) {
bitmap |= 1L << i;
bucketIds.add(buckets[i].getRecordId());
}
}
return RecordWriters.newMapBranchWriter(level, size, bitmap, bucketIds).write(writer);
}
private RecordId writeMapBucket(MapRecord base, Collection<MapEntry> entries, int level)
throws IOException {
// when no changed entries, return the base map (if any) as-is
if (entries == null || entries.isEmpty()) {
if (base != null) {
return base.getRecordId();
} else if (level == 0) {
return RecordWriters.newMapLeafWriter().write(writer);
} else {
return null;
}
}
// when no base map was given, write a fresh new map
if (base == null) {
// use leaf records for small maps or the last map level
if (entries.size() <= BUCKETS_PER_LEVEL
|| level == MapRecord.MAX_NUMBER_OF_LEVELS) {
return writeMapLeaf(level, entries);
}
// write a large map by dividing the entries into buckets
MapRecord[] buckets = new MapRecord[BUCKETS_PER_LEVEL];
List<List<MapEntry>> changes = splitToBuckets(entries, level);
for (int i = 0; i < BUCKETS_PER_LEVEL; i++) {
buckets[i] = mapRecordOrNull(writeMapBucket(null, changes.get(i), level + 1));
}
// combine the buckets into one big map
return writeMapBranch(level, entries.size(), buckets);
}
// if the base map is small, update in memory and write as a new map
if (base.isLeaf()) {
Map<String, MapEntry> map = newHashMap();
for (MapEntry entry : base.getEntries()) {
map.put(entry.getName(), entry);
}
for (MapEntry entry : entries) {
if (entry.getValue() != null) {
map.put(entry.getName(), entry);
} else {
map.remove(entry.getName());
}
}
return writeMapBucket(null, map.values(), level);
}
// finally, the if the base map is large, handle updates per bucket
int newSize = 0;
int newCount = 0;
MapRecord[] buckets = base.getBuckets();
List<List<MapEntry>> changes = splitToBuckets(entries, level);
for (int i = 0; i < BUCKETS_PER_LEVEL; i++) {
buckets[i] = mapRecordOrNull(writeMapBucket(buckets[i], changes.get(i), level + 1));
if (buckets[i] != null) {
newSize += buckets[i].size();
newCount++;
}
}
// OAK-654: what if the updated map is smaller?
if (newSize > BUCKETS_PER_LEVEL) {
return writeMapBranch(level, newSize, buckets);
} else if (newCount <= 1) {
// up to one bucket contains entries, so return that as the new map
for (MapRecord bucket : buckets) {
if (bucket != null) {
return bucket.getRecordId();
}
}
// no buckets remaining, return empty map
return writeMapBucket(null, null, level);
} else {
// combine all remaining entries into a leaf record
List<MapEntry> list = newArrayList();
for (MapRecord bucket : buckets) {
if (bucket != null) {
addAll(list, bucket.getEntries());
}
}
return writeMapLeaf(level, list);
}
}
private MapRecord mapRecordOrNull(RecordId id) {
return id == null ? null : new MapRecord(reader, id);
}
/**
* Writes a list record containing the given list of record identifiers.
*
* @param list list of record identifiers
* @return list record identifier
*/
private RecordId writeList(@Nonnull List<RecordId> list) throws IOException {
checkNotNull(list);
checkArgument(!list.isEmpty());
List<RecordId> thisLevel = list;
while (thisLevel.size() > 1) {
List<RecordId> nextLevel = newArrayList();
for (List<RecordId> bucket :
partition(thisLevel, ListRecord.LEVEL_SIZE)) {
if (bucket.size() > 1) {
nextLevel.add(writeListBucket(bucket));
} else {
nextLevel.add(bucket.get(0));
}
}
thisLevel = nextLevel;
}
return thisLevel.iterator().next();
}
private RecordId writeListBucket(List<RecordId> bucket) throws IOException {
checkArgument(bucket.size() > 1);
return RecordWriters.newListBucketWriter(bucket).write(writer);
}
private List<List<MapEntry>> splitToBuckets(Collection<MapEntry> entries, int level) {
int mask = (1 << MapRecord.BITS_PER_LEVEL) - 1;
int shift = 32 - (level + 1) * MapRecord.BITS_PER_LEVEL;
List<List<MapEntry>> buckets =
newArrayList(nCopies(MapRecord.BUCKETS_PER_LEVEL, (List<MapEntry>) null));
for (MapEntry entry : entries) {
int index = (entry.getHash() >> shift) & mask;
List<MapEntry> bucket = buckets.get(index);
if (bucket == null) {
bucket = newArrayList();
buckets.set(index, bucket);
}
bucket.add(entry);
}
return buckets;
}
private RecordId writeValueRecord(long length, RecordId blocks) throws IOException {
long len = (length - Segment.MEDIUM_LIMIT) | (0x3L << 62);
return RecordWriters.newValueWriter(blocks, len).write(writer);
}
private RecordId writeValueRecord(int length, byte... data) throws IOException {
checkArgument(length < Segment.MEDIUM_LIMIT);
return RecordWriters.newValueWriter(length, data).write(writer);
}
/**
* Writes a string value record.
*
* @param string string to be written
* @return value record identifier
*/
private RecordId writeString(@Nonnull String string) throws IOException {
RecordId id = stringCache.get(string);
if (id != null) {
return id; // shortcut if the same string was recently stored
}
byte[] data = string.getBytes(UTF_8);
if (data.length < Segment.MEDIUM_LIMIT) {
// only cache short strings to avoid excessive memory use
id = writeValueRecord(data.length, data);
stringCache.put(string, id);
return id;
}
int pos = 0;
List<RecordId> blockIds = newArrayListWithExpectedSize(
data.length / BLOCK_SIZE + 1);
// write as many full bulk segments as possible
while (pos + Segment.MAX_SEGMENT_SIZE <= data.length) {
SegmentId bulkId = store.newBulkSegmentId();
store.writeSegment(bulkId, data, pos, Segment.MAX_SEGMENT_SIZE);
for (int i = 0; i < Segment.MAX_SEGMENT_SIZE; i += BLOCK_SIZE) {
blockIds.add(new RecordId(bulkId, i));
}
pos += Segment.MAX_SEGMENT_SIZE;
}
// inline the remaining data as block records
while (pos < data.length) {
int len = Math.min(BLOCK_SIZE, data.length - pos);
blockIds.add(writeBlock(data, pos, len));
pos += len;
}
return writeValueRecord(data.length, writeList(blockIds));
}
private boolean sameStore(SegmentId id) {
return id.sameStore(store);
}
/**
* @param blob
* @return {@code true} iff {@code blob} is a {@code SegmentBlob}
* and originates from the same segment store.
*/
private boolean sameStore(Blob blob) {
return (blob instanceof SegmentBlob)
&& sameStore(((Record) blob).getRecordId().getSegmentId());
}
private RecordId writeBlob(@Nonnull Blob blob) throws IOException {
if (sameStore(blob)) {
SegmentBlob segmentBlob = (SegmentBlob) blob;
if (!isOldGeneration(segmentBlob.getRecordId())) {
return segmentBlob.getRecordId();
}
if (segmentBlob.isExternal()) {
return writeBlobId(segmentBlob.getBlobId());
}
}
String reference = blob.getReference();
if (reference != null && blobStore != null) {
String blobId = blobStore.getBlobId(reference);
if (blobId != null) {
return writeBlobId(blobId);
} else {
LOG.debug("No blob found for reference {}, inlining...", reference);
}
}
return writeStream(blob.getNewStream());
}
/**
* Write a reference to an external blob. This method handles blob IDs of
* every length, but behaves differently for small and large blob IDs.
*
* @param blobId Blob ID.
* @return Record ID pointing to the written blob ID.
* @see Segment#BLOB_ID_SMALL_LIMIT
*/
private RecordId writeBlobId(String blobId) throws IOException {
byte[] data = blobId.getBytes(UTF_8);
RecordId recordId;
if (data.length < Segment.BLOB_ID_SMALL_LIMIT) {
recordId = RecordWriters.newBlobIdWriter(data).write(writer);
} else {
recordId = RecordWriters.newBlobIdWriter(writeString(blobId)).write(writer);
}
binaryReferenceConsumer.consume(writer.getGeneration(), recordId.asUUID(), blobId);
return recordId;
}
private RecordId writeBlock(@Nonnull byte[] bytes, int offset, int length)
throws IOException {
checkNotNull(bytes);
checkPositionIndexes(offset, offset + length, bytes.length);
return RecordWriters.newBlockWriter(bytes, offset, length).write(writer);
}
private RecordId writeStream(@Nonnull InputStream stream) throws IOException {
boolean threw = true;
try {
RecordId id = SegmentStream.getRecordIdIfAvailable(stream, store);
if (id == null) {
// This is either not a segment stream or a one from another store:
// fully serialise the stream.
id = internalWriteStream(stream);
} else if (isOldGeneration(id)) {
// This is a segment stream from this store but from an old generation:
// try to link to the blocks if there are any.
SegmentStream segmentStream = (SegmentStream) stream;
List<RecordId> blockIds = segmentStream.getBlockIds();
if (blockIds == null) {
return internalWriteStream(stream);
} else {
return writeValueRecord(segmentStream.getLength(), writeList(blockIds));
}
}
threw = false;
return id;
} finally {
Closeables.close(stream, threw);
}
}
private RecordId internalWriteStream(@Nonnull InputStream stream) throws IOException {
// Special case for short binaries (up to about 16kB):
// store them directly as small- or medium-sized value records
byte[] data = new byte[Segment.MEDIUM_LIMIT];
int n = read(stream, data, 0, data.length);
if (n < Segment.MEDIUM_LIMIT) {
return writeValueRecord(n, data);
}
if (blobStore != null) {
String blobId = blobStore.writeBlob(new SequenceInputStream(
new ByteArrayInputStream(data, 0, n), stream));
return writeBlobId(blobId);
}
data = Arrays.copyOf(data, Segment.MAX_SEGMENT_SIZE);
n += read(stream, data, n, Segment.MAX_SEGMENT_SIZE - n);
long length = n;
List<RecordId> blockIds =
newArrayListWithExpectedSize(2 * n / BLOCK_SIZE);
// Write the data to bulk segments and collect the list of block ids
while (n != 0) {
SegmentId bulkId = store.newBulkSegmentId();
int len = Segment.align(n, 1 << Segment.RECORD_ALIGN_BITS);
LOG.debug("Writing bulk segment {} ({} bytes)", bulkId, n);
store.writeSegment(bulkId, data, 0, len);
for (int i = 0; i < n; i += BLOCK_SIZE) {
blockIds.add(new RecordId(bulkId, data.length - len + i));
}
n = read(stream, data, 0, data.length);
length += n;
}
return writeValueRecord(length, writeList(blockIds));
}
private RecordId writeProperty(@Nonnull PropertyState state) throws IOException {
Map<String, RecordId> previousValues = emptyMap();
return writeProperty(state, previousValues);
}
private RecordId writeProperty(@Nonnull PropertyState state,
@Nonnull Map<String, RecordId> previousValues)
throws IOException {
Type<?> type = state.getType();
int count = state.count();
List<RecordId> valueIds = newArrayList();
for (int i = 0; i < count; i++) {
if (type.tag() == PropertyType.BINARY) {
try {
valueIds.add(writeBlob(state.getValue(BINARY, i)));
} catch (IOException e) {
throw new IllegalStateException("Unexpected IOException", e);
}
} else {
String value = state.getValue(STRING, i);
RecordId valueId = previousValues.get(value);
if (valueId == null) {
valueId = writeString(value);
}
valueIds.add(valueId);
}
}
if (!type.isArray()) {
return valueIds.iterator().next();
} else if (count == 0) {
return RecordWriters.newListWriter().write(writer);
} else {
return RecordWriters.newListWriter(count, writeList(valueIds)).write(writer);
}
}
private RecordId writeTemplate(Template template) throws IOException {
checkNotNull(template);
RecordId id = templateCache.get(template);
if (id != null) {
return id; // shortcut if the same template was recently stored
}
Collection<RecordId> ids = newArrayList();
int head = 0;
RecordId primaryId = null;
PropertyState primaryType = template.getPrimaryType();
if (primaryType != null) {
head |= 1 << 31;
primaryId = writeString(primaryType.getValue(NAME));
ids.add(primaryId);
}
List<RecordId> mixinIds = null;
PropertyState mixinTypes = template.getMixinTypes();
if (mixinTypes != null) {
head |= 1 << 30;
mixinIds = newArrayList();
for (String mixin : mixinTypes.getValue(NAMES)) {
mixinIds.add(writeString(mixin));
}
ids.addAll(mixinIds);
checkState(mixinIds.size() < (1 << 10));
head |= mixinIds.size() << 18;
}
RecordId childNameId = null;
String childName = template.getChildName();
if (childName == Template.ZERO_CHILD_NODES) {
head |= 1 << 29;
} else if (childName == Template.MANY_CHILD_NODES) {
head |= 1 << 28;
} else {
childNameId = writeString(childName);
ids.add(childNameId);
}
PropertyTemplate[] properties = template.getPropertyTemplates();
RecordId[] propertyNames = new RecordId[properties.length];
byte[] propertyTypes = new byte[properties.length];
for (int i = 0; i < properties.length; i++) {
// Note: if the property names are stored in more than 255 separate
// segments, this will not work.
propertyNames[i] = writeString(properties[i].getName());
Type<?> type = properties[i].getType();
if (type.isArray()) {
propertyTypes[i] = (byte) -type.tag();
} else {
propertyTypes[i] = (byte) type.tag();
}
}
RecordId propNamesId = null;
if (propertyNames.length > 0) {
propNamesId = writeList(asList(propertyNames));
ids.add(propNamesId);
}
checkState(propertyNames.length < (1 << 18));
head |= propertyNames.length;
RecordId tid = RecordWriters.newTemplateWriter(ids, propertyNames,
propertyTypes, head, primaryId, mixinIds, childNameId,
propNamesId).write(writer);
templateCache.put(template, tid);
return tid;
}
private RecordId writeNode(@Nonnull NodeState state) throws IOException {
this.nodeWriteStats = new NodeWriteStats();
try {
return writeNode(state, 0);
} finally {
if (nodeWriteStats.isCompactOp) {
nodeCompactTimeStats.addValue(nanoTime() - nodeWriteStats.startTime);
LOG.info(nodeWriteStats.toString());
} else {
nodeWriteTimeStats.addValue(nanoTime() - nodeWriteStats.startTime);
}
}
}
private RecordId writeNode(@Nonnull NodeState state, int depth) throws IOException {
if (cancel.get()) {
// Poor man's Either Monad
throw new CancelledWriteException();
}
checkState(nodeWriteStats != null);
nodeWriteStats.nodeCount++;
RecordId compactedId = deduplicateNode(state);
if (compactedId != null) {
return compactedId;
}
nodeWriteStats.writesOps++;
RecordId recordId = writeNodeUncached(state, depth);
if (state instanceof SegmentNodeState) {
// This node state has been rewritten because it is from an older
// generation (e.g. due to compaction). Put it into the cache for
// deduplication of hard links to it (e.g. checkpoints).
SegmentNodeState sns = (SegmentNodeState) state;
nodeCache.put(sns.getStableId(), recordId, depth);
nodeWriteStats.isCompactOp = true;
}
return recordId;
}
private RecordId writeNodeUncached(@Nonnull NodeState state, int depth) throws IOException {
ModifiedNodeState after = null;
if (state instanceof ModifiedNodeState) {
after = (ModifiedNodeState) state;
}
RecordId beforeId = null;
if (after != null) {
beforeId = deduplicateNode(after.getBaseState());
}
SegmentNodeState before = null;
Template beforeTemplate = null;
if (beforeId != null) {
before = reader.readNode(beforeId);
beforeTemplate = before.getTemplate();
}
List<RecordId> ids = newArrayList();
Template template = new Template(reader, state);
if (template.equals(beforeTemplate)) {
ids.add(before.getTemplateId());
} else {
ids.add(writeTemplate(template));
}
String childName = template.getChildName();
if (childName == Template.MANY_CHILD_NODES) {
MapRecord base;
Map<String, RecordId> childNodes;
if (before != null
&& before.getChildNodeCount(2) > 1
&& after.getChildNodeCount(2) > 1) {
base = before.getChildNodeMap();
childNodes = new ChildNodeCollectorDiff(depth).diff(before, after);
} else {
base = null;
childNodes = newHashMap();
for (ChildNodeEntry entry : state.getChildNodeEntries()) {
childNodes.put(
entry.getName(),
writeNode(entry.getNodeState(), depth + 1));
}
}
ids.add(writeMap(base, childNodes));
} else if (childName != Template.ZERO_CHILD_NODES) {
ids.add(writeNode(state.getChildNode(template.getChildName()), depth + 1));
}
List<RecordId> pIds = newArrayList();
for (PropertyTemplate pt : template.getPropertyTemplates()) {
String name = pt.getName();
PropertyState property = state.getProperty(name);
assert property != null;
if (before != null) {
// If this property is already present in before (the base state)
// and it hasn't been modified use that one. This will result
// in an already compacted property to be reused given before
// has been already compacted.
PropertyState beforeProperty = before.getProperty(name);
if (property.equals(beforeProperty)) {
property = beforeProperty;
}
}
if (sameStore(property)) {
RecordId pid = ((Record) property).getRecordId();
if (isOldGeneration(pid)) {
pIds.add(writeProperty(property));
} else {
pIds.add(pid);
}
} else if (before == null || !sameStore(before)) {
pIds.add(writeProperty(property));
} else {
// reuse previously stored property, if possible
PropertyTemplate bt = beforeTemplate.getPropertyTemplate(name);
if (bt == null) {
pIds.add(writeProperty(property)); // new property
} else {
SegmentPropertyState bp = beforeTemplate.getProperty(before.getRecordId(), bt.getIndex());
if (property.equals(bp)) {
pIds.add(bp.getRecordId()); // no changes
} else if (bp.isArray() && bp.getType() != BINARIES) {
// reuse entries from the previous list
pIds.add(writeProperty(property, bp.getValueRecords()));
} else {
pIds.add(writeProperty(property));
}
}
}
}
if (!pIds.isEmpty()) {
ids.add(writeList(pIds));
}
RecordId stableId = null;
if (state instanceof SegmentNodeState) {
byte[] id = ((SegmentNodeState) state).getStableIdBytes();
stableId = writeBlock(id, 0, id.length);
}
return newNodeStateWriter(stableId, ids).write(writer);
}
/**
* Try to deduplicate the passed {@code node}. This succeeds if
* the passed node state has already been persisted to this store and
* either it has the same generation or it has been already compacted
* and is still in the de-duplication cache for nodes.
*
* @param node The node states to de-duplicate.
* @return the id of the de-duplicated node or {@code null} if none.
*/
private RecordId deduplicateNode(NodeState node) {
checkState(nodeWriteStats != null);
if (!(node instanceof SegmentNodeState)) {
// De-duplication only for persisted node states
return null;
}
SegmentNodeState sns = (SegmentNodeState) node;
if (!sameStore(sns)) {
// De-duplication only within same store
return null;
}
if (!isOldGeneration(sns.getRecordId())) {
// This segment node state is already in this store, no need to
// write it again
nodeWriteStats.deDupNodes++;
return sns.getRecordId();
}
// This is a segment node state from an old generation. Check
// whether an equivalent one of the current generation is in the
// cache
RecordId compacted = nodeCache.get(sns.getStableId());
if (compacted == null) {
nodeWriteStats.cacheMiss++;
return null;
}
nodeWriteStats.cacheHits++;
return compacted;
}
/**
* @param node
* @return {@code true} iff {@code node} originates from the same segment store.
*/
private boolean sameStore(SegmentNodeState node) {
return sameStore(node.getRecordId().getSegmentId());
}
/**
* @param property
* @return {@code true} iff {@code property} is a {@code SegmentPropertyState}
* and originates from the same segment store.
*/
private boolean sameStore(PropertyState property) {
return (property instanceof SegmentPropertyState)
&& sameStore(((Record) property).getRecordId().getSegmentId());
}
private boolean isOldGeneration(RecordId id) {
try {
int thatGen = id.getSegmentId().getGcGeneration();
int thisGen = writer.getGeneration();
return thatGen < thisGen;
} catch (SegmentNotFoundException snfe) {
// This SNFE means a defer compacted node state is too far
// in the past. It has been gc'ed already and cannot be
// compacted.
// Consider increasing SegmentGCOptions.getRetainedGenerations()
throw new SegmentNotFoundException(
"Cannot copy record from a generation that has been gc'ed already", snfe);
}
}
private class ChildNodeCollectorDiff extends DefaultNodeStateDiff {
private final int depth;
private final Map<String, RecordId> childNodes = newHashMap();
private IOException exception;
private ChildNodeCollectorDiff(int depth) {
this.depth = depth;
}
public Map<String, RecordId> diff(SegmentNodeState before, ModifiedNodeState after) throws IOException {
after.compareAgainstBaseState(before, this);
if (exception != null) {
throw new IOException(exception);
} else {
return childNodes;
}
}
@Override
public boolean childNodeAdded(String name, NodeState after) {
try {
childNodes.put(name, writeNode(after, depth + 1));
} catch (IOException e) {
exception = e;
return false;
}
return true;
}
@Override
public boolean childNodeChanged(
String name, NodeState before, NodeState after) {
try {
childNodes.put(name, writeNode(after, depth + 1));
} catch (IOException e) {
exception = e;
return false;
}
return true;
}
@Override
public boolean childNodeDeleted(String name, NodeState before) {
childNodes.put(name, null);
return true;
}
}
}
}
| OAK-4795: Node writer statistics is skewed
Only collect statistics for the node actually being written (and not for its base)
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1760371 13f79535-47bb-0310-9956-ffa450edef68
| oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java | OAK-4795: Node writer statistics is skewed Only collect statistics for the node actually being written (and not for its base) | <ide><path>ak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java
<ide> checkState(nodeWriteStats != null);
<ide> nodeWriteStats.nodeCount++;
<ide>
<del> RecordId compactedId = deduplicateNode(state);
<add> RecordId compactedId = deduplicateNode(state, nodeWriteStats);
<ide>
<ide> if (compactedId != null) {
<ide> return compactedId;
<ide> RecordId beforeId = null;
<ide>
<ide> if (after != null) {
<del> beforeId = deduplicateNode(after.getBaseState());
<add> // Pass null to indicate we don't want to update the node write statistics
<add> // when deduplicating the base state
<add> beforeId = deduplicateNode(after.getBaseState(), null);
<ide> }
<ide>
<ide> SegmentNodeState before = null;
<ide> * and is still in the de-duplication cache for nodes.
<ide> *
<ide> * @param node The node states to de-duplicate.
<add> * @param nodeWriteStats write statistics to update if not {@code null}.
<ide> * @return the id of the de-duplicated node or {@code null} if none.
<ide> */
<del> private RecordId deduplicateNode(NodeState node) {
<del> checkState(nodeWriteStats != null);
<del>
<add> private RecordId deduplicateNode(
<add> @Nonnull NodeState node,
<add> @CheckForNull NodeWriteStats nodeWriteStats) {
<ide> if (!(node instanceof SegmentNodeState)) {
<ide> // De-duplication only for persisted node states
<ide> return null;
<ide> if (!isOldGeneration(sns.getRecordId())) {
<ide> // This segment node state is already in this store, no need to
<ide> // write it again
<del> nodeWriteStats.deDupNodes++;
<add> if (nodeWriteStats != null) {
<add> nodeWriteStats.deDupNodes++;
<add> }
<ide> return sns.getRecordId();
<ide> }
<ide>
<ide> // cache
<ide> RecordId compacted = nodeCache.get(sns.getStableId());
<ide>
<del> if (compacted == null) {
<del> nodeWriteStats.cacheMiss++;
<del> return null;
<del> }
<del>
<del> nodeWriteStats.cacheHits++;
<add> if (nodeWriteStats != null) {
<add> if (compacted == null) {
<add> nodeWriteStats.cacheMiss++;
<add> } else {
<add> nodeWriteStats.cacheHits++;
<add> }
<add> }
<add>
<ide> return compacted;
<ide> }
<ide> |
|
Java | apache-2.0 | 612b316882ee680404dbf8e28cd53a0dd5713593 | 0 | saasquatch/json-schema-inferrer | package com.saasquatch.json_schema_inferrer;
import static com.saasquatch.json_schema_inferrer.JunkDrawer.format;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
public class JsonSchemaInferrerExamplesTest {
private static final String QUICKTYPE_REPO_BASE_URL =
"https://cdn.jsdelivr.net/gh/quicktype/quicktype@f75f66bff3d1f812b61c481637c12173778a29b8";
private static CloseableHttpClient httpClient;
private static final ObjectMapper mapper = new ObjectMapper();
private static Collection<JsonSchemaInferrer> testInferrers = getTestInferrers();
private static LoadingCache<String, JsonNode> testJsonCache =
CacheBuilder.newBuilder().softValues().build(new CacheLoader<String, JsonNode>() {
@Override
public JsonNode load(String url) throws Exception {
return loadJsonFromUrl(url);
}
});
@BeforeAll
public static void beforeAll() {
httpClient = HttpClients.custom().disableCookieManagement().build();
}
@AfterAll
public static void afterAll() throws Exception {
httpClient.close();
}
@Test
public void test() {
for (String jsonUrl : getSampleJsonUrls()) {
doTestForJsonUrl(jsonUrl);
}
}
@Test
public void testMulti() {
for (List<String> jsonUrls : Iterables.partition(getSampleJsonUrls(), 4)) {
doTestForJsonUrls(jsonUrls);
}
}
private static void doTestForJsonUrl(String jsonUrl) {
final JsonNode sampleJson;
// Not being able to load the sample JSON should not be considered a failure
try {
sampleJson = testJsonCache.get(jsonUrl);
if (sampleJson == null) {
return;
}
} catch (Exception e) {
System.out.printf(Locale.ROOT, "Exception encountered loading JSON from url[%s]. "
+ "Error message: [%s]. Skipping tests.\n", jsonUrl, e.getMessage());
return;
}
System.out.printf(Locale.ROOT, "Got valid JSON from url[%s]\n", jsonUrl);
for (JsonSchemaInferrer inferrer : testInferrers) {
final ObjectNode schemaJson = inferrer.inferForSample(sampleJson);
assertNotNull(schemaJson, format("Inferred schema for url[%s] is null", jsonUrl));
final Schema schema;
try {
schema = SchemaLoader.load(new JSONObject(schemaJson.toString()));
} catch (RuntimeException e) {
fail(format("Unable to parse the inferred schema for url[%s]", jsonUrl), e);
throw e;
}
try {
if (sampleJson.isObject()) {
schema.validate(new JSONObject(sampleJson.toString()));
} else if (sampleJson.isArray()) {
schema.validate(new JSONArray(sampleJson.toString()));
} else {
schema.validate(mapper.convertValue(sampleJson, Object.class));
}
} catch (ValidationException e) {
System.out.println(e.getClass().getSimpleName() + " encountered");
System.out.println(schemaJson.toPrettyString());
System.out.println("Error messages:");
e.getAllMessages().forEach(System.out::println);
fail(format("Inferred schema for url[%s] failed to validate", jsonUrl), e);
}
}
}
private static void doTestForJsonUrls(Collection<String> jsonUrls) {
final List<JsonNode> sampleJsons = jsonUrls.stream()
.map(jsonUrl -> {
try {
return testJsonCache.get(jsonUrl);
} catch (Exception e) {
System.out.printf(Locale.ROOT, "Exception encountered loading JSON from url[%s]. "
+ "Error message: [%s]. Skipping tests.\n", jsonUrl, e.getMessage());
return null;
}
})
.collect(Collectors.toList());
System.out.printf(Locale.ROOT, "Got valid JSONs from urls%s\n", jsonUrls);
for (JsonSchemaInferrer inferrer : testInferrers) {
final ObjectNode schemaJson = inferrer.inferForSamples(sampleJsons);
assertNotNull(schemaJson, format("Inferred schema for urls%s is null", jsonUrls));
final Schema schema;
try {
schema = SchemaLoader.load(new JSONObject(schemaJson.toString()));
} catch (RuntimeException e) {
fail(format("Unable to parse the inferred schema for urls%s", jsonUrls), e);
throw e;
}
for (JsonNode sampleJson : sampleJsons) {
try {
if (sampleJson.isObject()) {
schema.validate(new JSONObject(sampleJson.toString()));
} else if (sampleJson.isArray()) {
schema.validate(new JSONArray(sampleJson.toString()));
} else {
schema.validate(mapper.convertValue(sampleJson, Object.class));
}
} catch (ValidationException e) {
System.out.println(e.getClass().getSimpleName() + " encountered");
System.out.println(schemaJson.toPrettyString());
System.out.println("Error messages:");
e.getAllMessages().forEach(System.out::println);
fail(format("Inferred schema for urls%s failed to validate", jsonUrls), e);
}
}
}
}
private static Iterable<String> getSampleJsonUrls() {
return () -> getQuicktypeSampleJsonUrls().iterator();
}
private static Stream<String> getQuicktypeSampleJsonUrls() {
final Stream<String> misc = Stream
.of("00c36.json", "00ec5.json", "010b1.json", "016af.json", "033b1.json", "050b0.json",
"06bee.json", "07540.json", "0779f.json", "07c75.json", "09f54.json", "0a358.json",
"0a91a.json", "0b91a.json", "0cffa.json", "0e0c2.json", "0fecf.json", "10be4.json",
"112b5.json", "127a1.json", "13d8d.json", "14d38.json", "167d6.json", "16bc5.json",
"176f1.json", "1a7f5.json", "1b28c.json", "1b409.json", "2465e.json", "24f52.json",
"262f0.json", "26b49.json", "26c9c.json", "27332.json", "29f47.json", "2d4e2.json",
"2df80.json", "31189.json", "32431.json", "32d5c.json", "337ed.json", "33d2e.json",
"34702.json", "3536b.json", "3659d.json", "36d5d.json", "3a6b3.json", "3e9a3.json",
"3f1ce.json", "421d4.json", "437e7.json", "43970.json", "43eaf.json", "458db.json",
"4961a.json", "4a0d7.json", "4a455.json", "4c547.json", "4d6fb.json", "4e336.json",
"54147.json", "54d32.json", "570ec.json", "5dd0d.json", "5eae5.json", "5eb20.json",
"5f3a1.json", "5f7fe.json", "617e8.json", "61b66.json", "6260a.json", "65dec.json",
"66121.json", "6617c.json", "67c03.json", "68c30.json", "6c155.json", "6de06.json",
"6dec6.json", "6eb00.json", "70c77.json", "734ad.json", "75912.json", "7681c.json",
"76ae1.json", "77392.json", "7d397.json", "7d722.json", "7df41.json", "7dfa6.json",
"7eb30.json", "7f568.json", "7fbfb.json", "80aff.json", "82509.json", "8592b.json",
"88130.json", "8a62c.json", "908db.json", "9617f.json", "96f7c.json", "9847b.json",
"9929c.json", "996bd.json", "9a503.json", "9ac3b.json", "9eed5.json", "a0496.json",
"a1eca.json", "a3d8c.json", "a45b0.json", "a71df.json", "a9691.json", "ab0d1.json",
"abb4b.json", "ac944.json", "ad8be.json", "ae7f0.json", "ae9ca.json", "af2d1.json",
"b4865.json", "b6f2c.json", "b6fe5.json", "b9f64.json", "bb1ec.json", "be234.json",
"c0356.json", "c0a3a.json", "c3303.json", "c6cfd.json", "c8c7e.json", "cb0cc.json",
"cb81e.json", "ccd18.json", "cd238.json", "cd463.json", "cda6c.json", "cf0d8.json",
"cfbce.json", "d0908.json", "d23d5.json", "dbfb3.json", "dc44f.json", "dd1ce.json",
"dec3a.json", "df957.json", "e0ac7.json", "e2915.json", "e2a58.json", "e324e.json",
"e53b5.json", "e64a0.json", "e8a0b.json", "e8b04.json", "ed095.json", "f22f5.json",
"f3139.json", "f3edf.json", "f466a.json", "f6a65.json", "f74d5.json", "f82d9.json",
"f974d.json", "faff5.json", "fcca3.json", "fd329.json")
.map("/test/inputs/json/misc/"::concat);
final Stream<String> priority = Stream.of("blns-object.json", "bug427.json", "bug790.json",
"bug855-short.json", "bug863.json", "coin-pairs.json", "combinations1.json",
"combinations2.json", "combinations3.json", "combinations4.json", "combined-enum.json",
"direct-recursive.json", "empty-enum.json", "identifiers.json", "keywords.json",
"list.json", "name-style.json", "nbl-stats.json", "no-classes.json", "nst-test-suite.json",
"number-map.json", "optional-union.json", "recursive.json", "simple-identifiers.json",
"union-constructor-clash.json", "unions.json", "url.json")
.map("/test/inputs/json/priority/"::concat);
final Stream<String> samples = Stream
.of("bitcoin-block.json", "getting-started.json", "github-events.json", "kitchen-sink.json",
"pokedex.json", "reddit.json", "simple-object.json", "spotify-album.json",
"us-avg-temperatures.json", "us-senators.json")
.map("/test/inputs/json/samples/"::concat);
return Stream.of(misc, priority, samples).flatMap(Function.identity())
.map(QUICKTYPE_REPO_BASE_URL::concat);
}
private static Collection<JsonSchemaInferrer> getTestInferrers() {
final List<JsonSchemaInferrer> inferrers = new ArrayList<>();
for (SpecVersion specVersion : SpecVersion.values()) {
for (AdditionalPropertiesPolicy additionalPropertiesPolicy : Arrays.asList(
AdditionalPropertiesPolicies.noOp(), AdditionalPropertiesPolicies.existingTypes())) {
for (RequiredPolicy requiredPolicy : Arrays.asList(RequiredPolicies.noOp(),
RequiredPolicies.commonFieldNames())) {
for (boolean inferFormat : Arrays.asList(true, false)) {
for (TitleGenerator titleGenerator : Arrays.asList(TitleGenerators.noOp(),
TitleGenerators.useFieldNames())) {
if (specVersion == SpecVersion.DRAFT_07 && inferFormat) {
/*
* Skip tests for inferring format with draft-07 due to a disagreement between Java
* time and the schema library on what a valid time string is.
*/
continue;
}
final JsonSchemaInferrer.Builder builder =
JsonSchemaInferrer.newBuilder().withSpecVersion(specVersion)
.withAdditionalPropertiesPolicy(additionalPropertiesPolicy)
.withRequiredPolicy(requiredPolicy)
.withTitleGenerator(titleGenerator);
if (!inferFormat) {
builder.withFormatInferrer(FormatInferrers.noOp());
}
try {
inferrers.add(builder.build());
} catch (IllegalArgumentException e) {
// Ignore
}
}
}
}
}
}
return Collections.unmodifiableList(inferrers);
}
@Nullable
private static JsonNode loadJsonFromUrl(String jsonUrl) throws IOException {
final HttpGet request = new HttpGet(jsonUrl);
request.setConfig(RequestConfig.custom()
.setConnectTimeout(1, TimeUnit.SECONDS)
.setConnectionRequestTimeout(1, TimeUnit.SECONDS)
.setResponseTimeout(5, TimeUnit.SECONDS)
.build());
return httpClient.execute(request, new AbstractHttpClientResponseHandler<JsonNode>() {
@Override
public JsonNode handleEntity(HttpEntity entity) throws IOException {
final byte[] byteArray = EntityUtils.toByteArray(entity);
if (byteArray.length > 1 << 20) {
System.out.printf(Locale.ROOT, "JSON at url[%s] is too large [%d].\n", jsonUrl,
byteArray.length);
return null;
}
return mapper.readTree(byteArray);
}
});
}
}
| src/test/java/com/saasquatch/json_schema_inferrer/JsonSchemaInferrerExamplesTest.java | package com.saasquatch.json_schema_inferrer;
import static com.saasquatch.json_schema_inferrer.JunkDrawer.format;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
public class JsonSchemaInferrerExamplesTest {
private static final String QUICKTYPE_REPO_BASE_URL =
"https://cdn.jsdelivr.net/gh/quicktype/quicktype@f75f66bff3d1f812b61c481637c12173778a29b8";
private static CloseableHttpClient httpClient;
private static final ObjectMapper mapper = new ObjectMapper();
private static Collection<JsonSchemaInferrer> testInferrers = getTestInferrers();
private static LoadingCache<String, JsonNode> testJsonCache =
CacheBuilder.newBuilder().softValues().build(new CacheLoader<String, JsonNode>() {
@Override
public JsonNode load(String url) throws Exception {
return loadJsonFromUrl(url);
}
});
@BeforeAll
public static void beforeAll() {
httpClient = HttpClients.custom().disableCookieManagement().build();
}
@AfterAll
public static void afterAll() throws Exception {
httpClient.close();
}
@Test
public void test() {
for (String jsonUrl : getSampleJsonUrls()) {
doTestForJsonUrl(jsonUrl);
}
}
@Test
public void testMulti() {
for (List<String> jsonUrls : Iterables.partition(getSampleJsonUrls(), 4)) {
doTestForJsonUrls(jsonUrls);
}
}
private static void doTestForJsonUrl(String jsonUrl) {
final JsonNode sampleJson;
// Not being able to load the sample JSON should not be considered a failure
try {
sampleJson = testJsonCache.get(jsonUrl);
if (sampleJson == null) {
return;
}
} catch (Exception e) {
System.out.printf(Locale.ROOT, "Exception encountered loading JSON from url[%s]. "
+ "Error message: [%s]. Skipping tests.\n", jsonUrl, e.getMessage());
return;
}
System.out.printf(Locale.ROOT, "Got valid JSON from url[%s]\n", jsonUrl);
for (JsonSchemaInferrer inferrer : testInferrers) {
final ObjectNode schemaJson = inferrer.inferForSample(sampleJson);
assertNotNull(schemaJson, format("Inferred schema for url[%s] is null", jsonUrl));
final Schema schema;
try {
schema = SchemaLoader.load(new JSONObject(toMap(schemaJson)));
} catch (RuntimeException e) {
fail(format("Unable to parse the inferred schema for url[%s]", jsonUrl), e);
throw e;
}
try {
if (sampleJson.isObject()) {
schema.validate(new JSONObject(toMap(sampleJson)));
} else if (sampleJson.isArray()) {
schema.validate(new JSONArray(sampleJson.toString()));
} else {
schema.validate(mapper.convertValue(sampleJson, Object.class));
}
} catch (ValidationException e) {
System.out.println(e.getClass().getSimpleName() + " encountered");
System.out.println(schemaJson.toPrettyString());
System.out.println("Error messages:");
e.getAllMessages().forEach(System.out::println);
fail(format("Inferred schema for url[%s] failed to validate", jsonUrl), e);
}
}
}
private static void doTestForJsonUrls(Collection<String> jsonUrls) {
final List<JsonNode> sampleJsons = jsonUrls.stream()
.map(jsonUrl -> {
try {
return testJsonCache.get(jsonUrl);
} catch (Exception e) {
System.out.printf(Locale.ROOT, "Exception encountered loading JSON from url[%s]. "
+ "Error message: [%s]. Skipping tests.\n", jsonUrl, e.getMessage());
return null;
}
})
.collect(Collectors.toList());
System.out.printf(Locale.ROOT, "Got valid JSONs from urls%s\n", jsonUrls);
for (JsonSchemaInferrer inferrer : testInferrers) {
final ObjectNode schemaJson = inferrer.inferForSamples(sampleJsons);
assertNotNull(schemaJson, format("Inferred schema for urls%s is null", jsonUrls));
final Schema schema;
try {
schema = SchemaLoader.load(new JSONObject(toMap(schemaJson)));
} catch (RuntimeException e) {
fail(format("Unable to parse the inferred schema for urls%s", jsonUrls), e);
throw e;
}
for (JsonNode sampleJson : sampleJsons) {
try {
if (sampleJson.isObject()) {
schema.validate(new JSONObject(toMap(sampleJson)));
} else if (sampleJson.isArray()) {
schema.validate(new JSONArray(sampleJson.toString()));
} else {
schema.validate(mapper.convertValue(sampleJson, Object.class));
}
} catch (ValidationException e) {
System.out.println(e.getClass().getSimpleName() + " encountered");
System.out.println(schemaJson.toPrettyString());
System.out.println("Error messages:");
e.getAllMessages().forEach(System.out::println);
fail(format("Inferred schema for urls%s failed to validate", jsonUrls), e);
}
}
}
}
private static Iterable<String> getSampleJsonUrls() {
return () -> getQuicktypeSampleJsonUrls().iterator();
}
private static Stream<String> getQuicktypeSampleJsonUrls() {
final Stream<String> misc = Stream
.of("00c36.json", "00ec5.json", "010b1.json", "016af.json", "033b1.json", "050b0.json",
"06bee.json", "07540.json", "0779f.json", "07c75.json", "09f54.json", "0a358.json",
"0a91a.json", "0b91a.json", "0cffa.json", "0e0c2.json", "0fecf.json", "10be4.json",
"112b5.json", "127a1.json", "13d8d.json", "14d38.json", "167d6.json", "16bc5.json",
"176f1.json", "1a7f5.json", "1b28c.json", "1b409.json", "2465e.json", "24f52.json",
"262f0.json", "26b49.json", "26c9c.json", "27332.json", "29f47.json", "2d4e2.json",
"2df80.json", "31189.json", "32431.json", "32d5c.json", "337ed.json", "33d2e.json",
"34702.json", "3536b.json", "3659d.json", "36d5d.json", "3a6b3.json", "3e9a3.json",
"3f1ce.json", "421d4.json", "437e7.json", "43970.json", "43eaf.json", "458db.json",
"4961a.json", "4a0d7.json", "4a455.json", "4c547.json", "4d6fb.json", "4e336.json",
"54147.json", "54d32.json", "570ec.json", "5dd0d.json", "5eae5.json", "5eb20.json",
"5f3a1.json", "5f7fe.json", "617e8.json", "61b66.json", "6260a.json", "65dec.json",
"66121.json", "6617c.json", "67c03.json", "68c30.json", "6c155.json", "6de06.json",
"6dec6.json", "6eb00.json", "70c77.json", "734ad.json", "75912.json", "7681c.json",
"76ae1.json", "77392.json", "7d397.json", "7d722.json", "7df41.json", "7dfa6.json",
"7eb30.json", "7f568.json", "7fbfb.json", "80aff.json", "82509.json", "8592b.json",
"88130.json", "8a62c.json", "908db.json", "9617f.json", "96f7c.json", "9847b.json",
"9929c.json", "996bd.json", "9a503.json", "9ac3b.json", "9eed5.json", "a0496.json",
"a1eca.json", "a3d8c.json", "a45b0.json", "a71df.json", "a9691.json", "ab0d1.json",
"abb4b.json", "ac944.json", "ad8be.json", "ae7f0.json", "ae9ca.json", "af2d1.json",
"b4865.json", "b6f2c.json", "b6fe5.json", "b9f64.json", "bb1ec.json", "be234.json",
"c0356.json", "c0a3a.json", "c3303.json", "c6cfd.json", "c8c7e.json", "cb0cc.json",
"cb81e.json", "ccd18.json", "cd238.json", "cd463.json", "cda6c.json", "cf0d8.json",
"cfbce.json", "d0908.json", "d23d5.json", "dbfb3.json", "dc44f.json", "dd1ce.json",
"dec3a.json", "df957.json", "e0ac7.json", "e2915.json", "e2a58.json", "e324e.json",
"e53b5.json", "e64a0.json", "e8a0b.json", "e8b04.json", "ed095.json", "f22f5.json",
"f3139.json", "f3edf.json", "f466a.json", "f6a65.json", "f74d5.json", "f82d9.json",
"f974d.json", "faff5.json", "fcca3.json", "fd329.json")
.map("/test/inputs/json/misc/"::concat);
final Stream<String> priority = Stream.of("blns-object.json", "bug427.json", "bug790.json",
"bug855-short.json", "bug863.json", "coin-pairs.json", "combinations1.json",
"combinations2.json", "combinations3.json", "combinations4.json", "combined-enum.json",
"direct-recursive.json", "empty-enum.json", "identifiers.json", "keywords.json",
"list.json", "name-style.json", "nbl-stats.json", "no-classes.json", "nst-test-suite.json",
"number-map.json", "optional-union.json", "recursive.json", "simple-identifiers.json",
"union-constructor-clash.json", "unions.json", "url.json")
.map("/test/inputs/json/priority/"::concat);
final Stream<String> samples = Stream
.of("bitcoin-block.json", "getting-started.json", "github-events.json", "kitchen-sink.json",
"pokedex.json", "reddit.json", "simple-object.json", "spotify-album.json",
"us-avg-temperatures.json", "us-senators.json")
.map("/test/inputs/json/samples/"::concat);
return Stream.of(misc, priority, samples).flatMap(Function.identity())
.map(QUICKTYPE_REPO_BASE_URL::concat);
}
private static Collection<JsonSchemaInferrer> getTestInferrers() {
final List<JsonSchemaInferrer> inferrers = new ArrayList<>();
for (SpecVersion specVersion : SpecVersion.values()) {
for (AdditionalPropertiesPolicy additionalPropertiesPolicy : Arrays.asList(
AdditionalPropertiesPolicies.noOp(), AdditionalPropertiesPolicies.existingTypes())) {
for (RequiredPolicy requiredPolicy : Arrays.asList(RequiredPolicies.noOp(),
RequiredPolicies.nonNullCommonFieldNames())) {
for (boolean inferFormat : Arrays.asList(true, false)) {
for (TitleGenerator titleGenerator : Arrays.asList(TitleGenerators.noOp(),
TitleGenerators.useFieldNames())) {
if (specVersion == SpecVersion.DRAFT_07 && inferFormat) {
/*
* Skip tests for inferring format with draft-07 due to a disagreement between Java
* time and the schema library on what a valid time string is.
*/
continue;
}
final JsonSchemaInferrer.Builder builder =
JsonSchemaInferrer.newBuilder().withSpecVersion(specVersion)
.withAdditionalPropertiesPolicy(additionalPropertiesPolicy)
.withRequiredPolicy(requiredPolicy)
.withTitleGenerator(titleGenerator);
if (!inferFormat) {
builder.withFormatInferrer(FormatInferrers.noOp());
}
try {
inferrers.add(builder.build());
} catch (IllegalArgumentException e) {
// Ignore
}
}
}
}
}
}
return Collections.unmodifiableList(inferrers);
}
@Nullable
private static JsonNode loadJsonFromUrl(String jsonUrl) throws IOException {
final HttpGet request = new HttpGet(jsonUrl);
request.setConfig(RequestConfig.custom()
.setConnectTimeout(1, TimeUnit.SECONDS)
.setConnectionRequestTimeout(1, TimeUnit.SECONDS)
.setResponseTimeout(5, TimeUnit.SECONDS)
.build());
return httpClient.execute(request, new AbstractHttpClientResponseHandler<JsonNode>() {
@Override
public JsonNode handleEntity(HttpEntity entity) throws IOException {
final byte[] byteArray = EntityUtils.toByteArray(entity);
if (byteArray.length > 1 << 20) {
System.out.printf(Locale.ROOT, "JSON at url[%s] is too large [%d].\n", jsonUrl,
byteArray.length);
return null;
}
return mapper.readTree(byteArray);
}
});
}
private static Map<String, Object> toMap(Object o) {
return mapper.convertValue(o, new TypeReference<Map<String, Object>>() {});
}
}
| test fix
| src/test/java/com/saasquatch/json_schema_inferrer/JsonSchemaInferrerExamplesTest.java | test fix | <ide><path>rc/test/java/com/saasquatch/json_schema_inferrer/JsonSchemaInferrerExamplesTest.java
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Locale;
<del>import java.util.Map;
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.function.Function;
<ide> import java.util.stream.Collectors;
<ide> import org.junit.jupiter.api.AfterAll;
<ide> import org.junit.jupiter.api.BeforeAll;
<ide> import org.junit.jupiter.api.Test;
<del>import com.fasterxml.jackson.core.type.TypeReference;
<ide> import com.fasterxml.jackson.databind.JsonNode;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.fasterxml.jackson.databind.node.ObjectNode;
<ide> assertNotNull(schemaJson, format("Inferred schema for url[%s] is null", jsonUrl));
<ide> final Schema schema;
<ide> try {
<del> schema = SchemaLoader.load(new JSONObject(toMap(schemaJson)));
<add> schema = SchemaLoader.load(new JSONObject(schemaJson.toString()));
<ide> } catch (RuntimeException e) {
<ide> fail(format("Unable to parse the inferred schema for url[%s]", jsonUrl), e);
<ide> throw e;
<ide> }
<ide> try {
<ide> if (sampleJson.isObject()) {
<del> schema.validate(new JSONObject(toMap(sampleJson)));
<add> schema.validate(new JSONObject(sampleJson.toString()));
<ide> } else if (sampleJson.isArray()) {
<ide> schema.validate(new JSONArray(sampleJson.toString()));
<ide> } else {
<ide> assertNotNull(schemaJson, format("Inferred schema for urls%s is null", jsonUrls));
<ide> final Schema schema;
<ide> try {
<del> schema = SchemaLoader.load(new JSONObject(toMap(schemaJson)));
<add> schema = SchemaLoader.load(new JSONObject(schemaJson.toString()));
<ide> } catch (RuntimeException e) {
<ide> fail(format("Unable to parse the inferred schema for urls%s", jsonUrls), e);
<ide> throw e;
<ide> for (JsonNode sampleJson : sampleJsons) {
<ide> try {
<ide> if (sampleJson.isObject()) {
<del> schema.validate(new JSONObject(toMap(sampleJson)));
<add> schema.validate(new JSONObject(sampleJson.toString()));
<ide> } else if (sampleJson.isArray()) {
<ide> schema.validate(new JSONArray(sampleJson.toString()));
<ide> } else {
<ide> for (AdditionalPropertiesPolicy additionalPropertiesPolicy : Arrays.asList(
<ide> AdditionalPropertiesPolicies.noOp(), AdditionalPropertiesPolicies.existingTypes())) {
<ide> for (RequiredPolicy requiredPolicy : Arrays.asList(RequiredPolicies.noOp(),
<del> RequiredPolicies.nonNullCommonFieldNames())) {
<add> RequiredPolicies.commonFieldNames())) {
<ide> for (boolean inferFormat : Arrays.asList(true, false)) {
<ide> for (TitleGenerator titleGenerator : Arrays.asList(TitleGenerators.noOp(),
<ide> TitleGenerators.useFieldNames())) {
<ide> });
<ide> }
<ide>
<del> private static Map<String, Object> toMap(Object o) {
<del> return mapper.convertValue(o, new TypeReference<Map<String, Object>>() {});
<del> }
<del>
<ide> } |
|
Java | bsd-3-clause | e0fac72a2878c0bf17104bf13aa7bf3356e9a3f0 | 0 | interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl | /* $Id$ */
package ibis.io;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectStreamField;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Comparator;
import java.util.HashMap;
/**
* The <code>AlternativeTypeInfo</code> class maintains information about
* a specific <code>Class</code>, such as a list of serializable fields,
* whether it has <code>readObject</code> and <code>writeObject</code>
* methods, et cetera.
*
* The serializable fields are first ordered alphabetically, and then
* by type, in the order: double, long, float, int, short, char, byte,
* boolean, reference. This determines the order in which fields are
* serialized.
*/
final class AlternativeTypeInfo {
/**
* Maintains all <code>AlternativeTypeInfo</code> structures in a
* hashmap, to be accessed through their classname.
*/
private static HashMap alternativeTypes = new HashMap();
/** newInstance method of ObjectStreamClass, when it exists. */
private static Method newInstance = null;
/**
* The <code>Class</code> structure of the class represented by this
* <code>AlternativeTypeInfo</code> structure.
*/
Class clazz;
/** The ObjectStreamClass of clazz. */
private ObjectStreamClass objectStreamClass;
/** The sorted list of serializable fields. */
Field[] serializable_fields;
/**
* For each field, indicates whether the field is final.
* This is significant for deserialization, because it determines the
* way in which the field can be assigned to. The bytecode verifier
* does not allow arbitraty assignments to final fields.
*/
boolean[] fields_final;
/** Number of <code>double</code> fields. */
int double_count;
/** Number of <code>long</code> fields. */
int long_count;
/** Number of <code>float</code> fields. */
int float_count;
/** Number of <code>int</code> fields. */
int int_count;
/** Number of <code>short</code> fields. */
int short_count;
/** Number of <code>char</code> fields. */
int char_count;
/** Number of <code>byte</code> fields. */
int byte_count;
/** Number of <code>boolean</code> fields. */
int boolean_count;
/** Number of <code>reference</code> fields. */
int reference_count;
/** Indicates whether the superclass is serializable. */
boolean superSerializable;
/** The <code>AlternativeTypeInfo</code> structure of the superclass. */
AlternativeTypeInfo alternativeSuperInfo;
/**
* The "level" of a serializable class.
* The "level" of a serializable class is computed as follows:
* - if its superclass is serializable:
* the level of the superclass + 1.
* - if its superclass is not serializable:
* 1.
*/
int level;
/** serialPersistentFields of the class, if the class declares them. */
java.io.ObjectStreamField[] serial_persistent_fields = null;
/** Set if the class has a <code>readObject</code> method. */
boolean hasReadObject;
/** Set if the class has a <code>writeObject</code> method. */
boolean hasWriteObject;
/** Set if the class has a <code>writeReplace</code> method. */
boolean hasReplace;
/**
* A <code>Comparator</code> implementation for sorting the
* fields array.
*/
private static class FieldComparator implements Comparator {
/**
* Compare fields alphabetically.
*/
public int compare(Object o1, Object o2) {
Field f1 = (Field) o1;
Field f2 = (Field) o2;
return f1.getName().compareTo(f2.getName());
}
}
/** A <code>Comparator</code> for sorting the array of fields. */
private static FieldComparator fieldComparator = new FieldComparator();
/** The <code>writeObject</code> method, if there is one. */
private Method writeObjectMethod;
/** The <code>readObject</code> method, if there is one. */
private Method readObjectMethod;
/** The <code>writeReplace</code> method, if there is one. */
private Method writeReplaceMethod;
/** The <code>readResolve</code> method, if there is one. */
private Method readResolveMethod;
/** This is needed for the private field access hack. */
Field temporary_field;
/** This is needed for the private method access hack. */
Method temporary_method;
static {
try {
newInstance = ObjectStreamClass.class.getDeclaredMethod(
"newInstance", new Class[] {});
} catch (Exception e) {
// ignored.
}
if (newInstance != null) {
try {
newInstance.setAccessible(true);
} catch (Exception e) {
newInstance = null;
}
}
}
/**
* Return the name of the class.
*
* @return the name of the class.
*/
public String toString() {
return clazz.getName();
}
/**
* Try to create an object through the newInstance method of
* ObjectStreamClass.
* Return null if it fails for some reason.
*/
Object newInstance() {
if (newInstance != null) {
try {
return newInstance.invoke(objectStreamClass,
(java.lang.Object[]) null);
} catch (Exception e) {
// System.out.println("newInstance fails: got exception " + e);
return null;
}
}
// System.out.println("newInstance fails: no newInstance method");
return null;
}
/**
* Gets the <code>AlternativeTypeInfo</code> for class <code>type</code>.
*
* @param type the <code>Class</code> of the requested type.
* @return the <code>AlternativeTypeInfo</code> structure for this type.
*/
public static synchronized AlternativeTypeInfo getAlternativeTypeInfo(
Class type) {
AlternativeTypeInfo t
= (AlternativeTypeInfo) alternativeTypes.get(type);
if (t == null) {
t = new AlternativeTypeInfo(type);
alternativeTypes.put(type, t);
}
return t;
}
/**
* Gets the <code>AlternativeTypeInfo</code> for class
* <code>classname</code>.
*
* @param classname the name of the requested type.
* @return the <code>AlternativeTypeInfo</code> structure for this type.
*/
public static synchronized AlternativeTypeInfo getAlternativeTypeInfo(
String classname) throws ClassNotFoundException {
Class type = null;
try {
type = Class.forName(classname);
} catch (ClassNotFoundException e) {
type = Thread.currentThread().getContextClassLoader().loadClass(
classname);
}
return getAlternativeTypeInfo(type);
}
/**
* Gets the method with the given name, parameter types and return type.
*
* @param name the name of the method
* @param paramTypes its parameter types
* @param returnType its return type
* @return the requested method, or <code>null</code> if
* it cannot be found.
*/
private Method getMethod(String name, Class[] paramTypes, Class returnType) {
try {
Method method = clazz.getDeclaredMethod(name, paramTypes);
/* Check return type. */
if (method.getReturnType() != returnType) {
return null;
}
/* Check if method is static. */
if ((method.getModifiers() & Modifier.STATIC) != 0) {
return null;
}
/* Make method accessible, so that it may be called. */
if (!method.isAccessible()) {
temporary_method = method;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_method.setAccessible(true);
return null;
}
});
}
return method;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Invokes the <code>writeObject</code> method on object <code>o</code>.
*
* @param o the object on which <code>writeObject</code> is to
* be invoked
* @param out the <code>ObjectOutputStream</code> to be given
* as parameter
* @exception IOException
* when anything goes wrong
*/
void invokeWriteObject(Object o, ObjectOutputStream out)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// System.out.println("invoke writeObject");
writeObjectMethod.invoke(o, new Object[] { out });
}
/**
* Invokes the <code>readObject</code> method on object <code>o</code>.
*
* @param o the object on which <code>readObject</code> is to
* be invoked
* @param in the <code>ObjectInputStream</code> to be given
* as parameter
* @exception IOException
* when anything goes wrong
*/
void invokeReadObject(Object o, ObjectInputStream in)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// System.out.println("invoke readObject");
readObjectMethod.invoke(o, new Object[] { in });
}
/**
* Invokes the <code>readResolve</code> method on object <code>o</code>.
*
* @param o the object on which <code>readResolve</code> is to
* be invoked
* @exception IOException
* when anything goes wrong
*/
Object invokeReadResolve(Object o) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
return readResolveMethod.invoke(o, new Object[0]);
}
/**
* Invokes the <code>writeReplace</code> method on object <code>o</code>.
*
* @param o the object on which <code>writeReplace</code> is to
* be invoked
* @exception IOException
* when anything goes wrong
*/
Object invokeWriteReplace(Object o) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
return writeReplaceMethod.invoke(o, new Object[0]);
}
/**
* Constructor is private. Use {@link #getAlternativeTypeInfo(Class)} to
* obtain the <code>AlternativeTypeInfo</code> for a type.
*/
private AlternativeTypeInfo(Class clazz) {
this.clazz = clazz;
if (newInstance != null) {
objectStreamClass = ObjectStreamClass.lookup(clazz);
}
try {
/*
Here we figure out what field the type contains, and which fields
we should write. We must also sort them by type and name to ensure
that we read them correctly on the other side. We cache all of
this so we only do it once for each type.
*/
getSerialPersistentFields();
/* see if the supertype is serializable */
Class superClass = clazz.getSuperclass();
if (superClass != null) {
if (java.io.Serializable.class.isAssignableFrom(superClass)) {
superSerializable = true;
alternativeSuperInfo = getAlternativeTypeInfo(superClass);
level = alternativeSuperInfo.level + 1;
} else {
superSerializable = false;
level = 1;
}
}
/* Now see if it has a writeObject/readObject. */
writeObjectMethod = getMethod("writeObject",
new Class[] { ObjectOutputStream.class }, Void.TYPE);
readObjectMethod = getMethod("readObject",
new Class[] { ObjectInputStream.class }, Void.TYPE);
hasWriteObject = writeObjectMethod != null;
hasReadObject = readObjectMethod != null;
writeReplaceMethod = getMethod("writeReplace", new Class[0],
Object.class);
readResolveMethod = getMethod("readResolve", new Class[0],
Object.class);
hasReplace = writeReplaceMethod != null;
Field[] fields = clazz.getDeclaredFields();
/* getDeclaredFields does not specify or guarantee a specific
* order. Therefore, we sort the fields alphabetically, as does
* the IOGenerator.
*/
java.util.Arrays.sort(fields, fieldComparator);
int len = fields.length;
/* Create the datastructures to cache the fields we need. Since
* we don't know the size yet, we create large enough arrays,
* which will later be replaced;
*/
if (serial_persistent_fields != null) {
len = serial_persistent_fields.length;
}
Field[] double_fields = new Field[len];
Field[] long_fields = new Field[len];
Field[] float_fields = new Field[len];
Field[] int_fields = new Field[len];
Field[] short_fields = new Field[len];
Field[] char_fields = new Field[len];
Field[] byte_fields = new Field[len];
Field[] boolean_fields = new Field[len];
Field[] reference_fields = new Field[len];
if (serial_persistent_fields == null) {
/* Now count and store all the difference field types (only the
* ones that we should write!). Note that we store them into
* the array sorted by name !
*/
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (field == null) {
continue;
}
int modifiers = field.getModifiers();
if ((modifiers & (Modifier.TRANSIENT | Modifier.STATIC))
== 0) {
Class field_type = field.getType();
/* This part is a bit scary. We basically switch of the
* Java field access checks so we are allowed to read
* private fields ....
*/
if (!field.isAccessible()) {
temporary_field = field;
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
if (field_type.isPrimitive()) {
if (field_type == Boolean.TYPE) {
boolean_fields[boolean_count++] = field;
} else if (field_type == Character.TYPE) {
char_fields[char_count++] = field;
} else if (field_type == Byte.TYPE) {
byte_fields[byte_count++] = field;
} else if (field_type == Short.TYPE) {
short_fields[short_count++] = field;
} else if (field_type == Integer.TYPE) {
int_fields[int_count++] = field;
} else if (field_type == Long.TYPE) {
long_fields[long_count++] = field;
} else if (field_type == Float.TYPE) {
float_fields[float_count++] = field;
} else if (field_type == Double.TYPE) {
double_fields[double_count++] = field;
}
} else {
reference_fields[reference_count++] = field;
}
}
}
} else {
for (int i = 0; i < serial_persistent_fields.length; i++) {
Field field = findField(serial_persistent_fields[i]);
Class field_type = serial_persistent_fields[i].getType();
if (field != null && !field.isAccessible()) {
temporary_field = field;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
if (field_type.isPrimitive()) {
if (field_type == Boolean.TYPE) {
boolean_fields[boolean_count++] = field;
} else if (field_type == Character.TYPE) {
char_fields[char_count++] = field;
} else if (field_type == Byte.TYPE) {
byte_fields[byte_count++] = field;
} else if (field_type == Short.TYPE) {
short_fields[short_count++] = field;
} else if (field_type == Integer.TYPE) {
int_fields[int_count++] = field;
} else if (field_type == Long.TYPE) {
long_fields[long_count++] = field;
} else if (field_type == Float.TYPE) {
float_fields[float_count++] = field;
} else if (field_type == Double.TYPE) {
double_fields[double_count++] = field;
}
} else {
reference_fields[reference_count++] = field;
}
}
}
// Now resize the datastructures.
int size = double_count + long_count + float_count + int_count
+ short_count + char_count + byte_count + boolean_count
+ reference_count;
int index = 0;
if (size > 0) {
serializable_fields = new Field[size];
System.arraycopy(double_fields, 0, serializable_fields, index,
double_count);
index += double_count;
System.arraycopy(long_fields, 0, serializable_fields, index,
long_count);
index += long_count;
System.arraycopy(float_fields, 0, serializable_fields, index,
float_count);
index += float_count;
System.arraycopy(int_fields, 0, serializable_fields, index,
int_count);
index += int_count;
System.arraycopy(short_fields, 0, serializable_fields, index,
short_count);
index += short_count;
System.arraycopy(char_fields, 0, serializable_fields, index,
char_count);
index += char_count;
System.arraycopy(byte_fields, 0, serializable_fields, index,
byte_count);
index += byte_count;
System.arraycopy(boolean_fields, 0, serializable_fields, index,
boolean_count);
index += boolean_count;
System.arraycopy(reference_fields, 0, serializable_fields,
index, reference_count);
fields_final = new boolean[size];
for (int i = 0; i < size; i++) {
if (serializable_fields[i] != null) {
fields_final[i]
= ((serializable_fields[i].getModifiers()
& Modifier.FINAL) != 0);
} else {
fields_final[i] = false;
}
}
} else {
serializable_fields = null;
}
} catch (Exception e) {
throw new SerializationError("Cannot initialize serialization "
+ "info for " + clazz.getName(), e);
}
}
/**
* Looks for a declaration of serialPersistentFields, and, if present,
* makes it accessible, and stores it in
* <code>serial_persistent_fields</code>.
*/
private void getSerialPersistentFields() {
try {
Field f = clazz.getDeclaredField("serialPersistentFields");
int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
if (!f.isAccessible()) {
temporary_field = f;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
serial_persistent_fields
= (java.io.ObjectStreamField[]) f.get(null);
}
} catch (Exception e) {
// ignored, no serialPersistentFields
}
}
/**
* Gets the field with fieldname indicated by the name in <code>of</code>.
* If not present, returns <code>null</code>.
*/
private Field findField(ObjectStreamField of) {
try {
return clazz.getDeclaredField(of.getName());
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* Gets the index of a field with name <code>name</code> and type
* <code>tp</code> in either <code>SerialPersistentFields</code>, if
* it exists, or in the <code>serializable_fields</code> array.
* An exception is thrown when such a field is not found.
*
* @param name name of the field we are looking for
* @param tp type of the field we are looking for
* @return index in either <code>serial_persistent_fields</code> or
* <code>serializable_fields</code>.
* @exception IllegalArgumentException when no such field is found.
*/
int getOffset(String name, Class tp) throws IllegalArgumentException {
int offset = 0;
if (tp.isPrimitive()) {
if (serial_persistent_fields != null) {
for (int i = 0; i < serial_persistent_fields.length; i++) {
if (serial_persistent_fields[i].getType() == tp) {
if (name.equals(
serial_persistent_fields[i].getName())) {
return offset;
}
offset++;
}
}
} else if (serializable_fields != null) {
for (int i = 0; i < serializable_fields.length; i++) {
if (serializable_fields[i].getType() == tp) {
if (name.equals(serializable_fields[i].getName())) {
return offset;
}
offset++;
}
}
}
} else {
if (serial_persistent_fields != null) {
for (int i = 0; i < serial_persistent_fields.length; i++) {
if (!serial_persistent_fields[i].getType().isPrimitive()) {
if (name.equals(serial_persistent_fields[i].getName())) {
return offset;
}
offset++;
}
}
} else if (serializable_fields != null) {
for (int i = 0; i < serializable_fields.length; i++) {
if (!serializable_fields[i].getType().isPrimitive()) {
if (name.equals(serializable_fields[i].getName())) {
return offset;
}
offset++;
}
}
}
}
throw new IllegalArgumentException("no field named " + name
+ " with type " + tp);
}
}
| src/ibis/io/AlternativeTypeInfo.java | /* $Id$ */
package ibis.io;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectStreamField;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Comparator;
import java.util.HashMap;
/**
* The <code>AlternativeTypeInfo</code> class maintains information about
* a specific <code>Class</code>, such as a list of serializable fields,
* whether it has <code>readObject</code> and <code>writeObject</code>
* methods, et cetera.
*
* The serializable fields are first ordered alphabetically, and then
* by type, in the order: double, long, float, int, short, char, byte,
* boolean, reference. This determines the order in which fields are
* serialized.
*/
final class AlternativeTypeInfo {
/**
* Maintains all <code>AlternativeTypeInfo</code> structures in a
* hashmap, to be accessed through their classname.
*/
private static HashMap alternativeTypes = new HashMap();
/** newInstance method of ObjectStreamClass, when it exists. */
private static Method newInstance = null;
/**
* The <code>Class</code> structure of the class represented by this
* <code>AlternativeTypeInfo</code> structure.
*/
Class clazz;
/** The ObjectStreamClass of clazz. */
private ObjectStreamClass objectStreamClass;
/** The sorted list of serializable fields. */
Field[] serializable_fields;
/**
* For each field, indicates whether the field is final.
* This is significant for deserialization, because it determines the
* way in which the field can be assigned to. The bytecode verifier
* does not allow arbitraty assignments to final fields.
*/
boolean[] fields_final;
/** Number of <code>double</code> fields. */
int double_count;
/** Number of <code>long</code> fields. */
int long_count;
/** Number of <code>float</code> fields. */
int float_count;
/** Number of <code>int</code> fields. */
int int_count;
/** Number of <code>short</code> fields. */
int short_count;
/** Number of <code>char</code> fields. */
int char_count;
/** Number of <code>byte</code> fields. */
int byte_count;
/** Number of <code>boolean</code> fields. */
int boolean_count;
/** Number of <code>reference</code> fields. */
int reference_count;
/** Indicates whether the superclass is serializable. */
boolean superSerializable;
/** The <code>AlternativeTypeInfo</code> structure of the superclass. */
AlternativeTypeInfo alternativeSuperInfo;
/**
* The "level" of a serializable class.
* The "level" of a serializable class is computed as follows:
* - if its superclass is serializable:
* the level of the superclass + 1.
* - if its superclass is not serializable:
* 1.
*/
int level;
/** serialPersistentFields of the class, if the class declares them. */
java.io.ObjectStreamField[] serial_persistent_fields = null;
/** Set if the class has a <code>readObject</code> method. */
boolean hasReadObject;
/** Set if the class has a <code>writeObject</code> method. */
boolean hasWriteObject;
/** Set if the class has a <code>writeReplace</code> method. */
boolean hasReplace;
/**
* A <code>Comparator</code> implementation for sorting the
* fields array.
*/
private static class FieldComparator implements Comparator {
/**
* Compare fields alphabetically.
*/
public int compare(Object o1, Object o2) {
Field f1 = (Field) o1;
Field f2 = (Field) o2;
return f1.getName().compareTo(f2.getName());
}
}
/** A <code>Comparator</code> for sorting the array of fields. */
private static FieldComparator fieldComparator = new FieldComparator();
/** The <code>writeObject</code> method, if there is one. */
private Method writeObjectMethod;
/** The <code>readObject</code> method, if there is one. */
private Method readObjectMethod;
/** The <code>writeReplace</code> method, if there is one. */
private Method writeReplaceMethod;
/** The <code>readResolve</code> method, if there is one. */
private Method readResolveMethod;
/** This is needed for the private field access hack. */
Field temporary_field;
/** This is needed for the private method access hack. */
Method temporary_method;
static {
try {
newInstance = ObjectStreamClass.class.getDeclaredMethod(
"newInstance", new Class[] {});
} catch (Exception e) {
// ignored.
}
if (newInstance != null) {
try {
newInstance.setAccessible(true);
} catch (Exception e) {
newInstance = null;
}
}
}
/**
* Return the name of the class.
*
* @return the name of the class.
*/
public String toString() {
return clazz.getName();
}
/**
* Try to create an object through the newInstance method of
* ObjectStreamClass.
* Return null if it fails for some reason.
*/
Object newInstance() {
if (newInstance != null) {
try {
return newInstance.invoke(objectStreamClass,
(java.lang.Object[]) null);
} catch (Exception e) {
// System.out.println("newInstance fails: got exception " + e);
return null;
}
}
// System.out.println("newInstance fails: no newInstance method");
return null;
}
/**
* Gets the <code>AlternativeTypeInfo</code> for class <code>type</code>.
*
* @param type the <code>Class</code> of the requested type.
* @return the <code>AlternativeTypeInfo</code> structure for this type.
*/
public static synchronized AlternativeTypeInfo getAlternativeTypeInfo(
Class type) {
AlternativeTypeInfo t
= (AlternativeTypeInfo) alternativeTypes.get(type);
if (t == null) {
t = new AlternativeTypeInfo(type);
alternativeTypes.put(type, t);
}
return t;
}
/**
* Gets the <code>AlternativeTypeInfo</code> for class
* <code>classname</code>.
*
* @param classname the name of the requested type.
* @return the <code>AlternativeTypeInfo</code> structure for this type.
*/
public static synchronized AlternativeTypeInfo getAlternativeTypeInfo(
String classname) throws ClassNotFoundException {
Class type = null;
try {
type = Class.forName(classname);
} catch (ClassNotFoundException e) {
type = Thread.currentThread().getContextClassLoader().loadClass(
classname);
}
return getAlternativeTypeInfo(type);
}
/**
* Gets the method with the given name, parameter types and return type.
*
* @param name the name of the method
* @param paramTypes its parameter types
* @param returnType its return type
* @return the requested method, or <code>null</code> if
* it cannot be found.
*/
private Method getMethod(String name, Class[] paramTypes, Class returnType) {
try {
Method method = clazz.getDeclaredMethod(name, paramTypes);
/* Check return type. */
if (method.getReturnType() != returnType) {
return null;
}
/* Check if method is static. */
if ((method.getModifiers() & Modifier.STATIC) != 0) {
return null;
}
/* Make method accessible, so that it may be called. */
if (!method.isAccessible()) {
temporary_method = method;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_method.setAccessible(true);
return null;
}
});
}
return method;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Invokes the <code>writeObject</code> method on object <code>o</code>.
*
* @param o the object on which <code>writeObject</code> is to
* be invoked
* @param out the <code>ObjectOutputStream</code> to be given
* as parameter
* @exception IOException
* when anything goes wrong
*/
void invokeWriteObject(Object o, ObjectOutputStream out)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// System.out.println("invoke writeObject");
writeObjectMethod.invoke(o, new Object[] { out });
}
/**
* Invokes the <code>readObject</code> method on object <code>o</code>.
*
* @param o the object on which <code>readObject</code> is to
* be invoked
* @param in the <code>ObjectInputStream</code> to be given
* as parameter
* @exception IOException
* when anything goes wrong
*/
void invokeReadObject(Object o, ObjectInputStream in)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// System.out.println("invoke readObject");
readObjectMethod.invoke(o, new Object[] { in });
}
/**
* Invokes the <code>readResolve</code> method on object <code>o</code>.
*
* @param o the object on which <code>readResolve</code> is to
* be invoked
* @exception IOException
* when anything goes wrong
*/
Object invokeReadResolve(Object o) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
return readResolveMethod.invoke(o, new Object[0]);
}
/**
* Invokes the <code>writeReplace</code> method on object <code>o</code>.
*
* @param o the object on which <code>writeReplace</code> is to
* be invoked
* @exception IOException
* when anything goes wrong
*/
Object invokeWriteReplace(Object o) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
return writeReplaceMethod.invoke(o, new Object[0]);
}
/**
* Constructor is private. Use {@link #getAlternativeTypeInfo(Class)} to
* obtain the <code>AlternativeTypeInfo</code> for a type.
*/
private AlternativeTypeInfo(Class clazz) {
this.clazz = clazz;
if (newInstance != null) {
objectStreamClass = ObjectStreamClass.lookup(clazz);
}
try {
/*
Here we figure out what field the type contains, and which fields
we should write. We must also sort them by type and name to ensure
that we read them correctly on the other side. We cache all of
this so we only do it once for each type.
*/
getSerialPersistentFields();
/* see if the supertype is serializable */
Class superClass = clazz.getSuperclass();
if (superClass != null) {
if (java.io.Serializable.class.isAssignableFrom(superClass)) {
superSerializable = true;
alternativeSuperInfo = getAlternativeTypeInfo(superClass);
level = alternativeSuperInfo.level + 1;
} else {
superSerializable = false;
level = 1;
}
}
/* Now see if it has a writeObject/readObject. */
writeObjectMethod = getMethod("writeObject",
new Class[] { ObjectOutputStream.class }, Void.TYPE);
readObjectMethod = getMethod("readObject",
new Class[] { ObjectInputStream.class }, Void.TYPE);
hasWriteObject = writeObjectMethod != null;
hasReadObject = readObjectMethod != null;
writeReplaceMethod = getMethod("writeReplace", new Class[0],
Object.class);
readResolveMethod = getMethod("readResolve", new Class[0],
Object.class);
hasReplace = writeReplaceMethod != null;
Field[] fields = clazz.getDeclaredFields();
/* getDeclaredFields does not specify or guarantee a specific
* order. Therefore, we sort the fields alphabetically, as does
* the IOGenerator.
*/
java.util.Arrays.sort(fields, fieldComparator);
int len = fields.length;
/* Create the datastructures to cache the fields we need. Since
* we don't know the size yet, we create large enough arrays,
* which will later be replaced;
*/
if (serial_persistent_fields != null) {
len = serial_persistent_fields.length;
}
Field[] double_fields = new Field[len];
Field[] long_fields = new Field[len];
Field[] float_fields = new Field[len];
Field[] int_fields = new Field[len];
Field[] short_fields = new Field[len];
Field[] char_fields = new Field[len];
Field[] byte_fields = new Field[len];
Field[] boolean_fields = new Field[len];
Field[] reference_fields = new Field[len];
if (serial_persistent_fields == null) {
/* Now count and store all the difference field types (only the
* ones that we should write!). Note that we store them into
* the array sorted by name !
*/
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (field == null) {
continue;
}
int modifiers = field.getModifiers();
if ((modifiers & (Modifier.TRANSIENT | Modifier.STATIC))
== 0) {
Class field_type = field.getType();
/* This part is a bit scary. We basically switch of the
* Java field access checks so we are allowed to read
* private fields ....
*/
if (!field.isAccessible()) {
temporary_field = field;
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
if (field_type.isPrimitive()) {
if (field_type == Boolean.TYPE) {
boolean_fields[boolean_count++] = field;
} else if (field_type == Character.TYPE) {
char_fields[char_count++] = field;
} else if (field_type == Byte.TYPE) {
byte_fields[byte_count++] = field;
} else if (field_type == Short.TYPE) {
short_fields[short_count++] = field;
} else if (field_type == Integer.TYPE) {
int_fields[int_count++] = field;
} else if (field_type == Long.TYPE) {
long_fields[long_count++] = field;
} else if (field_type == Float.TYPE) {
float_fields[float_count++] = field;
} else if (field_type == Double.TYPE) {
double_fields[double_count++] = field;
}
} else {
reference_fields[reference_count++] = field;
}
}
}
} else {
for (int i = 0; i < serial_persistent_fields.length; i++) {
Field field = findField(serial_persistent_fields[i]);
Class field_type = serial_persistent_fields[i].getType();
if (field != null && !field.isAccessible()) {
temporary_field = field;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
if (field_type.isPrimitive()) {
if (field_type == Boolean.TYPE) {
boolean_fields[boolean_count++] = field;
} else if (field_type == Character.TYPE) {
char_fields[char_count++] = field;
} else if (field_type == Byte.TYPE) {
byte_fields[byte_count++] = field;
} else if (field_type == Short.TYPE) {
short_fields[short_count++] = field;
} else if (field_type == Integer.TYPE) {
int_fields[int_count++] = field;
} else if (field_type == Long.TYPE) {
long_fields[long_count++] = field;
} else if (field_type == Float.TYPE) {
float_fields[float_count++] = field;
} else if (field_type == Double.TYPE) {
double_fields[double_count++] = field;
}
} else {
reference_fields[reference_count++] = field;
}
}
}
// Now resize the datastructures.
int size = double_count + long_count + float_count + int_count
+ short_count + char_count + byte_count + boolean_count
+ reference_count;
int index = 0;
if (size > 0) {
serializable_fields = new Field[size];
System.arraycopy(double_fields, 0, serializable_fields, index,
double_count);
index += double_count;
System.arraycopy(long_fields, 0, serializable_fields, index,
long_count);
index += long_count;
System.arraycopy(float_fields, 0, serializable_fields, index,
float_count);
index += float_count;
System.arraycopy(int_fields, 0, serializable_fields, index,
int_count);
index += int_count;
System.arraycopy(short_fields, 0, serializable_fields, index,
short_count);
index += short_count;
System.arraycopy(char_fields, 0, serializable_fields, index,
char_count);
index += char_count;
System.arraycopy(byte_fields, 0, serializable_fields, index,
byte_count);
index += byte_count;
System.arraycopy(boolean_fields, 0, serializable_fields, index,
boolean_count);
index += boolean_count;
System.arraycopy(reference_fields, 0, serializable_fields,
index, reference_count);
fields_final = new boolean[size];
for (int i = 0; i < size; i++) {
if (serializable_fields[i] != null) {
fields_final[i]
= ((serializable_fields[i].getModifiers()
& Modifier.FINAL) != 0);
} else {
fields_final[i] = false;
}
}
} else {
serializable_fields = null;
}
} catch (Exception e) {
throw new SerializationError("Cannot initialize serialization "
+ "info for " + clazz.getName(), e);
}
}
/**
* Looks for a declaration of serialPersistentFields, and, if present,
* makes it accessible, and stores it in
* <code>serial_persistent_fields</code>.
*/
private void getSerialPersistentFields() {
try {
Field f = clazz.getDeclaredField("serialPersistentFields");
int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
if (!f.isAccessible()) {
temporary_field = f;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
temporary_field.setAccessible(true);
return null;
}
});
}
serial_persistent_fields
= (java.io.ObjectStreamField[]) f.get(null);
}
} catch (Exception e) {
// ignored, no serialPersistentFields
}
}
/**
* Gets the field with fieldname indicated by the name in <code>of</code>.
* If not present, returns <code>null</code>.
*/
private Field findField(ObjectStreamField of) {
try {
return clazz.getDeclaredField(of.getName());
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* Gets the index of a field with name <code>name</code> and type
* <code>tp</code> in either <code>SerialPersistentFields</code>, if
* it exists, or in the <code>serializable_fields</code> array.
* An exception is thrown when such a field is not found.
*
* @param name name of the field we are looking for
* @param tp type of the field we are looking for
* @return index in either <code>serial_persistent_fields</code> or
* <code>serializable_fields</code>.
* @exception IllegalArgumentException when no such field is found.
*/
int getOffset(String name, Class tp) throws IllegalArgumentException {
int offset = 0;
if (tp.isPrimitive()) {
if (serial_persistent_fields != null) {
for (int i = 0; i < serial_persistent_fields.length; i++) {
if (serial_persistent_fields[i].getType() == tp) {
if (name.equals(
serial_persistent_fields[i].getName())) {
return offset;
}
offset++;
}
}
} else if (serializable_fields != null) {
for (int i = 0; i < serializable_fields.length; i++) {
if (serializable_fields[i].getType() == tp) {
if (name.equals(serializable_fields[i].getName())) {
return offset;
}
offset++;
}
}
}
} else {
if (serial_persistent_fields != null) {
for (int i = 0; i < serial_persistent_fields.length; i++) {
if (!serial_persistent_fields[i].getType().isPrimitive()) {
if (name.equals(serial_persistent_fields[i].getName())) {
return offset;
}
offset++;
}
}
} else if (serializable_fields != null) {
for (int i = 0; i < serializable_fields.length; i++) {
if (!serializable_fields[i].getType().isPrimitive()) {
if (name.equals(serializable_fields[i].getName())) {
return offset;
}
offset++;
}
}
}
}
throw new IllegalArgumentException("no field named " + name
+ " with type " + tp);
}
}
| fixed import
git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@2899 aaf88347-d911-0410-b711-e54d386773bb
| src/ibis/io/AlternativeTypeInfo.java | fixed import | <ide><path>rc/ibis/io/AlternativeTypeInfo.java
<ide>
<ide> package ibis.io;
<ide>
<del>import java.io.IOException;
<ide> import java.io.ObjectInputStream;
<ide> import java.io.ObjectOutputStream;
<ide> import java.io.ObjectStreamClass; |
|
Java | mit | daac392107f3a9694b565f6c6c26b02e9c04034e | 0 | RangerWolf/Finance-News-Helper,RangerWolf/Finance-News-Helper,RangerWolf/Finance-News-Helper | package utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler;
public class MiscUtils {
public static List<String> mergeKeywordList(List<String> list) {
List<String> retList = Lists.newArrayList();
String tmp = "";
for(String word : list) {
if((tmp.length() + word.length()) < Constants.MAX_QUERY_WORDING_LEN) {
if(tmp.trim().length() == 0) tmp = word;
else tmp = tmp + " | " + word;
} else {
retList.add(tmp);
tmp = word;
}
}
retList.add(tmp);
return retList;
}
/**
* 简单的从目标地址进行网页源码采集
* @param urlTemplate
* @param queryWord
* @param charset
* @return
*/
public static String simpleJsoupGet(String urlTemplate, String queryWord, String charset) {
try {
String word = queryWord;
word = URLEncoder.encode(queryWord, charset);
String url = String.format(urlTemplate, word);
System.out.println("URL=" + url);
String ret = Jsoup.connect(url)
.header("Content-Type", "application/x-javascript; charset=" + charset)
.ignoreContentType(true)
.get().text();
return ret;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 在目标列表之中是否存在类似的字符串 阈值:0.75
* @param newStr 新的一个字符串
* @param targetList 目标字符串列表
* @return 是否存在类似的字符串
*/
public static boolean hasSimilarStr(String newStr, List<String> targetList) {
boolean hasSimilarStr = false;
JaroWinkler algorithm = new JaroWinkler();
if(targetList == null || targetList.size() == 0 ) return false;
for(String str : targetList) {
if(algorithm.getSimilarity(newStr, str) > 0.75) {
hasSimilarStr = true;
break;
}
}
return hasSimilarStr;
}
public static void enableProxy() {
System.setProperty("http.proxyHost", "cnnjproxy-ha.tw.trendnet.org"); // set proxy server
System.setProperty("http.proxyPort", "8080"); // set proxy port
}
public static void enableProxy(String host, String port) {
System.setProperty("http.proxyHost", host); // set proxy server
System.setProperty("http.proxyPort", port); // set proxy port
}
public static void disableProxy() {
try {
System.out.println(System.getProperty("http.proxyHost"));
System.setProperty("http.proxyHost", null);
} catch(Exception e) {
e.printStackTrace();
}
}
public final static String getHostName() {
String hostName = "unknown";
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
hostName =addr.getHostName().toString();//获得本机名称
} catch (UnknownHostException e) {
e.printStackTrace();
}
return hostName;
}
public final static String MD5(String s) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| src/utils/MiscUtils.java | package utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler;
public class MiscUtils {
public static List<String> mergeKeywordList(List<String> list) {
List<String> retList = Lists.newArrayList();
String tmp = "";
for(String word : list) {
if((tmp.length() + word.length()) < Constants.MAX_QUERY_WORDING_LEN) {
if(tmp.trim().length() == 0) tmp = word;
else tmp = tmp + " | " + word;
} else {
retList.add(tmp);
tmp = word;
}
}
retList.add(tmp);
return retList;
}
/**
* 简单的从目标地址进行网页源码采集
* @param urlTemplate
* @param queryWord
* @param charset
* @return
*/
public static String simpleJsoupGet(String urlTemplate, String queryWord, String charset) {
try {
String word = queryWord;
word = URLEncoder.encode(queryWord, charset);
String url = String.format(urlTemplate, word);
System.out.println("URL=" + url);
String ret = Jsoup.connect(url)
.header("Content-Type", "application/x-javascript; charset=" + charset)
.ignoreContentType(true)
.get().text();
return ret;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 在目标列表之中是否存在类似的字符串 阈值:0.85
* @param newStr 新的一个字符串
* @param targetList 目标字符串列表
* @return 是否存在类似的字符串
*/
public static boolean hasSimilarStr(String newStr, List<String> targetList) {
boolean hasSimilarStr = false;
JaroWinkler algorithm = new JaroWinkler();
if(targetList == null || targetList.size() == 0 ) return false;
for(String str : targetList) {
if(algorithm.getSimilarity(newStr, str) > 0.85) {
hasSimilarStr = true;
break;
}
}
return hasSimilarStr;
}
public static void enableProxy() {
System.setProperty("http.proxyHost", "cnnjproxy-ha.tw.trendnet.org"); // set proxy server
System.setProperty("http.proxyPort", "8080"); // set proxy port
}
public static void enableProxy(String host, String port) {
System.setProperty("http.proxyHost", host); // set proxy server
System.setProperty("http.proxyPort", port); // set proxy port
}
public static void disableProxy() {
try {
System.out.println(System.getProperty("http.proxyHost"));
System.setProperty("http.proxyHost", null);
} catch(Exception e) {
e.printStackTrace();
}
}
public final static String getHostName() {
String hostName = "unknown";
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
hostName =addr.getHostName().toString();//获得本机名称
} catch (UnknownHostException e) {
e.printStackTrace();
}
return hostName;
}
public final static String MD5(String s) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| 进一步降低相似度 | src/utils/MiscUtils.java | 进一步降低相似度 | <ide><path>rc/utils/MiscUtils.java
<ide> }
<ide>
<ide> /**
<del> * 在目标列表之中是否存在类似的字符串 阈值:0.85
<add> * 在目标列表之中是否存在类似的字符串 阈值:0.75
<ide> * @param newStr 新的一个字符串
<ide> * @param targetList 目标字符串列表
<ide> * @return 是否存在类似的字符串
<ide> JaroWinkler algorithm = new JaroWinkler();
<ide> if(targetList == null || targetList.size() == 0 ) return false;
<ide> for(String str : targetList) {
<del> if(algorithm.getSimilarity(newStr, str) > 0.85) {
<add> if(algorithm.getSimilarity(newStr, str) > 0.75) {
<ide> hasSimilarStr = true;
<ide> break;
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/test/java/javascalautils/OptionAsserts.java' did not match any file(s) known to git
| dac09183ae38c7dbdefb3768cf38a607c9e66211 | 1 | pnerg/java-scala-util | /*
* Created : 9/8/16
*
* Copyright (c) 2016 Ericsson AB, Sweden.
* All rights reserved.
* The Copyright to the computer program(s) herein is the property of Ericsson AB, Sweden.
* The program(s) may be used and/or copied with the written permission from Ericsson AB
* or in accordance with the terms and conditions stipulated in the agreement/contract
* under which the program(s) have been supplied.
*/
package javascalautils;
import org.junit.Assert;
/**
* Utility asserts related to the {@link javascalautils.Try} class.
* @author Peter Nerg.
* @since 1.10
*/
public interface OptionAsserts {
/**
* Asserts that the provided Option is defined.
* @param o The option to assert
*/
default void assertIsDefined(Option<?> o) {
Assert.assertTrue("The Option was not defined", o.isDefined());
}
/**
* Asserts that the provided Option is defined.
* @param o The option to assert
*/
default void assertIsNotDefined(Option<?> o) {
Assert.assertFalse("The Option ["+o+"] was defined", o.isDefined());
}
}
| src/test/java/javascalautils/OptionAsserts.java | added test interface OptionAsserts
| src/test/java/javascalautils/OptionAsserts.java | added test interface OptionAsserts | <ide><path>rc/test/java/javascalautils/OptionAsserts.java
<add>/*
<add> * Created : 9/8/16
<add> *
<add> * Copyright (c) 2016 Ericsson AB, Sweden.
<add> * All rights reserved.
<add> * The Copyright to the computer program(s) herein is the property of Ericsson AB, Sweden.
<add> * The program(s) may be used and/or copied with the written permission from Ericsson AB
<add> * or in accordance with the terms and conditions stipulated in the agreement/contract
<add> * under which the program(s) have been supplied.
<add> */
<add>package javascalautils;
<add>
<add>import org.junit.Assert;
<add>
<add>/**
<add> * Utility asserts related to the {@link javascalautils.Try} class.
<add> * @author Peter Nerg.
<add> * @since 1.10
<add> */
<add>public interface OptionAsserts {
<add>
<add> /**
<add> * Asserts that the provided Option is defined.
<add> * @param o The option to assert
<add> */
<add> default void assertIsDefined(Option<?> o) {
<add> Assert.assertTrue("The Option was not defined", o.isDefined());
<add> }
<add>
<add> /**
<add> * Asserts that the provided Option is defined.
<add> * @param o The option to assert
<add> */
<add> default void assertIsNotDefined(Option<?> o) {
<add> Assert.assertFalse("The Option ["+o+"] was defined", o.isDefined());
<add> }
<add>} |
|
Java | mit | b8cdf064cb5b4a33be4d6b4e2cc9b6f9495792eb | 0 | RJ45toCerebrum/AndroidProgramming | package com.example.tylerheers.molebuilderproto;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openscience.cdk.config.Elements;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IBond;
import org.rajawali3d.view.ISurface;
import org.rajawali3d.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
//TODO: Molecule information card; if available
//TODO: Fix Bond distances and add colors and better text of the atoms in 2D-renderer; make more visually pleasing when zooming in/ out
//TODO: make the selection tool better via; drag box selection
//TODO: Make tool bar on the toolbar slide-able instead it it always being there
//TODO: Undo actions --> Undoable actions include: 1) adding atoms/molecules, 2) removing atoms/molecules, 3) adding bonds
//TODO: More atom information in the 3D renderer such as: Dipole, Charge or each atoms, atom names, and electron cloud surface
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,
IAsyncResult<String>,
SceneContainer.SceneChangeListener
{
enum Mode
{
AddAtom, Selection, PanZoom
}
public static int maxAtoms = 30;
public static int maxSelectedAtoms = 10;
Mode currentMode = Mode.AddAtom;
View selectedButton = null;
SceneContainer sceneContainer;
private TextView sceneText;
private RelativeLayout canvasLayout;
private LinearLayout toolbarLayout;
private int toolBarWidth;
private SurfaceView surfView;
private MoleRenderer2D moleRenderer;
private MoleRenderer3D moleRenderer3D;
private List<View> modeButtons;
private SearchMoleDialog diag;
private ProgressBar convertMoleProgress;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sceneContainer = SceneContainer.getInstance();
sceneContainer.addSceneChangeListener(this);
ImageButton searchMoleButton = (ImageButton) findViewById(R.id.startMoleSearch);
searchMoleButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
currentMode = Mode.Selection;
updateModeButtonColors();
diag = new SearchMoleDialog();
diag.setRenderer2D(moleRenderer);
diag.show(getFragmentManager(), "123");
}
});
canvasLayout = (RelativeLayout) findViewById(R.id.canvasLayout);
toolbarLayout = (LinearLayout) findViewById(R.id.toolBarLayout);
toolBarWidth = toolbarLayout.getLayoutParams().width;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
sceneText = (TextView) findViewById(R.id.sceneInfoTextView);
updateSceneText();
}
ImageButton helpDiagButton = (ImageButton) findViewById(R.id.helpButton);
helpDiagButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HelpDialog helpDialog = new HelpDialog();
helpDialog.show(getFragmentManager(), "123");
}
});
initRenderer2D();
initModeButtons();
initImmediateActionButtons();
updateModeButtonColors();
// Test Code to delete
//TestCode();
}
protected void onPause() {
super.onPause();
}
protected void onResume()
{
super.onResume();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
sceneText = (TextView)findViewById(R.id.sceneInfoTextView);
}
}
private void initModeButtons()
{
modeButtons = new ArrayList<>(12);
LinearLayout atomButtonLayout = (LinearLayout)findViewById(R.id.atomScrollViewLayout);
String[] elementsArray = getResources().getStringArray(R.array.elements);
for(String e : elementsArray)
{
AtomButton button = null;
switch (e)
{
case "hydrogen":
button = new AtomButton(this);
button.setElement(Elements.Hydrogen);
button.setText(Elements.HYDROGEN.getSymbol());
break;
case "carbon":
button = new AtomButton(this);
button.setElement(Elements.Carbon);
button.setText(Elements.CARBON.getSymbol());
break;
case "nitrogen":
button = new AtomButton(this);
button.setElement(Elements.Nitrogen);
button.setText(Elements.NITROGEN.getSymbol());
break;
case "oxygen":
button = new AtomButton(this);
button.setElement(Elements.Oxygen);
button.setText(Elements.OXYGEN.getSymbol());
break;
case "phosphorus":
button = new AtomButton(this);
button.setElement(Elements.Phosphorus);
button.setText(Elements.PHOSPHORUS.getSymbol());
break;
case "sulfur":
button = new AtomButton(this);
button.setElement(Elements.Sulfur);
button.setText(Elements.SULFUR.getSymbol());
break;
}
if(button == null)
continue;
button.setLayoutParams(atomButtonLayout.getLayoutParams());
button.getLayoutParams().height = 190;
button.setClickable(true);
button.setOnClickListener(this);
atomButtonLayout.addView(button);
modeButtons.add(button);
}
initPeriodicTableButton();
ImageButton selectionButton = (ImageButton) findViewById(R.id.selectionButton);
selectionButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
currentMode = Mode.Selection;
selectedButton = v;
updateModeButtonColors();
}
});
selectionButton.setElevation(7);
// this is to get the view at the bottom of the linear layout
// even though its defined in the xml
atomButtonLayout.removeView(selectionButton);
atomButtonLayout.addView(selectionButton);
modeButtons.add(selectionButton);
ImageButton panZoomButton = (ImageButton)findViewById(R.id.panZoomButton);
panZoomButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
currentMode = Mode.PanZoom;
selectedButton = v;
updateModeButtonColors();
}
});
panZoomButton.setElevation(7);
atomButtonLayout.removeView(panZoomButton);
atomButtonLayout.addView(panZoomButton);
modeButtons.add(panZoomButton);
}
private void initPeriodicTableButton()
{
LinearLayout atomButtonLayout = (LinearLayout)findViewById(R.id.atomScrollViewLayout);
ImageButton periodicTableButton = new ImageButton(this);
periodicTableButton.setImageResource(R.drawable.periodic_table);
periodicTableButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
periodicTableButton.setLayoutParams(atomButtonLayout.getLayoutParams());
periodicTableButton.getLayoutParams().height = 220;
atomButtonLayout.addView(periodicTableButton);
periodicTableButton.setClickable(true);
periodicTableButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
currentMode = Mode.AddAtom;
selectedButton = v;
PeriodicTable pt = PeriodicTable.newInstance(0);
pt.setMainActivity((MainActivity) v.getContext());
pt.show(getFragmentManager(), "123");
}
});
periodicTableButton.setElevation(7);
modeButtons.add(periodicTableButton);
}
private void initImmediateActionButtons()
{
ImageButton singleBondButton = (ImageButton) findViewById(R.id.singleBondButton);
singleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.SINGLE);
}
});
ImageButton doubleBondButton = (ImageButton) findViewById(R.id.doubleBondButton);
doubleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.DOUBLE);
}
});
ImageButton tripleBondButton = (ImageButton) findViewById(R.id.tripleBondButton);
tripleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.TRIPLE);
}
});
ImageButton deleteAtom = (ImageButton) findViewById(R.id.deleteButton);
deleteAtom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.deleteSelected();
}
});
ImageButton deleteSweep = (ImageButton) findViewById(R.id.deleteSweepButton);
deleteSweep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sceneContainer.clearScene();
moleRenderer.updateBitmap();
}
});
init3DButton();
}
private void init3DButton()
{
ImageButton to3DButton = (ImageButton) findViewById(R.id.to3DButton);
to3DButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Animation buttonRotationAnim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_up_down);
buttonRotationAnim.setDuration(1000);
v.startAnimation(buttonRotationAnim);
if(moleRenderer3D == null)
{
if (sceneContainer.selectedMolecule == null) {
Toast.makeText(MainActivity.this,
"Must have a Molecule selected to Render in 3D",
Toast.LENGTH_SHORT).show();
return;
}
sendTo3DRenderer();
}
else
initRenderer2D();
}
});
float centreX = to3DButton.getX() + to3DButton.getWidth() / 2;
float centerY = to3DButton.getY() + to3DButton.getHeight() / 2;
to3DButton.setPivotX(centreX);
to3DButton.setPivotY(centerY);
}
private void initRenderer2D()
{
showToolBar(true);
canvasLayout.removeAllViewsInLayout();
moleRenderer3D = null;
moleRenderer = new MoleRenderer2D(this);
canvasLayout.addView(moleRenderer);
}
private void initRenderer3D(IAtomContainer mole)
{
showToolBar(false);
canvasLayout.removeAllViewsInLayout();
moleRenderer = null;
moleRenderer3D= null;
try {
moleRenderer3D = new MoleRenderer3D(this, mole);
}
catch (Exception e){
Log.e("Could not construct", e.getMessage());
initRenderer2D();
return;
}
surfView = new SurfaceView(this);
surfView.setRenderMode(ISurface.RENDERMODE_WHEN_DIRTY);
surfView.setSurfaceRenderer(moleRenderer3D);
surfView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
moleRenderer3D.onTouchEvent(event);
return true; //processed
}
});
if(surfView != null)
canvasLayout.addView(surfView);
}
private void initProgressBar()
{
convertMoleProgress = new ProgressBar(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
convertMoleProgress.setLayoutParams(params);
convertMoleProgress.setIndeterminate(true);
canvasLayout.addView(convertMoleProgress);
}
private void sendTo3DRenderer()
{
try
{
IAtomContainer container = sceneContainer.selectedMolecule.clone();
String smilesStr = Molecule.generateSmilesString(container);
String url = String.format(
"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/SDF?record_type=3d",
smilesStr);
new PostRequest(this).execute(url);
initProgressBar();
}
catch (CloneNotSupportedException ex) {
Log.e("Clone Exception", ex.getMessage());
}
catch (CDKException ex) {
Log.e("CDK Smiles Exception", ex.getMessage());
}
catch (Exception ex){
Log.e("Exception", ex.getMessage());
}
}
private void updateModeButtonColors()
{
for (View v: modeButtons)
{
if(v == selectedButton)
v.setBackgroundTintMode(PorterDuff.Mode.DARKEN);
else
v.setBackgroundTintMode(PorterDuff.Mode.LIGHTEN);
}
}
public void setSelectedButton(View v){
updateModeButtonColors();
selectedButton = v;
}
public Mode getCurrentMode() {return currentMode;}
public Elements getCurrentElement()
{
if(currentMode == Mode.AddAtom && selectedButton != null) {
AtomButton ab = (AtomButton) selectedButton;
return ab.getElement();
}
return null;
}
private void updateSceneText()
{
if(sceneText != null)
{
String numAtomsText = String.format("Number of Atoms: %d", sceneContainer.getAtomCount());
String numBondsText = String.format("\tNumber of Bonds: %d\n", sceneContainer.getBondCount());
String numMoleculesText = String.format("Number of Molecules: %d", sceneContainer.getMoleculeCount());
numAtomsText += numBondsText + numMoleculesText;
sceneText.setText(numAtomsText);
}
}
private void showToolBar(boolean show)
{
if(show) {
toolbarLayout.setVisibility(View.VISIBLE);
ViewGroup.LayoutParams layoutParams = toolbarLayout.getLayoutParams();
layoutParams.width = toolBarWidth;
}
else {
toolbarLayout.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams layoutParams = toolbarLayout.getLayoutParams();
layoutParams.width = 0;
}
}
@Override
public void onPostExecute(String results)
{
if(results == null) {
Toast.makeText(this, "Could not find molecule", Toast.LENGTH_LONG).show();
initRenderer2D();
return;
}
showToolBar(false);
IAtomContainer molecule = SdfConverter.convertSDFString(results);
if(molecule != null)
initRenderer3D(molecule);
else
Toast.makeText(this, "Sorry, Could not construct Molecule", Toast.LENGTH_LONG).show();
convertMoleProgress = null;
}
// onClick executed when atom buttons clicked
@Override
public void onClick(View v)
{
currentMode = Mode.AddAtom;
selectedButton = v;
updateModeButtonColors();
}
@Override
public void atomNumberChanged() {
updateSceneText();
}
@Override
public void bondNumberChanged() {
updateSceneText();
}
@Override
public void moleculeNumberChanged() {
updateSceneText();
}
public void TestCode()
{
// 1) Name, cid, Formula, Description
// 2) Image
// 3) smiles
ImageButton infoCard = (ImageButton) findViewById(R.id.testingInfoCardButton);
infoCard.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new PostRequest(new IAsyncResult<String>()
{
@Override
public void onPostExecute(String result)
{
Log.i("Result", " " + result);
// String findStr = "\"DescriptionURL\": ";
// int index = result.indexOf(findStr, 120);
// if (index != -1) {
// int index2 = result.indexOf("\n", index);
// if (index2 != -1) {
// Log.i("description", result.substring(index + findStr.length(), index2));
// }
// }
if(result != null)
{
try
{
JSONObject descriptionJson = new JSONObject(result);
JSONArray info = descriptionJson.getJSONObject("InformationList").getJSONArray("Information");
JSONObject cid_title = info.getJSONObject(0);
Log.i("Cid", String.valueOf(cid_title.getInt("CID")));
Log.i("Title", cid_title.getString("Title"));
for(int i = 1; i < info.length(); i++)
{
Log.i("Record", String.format("Record %d", i));
JSONObject jo = info.getJSONObject(i);
Log.i("Descriptions", jo.getString("Description"));
Log.i("Descriptions", jo.getString("DescriptionSourceName"));
Log.i("Descriptions", jo.getString("DescriptionURL"));
}
}
catch (JSONException ex) {
Toast.makeText(MainActivity.this, "Unable to gather information on this Molecule. Check connection or Molecule ID",
Toast.LENGTH_LONG).show();
}
}
}
}).execute("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/Serine/description/JSON");
// replace space with %20
// https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/dopeamine/description/JSON" this is for descriptions
}
});
}
}
| MoleBuilderProto/app/src/main/java/com/example/tylerheers/molebuilderproto/MainActivity.java | package com.example.tylerheers.molebuilderproto;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openscience.cdk.Atom;
import org.openscience.cdk.config.Elements;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IBond;
import org.rajawali3d.view.ISurface;
import org.rajawali3d.view.SurfaceView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//TODO: Molecule information card; if available
//TODO: Fix Bond distances and add colors or better text of the atoms in 2D-renderer
//TODO: quick access sliding toolbar in the 2D renderer to quick access to the pan/move and selection tool
//TODO: Undo actions
//TODO: atom charge and name text in the 3D renderer
//TODO: make the selection tool better via; drag box selection
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,
IAsyncResult<String>,
SceneContainer.SceneChangeListener
{
enum Mode
{
AddAtom, Selection, PanZoom
}
public static int maxAtoms = 30;
public static int maxSelectedAtoms = 10;
Mode currentMode = Mode.AddAtom;
View selectedButton = null;
SceneContainer sceneContainer;
private TextView sceneText;
private RelativeLayout canvasLayout;
private LinearLayout toolbarLayout;
private int toolBarWidth;
private SurfaceView surfView;
private MoleRenderer2D moleRenderer;
private MoleRenderer3D moleRenderer3D;
private List<View> modeButtons;
private SearchMoleDialog diag;
private ProgressBar convertMoleProgress;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sceneContainer = SceneContainer.getInstance();
sceneContainer.addSceneChangeListener(this);
ImageButton searchMoleButton = (ImageButton) findViewById(R.id.startMoleSearch);
searchMoleButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
currentMode = Mode.Selection;
updateModeButtonColors();
diag = new SearchMoleDialog();
diag.setRenderer2D(moleRenderer);
diag.show(getFragmentManager(), "123");
}
});
canvasLayout = (RelativeLayout) findViewById(R.id.canvasLayout);
toolbarLayout = (LinearLayout) findViewById(R.id.toolBarLayout);
toolBarWidth = toolbarLayout.getLayoutParams().width;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
sceneText = (TextView) findViewById(R.id.sceneInfoTextView);
updateSceneText();
}
ImageButton helpDiagButton = (ImageButton) findViewById(R.id.helpButton);
helpDiagButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HelpDialog helpDialog = new HelpDialog();
helpDialog.show(getFragmentManager(), "123");
}
});
initRenderer2D();
initModeButtons();
initImmediateActionButtons();
updateModeButtonColors();
// Test Code to delete
TestCode();
}
protected void onPause() {
super.onPause();
}
protected void onResume()
{
super.onResume();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
sceneText = (TextView)findViewById(R.id.sceneInfoTextView);
}
}
private void initModeButtons()
{
modeButtons = new ArrayList<>(12);
LinearLayout atomButtonLayout = (LinearLayout)findViewById(R.id.atomScrollViewLayout);
String[] elementsArray = getResources().getStringArray(R.array.elements);
for(String e : elementsArray)
{
AtomButton button = null;
switch (e)
{
case "hydrogen":
button = new AtomButton(this);
button.setElement(Elements.Hydrogen);
button.setText(Elements.HYDROGEN.getSymbol());
break;
case "carbon":
button = new AtomButton(this);
button.setElement(Elements.Carbon);
button.setText(Elements.CARBON.getSymbol());
break;
case "nitrogen":
button = new AtomButton(this);
button.setElement(Elements.Nitrogen);
button.setText(Elements.NITROGEN.getSymbol());
break;
case "oxygen":
button = new AtomButton(this);
button.setElement(Elements.Oxygen);
button.setText(Elements.OXYGEN.getSymbol());
break;
case "phosphorus":
button = new AtomButton(this);
button.setElement(Elements.Phosphorus);
button.setText(Elements.PHOSPHORUS.getSymbol());
break;
case "sulfur":
button = new AtomButton(this);
button.setElement(Elements.Sulfur);
button.setText(Elements.SULFUR.getSymbol());
break;
}
if(button == null)
continue;
button.setLayoutParams(atomButtonLayout.getLayoutParams());
button.getLayoutParams().height = 190;
button.setClickable(true);
button.setOnClickListener(this);
atomButtonLayout.addView(button);
modeButtons.add(button);
}
initPeriodicTableButton();
ImageButton selectionButton = (ImageButton) findViewById(R.id.selectionButton);
selectionButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
currentMode = Mode.Selection;
selectedButton = v;
updateModeButtonColors();
}
});
selectionButton.setElevation(7);
// this is to get the view at the bottom of the linear layout
// even though its defined in the xml
atomButtonLayout.removeView(selectionButton);
atomButtonLayout.addView(selectionButton);
modeButtons.add(selectionButton);
ImageButton panZoomButton = (ImageButton)findViewById(R.id.panZoomButton);
panZoomButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
currentMode = Mode.PanZoom;
selectedButton = v;
updateModeButtonColors();
}
});
panZoomButton.setElevation(7);
atomButtonLayout.removeView(panZoomButton);
atomButtonLayout.addView(panZoomButton);
modeButtons.add(panZoomButton);
}
private void initPeriodicTableButton()
{
LinearLayout atomButtonLayout = (LinearLayout)findViewById(R.id.atomScrollViewLayout);
ImageButton periodicTableButton = new ImageButton(this);
periodicTableButton.setImageResource(R.drawable.periodic_table);
periodicTableButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
periodicTableButton.setLayoutParams(atomButtonLayout.getLayoutParams());
periodicTableButton.getLayoutParams().height = 220;
atomButtonLayout.addView(periodicTableButton);
periodicTableButton.setClickable(true);
periodicTableButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
currentMode = Mode.AddAtom;
selectedButton = v;
PeriodicTable pt = PeriodicTable.newInstance(0);
pt.setMainActivity((MainActivity) v.getContext());
pt.show(getFragmentManager(), "123");
}
});
periodicTableButton.setElevation(7);
modeButtons.add(periodicTableButton);
}
private void initImmediateActionButtons()
{
ImageButton singleBondButton = (ImageButton) findViewById(R.id.singleBondButton);
singleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.SINGLE);
}
});
ImageButton doubleBondButton = (ImageButton) findViewById(R.id.doubleBondButton);
doubleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.DOUBLE);
}
});
ImageButton tripleBondButton = (ImageButton) findViewById(R.id.tripleBondButton);
tripleBondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.addBond(IBond.Order.TRIPLE);
}
});
ImageButton deleteAtom = (ImageButton) findViewById(R.id.deleteButton);
deleteAtom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
moleRenderer.deleteSelected();
}
});
ImageButton deleteSweep = (ImageButton) findViewById(R.id.deleteSweepButton);
deleteSweep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sceneContainer.clearScene();
moleRenderer.updateBitmap();
}
});
init3DButton();
}
private void init3DButton()
{
ImageButton to3DButton = (ImageButton) findViewById(R.id.to3DButton);
to3DButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Animation buttonRotationAnim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_up_down);
buttonRotationAnim.setDuration(1000);
v.startAnimation(buttonRotationAnim);
if(moleRenderer3D == null)
{
if (sceneContainer.selectedMolecule == null) {
Toast.makeText(MainActivity.this,
"Must have a Molecule selected to Render in 3D",
Toast.LENGTH_SHORT).show();
return;
}
sendTo3DRenderer();
}
else
initRenderer2D();
}
});
float centreX = to3DButton.getX() + to3DButton.getWidth() / 2;
float centerY = to3DButton.getY() + to3DButton.getHeight() / 2;
to3DButton.setPivotX(centreX);
to3DButton.setPivotY(centerY);
}
private void initRenderer2D()
{
showToolBar(true);
canvasLayout.removeAllViewsInLayout();
moleRenderer3D = null;
moleRenderer = new MoleRenderer2D(this);
canvasLayout.addView(moleRenderer);
}
private void initRenderer3D(IAtomContainer mole)
{
showToolBar(false);
canvasLayout.removeAllViewsInLayout();
moleRenderer = null;
moleRenderer3D= null;
try {
moleRenderer3D = new MoleRenderer3D(this, mole);
}
catch (Exception e){
Log.e("Could not construct", e.getMessage());
initRenderer2D();
return;
}
surfView = new SurfaceView(this);
surfView.setRenderMode(ISurface.RENDERMODE_WHEN_DIRTY);
surfView.setSurfaceRenderer(moleRenderer3D);
surfView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
moleRenderer3D.onTouchEvent(event);
return true; //processed
}
});
if(surfView != null)
canvasLayout.addView(surfView);
}
private void initProgressBar()
{
convertMoleProgress = new ProgressBar(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
convertMoleProgress.setLayoutParams(params);
convertMoleProgress.setIndeterminate(true);
canvasLayout.addView(convertMoleProgress);
}
private void sendTo3DRenderer()
{
try
{
IAtomContainer container = sceneContainer.selectedMolecule.clone();
String smilesStr = Molecule.generateSmilesString(container);
String url = String.format(
"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/SDF?record_type=3d",
smilesStr);
new PostRequest(this).execute(url);
initProgressBar();
}
catch (CloneNotSupportedException ex) {
Log.e("Clone Exception", ex.getMessage());
}
catch (CDKException ex) {
Log.e("CDK Smiles Exception", ex.getMessage());
}
catch (Exception ex){
Log.e("Exception", ex.getMessage());
}
}
private void updateModeButtonColors()
{
for (View v: modeButtons)
{
if(v == selectedButton)
v.setBackgroundTintMode(PorterDuff.Mode.DARKEN);
else
v.setBackgroundTintMode(PorterDuff.Mode.LIGHTEN);
}
}
public void setSelectedButton(View v){
updateModeButtonColors();
selectedButton = v;
}
public Mode getCurrentMode() {return currentMode;}
public Elements getCurrentElement()
{
if(currentMode == Mode.AddAtom && selectedButton != null) {
AtomButton ab = (AtomButton) selectedButton;
return ab.getElement();
}
return null;
}
private void updateSceneText()
{
if(sceneText != null)
{
String numAtomsText = String.format("Number of Atoms: %d", sceneContainer.getAtomCount());
String numBondsText = String.format("\tNumber of Bonds: %d\n", sceneContainer.getBondCount());
String numMoleculesText = String.format("Number of Molecules: %d", sceneContainer.getMoleculeCount());
numAtomsText += numBondsText + numMoleculesText;
sceneText.setText(numAtomsText);
}
}
private void showToolBar(boolean show)
{
if(show) {
toolbarLayout.setVisibility(View.VISIBLE);
ViewGroup.LayoutParams layoutParams = toolbarLayout.getLayoutParams();
layoutParams.width = toolBarWidth;
}
else {
toolbarLayout.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams layoutParams = toolbarLayout.getLayoutParams();
layoutParams.width = 0;
}
}
@Override
public void onPostExecute(String results)
{
if(results == null) {
Toast.makeText(this, "Could not find molecule", Toast.LENGTH_LONG).show();
initRenderer2D();
return;
}
showToolBar(false);
IAtomContainer molecule = SdfConverter.convertSDFString(results);
if(molecule != null)
initRenderer3D(molecule);
else
Toast.makeText(this, "Sorry, Could not construct Molecule", Toast.LENGTH_LONG).show();
convertMoleProgress = null;
}
// onClick executed when atom buttons clicked
@Override
public void onClick(View v)
{
currentMode = Mode.AddAtom;
selectedButton = v;
updateModeButtonColors();
}
@Override
public void atomNumberChanged() {
updateSceneText();
}
@Override
public void bondNumberChanged() {
updateSceneText();
}
@Override
public void moleculeNumberChanged() {
updateSceneText();
}
public void TestCode()
{
// 1) Name, cid, Formula, Description
// 2) Image
// 3) smiles
ImageButton infoCard = (ImageButton) findViewById(R.id.testingInfoCardButton);
infoCard.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new PostRequest(new IAsyncResult<String>()
{
@Override
public void onPostExecute(String result)
{
Log.i("Result", " " + result);
// String findStr = "\"DescriptionURL\": ";
// int index = result.indexOf(findStr, 120);
// if (index != -1) {
// int index2 = result.indexOf("\n", index);
// if (index2 != -1) {
// Log.i("description", result.substring(index + findStr.length(), index2));
// }
// }
if(result != null)
{
try
{
JSONObject descriptionJson = new JSONObject(result);
JSONArray info = descriptionJson.getJSONObject("InformationList").getJSONArray("Information");
JSONObject cid_title = info.getJSONObject(0);
Log.i("Cid", String.valueOf(cid_title.getInt("CID")));
Log.i("Title", cid_title.getString("Title"));
for(int i = 1; i < info.length(); i++)
{
Log.i("Record", String.format("Record %d", i));
JSONObject jo = info.getJSONObject(i);
Log.i("Descriptions", jo.getString("Description"));
Log.i("Descriptions", jo.getString("DescriptionSourceName"));
Log.i("Descriptions", jo.getString("DescriptionURL"));
}
}
catch (JSONException ex) {
Toast.makeText(MainActivity.this, "Unable to gather information on this Molecule. Check connection or Molecule ID",
Toast.LENGTH_LONG).show();
}
}
}
}).execute("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/Serine/description/JSON");
// replace space with %20
// https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/dopeamine/description/JSON" this is for descriptions
}
});
}
}
| Preparing create info card functionality
| MoleBuilderProto/app/src/main/java/com/example/tylerheers/molebuilderproto/MainActivity.java | Preparing create info card functionality | <ide><path>oleBuilderProto/app/src/main/java/com/example/tylerheers/molebuilderproto/MainActivity.java
<ide>
<ide>
<ide> import android.content.res.Configuration;
<del>import android.graphics.Color;
<ide> import android.graphics.PorterDuff;
<ide> import android.support.v7.app.AppCompatActivity;
<ide> import android.os.Bundle;
<del>import android.text.Html;
<ide> import android.util.Log;
<ide> import android.view.MotionEvent;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import android.view.animation.Animation;
<ide> import android.view.animation.AnimationUtils;
<del>import android.widget.Button;
<ide> import android.widget.ImageButton;
<ide> import android.widget.ImageView;
<ide> import android.widget.LinearLayout;
<ide> import org.json.JSONArray;
<ide> import org.json.JSONException;
<ide> import org.json.JSONObject;
<del>import org.openscience.cdk.Atom;
<ide> import org.openscience.cdk.config.Elements;
<ide> import org.openscience.cdk.exception.CDKException;
<ide> import org.openscience.cdk.interfaces.IAtomContainer;
<ide> import org.rajawali3d.view.SurfaceView;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.HashMap;
<ide> import java.util.List;
<ide>
<ide>
<ide> //TODO: Molecule information card; if available
<del>//TODO: Fix Bond distances and add colors or better text of the atoms in 2D-renderer
<del>//TODO: quick access sliding toolbar in the 2D renderer to quick access to the pan/move and selection tool
<del>//TODO: Undo actions
<del>//TODO: atom charge and name text in the 3D renderer
<add>//TODO: Fix Bond distances and add colors and better text of the atoms in 2D-renderer; make more visually pleasing when zooming in/ out
<ide> //TODO: make the selection tool better via; drag box selection
<add>//TODO: Make tool bar on the toolbar slide-able instead it it always being there
<add>//TODO: Undo actions --> Undoable actions include: 1) adding atoms/molecules, 2) removing atoms/molecules, 3) adding bonds
<add>//TODO: More atom information in the 3D renderer such as: Dipole, Charge or each atoms, atom names, and electron cloud surface
<ide> public class MainActivity extends AppCompatActivity
<ide> implements View.OnClickListener,
<ide> IAsyncResult<String>,
<ide> updateModeButtonColors();
<ide>
<ide> // Test Code to delete
<del> TestCode();
<add> //TestCode();
<ide> }
<ide>
<ide> protected void onPause() { |
|
JavaScript | mit | bb1de1e845afca195bc008dce3e514a72cf2bbb6 | 0 | RodgerLeblanc/LoveVectorStream | "use strict";
var useConfig = true; // set to false to pass config in debug
var request = require('request');
var VectorWatch = require('vectorwatch-sdk');
var vectorWatch = new VectorWatch();
var logger = vectorWatch.logger;
var cloudantUrl = 'your_own_cloudant_database_url' + process.env.STREAM_UUID;
var cloudantDbDocument = {};
if (!cloudantDbDocument.messages) {
try {
getCloudantDbDocument();
} catch (err) {
logger.error('Error with Cloudant: ' + err.message);
}
}
vectorWatch.on('config', function(event, response) {
logger.info('on config');
if (useConfig) {
var message = response.createAutocomplete('Message');
message.setHint('Enter your love message to share to the world. Make it short and sweet! (ie: Love touching your wrist)');
message.setAsYouType(1);
addOptionForOldMessage(event, message);
// Add love message samples
/*
message.addOption('I love you');
message.addOption('You are special to me');
message.addOption('Your wrist is wonderful');
*/
var update = response.createGridList('Update');
update.setHint('How many minutes before updating your stream with a new love message?');
update.addOption('1');
update.addOption('5');
update.addOption('15');
update.addOption('60');
update.addOption('120');
}
response.send();
});
function addOptionForOldMessage(event, message) {
var oldMessage;
try {
var userKey = event.req.body.userKey;
if (cloudantDbDocument.messages) {
var keys = Object.keys(cloudantDbDocument.messages);
for (var i in keys) {
var key = keys[i];
if (cloudantDbDocument.messages[key].userKey === userKey) {
oldMessage = cloudantDbDocument.messages[key].message;
break;
}
}
}
} catch(err) {
logger.error('Error getting channelLabel: ' + JSON.stringify(event) + '\n' + err.message);
}
if (oldMessage) {
message.addOption(oldMessage);
}
}
vectorWatch.on('options', function(event, response) {
});
vectorWatch.on('subscribe', function(event, response) {
logger.info('on subscribe: ' + event.channelLabel);
if (!useConfig) {
// For debug only
var userSettings = JSON.parse('{"Message":{"name":"Love you"},"Update":{"name":"1"}}');
event.userSettings.settings = userSettings;
}
try {
// Update Cloudant DB if new love message is different than the one in Cloudant DB for this user
var key = event.channelLabel;
if (!cloudantDbDocument.messages[key] || !cloudantDbDocument.messages[key].message) {
cloudantDbDocument.messages[key] = JSON.parse('{"message":"","lastUpdateTime":0}');
}
cloudantDbDocument.messages[key]["userKey"] = event.req.body.userKey;
var banned = cloudantDbDocument.banned;
if (banned.some(function(e, i, a) { return e === key; })) {
response.setValue('-Banned-');
response.send();
return;
}
var messageFromUserSettings = event.userSettings.settings.Message.name;
var messageFromCloudant = cloudantDbDocument.messages[key].message;
if (messageFromUserSettings !== messageFromCloudant) {
cloudantDbDocument.messages[key].message = messageFromUserSettings;
updateCloudantDb().catch(function(e) {
try {
// Retry once again, but update document first to get latest _rev
getCloudantDbDocument()
.then(function(body) {
cloudantDbDocument.messages[key].message = messageFromUserSettings;
updateCloudantDb().catch(function(e) {
logger.error('Second error trying to update Cloudant DB: ' + e);
})
});
} catch(err) {
logger.error('Error getting Cloudant DB document: ' + err.message);
}
});
}
} catch(err) {
logger.error('Error updating cloudant: ' + err.message);
}
var streamText = getRandomLoveMessage();
cloudantDbDocument.messages[key]["lastUpdateTime"] = Date.now;
response.setValue(streamText);
response.send();
});
vectorWatch.on('unsubscribe', function(event, response) {
logger.info('on unsubscribe: ' + event.channelLabel);
response.send();
});
vectorWatch.on('schedule', function(records) {
logger.info('on schedule');
if (records.length <= 0) { return; }
var forceUpdate = false;
updateStreamForEveryRecord(records, forceUpdate);
});
vectorWatch.on('webhook', function(event, response, records) {
logger.info('on webhook');
var forceUpdate = true;
try {
getCloudantDbDocument()
.then(updateStreamForEveryRecord(records, forceUpdate));
} catch(err) {
logger.error('Error getting Cloudant DB');
updateStreamForEveryRecord(records, forceUpdate);
}
response.setContentType('text/plain');
response.statusCode = 200;
response.setContent('Ok');
response.send();
});
function updateStreamForEveryRecord(records, forceUpdate) {
var streamText = getRandomLoveMessage();
records.forEach(function(record) {
try {
logger.info('record: ' + JSON.stringify(record));
var key = record.channelLabel;
if (!cloudantDbDocument.messages[key] || cloudantDbDocument.messages[key].lastUpdateTime === undefined) {
var messageObject = {};
messageObject['message'] = record.userSettings.Message.name;
messageObject['lastUpdateTime'] = 0;
messageObject['userKey'] = key;
cloudantDbDocument.messages[key] = messageObject;
}
var banned = cloudantDbDocument.banned;
if (banned.some(function(e, i, a) { return e === key; })) {
record.pushUpdate('-Banned-');
return;
}
var userSettings = record.userSettings;
var updateTimeInMs = parseInt(userSettings.Update.name) * 60 * 1000 - (10 * 1000); // 10 secs margin
var lastUpdateTime = cloudantDbDocument.messages[key].lastUpdateTime || 0;
var difference = Date.now - lastUpdateTime;
if ((difference > updateTimeInMs) || forceUpdate) {
record.pushUpdate(streamText);
cloudantDbDocument.messages[key].lastUpdateTime = Date.now;
}
} catch(err) {
logger.error('Error while updating record ' + record.channelLabel + ': ' + record.userSettings);
logger.error('Error message: ' + err.message);
}
});
}
function getRandomLoveMessage() {
var returnedMessage;
try {
var keys = Object.keys(cloudantDbDocument.messages);
logger.info('keys: ' + JSON.stringify(keys));
var randomIndex = Math.floor(Math.random() * keys.length);
logger.info('randomIndex: ' + randomIndex);
var key = keys[randomIndex];
logger.info('key: ' + key);
logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
returnedMessage = cloudantDbDocument.messages[key].message.replace(/love|heart|aime|coeur/gi, String.fromCharCode(0xe033));
logger.info('returnedMessage: ' + returnedMessage);
} catch(err) {
logger.error('Error while getting random love message');
}
return returnedMessage || "You're lovely";
}
function getCloudantDbDocument() {
return new Promise(function(resolve, reject) {
request(cloudantUrl, function(error, httpResponse, body) {
if (error) {
reject('Error calling ' + cloudantUrl + ': ' + error.message);
return;
}
if (httpResponse && httpResponse.statusCode !== 200) {
reject('Status code error for ' + cloudantUrl + ': ' + httpResponse.statusCode);
return;
}
try {
logger.info('response: ' + body);
cloudantDbDocument = JSON.parse(body);
logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
} catch(err) {
logger.info('Error parsing JSON response');
}
});
});
}
function updateCloudantDb() {
return new Promise(function(resolve, reject) {
request.put({
url: cloudantUrl,
body: JSON.stringify(cloudantDbDocument)
}, function(error, httpResponse, body) {
if (error) {
reject('Error calling ' + cloudantUrl + ': ' + error.message);
return;
}
if (httpResponse && httpResponse.statusCode !== 200) {
reject('Status code error for ' + cloudantUrl + ': ' + httpResponse.statusCode);
return;
}
try {
logger.info('response: ' + body);
body = JSON.parse(body);
cloudantDbDocument._rev = body.rev;
logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
} catch(err) {
logger.info('Error parsing JSON response');
}
});
});
}
| Love.js | "use strict";
var useConfig = true; // set to false to pass config in debug
var request = require('request');
var VectorWatch = require('vectorwatch-sdk');
var vectorWatch = new VectorWatch();
var logger = vectorWatch.logger;
var cloudantUrl = 'your_own_cloudant_database_url' + process.env.STREAM_UUID;
var cloudantDbDocument = {};
if (!cloudantDbDocument.messages) {
try {
getCloudantDbDocument();
} catch (err) {
logger.error('Error with Cloudant: ' + err.message);
}
}
vectorWatch.on('config', function(event, response) {
logger.info('on config');
if (useConfig) {
var message = response.createAutocomplete('Message');
message.setHint('Enter your love message to share to the world. Make it short and sweet! (ie: Love touching your wrist)');
message.setAsYouType(1);
addOptionForOldMessage(event, message);
// Add love message samples
/*
message.addOption('I love you');
message.addOption('You are special to me');
message.addOption('Your wrist is wonderful');
*/
var update = response.createGridList('Update');
update.setHint('How many minutes before updating your stream with a new love message?');
update.addOption('1');
update.addOption('5');
update.addOption('15');
update.addOption('60');
update.addOption('120');
}
response.send();
});
function addOptionForOldMessage(event, message) {
var oldMessage;
try {
var userKey = event.req.body.userKey;
if (cloudantDbDocument.messages) {
var keys = Object.keys(cloudantDbDocument.messages);
for (var i in keys) {
var key = keys[i];
if (cloudantDbDocument.messages[key].userKey === userKey) {
oldMessage = cloudantDbDocument.messages[key].message;
break;
}
}
}
} catch(err) {
logger.error('Error getting channelLabel: ' + JSON.stringify(event) + '\n' + err.message);
}
if (oldMessage) {
message.addOption(oldMessage);
}
}
vectorWatch.on('options', function(event, response) {
});
vectorWatch.on('subscribe', function(event, response) {
logger.info('on subscribe: ' + event.channelLabel);
if (!useConfig) {
// For debug only
var userSettings = JSON.parse('{"Message":{"name":"Love you"},"Update":{"name":"1"}}');
event.userSettings.settings = userSettings;
}
try {
// Update Cloudant DB if new love message is different than the one in Cloudant DB for this user
var key = event.channelLabel;
if (!cloudantDbDocument.messages[key] || !cloudantDbDocument.messages[key].message) {
cloudantDbDocument.messages[key] = JSON.parse('{"message":"","lastUpdateTime":0}');
}
cloudantDbDocument.messages[key]["userKey"] = event.req.body.userKey;
var banned = cloudantDbDocument.banned;
if (banned.some(function(e, i, a) { return e === key; })) {
response.setValue('-Banned-');
response.send();
return;
}
var messageFromUserSettings = event.userSettings.settings.Message.name;
var messageFromCloudant = cloudantDbDocument.messages[key].message;
if (messageFromUserSettings !== messageFromCloudant) {
cloudantDbDocument.messages[key].message = messageFromUserSettings;
updateCloudantDb().catch(function(e) {
try {
// Retry once again, but update document first to get latest _rev
getCloudantDbDocument()
.then(function(body) {
cloudantDbDocument.messages[key].message = messageFromUserSettings;
updateCloudantDb().catch(function(e) {
logger.error('Second error trying to update Cloudant DB: ' + e);
})
});
} catch(err) {
logger.error('Error getting Cloudant DB document: ' + err.message);
}
});
}
} catch(err) {
logger.error('Error updating cloudant: ' + err.message);
}
var streamText = getRandomLoveMessage();
cloudantDbDocument.messages[key]["lastUpdateTime"] = Date.now;
response.setValue(streamText);
response.send();
});
vectorWatch.on('unsubscribe', function(event, response) {
logger.info('on unsubscribe: ' + event.channelLabel);
response.send();
});
vectorWatch.on('schedule', function(records) {
logger.info('on schedule');
if (records.length <= 0) { return; }
var forceUpdate = false;
updateStreamForEveryRecord(records, forceUpdate);
});
vectorWatch.on('webhook', function(event, response, records) {
logger.info('on webhook');
var forceUpdate = true;
try {
getCloudantDbDocument()
.then(updateStreamForEveryRecord(records, forceUpdate));
} catch(err) {
logger.error('Error getting Cloudant DB');
updateStreamForEveryRecord(records, forceUpdate);
}
response.setContentType('text/plain');
response.statusCode = 200;
response.setContent('Ok');
response.send();
});
function updateStreamForEveryRecord(records, forceUpdate) {
var streamText = getRandomLoveMessage();
records.forEach(function(record) {
try {
logger.info('record: ' + JSON.stringify(record));
var key = record.channelLabel;
if (!cloudantDbDocument.messages[key] || !cloudantDbDocument.messages[key].lastUpdateTime) {
cloudantDbDocument.messages[key] = JSON.parse('{"lastUpdateTime":0}');
}
var banned = cloudantDbDocument.banned;
if (banned.some(function(e, i, a) { return e === key; })) {
record.pushUpdate('-Banned-');
return;
}
var userSettings = record.userSettings;
var updateTimeInMs = parseInt(userSettings.Update.name) * 60 * 1000 - (10 * 1000); // 10 secs margin
var lastUpdateTime = cloudantDbDocument.messages[key].lastUpdateTime || 0;
var difference = Date.now - lastUpdateTime;
if ((difference > updateTimeInMs) || forceUpdate) {
record.pushUpdate(streamText);
cloudantDbDocument.messages[key].lastUpdateTime = Date.now;
}
} catch(err) {
logger.error('Error while updating record ' + record.channelLabel + ': ' + record.userSettings);
logger.error('Error message: ' + err.message);
}
});
}
function getRandomLoveMessage() {
var returnedMessage;
try {
var keys = Object.keys(cloudantDbDocument.messages);
var randomIndex = Math.floor(Math.random() * keys.length);
var key = keys[randomIndex];
returnedMessage = cloudantDbDocument.messages[key].message.replace(/love|heart|aime|coeur/gi, String.fromCharCode(0xe033));
} catch(err) {
logger.error('Error while getting random love message');
}
return returnedMessage || "You're lovely";
}
function getCloudantDbDocument() {
return new Promise(function(resolve, reject) {
request(cloudantUrl, function(error, httpResponse, body) {
if (error) {
reject('Error calling ' + cloudantUrl + ': ' + error.message);
return;
}
if (httpResponse && httpResponse.statusCode !== 200) {
reject('Status code error for ' + cloudantUrl + ': ' + httpResponse.statusCode);
return;
}
try {
logger.info('response: ' + body);
cloudantDbDocument = JSON.parse(body);
logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
} catch(err) {
logger.info('Error parsing JSON response');
}
});
});
}
function updateCloudantDb() {
return new Promise(function(resolve, reject) {
request.put({
url: cloudantUrl,
body: JSON.stringify(cloudantDbDocument)
}, function(error, httpResponse, body) {
if (error) {
reject('Error calling ' + cloudantUrl + ': ' + error.message);
return;
}
if (httpResponse && httpResponse.statusCode !== 200) {
reject('Status code error for ' + cloudantUrl + ': ' + httpResponse.statusCode);
return;
}
try {
logger.info('response: ' + body);
body = JSON.parse(body);
cloudantDbDocument._rev = body.rev;
logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
} catch(err) {
logger.info('Error parsing JSON response');
}
});
});
}
| Fixed a broken undefined value check | Love.js | Fixed a broken undefined value check | <ide><path>ove.js
<ide> try {
<ide> logger.info('record: ' + JSON.stringify(record));
<ide> var key = record.channelLabel;
<del> if (!cloudantDbDocument.messages[key] || !cloudantDbDocument.messages[key].lastUpdateTime) {
<del> cloudantDbDocument.messages[key] = JSON.parse('{"lastUpdateTime":0}');
<add> if (!cloudantDbDocument.messages[key] || cloudantDbDocument.messages[key].lastUpdateTime === undefined) {
<add> var messageObject = {};
<add> messageObject['message'] = record.userSettings.Message.name;
<add> messageObject['lastUpdateTime'] = 0;
<add> messageObject['userKey'] = key;
<add> cloudantDbDocument.messages[key] = messageObject;
<ide> }
<ide>
<ide> var banned = cloudantDbDocument.banned;
<ide> var returnedMessage;
<ide> try {
<ide> var keys = Object.keys(cloudantDbDocument.messages);
<add> logger.info('keys: ' + JSON.stringify(keys));
<ide> var randomIndex = Math.floor(Math.random() * keys.length);
<add> logger.info('randomIndex: ' + randomIndex);
<ide> var key = keys[randomIndex];
<add> logger.info('key: ' + key);
<add> logger.info('cloudantDbDocument: ' + JSON.stringify(cloudantDbDocument));
<ide> returnedMessage = cloudantDbDocument.messages[key].message.replace(/love|heart|aime|coeur/gi, String.fromCharCode(0xe033));
<add> logger.info('returnedMessage: ' + returnedMessage);
<ide> } catch(err) {
<ide> logger.error('Error while getting random love message');
<ide> } |
|
Java | apache-2.0 | 94a5b6f8a8e29e0f5ad09a98794d5bbd31d57324 | 0 | MichaelNedzelsky/intellij-community,blademainer/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,retomerz/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,semonte/intellij-community,hurricup/intellij-community,slisson/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,signed/intellij-community,jagguli/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,izonder/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,slisson/intellij-community,samthor/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,petteyg/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,caot/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,dslomov/intellij-community,adedayo/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ibinti/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,apixandru/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,supersven/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,jagguli/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ryano144/intellij-community,retomerz/intellij-community,jagguli/intellij-community,slisson/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,supersven/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,jagguli/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,wreckJ/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,semonte/intellij-community,supersven/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,allotria/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,slisson/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ibinti/intellij-community,fitermay/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,petteyg/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,xfournet/intellij-community,robovm/robovm-studio,signed/intellij-community,petteyg/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,kool79/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,xfournet/intellij-community,FHannes/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,holmes/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,diorcety/intellij-community,fnouama/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,semonte/intellij-community,asedunov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,holmes/intellij-community,kool79/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,allotria/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,allotria/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,allotria/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,kool79/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,signed/intellij-community,kool79/intellij-community,vladmm/intellij-community,xfournet/intellij-community,blademainer/intellij-community,kool79/intellij-community,robovm/robovm-studio,robovm/robovm-studio,clumsy/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,xfournet/intellij-community,kool79/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,retomerz/intellij-community,xfournet/intellij-community,supersven/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,asedunov/intellij-community,semonte/intellij-community,fnouama/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,allotria/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,caot/intellij-community,da1z/intellij-community,Lekanich/intellij-community,supersven/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,signed/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,slisson/intellij-community,jagguli/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,suncycheng/intellij-community,caot/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,dslomov/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,caot/intellij-community,vladmm/intellij-community,FHannes/intellij-community,semonte/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,adedayo/intellij-community,caot/intellij-community,signed/intellij-community,dslomov/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,caot/intellij-community,fnouama/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,supersven/intellij-community,signed/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,da1z/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,supersven/intellij-community,FHannes/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,signed/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,asedunov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,slisson/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,clumsy/intellij-community,semonte/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,signed/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,signed/intellij-community,apixandru/intellij-community,caot/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ibinti/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,petteyg/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,samthor/intellij-community,samthor/intellij-community,diorcety/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,samthor/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ryano144/intellij-community,robovm/robovm-studio,samthor/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,fitermay/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,fnouama/intellij-community,supersven/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,holmes/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,robovm/robovm-studio,adedayo/intellij-community,youdonghai/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import org.intellij.lang.annotations.MagicConstant;
import java.awt.*;
import java.io.Serializable;
public class VerticalFlowLayout extends FlowLayout implements Serializable {
public static final int BOTTOM = 2;
public static final int MIDDLE = 1;
public static final int TOP = 0;
private boolean myVerticalFill;
private boolean myHorizontalFill;
private final int vGap;
private final int hGap;
@MagicConstant(intValues = {TOP, MIDDLE, BOTTOM})
public @interface VerticalFlowAlignment {}
public VerticalFlowLayout() {
this(TOP, 5, 5, true, false);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment) {
this(alignment, 5, 5, true, false);
}
public VerticalFlowLayout(boolean fillHorizontally, boolean fillVertically) {
this(TOP, 5, 5, fillHorizontally, fillVertically);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment, boolean fillHorizontally, boolean fillVertically) {
this(alignment, 5, 5, fillHorizontally, fillVertically);
}
public VerticalFlowLayout(int hGap, int vGap) {
this(TOP, hGap, vGap, true, false);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment, int hGap, int vGap, boolean fillHorizontally, boolean fillVertically) {
setAlignment(alignment);
this.hGap = hGap;
this.vGap = vGap;
myHorizontalFill = fillHorizontally;
myVerticalFill = fillVertically;
}
@Override
public void layoutContainer(Container container) {
Insets insets = container.getInsets();
int i = container.getSize().height - (insets.top + insets.bottom + vGap * 2);
int j = container.getSize().width - (insets.left + insets.right + hGap * 2);
int k = container.getComponentCount();
int l = insets.left + hGap;
int i1 = 0;
int j1 = 0;
int k1 = 0;
for(int l1 = 0; l1 < k; l1++){
Component component = container.getComponent(l1);
if (!component.isVisible()) continue;
Dimension dimension = component.getPreferredSize();
if (myVerticalFill && l1 == k - 1){
dimension.height = Math.max(i - i1, component.getPreferredSize().height);
}
if (myHorizontalFill){
component.setSize(j, dimension.height);
dimension.width = j;
}
else{
component.setSize(dimension.width, dimension.height);
}
if (i1 + dimension.height > i){
a(container, l, insets.top + vGap, j1, i - i1, k1, l1);
i1 = dimension.height;
l += hGap + j1;
j1 = dimension.width;
k1 = l1;
continue;
}
if (i1 > 0){
i1 += vGap;
}
i1 += dimension.height;
j1 = Math.max(j1, dimension.width);
}
a(container, l, insets.top + vGap, j1, i - i1, k1, k);
}
private void a(Container container, int i, int j, int k, int l, int i1, int j1) {
int k1 = getAlignment();
if (k1 == 1){
j += l / 2;
}
if (k1 == 2){
j += l;
}
for(int l1 = i1; l1 < j1; l1++){
Component component = container.getComponent(l1);
Dimension dimension = component.getSize();
if (component.isVisible()){
int i2 = i + (k - dimension.width) / 2;
component.setLocation(i2, j);
j += vGap + dimension.height;
}
}
}
public boolean getHorizontalFill() {
return myHorizontalFill;
}
public void setHorizontalFill(boolean flag) {
myHorizontalFill = flag;
}
public boolean getVerticalFill() {
return myVerticalFill;
}
public void setVerticalFill(boolean flag) {
myVerticalFill = flag;
}
@Override
public Dimension minimumLayoutSize(Container container) {
Dimension dimension = new Dimension(0, 0);
for(int i = 0; i < container.getComponentCount(); i++){
Component component = container.getComponent(i);
if (!component.isVisible()) continue;
Dimension dimension1 = component.getMinimumSize();
dimension.width = Math.max(dimension.width, dimension1.width);
if (i > 0){
dimension.height += vGap;
}
dimension.height += dimension1.height;
}
Insets insets = container.getInsets();
dimension.width += insets.left + insets.right + hGap * 2;
dimension.height += insets.top + insets.bottom + vGap * 2;
return dimension;
}
@Override
public Dimension preferredLayoutSize(Container container) {
Dimension dimension = new Dimension(0, 0);
for(int i = 0; i < container.getComponentCount(); i++){
Component component = container.getComponent(i);
if (!component.isVisible()) continue;
Dimension dimension1 = component.getPreferredSize();
dimension.width = Math.max(dimension.width, dimension1.width);
if (i > 0){
dimension.height += vGap;
}
dimension.height += dimension1.height;
}
Insets insets = container.getInsets();
dimension.width += insets.left + insets.right + hGap * 2;
dimension.height += insets.top + insets.bottom + vGap * 2;
return dimension;
}
}
| platform/util/src/com/intellij/openapi/ui/VerticalFlowLayout.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import org.intellij.lang.annotations.MagicConstant;
import java.awt.*;
import java.io.Serializable;
public class VerticalFlowLayout extends FlowLayout implements Serializable {
public static final int BOTTOM = 2;
public static final int MIDDLE = 1;
public static final int TOP = 0;
private boolean myVerticalFill;
private boolean myHorizontalFill;
private final int vGap;
private final int hGap;
@MagicConstant(intValues = {TOP, MIDDLE, BOTTOM})
public @interface VerticalFlowAlignment {}
public VerticalFlowLayout() {
this(TOP, 5, 5, true, false);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment) {
this(alignment, 5, 5, true, false);
}
public VerticalFlowLayout(boolean fillHorizontally, boolean fillVertically) {
this(TOP, 5, 5, fillHorizontally, fillVertically);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment, boolean fillHorizontally, boolean fillVertically) {
this(alignment, 5, 5, fillHorizontally, fillVertically);
}
public VerticalFlowLayout(int hGap, int vGap) {
this(TOP, hGap, vGap, true, false);
}
public VerticalFlowLayout(@VerticalFlowAlignment int alignment, int hGap, int vGap, boolean fillHorizontally, boolean fillVertically) {
setAlignment(alignment);
this.hGap = hGap;
this.vGap = vGap;
myHorizontalFill = fillHorizontally;
myVerticalFill = fillVertically;
}
@Override
public void layoutContainer(Container container) {
Insets insets = container.getInsets();
int i = container.getSize().height - (insets.top + insets.bottom + vGap * 2);
int j = container.getSize().width - (insets.left + insets.right + hGap * 2);
int k = container.getComponentCount();
int l = insets.left + hGap;
int i1 = 0;
int j1 = 0;
int k1 = 0;
for(int l1 = 0; l1 < k; l1++){
Component component = container.getComponent(l1);
if (!component.isVisible()) continue;
Dimension dimension = component.getPreferredSize();
if (myVerticalFill && l1 == k - 1){
dimension.height = Math.max(i - i1, component.getPreferredSize().height);
}
if (myHorizontalFill){
component.setSize(j, dimension.height);
dimension.width = j;
}
else{
component.setSize(dimension.width, dimension.height);
}
if (i1 + dimension.height > i){
a(container, l, insets.top + vGap, j1, i - i1, k1, l1);
i1 = dimension.height;
l += hGap + j1;
j1 = dimension.width;
k1 = l1;
continue;
}
if (i1 > 0){
i1 += vGap;
}
i1 += dimension.height;
j1 = Math.max(j1, dimension.width);
}
a(container, l, insets.top + vGap, j1, i - i1, k1, k);
}
private void a(Container container, int i, int j, int k, int l, int i1, int j1) {
int k1 = getAlignment();
if (k1 == 1){
j += l / 2;
}
if (k1 == 2){
j += l;
}
for(int l1 = i1; l1 < j1; l1++){
Component component = container.getComponent(l1);
Dimension dimension = component.getSize();
if (component.isVisible()){
int i2 = i + (k - dimension.width) / 2;
component.setLocation(i2, j);
j += vGap + dimension.height;
}
}
}
public boolean getHorizontalFill() {
return myHorizontalFill;
}
public void setHorizontalFill(boolean flag) {
myHorizontalFill = flag;
}
public boolean getVerticalFill() {
return myVerticalFill;
}
public void setVerticalFill(boolean flag) {
myVerticalFill = flag;
}
@Override
public Dimension minimumLayoutSize(Container container) {
Dimension dimension = new Dimension(0, 0);
for(int i = 0; i < container.getComponentCount(); i++){
Component component = container.getComponent(i);
if (!component.isVisible()) continue;
Dimension dimension1 = component.getMinimumSize();
dimension.width = Math.max(dimension.width, dimension1.width);
if (i > 0){
dimension.height += vGap;
}
dimension.height += dimension1.height;
}
Insets insets = container.getInsets();
dimension.width += insets.left + insets.right + hGap * 2;
dimension.height += insets.top + insets.bottom + vGap * 2;
return dimension;
}
@Override
public Dimension preferredLayoutSize(Container container) {
Dimension dimension = new Dimension(0, 0);
for(int i = 0; i < container.getComponentCount(); i++){
Component component = container.getComponent(i);
if (!component.isVisible()) continue;
Dimension dimension1 = component.getPreferredSize();
dimension.width = Math.max(dimension.width, dimension1.width);
if (i > 0){
dimension.height += hGap;
}
dimension.height += dimension1.height;
}
Insets insets = container.getInsets();
dimension.width += insets.left + insets.right + hGap * 2;
dimension.height += insets.top + insets.bottom + vGap * 2;
return dimension;
}
}
| fixed vertical layout preferred layout height
| platform/util/src/com/intellij/openapi/ui/VerticalFlowLayout.java | fixed vertical layout preferred layout height | <ide><path>latform/util/src/com/intellij/openapi/ui/VerticalFlowLayout.java
<ide> Dimension dimension1 = component.getPreferredSize();
<ide> dimension.width = Math.max(dimension.width, dimension1.width);
<ide> if (i > 0){
<del> dimension.height += hGap;
<add> dimension.height += vGap;
<ide> }
<ide> dimension.height += dimension1.height;
<ide> } |
|
JavaScript | apache-2.0 | c68fa8dc64c1e8a2b9a28ae2736587c37270a2e0 | 0 | mcanthony/ares-project,mcanthony/ares-project,mcanthony/ares-project,mcanthony/ares-project,enyojs/ares-project,enyojs/ares-project,enyojs/ares-project,enyojs/ares-project,mcanthony/ares-project,enyojs/ares-project,mcanthony/ares-project | /* jshint indent: false */ // TODO: ENYO-3311
/*global analyzer, ares, enyo, $L, ProjectCtrl */
enyo.kind({
name: "Phobos",
classes: "enyo-unselectable",
components: [
{kind: "FittableRows", classes: "enyo-fit", components: [
{name: "body", fit: true, kind: "FittableColumns", components: [
{name: "middle", fit: true, classes: "panel", components: [
{classes: "enyo-fit ares_phobos_panel border ", components: [
{
kind: "AceWrapper",
name: "aceWrapper",
classes: "enyo-fit ace-code-editor",
onAutoCompletion: "startAutoCompletion",
onChange: "docChanged",
onCursorChange: "cursorChanged",
onFind: "findpop",
onFkey: "fkeypressed",
onScroll: "handleScroll",
onWordwrap: "toggleww"
},
{name: "imageViewer", kind: "enyo.Image"}
]}
]},
{name: "right", kind: "rightPanels", showing: false, classes: "ares_phobos_right", arrangerKind: "CardArranger"}
]}
]},
{name: "autocomplete", kind: "Phobos.AutoComplete"},
{name: "findpop", kind: "FindPopup", centered: true, modal: true, floating: true, onFindNext: "findNext", onFindPrevious: "findPrevious", onReplace: "replace", onReplaceAll:"replaceAll", onHide:"doAceFocus", onClose: "findClose", onReplaceFind: "replacefind"},
{
name: "editorSettingsPopup",
kind: "onyx.Popup",
classes:"enyo-unselectable ares-classic-popup",
centered: true,
modal: true,
floating: true,
autoDismiss: false,
onCloseSettings: "closeEditorPopup",
onChangeSettings:"applyPreviewSettings",
onChangeRightPane: "changeRightPane",
components: [
{name:"title", classes: "title draggable", kind: "Ares.PopupTitle", content: "EDITOR GLOBAL SETTINGS"},
{kind: "editorSettings", classes:"ace-settings-popup" }
],
}
],
events: {
onHideWaitPopup: "",
onError: "",
onRegisterMe: "",
onFileEdited: " ",
onChildRequest: "",
onAceFocus: ""
},
handlers: {
onCss: "newcssAction",
onReparseAsked: "reparseAction",
onInitNavigation: "initNavigation",
onNavigateInCodeEditor: "navigateInCodeEditor"
},
published: {
projectData: null,
objectsToDump: []
},
editedDocs:"",
injected: false,
debug: false,
// Container of the code to analyze and of the analysis result
analysis: {},
helper: null, // Analyzer.KindHelper
closeAll: false,
create: function() {
ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value
this.inherited(arguments);
this.helper = new analyzer.Analyzer.KindHelper();
},
getProjectController: function() {
// create projectCtrl only when needed. In any case, there's only
// one Phobos and one projectCtrl in Ares
this.projectCtrl = this.projectData.getProjectCtrl();
if ( ! this.projectCtrl) {
this.projectCtrl = new ProjectCtrl({projectData: this.projectData});
// wire event propagation from there to Phobos
this.projectCtrl.setOwner(this);
this.projectData.setProjectCtrl(this.projectCtrl);
}
},
saveNeeded: function() {
return this.docData.getEdited();
},
openDoc: function(inDocData) {
// If we are changing documents, reparse any changes into the current projectIndexer
if (this.docData && this.docData.getEdited()) {
this.reparseUsersCode(true);
}
// Set up the new doucment
this.docData = inDocData;
this.setProjectData(this.docData.getProjectData());
this.getProjectController();
this.setAutoCompleteData();
// Save the value to set it again after data has been loaded into ACE
var edited = this.docData.getEdited();
var file = this.docData.getFile();
var extension = file.name.split(".").pop();
this.hideWaitPopup();
this.analysis = null;
var mode = {
json: "json",
design: "json",
js: "javascript",
html: "html",
css: "css",
coffee: "coffee",
dot: "dot",
patch: "diff",
diff: "diff",
jade: "jade",
less: "less",
md: "markdown",
markdown: "markdown",
svg: "svg",
xml: "xml",
jpeg: "image",
jpg: "image",
png: "image",
gif: "image"
}[extension] || "text";
this.docData.setMode(mode);
var hasAce = this.adjustPanelsForMode(mode, this.$.editorSettings.getSettingFromLS().rightpane);
if (hasAce) {
var aceSession = this.docData.getAceSession();
if (aceSession) {
this.$.aceWrapper.setSession(aceSession);
} else {
aceSession = this.$.aceWrapper.createSession(this.docData.getData(), mode);
this.$.aceWrapper.setSession(aceSession);
this.docData.setAceSession(aceSession);
}
// Pass to the autocomplete compononent a reference to ace
this.$.autocomplete.setAceWrapper(this.$.aceWrapper);
this.focusEditor();
/* set editor to user pref */
this.$.aceWrapper.applyAceSettings(this.$.editorSettings.getSettingFromLS());
this.$.aceWrapper.editingMode = mode;
} else {
var config = this.projectData.getService().getConfig();
var fileUrl = config.origin + config.pathname + "/file" + file.path;
this.$.imageViewer.setAttribute("src", fileUrl);
}
this.manageDesignerButton();
this.reparseUsersCode(true);
this.projectCtrl.buildProjectDb();
this.docData.setEdited(edited);
},
adjustPanelsForMode: function(mode, rightpane) {
this.trace("mode:", mode);
var showModes = {
javascript: {
imageViewer: false,
aceWrapper: true,
saveButton: true,
saveAsButton: true,
newKindButton: true,
designerDecorator: true,
right: rightpane
},
image: {
imageViewer: true,
aceWrapper: false,
saveButton: false,
saveAsButton: false,
newKindButton: false,
designerDecorator: false,
right: false
},
text: {
imageViewer: false,
aceWrapper: true,
saveButton: true,
saveAsButton: true,
newKindButton: false,
designerDecorator: false,
right: false
}
};
var showStuff, showSettings = showModes[mode] || showModes['text'];
for (var stuff in showSettings) {
showStuff = showSettings[stuff];
this.trace("show", stuff, ":", showStuff);
// FIXME need to clean up this code ENYO-3633
if(this.$[stuff] !== undefined){
if (typeof this.$[stuff].setShowing === 'function') {
this.$[stuff].setShowing(showStuff) ;
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
} else if (this.owner.$.editorFileMenu.$[stuff] !== undefined && this.owner.$.designerFileMenu.$[stuff] !== undefined) {
var editorFileMenu = this.owner.$.editorFileMenu.$[stuff];
var designerFileMenu = this.owner.$.designerFileMenu.$[stuff];
if (typeof editorFileMenu.setShowing === 'function' && typeof designerFileMenu.setShowing === 'function') {
editorFileMenu.setShowing(showStuff);
designerFileMenu.setShowing(showStuff);
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
} else {
if (typeof this.owner.$[stuff].setShowing === 'function') {
this.owner.$[stuff].setShowing(showStuff) ;
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
}
}
// xxxIndex: specify what to show in the "RightPanels" kinds (declared at the end of this file)
// xxxIndex is ignored when matching show setting is false
var modes = {
json: {rightIndex: 0},
javascript: {rightIndex: 1},
html: {rightIndex: 2},
css: {rightIndex: 3},
text: {rightIndex: 0},
image: {rightIndex: 0}
};
var settings = modes[mode]||modes['text'];
this.$.right.setIndex(settings.rightIndex);
this.resizeHandler();
return showSettings.aceWrapper ;
},
hideWaitPopup: function() {
this.doHideWaitPopup();
},
//
setAutoCompleteData: function() {
this.$.autocomplete.hide();
this.$.autocomplete.setProjectData(this.projectData);
this.manageDesignerButton();
},
resetAutoCompleteData: function() {
this.$.autocomplete.setProjectData(null);
},
/**
* Enable "Designer" button only if project & enyo index are both valid
*/
manageDesignerButton: function() {
this.doChildRequest({ task: [ "enableDesignerButton", this.projectCtrl.fullAnalysisDone ]} );
},
/**
* Receive the project data reference which allows to access the analyzer
* output for the project's files, enyo/onyx and all the other project
* related information shared between phobos and deimos.
* @param oldProjectData
* @protected
*/
projectDataChanged: function(oldProjectData) {
if (this.projectData) {
this.projectData.on('update:project-indexer', this.projectIndexerChanged, this);
}
if (oldProjectData) {
oldProjectData.off('update:project-indexer', this.projectIndexerChanged);
}
},
/**
* The current project analyzer output has changed
* Re-scan the indexer
* @param value the new analyzer output
* @protected
*/
projectIndexerChanged: function() {
this.trace("Project analysis ready");
this.manageDesignerButton();
},
dumpInfo: function(inObject) {
var h = [];
this.$.right.setDumpCount(0);
if (!inObject || !inObject.superkinds) {
h.push("no content");
this.objectsToDump = h;
this.$.right.setDumpCount(this.objectsToDump.length);
return;
}
var c = inObject;
h.push(c.name);
h.push("Extends");
for (var i=0, p; (p=c.superkinds[i]); i++) {
p = {name: c.superkinds[i], isExtended: true};
h.push(p);
}
if (c.components.length) {
h.push("Components");
for (i=0, p; (p=c.components[i]); i++) {
h.push(p);
}
}
h.push("Properties");
for (i=0, p; (p=c.properties[i]); i++) {
h.push(p);
}
this.objectsToDump = h;
this.$.right.setDumpCount(this.objectsToDump.length);
},
// invoked by reparse button in right panel (the file index)
reparseAction: function(inSender, inEvent) {
this.reparseUsersCode(true);
},
initNavigation: function(inSender, inEvent) {
var item = inEvent.item.$.item,
index = inEvent.item.index,
object = this.objectsToDump[index];
if (object.isExtended){
item.setFixedItem(object.name);
} else if (object.name){
item.setNavigateItem(object.name);
} else {
item.setTitle(object);
}
item.setIndex(index);
return true;
},
navigateInCodeEditor: function(inSender, inEvent) {
var itemToSelect = this.objectsToDump[inEvent.index];
if(itemToSelect.start && itemToSelect.end){
this.$.aceWrapper.navigateToPosition(itemToSelect.start, itemToSelect.end);
this.doAceFocus();
}
},
//* Updates the projectIndexer (notifying watchers by default) and resets the local analysis file
reparseUsersCode: function(inhibitUpdate) {
var mode = this.docData.getMode();
var codeLooksGood = false;
var module = {
name: this.docData.getFile().name,
code: this.$.aceWrapper.getValue(),
path: this.projectCtrl.projectUrl + this.docData.getFile().dir + this.docData.getFile().name
};
this.trace("called with mode " , mode , " inhibitUpdate " , inhibitUpdate , " on " + module.name);
switch(mode) {
case "javascript":
try {
this.analysis = module;
this.projectData.getProjectIndexer().reIndexModule(module);
if (inhibitUpdate !== true) {
this.projectData.updateProjectIndexer();
}
this.updateObjectsLines(module);
// dump the object where the cursor is positioned, if it exists
this.dumpInfo(module.objects && module.objects[module.currentObject]);
// Give the information to the autocomplete component
this.$.autocomplete.setAnalysis(this.analysis);
codeLooksGood = true;
} catch(error) {
enyo.log("An error occured during the code analysis: " , error);
this.dumpInfo(null);
this.$.autocomplete.setAnalysis(null);
}
break;
case "json":
if (module.name.slice(-7) == ".design") {
this.projectData.getProjectIndexer().reIndexDesign(module);
if (inhibitUpdate !== true) {
this.projectData.updateProjectIndexer();
}
}
this.analysis = null;
this.$.autocomplete.setAnalysis(null);
break;
default:
this.analysis = null;
this.$.autocomplete.setAnalysis(null);
break;
}
return codeLooksGood ;
},
/**
* Add for each object the corresponding range of lines in the file
* Update the information about the object currently referenced
* by the cursor position
* TODO: see if this should go in Analyzer2
*/
updateObjectsLines: function(module) {
module.ranges = [];
if (module.objects && module.objects.length > 0) {
var start = 0, range;
for( var idx = 1; idx < module.objects.length ; idx++ ) {
range = { first: start, last: module.objects[idx].line - 1};
module.ranges.push(range); // Push a range for previous object
start = module.objects[idx].line;
}
// Push a range for the last object
range = { first: start, last: 1000000000};
module.ranges.push(range);
}
var position = this.$.aceWrapper.getCursorPositionInDocument();
module.currentObject = this.findCurrentEditedObject(position);
module.currentRange = module.ranges[module.currentObject];
module.currentLine = position.row;
},
/**
* Return the index (in the analyzer result ) of the enyo kind
* currently edited (in which the cursor is)
* Otherwise return -1
* @returns {Number}
*/
findCurrentEditedObject: function(position) {
if (this.analysis && this.analysis.ranges) {
for( var idx = 0 ; idx < this.analysis.ranges.length ; idx++ ) {
if (position.row <= this.analysis.ranges[idx].last) {
return idx;
}
}
}
return -1;
},
/**
* Navigate from Phobos to Deimos. Pass Deimos all relevant info.
*/
designerAction: function() {
// Update the projectIndexer and notify watchers
this.reparseUsersCode();
var kinds = this.extractKindsData(),
data = {
kinds: kinds,
projectData: this.projectData,
fileIndexer: this.analysis
};
if (kinds.length > 0) {
// Request to design the current document, passing info about all kinds in the file
this.doChildRequest({ task: [ 'designDocument', data ]});
} // else - The error has been displayed by extractKindsData()
},
//* Extract info about kinds from the current file needed by the designer
extractKindsData: function() {
var c = this.$.aceWrapper.getValue(),
kinds = [];
if (this.analysis) {
var nbKinds = 0;
var errorMsg;
var i, o;
var oLen = this.analysis.objects.length;
for (i=0; i < oLen; i++) {
o = this.analysis.objects[i];
if (o.type !== "kind") {
errorMsg = $L("Ares does not support methods out of a kind. Please place '" + o.name + "' into a separate .js file");
} else {
nbKinds++;
}
}
if (nbKinds === 0) {
errorMsg = $L("No kinds found in this file");
}
if (errorMsg) {
this.doError({msg: errorMsg});
return [];
}
for (i=0; i < oLen; i++) {
o = this.analysis.objects[i];
var start = o.componentsBlockStart;
var end = o.componentsBlockEnd;
var kindBlock = enyo.json.codify.from(c.substring(o.block.start, o.block.end));
var name = o.name;
var kind = kindBlock.kind || o.superkind;
var comps = [];
if (start && end) {
var js = c.substring(start, end);
/* jshint evil: true */
comps = eval("(" + js + ")"); // TODO: ENYO-2074, replace eval. Why eval? Because JSON.parse doesn't support unquoted keys...
/* jshint evil: false */
}
var comp = {
name: name,
kind: kind,
components: comps
};
for (var j=0; j < o.properties.length; j++) {
var prop = o.properties[j];
var pName = prop.name;
var value = this.verifyValueType(analyzer.Documentor.stripQuotes(prop.value[0].name));
if ((start === undefined || prop.start < start) && pName !== "components") {
if (value === "{" || value === "[" || value === "function") {
comp[pName] = kindBlock[pName];
} else {
comp[pName] = value;
}
}
}
kinds.push(comp);
}
}
return kinds;
},
/**
* Converts string representation of boolean values
* to boolean
* TODO: Verify false-positives (ex: strings meant to be strings)
* @param inProps: the value to match
* @returns boolean value if match found: inValue if no matches
* @protected
*/
verifyValueType: function(inValue) {
if (inValue === "true") {
inValue = true;
} else if (inValue === "false") {
inValue = false;
}
return inValue;
},
/**
* Lists the handler methods mentioned in the "handlers"
* attributes and in the sub-components of the kind object
* passed as a parameter
* @param object: the kind definition to explore
* @param declared: list of handler methods already listed
* @returns the list of declared handler methods
*/
listHandlers: function(object, declared) {
try {
this.helper.setDefinition(object);
return this.helper.listHandlers(declared);
} catch(error) {
enyo.log("Unexpected error: " , error); // TODO TBC
}
},
/**
* This function checks all the kinds and add the missing
* handler functions listed in the "onXXXX" attributes
* @protected
* Note: This implies to reparse/analyze the file before
* and after the operation.
*/
insertMissingHandlers: function() {
if (this.analysis) {
// Reparse to get the definition of possibly added onXXXX attributes
this.reparseUsersCode(true);
/*
* Insert missing handlers starting from the end of the
* file to limit the need of reparsing/reanalysing
* the file
*/
for( var i = this.analysis.objects.length -1 ; i >= 0 ; i-- ) {
var obj = this.analysis.objects[i];
if (obj.components) {
this.insertMissingHandlersIntoKind(obj);
}
}
// Reparse to get the definition of the newly added methods
this.reparseUsersCode(true);
} else {
// There is no parser data for the current file
enyo.log("Unable to insert missing handler methods");
}
},
/**
* This function checks the kind passed as an inout parameter
* and add the missing handler functions listed in the "onXXXX" attributes
* @param object
* @protected
*/
insertMissingHandlersIntoKind: function(object) {
var commaTerminated = false,
commaInsertionIndex = 0;
// List existing handlers
var existing = {};
for(var j = 0 ; j < object.properties.length ; j++) {
var p = object.properties[j];
commaTerminated = p.commaTerminated;
if (p.value[0].name === 'function') {
existing[p.name] = "";
commaInsertionIndex = p.value[0].block.end; // Index of function block ending curly braket
} else {
commaInsertionIndex = p.value[0].end; // Index of property definition
}
}
// List the handler methods declared in the components and in handlers map
var declared = this.listHandlers(object, {});
// insert the missing handler methods code in the editor
if (object.block) {
var lineTermination = this.$.aceWrapper.getNewLineCharacter(),
codeInsertionIndex = object.block.end - 1, // Index before kind block ending curly braket
codeInsertionPosition;
var commaInsertionPosition = null;
if (!commaTerminated) {
commaInsertionPosition = this.$.aceWrapper.mapToLineColumns([commaInsertionIndex]);
commaTerminated = true;
}
// Prepare the code to insert
var codeToInsert = "";
for(var item in declared) {
if (item !== "" && existing[item] === undefined) {
// use correct line terminations
codeToInsert += (commaTerminated ? "" : "," + lineTermination);
commaTerminated = false;
codeToInsert += ("\t" + item + ": function(inSender, inEvent) {" + lineTermination);
// Auto trace line Insert's
if(this.$.editorSettings.settings.autotrace === true && this.$.editorSettings.settings.autotraceLine !== null){
codeToInsert += ('\t\t' + this.$.editorSettings.settings.autotraceLine + lineTermination);
}
codeToInsert += ("\t\t// TO DO - Auto-generated code" + lineTermination + "\t}");
}
}
if (codeToInsert !== "") {
// add a comma after the last function/property if required
if (commaInsertionPosition) {
this.$.aceWrapper.insertPosition(commaInsertionPosition[0], ",");
codeInsertionIndex++; // position shifted because of comma character addition
}
commaInsertionIndex++; // index after comma character added or already present
// detect if block ending curly braket is contiguous to previous function or property ending: curly bracket w/wo comma, value w/wo comma
if (commaInsertionIndex === codeInsertionIndex) {
commaInsertionPosition = this.$.aceWrapper.mapToLineColumns([commaInsertionIndex]);
this.$.aceWrapper.insertNewLine(commaInsertionPosition[0]);
codeInsertionIndex += lineTermination.length; // shifted because of line termination addition, is sentitive to line termination mode
}
// Add a new line before kind block ending curly braket
codeInsertionPosition = this.$.aceWrapper.mapToLineColumns([codeInsertionIndex]);
this.$.aceWrapper.insertNewLine(codeInsertionPosition[0]);
// Get the corresponding Ace range to replace/insert the missing code
// NB: aceWrapper.replace() allow to use the undo/redo stack.
var codeInsertionRange = this.$.aceWrapper.mapToLineColumnRange(codeInsertionIndex, codeInsertionIndex);
this.$.aceWrapper.replaceRange(codeInsertionRange, codeToInsert);
}
} else {
// There is no block information for that kind - Parser is probably not up-to-date
enyo.log("Unable to insert missing handler methods");
}
},
// called when designer has modified the components
updateComponentsCode: function(kinds) {
this.injected = true;
for( var i = this.analysis.objects.length -1 ; i >= 0 ; i-- ) {
if (kinds[i]) {
// Insert the new version of components (replace components block, or insert at end)
var obj = this.analysis.objects[i];
var content = kinds[i];
var start = obj.componentsBlockStart;
var end = obj.componentsBlockEnd;
var kindStart = obj.block.start;
if (!(start && end)) {
// If this kind doesn't have a components block yet, insert a new one
// at the end of the file
var last = obj.properties[obj.properties.length-1];
if (last) {
content = (last.commaTerminated ? "" : ",") + "\n\t" + "components: []";
kindStart = obj.block.end - 2;
end = obj.block.end - 2;
}
}
// Get the corresponding Ace range to replace the component definition
// NB: aceWrapper.replace() allow to use the undo/redo stack.
var range = this.$.aceWrapper.mapToLineColumnRange(kindStart, end);
this.$.aceWrapper.replaceRange(range, content);
}
}
this.injected = false;
/*
* Insert the missing handlers
* NB: reparseUsersCode() is invoked by insertMissingHandlers()
*/
this.insertMissingHandlers();
//file is edited if only we have a difference between stored file data and editor value
if(this.getEditorContent().localeCompare(this.docData.getData())!==0){
this.docData.setEdited(true);
this.doFileEdited();
}
},
docChanged: function(inSender, inEvent) {
//this.injected === false then modification coming from user
if(!this.injected && !this.docData.getEdited()){
this.docData.setEdited(true);
this.doFileEdited();
}
this.trace("data:", enyo.json.stringify(inEvent.data));
if (this.analysis) {
// Call the autocomplete component
this.$.autocomplete.start(inEvent);
}
return true; // Stop the propagation of the event
},
editorUserSyntaxError:function(){
var userSyntaxError = [];
userSyntaxError = this.$.autocomplete.aceWrapper.editor.session.$annotations.length;
return userSyntaxError;
},
cursorChanged: function(inSender, inEvent) {
var position = this.$.aceWrapper.getCursorPositionInDocument();
this.trace(inSender.id, " ", inEvent.type, " ", enyo.json.stringify(position));
// Check if we moved to another enyo kind and display it in the right pane
var tempo = this.analysis;
if (tempo && tempo.currentLine !== undefined && tempo.currentLine != position.row) { // If no more on the same line
tempo.currentLine = position.row;
// Check if the cursor references another object
if (tempo.currentRange !== undefined && (position.row < tempo.currentRange.first || position.row > tempo.currentRange.last)) {
tempo.currentObject = this.findCurrentEditedObject(position);
tempo.currentRange = tempo.ranges[tempo.currentObject];
this.dumpInfo(tempo.objects && tempo.objects[tempo.currentObject]);
}
}
this.$.autocomplete.cursorChanged(position);
return true; // Stop the propagation of the event
},
startAutoCompletion: function() {
this.$.autocomplete.start(null);
},
newKindAction: function() {
// Insert a new empty enyo kind at the end of the file
var newKind = 'enyo.kind({\n name : "@cursor@",\n kind : "Control",\n components : []\n});';
this.$.aceWrapper.insertAtEndOfFile(newKind, '@cursor@');
},
newcssAction: function(inSender, inEvent){
this.$.aceWrapper.insertAtEndOfFile(inEvent.outPut);
},
/*
* cleanup data. Typically called when closing a document
* @protected
*/
closeSession: function() {
if (this.docData) {
this.$.aceWrapper.destroySession(this.docData.getAceSession());
this.resetAutoCompleteData();
this.docData = null;
}
},
// Show Find popup
findpop: function(){
var selected = this.$.aceWrapper.getSelection();
if(selected){
this.$.findpop.setFindInput(selected);
}
this.$.findpop.removeMessage();
this.$.findpop.disableReplaceButtons(true);
this.$.findpop.show();
return true;
},
findNext: function(inSender, inEvent){
var options = {backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.find(this.$.findpop.findValue, options);
this.$.findpop.updateAfterFind(this.$.aceWrapper.getSelection());
},
findPrevious: function(){
var options = {backwards: true, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.find(this.$.findpop.findValue, options);
this.$.findpop.updateAfterFind(this.$.aceWrapper.getSelection());
},
replaceAll: function(){
var occurences = this.$.aceWrapper.replaceAll(this.$.findpop.findValue , this.$.findpop.replaceValue);
this.$.findpop.updateMessage(this.$.aceWrapper.getSelection(), occurences);
},
replacefind: function(){
var options = {backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.replacefind(this.$.findpop.findValue , this.$.findpop.replaceValue, options);
this.$.findpop.updateMessage(this.$.aceWrapper.getSelection());
},
//ACE replace doesn't replace the currently-selected match. It instead replaces the *next* match. Seems less-than-useful
//It was not working because ACE(Ace.js) was doing "find" action before "replace".
replace: function(){
this.$.aceWrapper.replace(this.$.findpop.findValue, this.$.findpop.replaceValue);
},
focusEditor: function(inSender, inEvent) {
this.$.aceWrapper.focus();
},
getEditorContent: function() {
return this.$.aceWrapper.getValue();
},
handleScroll: function(inSender, inEvent) {
this.$.autocomplete.hide();
},
findClose: function(){
this.$.findpop.hide();
},
toggleww: function(){
if(this.$.aceWrapper.wordWrap === "true" || this.$.aceWrapper.wordWrap === true){
this.$.aceWrapper.wordWrap = false;
this.$.aceWrapper.wordWrapChanged();
}else{
this.$.aceWrapper.wordWrap = true;
this.$.aceWrapper.wordWrapChanged();
}
},
/** @public */
requestSelectedText: function() {
return this.$.aceWrapper.requestSelectedText();
},
/**
* Add a new kind (requested from the designer)
* A switch to the designer is performed to fully reload the kinds in the designer.
* @param config
* @public
*/
addNewKind: function(config) {
var newKind = 'enyo.kind('+config+'\n);';
this.$.aceWrapper.insertAtEndOfFile(newKind, '@cursor@');
this.designerAction();
},
/**
* Insert a new kind (requested from the designer)
* A switch to the designer is performed to fully reload the kinds in the designer.
* @param kind_index, config
* @public
*/
replaceKind: function(kind_index, config){
var obj = this.analysis.objects[kind_index];
var range = this.$.aceWrapper.mapToLineColumnRange(obj.block.start, obj.block.end);
this.$.aceWrapper.replaceRange(range, config);
this.designerAction();
},
//* editor setting
editorSettings: function() {
this.$.editorSettingsPopup.show();
this.$.editorSettings.initSettings();
},
closeEditorPopup: function(){
this.$.editorSettingsPopup.hide();
this.doAceFocus();
return true;
},
changeRightPane: function(settings){
if(this.docData){
this.adjustPanelsForMode(this.docData.getMode(), settings.rightpane);
}
},
applySettings: function(settings){
//apply Ace settings
this.$.aceWrapper.applyAceSettings(settings);
if(this.docData){
this.adjustPanelsForMode(this.docData.getMode(), settings.rightpane);
}
},
fkeypressed: function(inSender, inEvent) {
var key = inEvent;
this.$.aceWrapper.insertAtCursor(this.$.editorSettings.settings.keys[ key ]);
},
//* Trigger an Ace undo and bubble updated code
undoAndUpdate: function(next) {
ares.assertCb(next);
this.$.aceWrapper.undo();
this.updateCodeInDesigner(next);
},
//* Trigger an Ace undo and bubble updated code
redoAndUpdate: function(next) {
ares.assertCb(next);
this.$.aceWrapper.redo();
this.updateCodeInDesigner(next);
},
//* Send up an updated copy of the code
updateCodeInDesigner: function(next) {
// Update the projectIndexer and notify watchers
this.reparseUsersCode(true);
var data = {kinds: this.extractKindsData(), projectData: this.projectData, fileIndexer: this.analysis};
if (data.kinds.length > 0) {
this.doChildRequest({task: [ "loadDesignerUI", data, next ]});
} // else - The error has been displayed by extractKindsData()
},
resizeHandler: function() {
this.inherited(arguments);
this.$.body.reflow();
this.$.aceWrapper.resize();
}
});
enyo.kind({
name: "rightPanels", kind: "Panels", wrap: false, draggable:false,
events: {
onCss: "",
onReparseAsked: "",
onInitNavigation: "",
onNavigateInCodeEditor: ""
},
components: [
{// right panel for JSON goes here
},
{kind: "enyo.Control", classes: "enyo-fit", components: [
{name: "right", classes: "enyo-fit ares_phobos_panel border", components: [
{kind: "onyx.Button", content: "Reparse", ontap: "doReparseAsked"},
{kind: "enyo.Scroller", classes: "enyo-fit ace-helper-panel",components: [
{tag:"ul", kind: "enyo.Repeater", name: "dump", onSetupItem: "sendInitHelperReapeter", ontap: "sendNavigate", components: [
{tag:"li", classes:"ace-helper-list", kind:"RightPanel.Helper", name: "item"}
]}
]}
]}
]},
{// right panel for HTML goes here
},
{kind: "enyo.Control", classes: "enyo-fit", components: [ // right panel for CSS here
{kind: "cssBuilder", classes: "enyo-fit ares_phobos_panel border", onInsert: "test"}
]}
],
create: function() {
this.inherited(arguments);
},
test: function(inEvent) {
this.doCss(inEvent);
},
sendInitHelperReapeter: function(inSender, inEvent) {
this.doInitNavigation({item: inEvent.item});
},
sendNavigate: function(inSender, inEvent){
this.doNavigateInCodeEditor({index:inEvent.index});
},
setDumpCount: function(count){
this.$.dump.setCount(count);
}
});
enyo.kind({
name: "RightPanel.Helper",
published: {
title: "",
fixedItem: "",
navigateItem: "",
index: -1
},
components: [
{name: "title", classes: "ace-title"},
{name: "fixedItem", classes: "ace-fixed-item"},
{name: "navigateItem", kind: "control.Link", classes: "ace-navigate-item"}
],
titleChanged: function() {
this.$.title.setContent(this.title);
},
fixedItemChanged: function() {
this.$.fixedItem.setContent(this.fixedItem);
},
navigateItemChanged: function() {
this.$.navigateItem.setContent(this.navigateItem);
}
});
| phobos/source/Phobos.js | /* jshint indent: false */ // TODO: ENYO-3311
/*global analyzer, ares, enyo, $L, ProjectCtrl */
enyo.kind({
name: "Phobos",
classes: "enyo-unselectable",
components: [
{kind: "FittableRows", classes: "enyo-fit", components: [
{name: "body", fit: true, kind: "FittableColumns", components: [
{name: "middle", fit: true, classes: "panel", components: [
{classes: "enyo-fit ares_phobos_panel border ", components: [
{
kind: "AceWrapper",
name: "aceWrapper",
classes: "enyo-fit ace-code-editor",
onAutoCompletion: "startAutoCompletion",
onChange: "docChanged",
onCursorChange: "cursorChanged",
onFind: "findpop",
onFkey: "fkeypressed",
onScroll: "handleScroll",
onWordwrap: "toggleww"
},
{name: "imageViewer", kind: "enyo.Image"}
]}
]},
{name: "right", kind: "rightPanels", showing: false, classes: "ares_phobos_right", arrangerKind: "CardArranger"}
]}
]},
{name: "autocomplete", kind: "Phobos.AutoComplete"},
{name: "findpop", kind: "FindPopup", centered: true, modal: true, floating: true, onFindNext: "findNext", onFindPrevious: "findPrevious", onReplace: "replace", onReplaceAll:"replaceAll", onHide:"doAceFocus", onClose: "findClose", onReplaceFind: "replacefind"},
{
name: "editorSettingsPopup",
kind: "onyx.Popup",
classes:"enyo-unselectable ares-classic-popup",
centered: true,
modal: true,
floating: true,
autoDismiss: false,
onCloseSettings: "closeEditorPopup",
onChangeSettings:"applyPreviewSettings",
onChangeRightPane: "changeRightPane",
components: [
{name:"title", classes: "title draggable", kind: "Ares.PopupTitle", content: "EDITOR GLOBAL SETTINGS"},
{kind: "editorSettings", classes:"ace-settings-popup" }
],
}
],
events: {
onHideWaitPopup: "",
onError: "",
onRegisterMe: "",
onFileEdited: " ",
onChildRequest: "",
onAceFocus: ""
},
handlers: {
onCss: "newcssAction",
onReparseAsked: "reparseAction",
onInitNavigation: "initNavigation",
onNavigateInCodeEditor: "navigateInCodeEditor"
},
published: {
projectData: null,
objectsToDump: []
},
editedDocs:"",
injected: false,
debug: false,
// Container of the code to analyze and of the analysis result
analysis: {},
helper: null, // Analyzer.KindHelper
closeAll: false,
create: function() {
ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value
this.inherited(arguments);
this.helper = new analyzer.Analyzer.KindHelper();
},
getProjectController: function() {
// create projectCtrl only when needed. In any case, there's only
// one Phobos and one projectCtrl in Ares
this.projectCtrl = this.projectData.getProjectCtrl();
if ( ! this.projectCtrl) {
this.projectCtrl = new ProjectCtrl({projectData: this.projectData});
// wire event propagation from there to Phobos
this.projectCtrl.setOwner(this);
this.projectData.setProjectCtrl(this.projectCtrl);
}
},
saveNeeded: function() {
return this.docData.getEdited();
},
openDoc: function(inDocData) {
// If we are changing documents, reparse any changes into the current projectIndexer
if (this.docData && this.docData.getEdited()) {
this.reparseUsersCode(true);
}
// Set up the new doucment
this.docData = inDocData;
this.setProjectData(this.docData.getProjectData());
this.getProjectController();
this.setAutoCompleteData();
// Save the value to set it again after data has been loaded into ACE
var edited = this.docData.getEdited();
var file = this.docData.getFile();
var extension = file.name.split(".").pop();
this.hideWaitPopup();
this.analysis = null;
var mode = {
json: "json",
design: "json",
js: "javascript",
html: "html",
css: "css",
coffee: "coffee",
dot: "dot",
patch: "diff",
diff: "diff",
jade: "jade",
less: "less",
md: "markdown",
markdown: "markdown",
svg: "svg",
xml: "xml",
jpeg: "image",
jpg: "image",
png: "image",
gif: "image"
}[extension] || "text";
this.docData.setMode(mode);
var hasAce = this.adjustPanelsForMode(mode, this.$.editorSettings.getSettingFromLS().rightpane);
if (hasAce) {
var aceSession = this.docData.getAceSession();
if (aceSession) {
this.$.aceWrapper.setSession(aceSession);
} else {
aceSession = this.$.aceWrapper.createSession(this.docData.getData(), mode);
this.$.aceWrapper.setSession(aceSession);
this.docData.setAceSession(aceSession);
}
// Pass to the autocomplete compononent a reference to ace
this.$.autocomplete.setAceWrapper(this.$.aceWrapper);
this.focusEditor();
/* set editor to user pref */
this.$.aceWrapper.applyAceSettings(this.$.editorSettings.getSettingFromLS());
this.$.aceWrapper.editingMode = mode;
} else {
var config = this.projectData.getService().getConfig();
var fileUrl = config.origin + config.pathname + "/file" + file.path;
this.$.imageViewer.setAttribute("src", fileUrl);
}
this.manageDesignerButton();
this.reparseUsersCode(true);
this.projectCtrl.buildProjectDb();
this.docData.setEdited(edited);
},
adjustPanelsForMode: function(mode, rightpane) {
this.trace("mode:", mode);
var showModes = {
javascript: {
imageViewer: false,
aceWrapper: true,
saveButton: true,
saveAsButton: true,
newKindButton: true,
designerDecorator: true,
right: rightpane
},
image: {
imageViewer: true,
aceWrapper: false,
saveButton: false,
saveAsButton: false,
newKindButton: false,
designerDecorator: false,
right: false
},
text: {
imageViewer: false,
aceWrapper: true,
saveButton: true,
saveAsButton: true,
newKindButton: false,
designerDecorator: false,
right: false
}
};
var showStuff, showSettings = showModes[mode] || showModes['text'];
for (var stuff in showSettings) {
showStuff = showSettings[stuff];
this.trace("show", stuff, ":", showStuff);
// FIXME need to clean up this code ENYO-3633
if(this.$[stuff] !== undefined){
if (typeof this.$[stuff].setShowing === 'function') {
this.$[stuff].setShowing(showStuff) ;
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
} else if (this.owner.$.editorFileMenu.$[stuff] !== undefined && this.owner.$.designerFileMenu.$[stuff] !== undefined) {
var editorFileMenu = this.owner.$.editorFileMenu.$[stuff];
var designerFileMenu = this.owner.$.designerFileMenu.$[stuff];
if (typeof editorFileMenu.setShowing === 'function' && typeof designerFileMenu.setShowing === 'function') {
editorFileMenu.setShowing(showStuff);
designerFileMenu.setShowing(showStuff);
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
} else {
if (typeof this.owner.$[stuff].setShowing === 'function') {
this.owner.$[stuff].setShowing(showStuff) ;
} else {
this.warn("BUG: attempting to show/hide a non existing element: ", stuff);
}
}
}
// xxxIndex: specify what to show in the "RightPanels" kinds (declared at the end of this file)
// xxxIndex is ignored when matching show setting is false
var modes = {
json: {rightIndex: 0},
javascript: {rightIndex: 1},
html: {rightIndex: 2},
css: {rightIndex: 3},
text: {rightIndex: 0},
image: {rightIndex: 0}
};
var settings = modes[mode]||modes['text'];
this.$.right.setIndex(settings.rightIndex);
this.resizeHandler();
return showSettings.aceWrapper ;
},
hideWaitPopup: function() {
this.doHideWaitPopup();
},
//
setAutoCompleteData: function() {
this.$.autocomplete.hide();
this.$.autocomplete.setProjectData(this.projectData);
this.manageDesignerButton();
},
resetAutoCompleteData: function() {
this.$.autocomplete.setProjectData(null);
},
/**
* Enable "Designer" button only if project & enyo index are both valid
*/
manageDesignerButton: function() {
this.doChildRequest({ task: [ "enableDesignerButton", this.projectCtrl.fullAnalysisDone ]} );
},
/**
* Receive the project data reference which allows to access the analyzer
* output for the project's files, enyo/onyx and all the other project
* related information shared between phobos and deimos.
* @param oldProjectData
* @protected
*/
projectDataChanged: function(oldProjectData) {
if (this.projectData) {
this.projectData.on('update:project-indexer', this.projectIndexerChanged, this);
}
if (oldProjectData) {
oldProjectData.off('update:project-indexer', this.projectIndexerChanged);
}
},
/**
* The current project analyzer output has changed
* Re-scan the indexer
* @param value the new analyzer output
* @protected
*/
projectIndexerChanged: function() {
this.trace("Project analysis ready");
this.manageDesignerButton();
},
dumpInfo: function(inObject) {
var h = [];
this.$.right.setDumpCount(0);
if (!inObject || !inObject.superkinds) {
h.push("no content");
this.objectsToDump = h;
this.$.right.setDumpCount(this.objectsToDump.length);
return;
}
var c = inObject;
h.push(c.name);
h.push("Extends");
for (var i=0, p; (p=c.superkinds[i]); i++) {
p = {name: c.superkinds[i], isExtended: true};
h.push(p);
}
if (c.components.length) {
h.push("Components");
for (i=0, p; (p=c.components[i]); i++) {
h.push(p);
}
}
h.push("Properties");
for (i=0, p; (p=c.properties[i]); i++) {
h.push(p);
}
this.objectsToDump = h;
this.$.right.setDumpCount(this.objectsToDump.length);
},
// invoked by reparse button in right panel (the file index)
reparseAction: function(inSender, inEvent) {
this.reparseUsersCode(true);
},
initNavigation: function(inSender, inEvent) {
var item = inEvent.item.$.item,
index = inEvent.item.index,
object = this.objectsToDump[index];
if (object.isExtended){
item.setFixedItem(object.name);
} else if (object.name){
item.setNavigateItem(object.name);
} else {
item.setTitle(object);
}
item.setIndex(index);
return true;
},
navigateInCodeEditor: function(inSender, inEvent) {
var itemToSelect = this.objectsToDump[inEvent.index];
if(itemToSelect.start && itemToSelect.end){
this.$.aceWrapper.navigateToPosition(itemToSelect.start, itemToSelect.end);
this.doAceFocus();
}
},
//* Updates the projectIndexer (notifying watchers by default) and resets the local analysis file
reparseUsersCode: function(inhibitUpdate) {
var mode = this.docData.getMode();
var codeLooksGood = false;
var module = {
name: this.docData.getFile().name,
code: this.$.aceWrapper.getValue(),
path: this.projectCtrl.projectUrl + this.docData.getFile().dir + this.docData.getFile().name
};
this.trace("called with mode " , mode , " inhibitUpdate " , inhibitUpdate , " on " + module.name);
switch(mode) {
case "javascript":
try {
this.analysis = module;
this.projectData.getProjectIndexer().reIndexModule(module);
if (inhibitUpdate !== true) {
this.projectData.updateProjectIndexer();
}
this.updateObjectsLines(module);
// dump the object where the cursor is positioned, if it exists
this.dumpInfo(module.objects && module.objects[module.currentObject]);
// Give the information to the autocomplete component
this.$.autocomplete.setAnalysis(this.analysis);
codeLooksGood = true;
} catch(error) {
enyo.log("An error occured during the code analysis: " , error);
this.dumpInfo(null);
this.$.autocomplete.setAnalysis(null);
}
break;
case "json":
if (module.name.slice(-7) == ".design") {
this.projectData.getProjectIndexer().reIndexDesign(module);
if (inhibitUpdate !== true) {
this.projectData.updateProjectIndexer();
}
}
this.analysis = null;
this.$.autocomplete.setAnalysis(null);
break;
default:
this.analysis = null;
this.$.autocomplete.setAnalysis(null);
break;
}
return codeLooksGood ;
},
/**
* Add for each object the corresponding range of lines in the file
* Update the information about the object currently referenced
* by the cursor position
* TODO: see if this should go in Analyzer2
*/
updateObjectsLines: function(module) {
module.ranges = [];
if (module.objects && module.objects.length > 0) {
var start = 0, range;
for( var idx = 1; idx < module.objects.length ; idx++ ) {
range = { first: start, last: module.objects[idx].line - 1};
module.ranges.push(range); // Push a range for previous object
start = module.objects[idx].line;
}
// Push a range for the last object
range = { first: start, last: 1000000000};
module.ranges.push(range);
}
var position = this.$.aceWrapper.getCursorPositionInDocument();
module.currentObject = this.findCurrentEditedObject(position);
module.currentRange = module.ranges[module.currentObject];
module.currentLine = position.row;
},
/**
* Return the index (in the analyzer result ) of the enyo kind
* currently edited (in which the cursor is)
* Otherwise return -1
* @returns {Number}
*/
findCurrentEditedObject: function(position) {
if (this.analysis && this.analysis.ranges) {
for( var idx = 0 ; idx < this.analysis.ranges.length ; idx++ ) {
if (position.row <= this.analysis.ranges[idx].last) {
return idx;
}
}
}
return -1;
},
/**
* Navigate from Phobos to Deimos. Pass Deimos all relevant info.
*/
designerAction: function() {
// Update the projectIndexer and notify watchers
this.reparseUsersCode();
var kinds = this.extractKindsData(),
data = {
kinds: kinds,
projectData: this.projectData,
fileIndexer: this.analysis
};
if (kinds.length > 0) {
// Request to design the current document, passing info about all kinds in the file
this.doChildRequest({ task: [ 'designDocument', data ]});
} // else - The error has been displayed by extractKindsData()
},
//* Extract info about kinds from the current file needed by the designer
extractKindsData: function() {
var c = this.$.aceWrapper.getValue(),
kinds = [];
if (this.analysis) {
var nbKinds = 0;
var errorMsg;
var i, o;
var oLen = this.analysis.objects.length;
for (i=0; i < oLen; i++) {
o = this.analysis.objects[i];
if (o.type !== "kind") {
errorMsg = $L("Ares does not support methods out of a kind. Please place '" + o.name + "' into a separate .js file");
} else {
nbKinds++;
}
}
if (nbKinds === 0) {
errorMsg = $L("No kinds found in this file");
}
if (errorMsg) {
this.doError({msg: errorMsg});
return [];
}
for (i=0; i < oLen; i++) {
o = this.analysis.objects[i];
var start = o.componentsBlockStart;
var end = o.componentsBlockEnd;
var kindBlock = enyo.json.codify.from(c.substring(o.block.start, o.block.end));
var name = o.name;
var kind = kindBlock.kind || o.superkind;
var comps = [];
if (start && end) {
var js = c.substring(start, end);
/* jshint evil: true */
comps = eval("(" + js + ")"); // TODO: ENYO-2074, replace eval. Why eval? Because JSON.parse doesn't support unquoted keys...
/* jshint evil: false */
}
var comp = {
name: name,
kind: kind,
components: comps
};
for (var j=0; j < o.properties.length; j++) {
var prop = o.properties[j];
var pName = prop.name;
var value = this.verifyValueType(analyzer.Documentor.stripQuotes(prop.value[0].name));
if ((start === undefined || prop.start < start) && pName !== "components") {
if (value === "{" || value === "[" || value === "function") {
comp[pName] = kindBlock[pName];
} else {
comp[pName] = value;
}
}
}
kinds.push(comp);
}
}
return kinds;
},
/**
* Converts string representation of boolean values
* to boolean
* TODO: Verify false-positives (ex: strings meant to be strings)
* @param inProps: the value to match
* @returns boolean value if match found: inValue if no matches
* @protected
*/
verifyValueType: function(inValue) {
if (inValue === "true") {
inValue = true;
} else if (inValue === "false") {
inValue = false;
}
return inValue;
},
/**
* Lists the handler methods mentioned in the "handlers"
* attributes and in the sub-components of the kind object
* passed as a parameter
* @param object: the kind definition to explore
* @param declared: list of handler methods already listed
* @returns the list of declared handler methods
*/
listHandlers: function(object, declared) {
try {
this.helper.setDefinition(object);
return this.helper.listHandlers(declared);
} catch(error) {
enyo.log("Unexpected error: " , error); // TODO TBC
}
},
/**
* This function checks all the kinds and add the missing
* handler functions listed in the "onXXXX" attributes
* @protected
* Note: This implies to reparse/analyze the file before
* and after the operation.
*/
insertMissingHandlers: function() {
if (this.analysis) {
// Reparse to get the definition of possibly added onXXXX attributes
this.reparseUsersCode(true);
/*
* Insert missing handlers starting from the end of the
* file to limit the need of reparsing/reanalysing
* the file
*/
for( var i = this.analysis.objects.length -1 ; i >= 0 ; i-- ) {
var obj = this.analysis.objects[i];
if (obj.components) {
this.insertMissingHandlersIntoKind(obj);
}
}
// Reparse to get the definition of the newly added methods
this.reparseUsersCode(true);
} else {
// There is no parser data for the current file
enyo.log("Unable to insert missing handler methods");
}
},
/**
* This function checks the kind passed as an inout parameter
* and add the missing handler functions listed in the "onXXXX" attributes
* @param object
* @protected
*/
insertMissingHandlersIntoKind: function(object) {
var commaTerminated = false,
commaInsertionIndex = 0;
// List existing handlers
var existing = {};
for(var j = 0 ; j < object.properties.length ; j++) {
var p = object.properties[j];
commaTerminated = p.commaTerminated;
if (p.value[0].name === 'function') {
existing[p.name] = "";
commaInsertionIndex = p.value[0].block.end; // Index of function block ending curly braket
} else {
commaInsertionIndex = p.value[0].end; // Index of property definition
}
}
// List the handler methods declared in the components and in handlers map
var declared = this.listHandlers(object, {});
// insert the missing handler methods code in the editor
if (object.block) {
var lineTermination = this.$.aceWrapper.getNewLineCharacter(),
codeInsertionIndex = object.block.end - 1, // Index before kind block ending curly braket
codeInsertionPosition;
var commaInsertionPosition = null;
if (!commaTerminated) {
commaInsertionPosition = this.$.aceWrapper.mapToLineColumns([commaInsertionIndex]);
commaTerminated = true;
}
// Prepare the code to insert
var codeToInsert = "";
for(var item in declared) {
if (item !== "" && existing[item] === undefined) {
// use correct line terminations
codeToInsert += (commaTerminated ? "" : "," + lineTermination);
commaTerminated = false;
codeToInsert += ("\t" + item + ": function(inSender, inEvent) {" + lineTermination);
if(this.$.editorSettingsPopup.settings.autotrace === true){
codeToInsert += ('\t\t' + this.$.editorSettingsPopup.settings.autotraceLine + lineTermination);
}
codeToInsert += ("\t\t// TO DO - Auto-generated code" + lineTermination + "\t}");
}
}
if (codeToInsert !== "") {
// add a comma after the last function/property if required
if (commaInsertionPosition) {
this.$.aceWrapper.insertPosition(commaInsertionPosition[0], ",");
codeInsertionIndex++; // position shifted because of comma character addition
}
commaInsertionIndex++; // index after comma character added or already present
// detect if block ending curly braket is contiguous to previous function or property ending: curly bracket w/wo comma, value w/wo comma
if (commaInsertionIndex === codeInsertionIndex) {
commaInsertionPosition = this.$.aceWrapper.mapToLineColumns([commaInsertionIndex]);
this.$.aceWrapper.insertNewLine(commaInsertionPosition[0]);
codeInsertionIndex += lineTermination.length; // shifted because of line termination addition, is sentitive to line termination mode
}
// Add a new line before kind block ending curly braket
codeInsertionPosition = this.$.aceWrapper.mapToLineColumns([codeInsertionIndex]);
this.$.aceWrapper.insertNewLine(codeInsertionPosition[0]);
// Get the corresponding Ace range to replace/insert the missing code
// NB: aceWrapper.replace() allow to use the undo/redo stack.
var codeInsertionRange = this.$.aceWrapper.mapToLineColumnRange(codeInsertionIndex, codeInsertionIndex);
this.$.aceWrapper.replaceRange(codeInsertionRange, codeToInsert);
}
} else {
// There is no block information for that kind - Parser is probably not up-to-date
enyo.log("Unable to insert missing handler methods");
}
},
// called when designer has modified the components
updateComponentsCode: function(kinds) {
this.injected = true;
for( var i = this.analysis.objects.length -1 ; i >= 0 ; i-- ) {
if (kinds[i]) {
// Insert the new version of components (replace components block, or insert at end)
var obj = this.analysis.objects[i];
var content = kinds[i];
var start = obj.componentsBlockStart;
var end = obj.componentsBlockEnd;
var kindStart = obj.block.start;
if (!(start && end)) {
// If this kind doesn't have a components block yet, insert a new one
// at the end of the file
var last = obj.properties[obj.properties.length-1];
if (last) {
content = (last.commaTerminated ? "" : ",") + "\n\t" + "components: []";
kindStart = obj.block.end - 2;
end = obj.block.end - 2;
}
}
// Get the corresponding Ace range to replace the component definition
// NB: aceWrapper.replace() allow to use the undo/redo stack.
var range = this.$.aceWrapper.mapToLineColumnRange(kindStart, end);
this.$.aceWrapper.replaceRange(range, content);
}
}
this.injected = false;
/*
* Insert the missing handlers
* NB: reparseUsersCode() is invoked by insertMissingHandlers()
*/
this.insertMissingHandlers();
//file is edited if only we have a difference between stored file data and editor value
if(this.getEditorContent().localeCompare(this.docData.getData())!==0){
this.docData.setEdited(true);
this.doFileEdited();
}
},
docChanged: function(inSender, inEvent) {
//this.injected === false then modification coming from user
if(!this.injected && !this.docData.getEdited()){
this.docData.setEdited(true);
this.doFileEdited();
}
this.trace("data:", enyo.json.stringify(inEvent.data));
if (this.analysis) {
// Call the autocomplete component
this.$.autocomplete.start(inEvent);
}
return true; // Stop the propagation of the event
},
editorUserSyntaxError:function(){
var userSyntaxError = [];
userSyntaxError = this.$.autocomplete.aceWrapper.editor.session.$annotations.length;
return userSyntaxError;
},
cursorChanged: function(inSender, inEvent) {
var position = this.$.aceWrapper.getCursorPositionInDocument();
this.trace(inSender.id, " ", inEvent.type, " ", enyo.json.stringify(position));
// Check if we moved to another enyo kind and display it in the right pane
var tempo = this.analysis;
if (tempo && tempo.currentLine !== undefined && tempo.currentLine != position.row) { // If no more on the same line
tempo.currentLine = position.row;
// Check if the cursor references another object
if (tempo.currentRange !== undefined && (position.row < tempo.currentRange.first || position.row > tempo.currentRange.last)) {
tempo.currentObject = this.findCurrentEditedObject(position);
tempo.currentRange = tempo.ranges[tempo.currentObject];
this.dumpInfo(tempo.objects && tempo.objects[tempo.currentObject]);
}
}
this.$.autocomplete.cursorChanged(position);
return true; // Stop the propagation of the event
},
startAutoCompletion: function() {
this.$.autocomplete.start(null);
},
newKindAction: function() {
// Insert a new empty enyo kind at the end of the file
var newKind = 'enyo.kind({\n name : "@cursor@",\n kind : "Control",\n components : []\n});';
this.$.aceWrapper.insertAtEndOfFile(newKind, '@cursor@');
},
newcssAction: function(inSender, inEvent){
this.$.aceWrapper.insertAtEndOfFile(inEvent.outPut);
},
/*
* cleanup data. Typically called when closing a document
* @protected
*/
closeSession: function() {
if (this.docData) {
this.$.aceWrapper.destroySession(this.docData.getAceSession());
this.resetAutoCompleteData();
this.docData = null;
}
},
// Show Find popup
findpop: function(){
var selected = this.$.aceWrapper.getSelection();
if(selected){
this.$.findpop.setFindInput(selected);
}
this.$.findpop.removeMessage();
this.$.findpop.disableReplaceButtons(true);
this.$.findpop.show();
return true;
},
findNext: function(inSender, inEvent){
var options = {backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.find(this.$.findpop.findValue, options);
this.$.findpop.updateAfterFind(this.$.aceWrapper.getSelection());
},
findPrevious: function(){
var options = {backwards: true, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.find(this.$.findpop.findValue, options);
this.$.findpop.updateAfterFind(this.$.aceWrapper.getSelection());
},
replaceAll: function(){
var occurences = this.$.aceWrapper.replaceAll(this.$.findpop.findValue , this.$.findpop.replaceValue);
this.$.findpop.updateMessage(this.$.aceWrapper.getSelection(), occurences);
},
replacefind: function(){
var options = {backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: false};
this.$.aceWrapper.replacefind(this.$.findpop.findValue , this.$.findpop.replaceValue, options);
this.$.findpop.updateMessage(this.$.aceWrapper.getSelection());
},
//ACE replace doesn't replace the currently-selected match. It instead replaces the *next* match. Seems less-than-useful
//It was not working because ACE(Ace.js) was doing "find" action before "replace".
replace: function(){
this.$.aceWrapper.replace(this.$.findpop.findValue, this.$.findpop.replaceValue);
},
focusEditor: function(inSender, inEvent) {
this.$.aceWrapper.focus();
},
getEditorContent: function() {
return this.$.aceWrapper.getValue();
},
handleScroll: function(inSender, inEvent) {
this.$.autocomplete.hide();
},
findClose: function(){
this.$.findpop.hide();
},
toggleww: function(){
if(this.$.aceWrapper.wordWrap === "true" || this.$.aceWrapper.wordWrap === true){
this.$.aceWrapper.wordWrap = false;
this.$.aceWrapper.wordWrapChanged();
}else{
this.$.aceWrapper.wordWrap = true;
this.$.aceWrapper.wordWrapChanged();
}
},
/** @public */
requestSelectedText: function() {
return this.$.aceWrapper.requestSelectedText();
},
/**
* Add a new kind (requested from the designer)
* A switch to the designer is performed to fully reload the kinds in the designer.
* @param config
* @public
*/
addNewKind: function(config) {
var newKind = 'enyo.kind('+config+'\n);';
this.$.aceWrapper.insertAtEndOfFile(newKind, '@cursor@');
this.designerAction();
},
/**
* Insert a new kind (requested from the designer)
* A switch to the designer is performed to fully reload the kinds in the designer.
* @param kind_index, config
* @public
*/
replaceKind: function(kind_index, config){
var obj = this.analysis.objects[kind_index];
var range = this.$.aceWrapper.mapToLineColumnRange(obj.block.start, obj.block.end);
this.$.aceWrapper.replaceRange(range, config);
this.designerAction();
},
//* editor setting
editorSettings: function() {
this.$.editorSettingsPopup.show();
this.$.editorSettings.initSettings();
},
closeEditorPopup: function(){
this.$.editorSettingsPopup.hide();
this.doAceFocus();
return true;
},
changeRightPane: function(settings){
if(this.docData){
this.adjustPanelsForMode(this.docData.getMode(), settings.rightpane);
}
},
applySettings: function(settings){
//apply Ace settings
this.$.aceWrapper.applyAceSettings(settings);
if(this.docData){
this.adjustPanelsForMode(this.docData.getMode(), settings.rightpane);
}
},
fkeypressed: function(inSender, inEvent) {
var key = inEvent;
this.$.aceWrapper.insertAtCursor(this.$.editorSettings.settings.keys[ key ]);
},
//* Trigger an Ace undo and bubble updated code
undoAndUpdate: function(next) {
ares.assertCb(next);
this.$.aceWrapper.undo();
this.updateCodeInDesigner(next);
},
//* Trigger an Ace undo and bubble updated code
redoAndUpdate: function(next) {
ares.assertCb(next);
this.$.aceWrapper.redo();
this.updateCodeInDesigner(next);
},
//* Send up an updated copy of the code
updateCodeInDesigner: function(next) {
// Update the projectIndexer and notify watchers
this.reparseUsersCode(true);
var data = {kinds: this.extractKindsData(), projectData: this.projectData, fileIndexer: this.analysis};
if (data.kinds.length > 0) {
this.doChildRequest({task: [ "loadDesignerUI", data, next ]});
} // else - The error has been displayed by extractKindsData()
},
resizeHandler: function() {
this.inherited(arguments);
this.$.body.reflow();
this.$.aceWrapper.resize();
}
});
enyo.kind({
name: "rightPanels", kind: "Panels", wrap: false, draggable:false,
events: {
onCss: "",
onReparseAsked: "",
onInitNavigation: "",
onNavigateInCodeEditor: ""
},
components: [
{// right panel for JSON goes here
},
{kind: "enyo.Control", classes: "enyo-fit", components: [
{name: "right", classes: "enyo-fit ares_phobos_panel border", components: [
{kind: "onyx.Button", content: "Reparse", ontap: "doReparseAsked"},
{kind: "enyo.Scroller", classes: "enyo-fit ace-helper-panel",components: [
{tag:"ul", kind: "enyo.Repeater", name: "dump", onSetupItem: "sendInitHelperReapeter", ontap: "sendNavigate", components: [
{tag:"li", classes:"ace-helper-list", kind:"RightPanel.Helper", name: "item"}
]}
]}
]}
]},
{// right panel for HTML goes here
},
{kind: "enyo.Control", classes: "enyo-fit", components: [ // right panel for CSS here
{kind: "cssBuilder", classes: "enyo-fit ares_phobos_panel border", onInsert: "test"}
]}
],
create: function() {
this.inherited(arguments);
},
test: function(inEvent) {
this.doCss(inEvent);
},
sendInitHelperReapeter: function(inSender, inEvent) {
this.doInitNavigation({item: inEvent.item});
},
sendNavigate: function(inSender, inEvent){
this.doNavigateInCodeEditor({index:inEvent.index});
},
setDumpCount: function(count){
this.$.dump.setCount(count);
}
});
enyo.kind({
name: "RightPanel.Helper",
published: {
title: "",
fixedItem: "",
navigateItem: "",
index: -1
},
components: [
{name: "title", classes: "ace-title"},
{name: "fixedItem", classes: "ace-fixed-item"},
{name: "navigateItem", kind: "control.Link", classes: "ace-navigate-item"}
],
titleChanged: function() {
this.$.title.setContent(this.title);
},
fixedItemChanged: function() {
this.$.fixedItem.setContent(this.fixedItem);
},
navigateItemChanged: function() {
this.$.navigateItem.setContent(this.navigateItem);
}
});
| Change editorSettingsPopup too editorSettings
| phobos/source/Phobos.js | Change editorSettingsPopup too editorSettings | <ide><path>hobos/source/Phobos.js
<ide> codeToInsert += (commaTerminated ? "" : "," + lineTermination);
<ide> commaTerminated = false;
<ide> codeToInsert += ("\t" + item + ": function(inSender, inEvent) {" + lineTermination);
<del> if(this.$.editorSettingsPopup.settings.autotrace === true){
<del> codeToInsert += ('\t\t' + this.$.editorSettingsPopup.settings.autotraceLine + lineTermination);
<add> // Auto trace line Insert's
<add> if(this.$.editorSettings.settings.autotrace === true && this.$.editorSettings.settings.autotraceLine !== null){
<add> codeToInsert += ('\t\t' + this.$.editorSettings.settings.autotraceLine + lineTermination);
<ide> }
<ide> codeToInsert += ("\t\t// TO DO - Auto-generated code" + lineTermination + "\t}");
<ide> } |
|
Java | apache-2.0 | b12db577dca502bcd082ed2668d352a74e59a49b | 0 | CAFAudit/audit-service,CAFAudit/audit-service,CAFAudit/audit-service |
/*
* Copyright 2015-2017 EntIT Software LLC, a Micro Focus company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hpe.caf.auditing.plugins.unittest;
import com.hpe.caf.auditing.AuditChannel;
import com.hpe.caf.auditing.AuditEventBuilder;
import com.hpe.caf.auditing.AuditIndexingHint;
import java.util.Date;
/**
* Auto-generated class for writing ProductX events to the audit log
*/
public final class AuditLog
{
private static final String APPLICATION_IDENTIFIER = "ProductX";
private AuditLog() {
}
/**
* Checks that the AuditLog queue exists and creates it if it doesn't.
* This function should be called before any of the audit... functions are called.
*/
public static void declareApplication(final AuditChannel channel)
throws Exception
{
channel.declareApplication(APPLICATION_IDENTIFIER);
}
/**
* Audit the viewDocument event
* @param channel Identifies the channel to be used for message queuing
* @param tenantId Identifies the tenant that the user belongs to
* @param userId Identifies the user who triggered the event
* @param correlationId Identifies the same user action
* @param String_Param Description for String_Param
* @param String_Fulltext_Param Description for String_Fulltext_Param
* @param String_Keyword_Param Description for String_Keyword_Param
* @param String_With_Constraints_Param Description for String_With_Constraints_Param
* @param Int16_Param Description for Int16_Param
* @param Int32_Param Description for Int32_Param
* @param Int64_Param Description for Int64_Param
* @param Float_Param Description for Float_Param
* @param Double_Param Description for Double_Param
* @param Boolean_Param Description for Boolean_Param
* @param Date_Param Description for Date_Param
*/
public static void auditViewDocument
(
final AuditChannel channel,
final String tenantId,
final String userId,
final String correlationId,
final String String_Param,
final String String_Fulltext_Param,
final String String_Keyword_Param,
final String String_With_Constraints_Param,
final short Int16_Param,
final int Int32_Param,
final long Int64_Param,
final float Float_Param,
final double Double_Param,
final boolean Boolean_Param,
final Date Date_Param
)
throws Exception
{
final AuditEventBuilder auditEventBuilder = channel.createEventBuilder();
auditEventBuilder.setApplication(APPLICATION_IDENTIFIER);
auditEventBuilder.setTenant(tenantId);
auditEventBuilder.setUser(userId);
auditEventBuilder.setCorrelationId(correlationId);
auditEventBuilder.setEventType("documentEvents", "viewDocument");
auditEventBuilder.addEventParameter("String_Param", null, String_Param);
auditEventBuilder.addEventParameter("String_Fulltext_Param", null, String_Fulltext_Param, AuditIndexingHint.FULLTEXT);
auditEventBuilder.addEventParameter("String_Keyword_Param", null, String_Keyword_Param, AuditIndexingHint.KEYWORD);
auditEventBuilder.addEventParameter("String_With_Constraints_Param", null, String_With_Constraints_Param, 1, 32);
auditEventBuilder.addEventParameter("Int16_Param", null, Int16_Param);
auditEventBuilder.addEventParameter("Int32_Param", null, Int32_Param);
auditEventBuilder.addEventParameter("Int64_Param", null, Int64_Param);
auditEventBuilder.addEventParameter("Float_Param", null, Float_Param);
auditEventBuilder.addEventParameter("Double_Param", null, Double_Param);
auditEventBuilder.addEventParameter("Boolean_Param", null, Boolean_Param);
auditEventBuilder.addEventParameter("Date_Param", null, Date_Param);
auditEventBuilder.send();
}
}
| caf-audit-maven-plugin/src/test/resources/transform/AuditLog.java | /*
* Copyright 2015-2017 EntIT Software LLC, a Micro Focus company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hpe.caf.auditing.plugins.unittest;
import com.hpe.caf.auditing.AuditChannel;
import com.hpe.caf.auditing.AuditEventBuilder;
import com.hpe.caf.auditing.AuditIndexingHint;
import java.util.Date;
/**
* Auto-generated class for writing ProductX events to the audit log
*/
public final class AuditLog
{
private static final String APPLICATION_IDENTIFIER = "ProductX";
private AuditLog() {
}
/**
* Checks that the AuditLog queue exists and creates it if it doesn't.
* This function should be called before any of the audit... functions are called.
*/
public static void declareApplication(final AuditChannel channel)
throws Exception
{
channel.declareApplication(APPLICATION_IDENTIFIER);
}
/**
* Audit the viewDocument event
* @param channel Identifies the channel to be used for message queuing
* @param tenantId Identifies the tenant that the user belongs to
* @param userId Identifies the user who triggered the event
* @param correlationId Identifies the same user action
* @param String_Param Description for String_Param
* @param String_Fulltext_Param Description for String_Fulltext_Param
* @param String_Keyword_Param Description for String_Keyword_Param
* @param String_With_Constraints_Param Description for String_With_Constraints_Param
* @param Int16_Param Description for Int16_Param
* @param Int32_Param Description for Int32_Param
* @param Int64_Param Description for Int64_Param
* @param Float_Param Description for Float_Param
* @param Double_Param Description for Double_Param
* @param Boolean_Param Description for Boolean_Param
* @param Date_Param Description for Date_Param
*/
public static void auditViewDocument
(
final AuditChannel channel,
final String tenantId,
final String userId,
final String correlationId,
final String String_Param,
final String String_Fulltext_Param,
final String String_Keyword_Param,
final String String_With_Constraints_Param,
final short Int16_Param,
final int Int32_Param,
final long Int64_Param,
final float Float_Param,
final double Double_Param,
final boolean Boolean_Param,
final Date Date_Param
)
throws Exception
{
final AuditEventBuilder auditEventBuilder = channel.createEventBuilder();
auditEventBuilder.setApplication(APPLICATION_IDENTIFIER);
auditEventBuilder.setTenant(tenantId);
auditEventBuilder.setUser(userId);
auditEventBuilder.setCorrelationId(correlationId);
auditEventBuilder.setEventType("documentEvents", "viewDocument");
auditEventBuilder.addEventParameter("String_Param", null, String_Param);
auditEventBuilder.addEventParameter("String_Fulltext_Param", null, String_Fulltext_Param, AuditIndexingHint.FULLTEXT);
auditEventBuilder.addEventParameter("String_Keyword_Param", null, String_Keyword_Param, AuditIndexingHint.KEYWORD);
auditEventBuilder.addEventParameter("String_With_Constraints_Param", null, String_With_Constraints_Param, 1, 32);
auditEventBuilder.addEventParameter("Int16_Param", null, Int16_Param);
auditEventBuilder.addEventParameter("Int32_Param", null, Int32_Param);
auditEventBuilder.addEventParameter("Int64_Param", null, Int64_Param);
auditEventBuilder.addEventParameter("Float_Param", null, Float_Param);
auditEventBuilder.addEventParameter("Double_Param", null, Double_Param);
auditEventBuilder.addEventParameter("Boolean_Param", null, Boolean_Param);
auditEventBuilder.addEventParameter("Date_Param", null, Date_Param);
auditEventBuilder.send();
}
}
| CAF-3615: Fixing failing test (#44)
| caf-audit-maven-plugin/src/test/resources/transform/AuditLog.java | CAF-3615: Fixing failing test (#44) | <ide><path>af-audit-maven-plugin/src/test/resources/transform/AuditLog.java
<add>
<ide> /*
<ide> * Copyright 2015-2017 EntIT Software LLC, a Micro Focus company.
<ide> * |
|
JavaScript | mit | 0de43bc06365f3e71b3a42151818e57504e5a28e | 0 | form-o-fill/form-o-fill-chrome-extension,form-o-fill/form-o-fill-chrome-extension,form-o-fill/form-o-fill-chrome-extension | /*eslint-env node */
"use strict";
// npm install --save-dev gulp gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css gulp-load-plugins chai gulp-mocha sinon sinon-chai jsdom
var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */
// Small webserver for testing with protractor
var connect = require('gulp-connect');
// End to End testing
var protractor = require("gulp-protractor").protractor;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
// Load the manifest as JSON
var manifest = require('./src/manifest');
// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";
// Configuration for the testserver
var serverConfig = {
port: 8888,
root: "testcases/docroot-for-testing"
};
var serverConfigIntegration = {
port: 8889,
root: "testcases/docroot-for-testing"
};
//
// Replacements config for gulp-replace
//
// 1. Sets debug: false (in utils.js)
// 2. Removes Logger statements
// 3. Remove everything in .js files between "// REMOVE START" and "REMOVE END"
// These blocks contain development code that gets optimized away
// 4. Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
// These blocks contain development code that gets optimized away
// 5. Activate blocks between "<!-- BUILD START" and "BUILD END -->"
// These contain the optimized files for the final build
// 6. Remove the "js:" array from the manifest
// These blocks contain development code that gets optimized away
// 7. Remove the "scripts:" array from the manifest
// These blocks contain development code that gets optimized away
// 8. Rename the "jsBuild" part in the manifest to be the "js" part
// These contain the optimized files for the final build
// 9. Rename the "scriptsBuild" part in the manifest to be the "scripts" part
// These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
var replaceOpts = {
preserveOrder: true,
patterns: [
{
match: /debug\s*:\s*true,/g,
replacement: "debug: false,"
},
{
match: /.*Logger.*/g,
replacement: ""
},
{
match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
replacement: ""
},
{
match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
replacement: ""
},
{
match: /<!-- BUILD START/g,
replacement: ""
},
{
match: /BUILD END -->/g,
replacement: ""
},
{
match: /^.*"js":[\s\S]*?\],.*$/gm,
replacement: ""
},
{
match: /^.*"scripts"[\s\S]*?\],.*$/gm,
replacement: ""
},
{
match: /"jsBuild"/g,
replacement: "\"js\""
},
{
match: /"scriptsBuild"/g,
replacement: "\"scripts\""
},
{
match: /##VERSION##/g,
replacement: manifest.version
}
]
};
var runTests = function() {
return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
R: 'dot',
c: true,
debug: true
})).on('error', console.warn.bind(console));
};
// Output which version to build where to
gulp.task('announce', function() {
gulpUtil.log(
'Building version', chalk.cyan(manifest.version),
'of', chalk.cyan(manifest.name),
'as', chalk.cyan("dist/" + distFilename)
);
});
// Cleans build and dist dirs
// I sense a bug here!
gulp.task('clean', ["announce"], function() {
return gulp.src(['build/**'], {read: false})
.pipe(rm({async: false}));
});
// ESLINT the javascript BEFORE uglifier ran over them
gulp.task('lint', function () {
return gulp.src(['src/js/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
// Optimize CSS
gulp.task('css', ['clean'], function () {
return gulp.src(["src/css/*.css", "!src/css/content.css", "!src/css/popup.css"])
.pipe(replace(replaceOpts))
.pipe(concat('formofill.css'))
.pipe(minifyCSS())
.pipe(gulp.dest('build/css/'));
});
// Build global.js
// Sadly until I use require.js here the order is important :(
gulp.task('globalJs', ['clean'], function () {
return gulp.src([
"src/js/global/utils.js",
"src/js/global/jsonf.js",
"src/js/global/storage.js",
"src/js/global/rule.js",
"src/js/global/rules.js",
"src/js/global/i18n.js",
"src/js/global/libs.js"
])
.pipe(replace(replaceOpts))
.pipe(concat('global.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build background.js
gulp.task('backgroundJs', ['clean'], function () {
return gulp.src("src/js/background/*.js")
.pipe(replace(replaceOpts))
.pipe(concat('background.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build content.js
gulp.task('contentJs', ['clean'], function () {
return gulp.src("src/js/content/*.js")
.pipe(replace(replaceOpts))
.pipe(concat('content.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build options.js
gulp.task('optionsJs', ['clean'], function () {
return gulp.src(["src/js/options/*.js", "!src/js/options/logs.js"])
.pipe(replace(replaceOpts))
.pipe(concat('options.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build popup.js
gulp.task('popupJs', ['clean'], function () {
return gulp.src("src/js/popup.js")
.pipe(replace(replaceOpts))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js'));
});
// Copies files that can be copied without changes
gulp.task('copyUnchanged', ['clean'], function() {
["fonts", "images", "vendor", "_locales"].forEach(function (dir) {
gulp.src('src/' + dir + '/**/*')
.pipe(gulp.dest('build/' + dir));
});
return gulp.src(['src/css/content.css', 'src/css/popup.css'])
.pipe(minifyCSS())
.pipe(replace(replaceOpts))
.pipe(gulp.dest('build/css'));
});
// Copies HTML files and removes comment and blocks (see above)
gulp.task('copyHtml', ['copyUnchanged'], function() {
return gulp.src(['src/html/**/*.html', '!src/html/option/_logs_*.html'])
.pipe(replace(replaceOpts))
.pipe(cleanhtml())
.pipe(gulp.dest('build/html'));
});
// Copies and replaces the manifest.json file (see above)
gulp.task('mangleManifest', [ 'clean' ], function() {
return gulp.src('src/manifest.json')
.pipe(replace(replaceOpts))
.pipe(gulp.dest('build'));
});
// Build a distribution
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'css', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
gulp.src(['build/**'])
.pipe(zip(distFilename))
.pipe(gulp.dest('dist'));
});
// Run tests
gulp.task('test', function () {
gulpUtil.log('Running tests');
return runTests().on('error', function (e) {
throw e;
});
});
// Run tests through watching
gulp.task('watch', function () {
gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});
// Integration testing(end-to-end)
// Uses protractor as an abstraction layer over chromedriver
// Chromedriver can be used without a running selenium server
// Starts a simple webserver on port 8888
gulp.task('integration', function () {
gulpUtil.log(
"If this fails with",
chalk.red("[launcher] Error: Could not find chromedriver"),
"run",
chalk.cyan("node_modules/protractor/bin/webdriver-manager update")
);
// Start a small webserver
connect.server(serverConfigIntegration);
return gulp.src([
"./test/support/integration_helper.js",
"./test/integration/*_scene.js"
])
.pipe(protractor({
configFile: "test/support/protractor.config.js",
args: ['--baseUrl', 'http://127.0.0.1:' + serverConfigIntegration.port]
}))
.on('error', function(e) {
throw e
})
.on('end', function() {
connect.serverClose();
});
});
// Start server for testing purposes
gulp.task('server', function() {
connect.server(serverConfig);
});
// Updates the selenium stuff in node_modules
gulp.task('webdriver_update', webdriverUpdate);
// running "gulp" will execute this
gulp.task('default', function () {
runTests();
});
| gulpfile.js | /*eslint-env node */
"use strict";
// npm install --save-dev gulp gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css gulp-load-plugins chai gulp-mocha sinon sinon-chai jsdom
var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */
// Small webserver for testing with protractor
var connect = require('gulp-connect');
// End to End testing
var protractor = require("gulp-protractor").protractor;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
// Load the manifest as JSON
var manifest = require('./src/manifest');
// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";
// Configuration for the testserver
var serverConfig = {
port: 8889,
root: "testcases/docroot-for-testing"
};
//
// Replacements config for gulp-replace
//
// 1. Sets debug: false (in utils.js)
// 2. Removes Logger statements
// 3. Remove everything in .js files between "// REMOVE START" and "REMOVE END"
// These blocks contain development code that gets optimized away
// 4. Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
// These blocks contain development code that gets optimized away
// 5. Activate blocks between "<!-- BUILD START" and "BUILD END -->"
// These contain the optimized files for the final build
// 6. Remove the "js:" array from the manifest
// These blocks contain development code that gets optimized away
// 7. Remove the "scripts:" array from the manifest
// These blocks contain development code that gets optimized away
// 8. Rename the "jsBuild" part in the manifest to be the "js" part
// These contain the optimized files for the final build
// 9. Rename the "scriptsBuild" part in the manifest to be the "scripts" part
// These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
var replaceOpts = {
preserveOrder: true,
patterns: [
{
match: /debug\s*:\s*true,/g,
replacement: "debug: false,"
},
{
match: /.*Logger.*/g,
replacement: ""
},
{
match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
replacement: ""
},
{
match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
replacement: ""
},
{
match: /<!-- BUILD START/g,
replacement: ""
},
{
match: /BUILD END -->/g,
replacement: ""
},
{
match: /^.*"js":[\s\S]*?\],.*$/gm,
replacement: ""
},
{
match: /^.*"scripts"[\s\S]*?\],.*$/gm,
replacement: ""
},
{
match: /"jsBuild"/g,
replacement: "\"js\""
},
{
match: /"scriptsBuild"/g,
replacement: "\"scripts\""
},
{
match: /##VERSION##/g,
replacement: manifest.version
}
]
};
var runTests = function() {
return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
R: 'dot',
c: true,
debug: true
})).on('error', console.warn.bind(console));
};
// Output which version to build where to
gulp.task('announce', function() {
gulpUtil.log(
'Building version', chalk.cyan(manifest.version),
'of', chalk.cyan(manifest.name),
'as', chalk.cyan("dist/" + distFilename)
);
});
// Cleans build and dist dirs
// I sense a bug here!
gulp.task('clean', ["announce"], function() {
return gulp.src(['build/**'], {read: false})
.pipe(rm({async: false}));
});
// ESLINT the javascript BEFORE uglifier ran over them
gulp.task('lint', function () {
return gulp.src(['src/js/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
// Optimize CSS
gulp.task('css', ['clean'], function () {
return gulp.src(["src/css/*.css", "!src/css/content.css", "!src/css/popup.css"])
.pipe(replace(replaceOpts))
.pipe(concat('formofill.css'))
.pipe(minifyCSS())
.pipe(gulp.dest('build/css/'));
});
// Build global.js
// Sadly until I use require.js here the order is important :(
gulp.task('globalJs', ['clean'], function () {
return gulp.src([
"src/js/global/utils.js",
"src/js/global/jsonf.js",
"src/js/global/storage.js",
"src/js/global/rule.js",
"src/js/global/rules.js",
"src/js/global/i18n.js",
"src/js/global/libs.js"
])
.pipe(replace(replaceOpts))
.pipe(concat('global.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build background.js
gulp.task('backgroundJs', ['clean'], function () {
return gulp.src("src/js/background/*.js")
.pipe(replace(replaceOpts))
.pipe(concat('background.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build content.js
gulp.task('contentJs', ['clean'], function () {
return gulp.src("src/js/content/*.js")
.pipe(replace(replaceOpts))
.pipe(concat('content.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build options.js
gulp.task('optionsJs', ['clean'], function () {
return gulp.src(["src/js/options/*.js", "!src/js/options/logs.js"])
.pipe(replace(replaceOpts))
.pipe(concat('options.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js/'));
});
// Build popup.js
gulp.task('popupJs', ['clean'], function () {
return gulp.src("src/js/popup.js")
.pipe(replace(replaceOpts))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest('build/js'));
});
// Copies files that can be copied without changes
gulp.task('copyUnchanged', ['clean'], function() {
["fonts", "images", "vendor", "_locales"].forEach(function (dir) {
gulp.src('src/' + dir + '/**/*')
.pipe(gulp.dest('build/' + dir));
});
return gulp.src(['src/css/content.css', 'src/css/popup.css'])
.pipe(minifyCSS())
.pipe(replace(replaceOpts))
.pipe(gulp.dest('build/css'));
});
// Copies HTML files and removes comment and blocks (see above)
gulp.task('copyHtml', ['copyUnchanged'], function() {
return gulp.src(['src/html/**/*.html', '!src/html/option/_logs_*.html'])
.pipe(replace(replaceOpts))
.pipe(cleanhtml())
.pipe(gulp.dest('build/html'));
});
// Copies and replaces the manifest.json file (see above)
gulp.task('mangleManifest', [ 'clean' ], function() {
return gulp.src('src/manifest.json')
.pipe(replace(replaceOpts))
.pipe(gulp.dest('build'));
});
// Build a distribution
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'css', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
gulp.src(['build/**'])
.pipe(zip(distFilename))
.pipe(gulp.dest('dist'));
});
// Run tests
gulp.task('test', function () {
gulpUtil.log('Running tests');
return runTests().on('error', function (e) {
throw e;
});
});
// Run tests through watching
gulp.task('watch', function () {
gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});
// Integration testing(end-to-end)
// Uses protractor as an abstraction layer over chromedriver
// Chromedriver can be used without a running selenium server
// Starts a simple webserver on port 8888
gulp.task('integration', function () {
// Start a small webserver
connect.server(serverConfig);
return gulp.src([
"./test/support/integration_helper.js",
"./test/integration/*_scene.js"
])
.pipe(protractor({
configFile: "test/support/protractor.config.js",
args: ['--baseUrl', 'http://127.0.0.1:' + serverConfig.port]
}))
.on('error', function(e) {
throw e
})
.on('end', function() {
connect.serverClose();
});
});
// Start server for testing purposes
gulp.task('server', function() {
connect.server(serverConfig);
});
// Updates the selenium stuff in node_modules
gulp.task('webdriver_update', webdriverUpdate);
// running "gulp" will execute this
gulp.task('default', function () {
runTests();
});
| show some help for gulp integration
| gulpfile.js | show some help for gulp integration | <ide><path>ulpfile.js
<ide>
<ide> // Configuration for the testserver
<ide> var serverConfig = {
<add> port: 8888,
<add> root: "testcases/docroot-for-testing"
<add>};
<add>
<add>var serverConfigIntegration = {
<ide> port: 8889,
<ide> root: "testcases/docroot-for-testing"
<ide> };
<ide> // Chromedriver can be used without a running selenium server
<ide> // Starts a simple webserver on port 8888
<ide> gulp.task('integration', function () {
<add>
<add> gulpUtil.log(
<add> "If this fails with",
<add> chalk.red("[launcher] Error: Could not find chromedriver"),
<add> "run",
<add> chalk.cyan("node_modules/protractor/bin/webdriver-manager update")
<add> );
<add>
<ide> // Start a small webserver
<del> connect.server(serverConfig);
<add> connect.server(serverConfigIntegration);
<ide>
<ide> return gulp.src([
<ide> "./test/support/integration_helper.js",
<ide> ])
<ide> .pipe(protractor({
<ide> configFile: "test/support/protractor.config.js",
<del> args: ['--baseUrl', 'http://127.0.0.1:' + serverConfig.port]
<add> args: ['--baseUrl', 'http://127.0.0.1:' + serverConfigIntegration.port]
<ide> }))
<ide> .on('error', function(e) {
<ide> throw e |
|
Java | mit | 0e2a0bfb1ad1e14dcdc5831b7671f825fcd60c8d | 0 | jharris119/sudoku,jharris119/sudoku,jharris119/sudoku | package web;
import csp.Sudoku;
import org.json.*;
import java.util.HashSet;
import java.util.Set;
public class SudokuJSONSerializer {
static Sudoku fromJSON(String string) {
JSONObject root = new JSONObject(new JSONTokener(string));
return new Sudoku(parseGivens(root), root.getInt("boxesPerRow"), root.getInt("boxesPerColumn"));
}
static String toJSON(Sudoku sudoku) {
JSONArray arr = new JSONArray();
if (!sudoku.isSolved()) {
sudoku.getGivens().forEach((given) -> arr.put(stringifyCandidate(given)));
return new JSONStringer()
.object()
.key("givens")
.value(arr)
.endObject()
.toString();
}
else {
sudoku.getSolution().forEach((candidate) -> arr.put(stringifyCandidate(candidate)));
return new JSONStringer()
.object()
.key("solution")
.value(arr)
.endObject()
.toString();
}
}
private static Set<Sudoku.Candidate> parseGivens(JSONObject root) {
JSONArray givens = root.getJSONArray("givens");
Set<Sudoku.Candidate> candidates = new HashSet<>();
for (int i = 0; i < givens.length(); ++i) {
candidates.add(parseCandidate(givens.getJSONObject(i)));
}
return candidates;
}
private static Sudoku.Candidate parseCandidate(JSONObject candidate) {
return new Sudoku.Candidate(candidate.getInt("row"), candidate.getInt("column"), candidate.getInt("digit"));
}
private static JSONObject stringifyCandidate(Sudoku.Candidate candidate) {
JSONObject blob = new JSONObject();
blob.put("row", candidate.row);
blob.put("column", candidate.column);
blob.put("digit", candidate.digit);
return blob;
};
}
| src/main/java/web/SudokuJSONSerializer.java | package web;
import csp.Sudoku;
import org.json.*;
import java.util.HashSet;
import java.util.Set;
public class SudokuJSONSerializer {
static Sudoku fromJSON(String string) {
JSONObject root = new JSONObject(new JSONTokener(string));
return new Sudoku(parseGivens(root), root.getInt("boxesPerRow"), root.getInt("boxesPerColumn"));
}
static String toJSON(Sudoku sudoku) {
if (!sudoku.isSolved()) {
return new JSONStringer()
.object()
.key("givens")
.value(stringifyGivens(sudoku))
.endObject()
.toString();
}
JSONArray candidates = new JSONArray();
sudoku.getSolution().forEach((candidate) -> candidates.put(stringifyCandidate(candidate)));
return new JSONStringer()
.object()
.key("solution")
.value(candidates)
.endObject()
.toString();
}
private static Set<Sudoku.Candidate> parseGivens(JSONObject root) {
JSONArray givens = root.getJSONArray("givens");
Set<Sudoku.Candidate> candidates = new HashSet<>();
for (int i = 0; i < givens.length(); ++i) {
candidates.add(parseCandidate(givens.getJSONObject(i)));
}
return candidates;
}
private static JSONArray stringifyGivens(Sudoku sudoku) {
JSONArray arr = new JSONArray();
sudoku.getGivens().forEach((given) -> arr.put(stringifyCandidate(given)));
return arr;
}
private static Sudoku.Candidate parseCandidate(JSONObject candidate) {
return new Sudoku.Candidate(candidate.getInt("row"), candidate.getInt("column"), candidate.getInt("digit"));
}
private static JSONObject stringifyCandidate(Sudoku.Candidate candidate) {
JSONObject blob = new JSONObject();
blob.put("row", candidate.row);
blob.put("column", candidate.column);
blob.put("digit", candidate.digit);
return blob;
};
}
| clean up SudokuJSONSerializer.java
| src/main/java/web/SudokuJSONSerializer.java | clean up SudokuJSONSerializer.java | <ide><path>rc/main/java/web/SudokuJSONSerializer.java
<ide> }
<ide>
<ide> static String toJSON(Sudoku sudoku) {
<add> JSONArray arr = new JSONArray();
<add>
<ide> if (!sudoku.isSolved()) {
<add> sudoku.getGivens().forEach((given) -> arr.put(stringifyCandidate(given)));
<ide> return new JSONStringer()
<ide> .object()
<ide> .key("givens")
<del> .value(stringifyGivens(sudoku))
<add> .value(arr)
<ide> .endObject()
<ide> .toString();
<ide> }
<del>
<del> JSONArray candidates = new JSONArray();
<del> sudoku.getSolution().forEach((candidate) -> candidates.put(stringifyCandidate(candidate)));
<del> return new JSONStringer()
<del> .object()
<del> .key("solution")
<del> .value(candidates)
<del> .endObject()
<del> .toString();
<add> else {
<add> sudoku.getSolution().forEach((candidate) -> arr.put(stringifyCandidate(candidate)));
<add> return new JSONStringer()
<add> .object()
<add> .key("solution")
<add> .value(arr)
<add> .endObject()
<add> .toString();
<add> }
<ide> }
<ide>
<ide> private static Set<Sudoku.Candidate> parseGivens(JSONObject root) {
<ide> candidates.add(parseCandidate(givens.getJSONObject(i)));
<ide> }
<ide> return candidates;
<del> }
<del>
<del> private static JSONArray stringifyGivens(Sudoku sudoku) {
<del> JSONArray arr = new JSONArray();
<del>
<del> sudoku.getGivens().forEach((given) -> arr.put(stringifyCandidate(given)));
<del> return arr;
<ide> }
<ide>
<ide> private static Sudoku.Candidate parseCandidate(JSONObject candidate) { |
|
Java | apache-2.0 | 97229bad8b486fac286243463d6191270976465b | 0 | optimizely/android-sdk,optimizely/android-sdk,optimizely/android-sdk | /****************************************************************************
* Copyright 2016-2017, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
***************************************************************************/
package com.optimizely.ab.android.sdk;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.annotation.RequiresApi;
import android.support.annotation.VisibleForTesting;
import com.optimizely.ab.Optimizely;
import com.optimizely.ab.android.event_handler.OptlyEventHandler;
import com.optimizely.ab.android.shared.Cache;
import com.optimizely.ab.android.shared.Client;
import com.optimizely.ab.android.shared.OptlyStorage;
import com.optimizely.ab.android.shared.ServiceScheduler;
import com.optimizely.ab.android.user_profile.AndroidUserProfile;
import com.optimizely.ab.bucketing.UserProfile;
import com.optimizely.ab.config.parser.ConfigParseException;
import com.optimizely.ab.event.internal.payload.Event;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Handles loading the Optimizely data file
*/
public class OptimizelyManager {
@NonNull private OptimizelyClient optimizelyClient = new OptimizelyClient(null,
LoggerFactory.getLogger(OptimizelyClient.class));
@NonNull private final String projectId;
@NonNull private final Long eventHandlerDispatchInterval;
@NonNull private final TimeUnit eventHandlerDispatchIntervalTimeUnit;
@NonNull private final Long dataFileDownloadInterval;
@NonNull private final TimeUnit dataFileDownloadIntervalTimeUnit;
@NonNull private final Executor executor;
@NonNull private final Logger logger;
@Nullable private DataFileServiceConnection dataFileServiceConnection;
@Nullable private OptimizelyStartListener optimizelyStartListener;
@Nullable private UserProfile userProfile;
OptimizelyManager(@NonNull String projectId,
@NonNull Long eventHandlerDispatchInterval,
@NonNull TimeUnit eventHandlerDispatchIntervalTimeUnit,
@NonNull Long dataFileDownloadInterval,
@NonNull TimeUnit dataFileDownloadIntervalTimeUnit,
@NonNull Executor executor,
@NonNull Logger logger) {
this.projectId = projectId;
this.eventHandlerDispatchInterval = eventHandlerDispatchInterval;
this.eventHandlerDispatchIntervalTimeUnit = eventHandlerDispatchIntervalTimeUnit;
this.dataFileDownloadInterval = dataFileDownloadInterval;
this.dataFileDownloadIntervalTimeUnit = dataFileDownloadIntervalTimeUnit;
this.executor = executor;
this.logger = logger;
}
@NonNull
public Long getDataFileDownloadInterval() {
return dataFileDownloadInterval;
}
@NonNull
public TimeUnit getDataFileDownloadIntervalTimeUnit() {
return dataFileDownloadIntervalTimeUnit;
}
/**
* Returns the {@link OptimizelyManager} builder
*
* @param projectId your project's id
* @return a {@link OptimizelyManager.Builder}
*/
@NonNull
public static Builder builder(@NonNull String projectId) {
return new Builder(projectId);
}
@Nullable
DataFileServiceConnection getDataFileServiceConnection() {
return dataFileServiceConnection;
}
void setDataFileServiceConnection(@Nullable DataFileServiceConnection dataFileServiceConnection) {
this.dataFileServiceConnection = dataFileServiceConnection;
}
@Nullable
OptimizelyStartListener getOptimizelyStartListener() {
return optimizelyStartListener;
}
void setOptimizelyStartListener(@Nullable OptimizelyStartListener optimizelyStartListener) {
this.optimizelyStartListener = optimizelyStartListener;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance. Will also cache the instance
* for future lookups via getClient
*
* @param context any {@link Context} instance
* @param datafile the datafile
* @return an {@link OptimizelyClient} instance
*/
public OptimizelyClient initialize(@NonNull Context context, @NonNull String datafile) {
if (!isAndroidVersionSupported()) {
return optimizelyClient;
}
AndroidUserProfile userProfile =
(AndroidUserProfile) AndroidUserProfile.newInstance(getProjectId(), context);
// The User Profile is started on the main thread on an asynchronous start.
// Starting simply creates the file if it doesn't exist so it's not
// terribly expensive. Blocking the UI thread prevents touch input...
userProfile.start();
try {
optimizelyClient = buildOptimizely(context, datafile, userProfile);
} catch (ConfigParseException e) {
logger.error("Unable to parse compiled data file", e);
} catch (Exception e) {
logger.error("Unable to build OptimizelyClient instance", e);
}
// After instantiating the OptimizelyClient, we will begin the datafile sync so that next time
// the user can instantiate with the latest datafile
final Intent intent = new Intent(context.getApplicationContext(), DataFileService.class);
if (dataFileServiceConnection == null) {
this.dataFileServiceConnection = new DataFileServiceConnection(this, context);
context.getApplicationContext().bindService(intent, dataFileServiceConnection, Context.BIND_AUTO_CREATE);
}
return optimizelyClient;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance. Will also cache the instance
* for future lookups via getClient. The datafile should be stored in res/raw.
*
* @param context any {@link Context} instance
* @param dataFileRes the R id that the data file is located under.
* @return an {@link OptimizelyClient} instance
*/
@NonNull
public OptimizelyClient initialize(@NonNull Context context, @RawRes int dataFileRes) {
try {
String datafile = loadRawResource(context, dataFileRes);
return initialize(context, datafile);
} catch (IOException e) {
logger.error("Unable to load compiled data file", e);
}
// return dummy client if not able to initialize a valid one
return optimizelyClient;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance using the datafile cached on disk
* if not available then it will return a dummy instance.
*
* @param context any {@link Context} instance
* @return an {@link OptimizelyClient} instance
*/
public OptimizelyClient initialize(@NonNull Context context) {
DataFileCache dataFileCache = new DataFileCache(
projectId,
new Cache(context, LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class)
);
JSONObject datafile = dataFileCache.load();
if (datafile != null) {
return initialize(context, datafile.toString());
}
// return dummy client if not able to initialize a valid one
return optimizelyClient;
}
/**
* Starts Optimizely asynchronously
* <p>
* An {@link OptimizelyClient} instance will be delivered to
* {@link OptimizelyStartListener#onStart(OptimizelyClient)}. The callback will only be hit
* once. If there is a cached datafile the returned instance will be built from it. The cached
* datafile will be updated from network if it is different from the cache. If there is no
* cached datafile the returned instance will always be built from the remote datafile.
*
* @param activity an Activity, used to automatically unbind {@link DataFileService}
* @param optimizelyStartListener callback that {@link OptimizelyClient} instances are sent to.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void initialize(@NonNull Activity activity, @NonNull OptimizelyStartListener optimizelyStartListener) {
if (!isAndroidVersionSupported()) {
return;
}
activity.getApplication().registerActivityLifecycleCallbacks(new OptlyActivityLifecycleCallbacks(this));
initialize(activity.getApplicationContext(), optimizelyStartListener);
}
/**
* @param context any type of context instance
* @param optimizelyStartListener callback that {@link OptimizelyClient} instances are sent to.
* @see #initialize(Activity, OptimizelyStartListener)
* <p>
* This method does the same thing except it can be used with a generic {@link Context}.
* When using this method be sure to call {@link #stop(Context)} to unbind {@link DataFileService}.
*/
public void initialize(@NonNull Context context, @NonNull OptimizelyStartListener optimizelyStartListener) {
if (!isAndroidVersionSupported()) {
return;
}
this.optimizelyStartListener = optimizelyStartListener;
final Intent intent = new Intent(context.getApplicationContext(), DataFileService.class);
if (dataFileServiceConnection == null) {
this.dataFileServiceConnection = new DataFileServiceConnection(this, context);
context.getApplicationContext().bindService(intent, dataFileServiceConnection, Context.BIND_AUTO_CREATE);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void stop(@NonNull Activity activity, @NonNull OptlyActivityLifecycleCallbacks optlyActivityLifecycleCallbacks) {
stop(activity);
activity.getApplication().unregisterActivityLifecycleCallbacks(optlyActivityLifecycleCallbacks);
}
/**
* Unbinds {@link DataFileService}
* <p>
* Calling this is not necessary if using {@link #initialize(Activity, OptimizelyStartListener)} which
* handles unbinding implicitly.
*
* @param context any {@link Context} instance
*/
@SuppressWarnings("WeakerAccess")
public void stop(@NonNull Context context) {
if (!isAndroidVersionSupported()) {
return;
}
if (dataFileServiceConnection != null && dataFileServiceConnection.isBound()) {
context.getApplicationContext().unbindService(dataFileServiceConnection);
dataFileServiceConnection = null;
}
this.optimizelyStartListener = null;
}
/**
* Gets a cached Optimizely instance
* <p>
* If {@link #initialize(Activity, OptimizelyStartListener)} or {@link #initialize(Context, OptimizelyStartListener)}
* has not been called yet the returned {@link OptimizelyClient} instance will be a dummy instance
* that logs warnings in order to prevent {@link NullPointerException}.
* <p>
* Using {@link #initialize(Activity, OptimizelyStartListener)} or {@link #initialize(Context, OptimizelyStartListener)}
* will update the cached instance with a new {@link OptimizelyClient} built from a cached local
* datafile on disk or a remote datafile on the CDN.
*
* @return the cached instance of {@link OptimizelyClient}
*/
@NonNull
public OptimizelyClient getOptimizely() {
isAndroidVersionSupported();
return optimizelyClient;
}
private String loadRawResource(Context context, @RawRes int rawRes) throws IOException {
Resources res = context.getResources();
InputStream in = res.openRawResource(rawRes);
byte[] b = new byte[in.available()];
int read = in.read(b);
if (read > -1) {
return new String(b);
} else {
throw new IOException("Couldn't parse raw res fixture, no bytes");
}
}
/**
* Check if the datafile is cached on the disk
*
* @param context any {@link Context} instance
* @return True if the datafile is cached on the disk
*/
public boolean isDatafileCached(Context context) {
DataFileCache dataFileCache = new DataFileCache(
projectId,
new Cache(context, LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class)
);
return dataFileCache.exists();
}
/**
* Returns the URL of the versioned datafile that this SDK expects to use
* @param projectId The id of the project for which we are getting the datafile
* @return the CDN location of the datafile
*/
public static @NonNull String getDatafileUrl(String projectId) {
return DataFileService.getDatafileUrl(projectId);
}
@NonNull
String getProjectId() {
return projectId;
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
void injectOptimizely(@NonNull final Context context, final @NonNull AndroidUserProfile userProfile, @NonNull final ServiceScheduler serviceScheduler, @NonNull final String dataFile) {
AsyncTask<Void, Void, UserProfile> initUserProfileTask = new AsyncTask<Void, Void, UserProfile>() {
@Override
protected UserProfile doInBackground(Void[] params) {
userProfile.start();
return userProfile;
}
@Override
protected void onPostExecute(UserProfile userProfile) {
Intent intent = new Intent(context, DataFileService.class);
intent.putExtra(DataFileService.EXTRA_PROJECT_ID, projectId);
serviceScheduler.schedule(intent, dataFileDownloadIntervalTimeUnit.toMillis(dataFileDownloadInterval));
try {
OptimizelyManager.this.optimizelyClient = buildOptimizely(context, dataFile, userProfile);
OptimizelyManager.this.userProfile = userProfile;
logger.info("Sending Optimizely instance to listener");
if (optimizelyStartListener != null) {
optimizelyStartListener.onStart(optimizelyClient);
} else {
logger.info("No listener to send Optimizely to");
}
} catch (Exception e) {
logger.error("Unable to build optimizely instance", e);
}
}
};
try {
initUserProfileTask.executeOnExecutor(executor);
} catch (Exception e) {
logger.error("Unable to initialize the user profile while injecting Optimizely", e);
}
}
private OptimizelyClient buildOptimizely(@NonNull Context context, @NonNull String dataFile, @NonNull UserProfile userProfile) throws ConfigParseException {
OptlyEventHandler eventHandler = OptlyEventHandler.getInstance(context);
eventHandler.setDispatchInterval(eventHandlerDispatchInterval, eventHandlerDispatchIntervalTimeUnit);
Event.ClientEngine clientEngine = OptimizelyClientEngine.getClientEngineFromContext(context);
Optimizely optimizely = Optimizely.builder(dataFile, eventHandler)
.withUserProfile(userProfile)
.withClientEngine(clientEngine)
.withClientVersion(BuildConfig.CLIENT_VERSION)
.build();
return new OptimizelyClient(optimizely, LoggerFactory.getLogger(OptimizelyClient.class));
}
@VisibleForTesting
public UserProfile getUserProfile() {
return userProfile;
}
private boolean isAndroidVersionSupported() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return true;
} else {
logger.warn("Optimizely will not work on this phone. It's Android version {} is less the minimum supported" +
"version {}", Build.VERSION.SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH);
return false;
}
}
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
static class OptlyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@NonNull private OptimizelyManager optimizelyManager;
OptlyActivityLifecycleCallbacks(@NonNull OptimizelyManager optimizelyManager) {
this.optimizelyManager = optimizelyManager;
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityCreated(Activity, Bundle)
*/
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityStarted(Activity)
*/
@Override
public void onActivityStarted(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityResumed(Activity)
*/
@Override
public void onActivityResumed(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityPaused(Activity)
*/
@Override
public void onActivityPaused(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityStopped(Activity)
*/
@Override
public void onActivityStopped(Activity activity) {
optimizelyManager.stop(activity, this);
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivitySaveInstanceState(Activity, Bundle)
*/
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityDestroyed(Activity)
*/
@Override
public void onActivityDestroyed(Activity activity) {
// NO-OP
}
}
static class DataFileServiceConnection implements ServiceConnection {
@NonNull private final OptimizelyManager optimizelyManager;
@NonNull private final Context context;
private boolean bound = false;
DataFileServiceConnection(@NonNull OptimizelyManager optimizelyManager, @NonNull Context context) {
this.optimizelyManager = optimizelyManager;
this.context = context;
}
/**
* @hide
* @see ServiceConnection#onServiceConnected(ComponentName, IBinder)
*/
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
if (!(service instanceof DataFileService.LocalBinder)) {
return;
}
// We've bound to DataFileService, cast the IBinder and get DataFileService instance
DataFileService.LocalBinder binder = (DataFileService.LocalBinder) service;
final DataFileService dataFileService = binder.getService();
if (dataFileService != null) {
DataFileClient dataFileClient = new DataFileClient(
new Client(new OptlyStorage(dataFileService.getApplicationContext()), LoggerFactory.getLogger(OptlyStorage.class)),
LoggerFactory.getLogger(DataFileClient.class));
DataFileCache dataFileCache = new DataFileCache(
optimizelyManager.getProjectId(),
new Cache(dataFileService.getApplicationContext(), LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class));
DataFileLoader dataFileLoader = new DataFileLoader(dataFileService,
dataFileClient,
dataFileCache,
Executors.newSingleThreadExecutor(),
LoggerFactory.getLogger(DataFileLoader.class));
dataFileService.getDataFile(optimizelyManager.getProjectId(), dataFileLoader, new DataFileLoadedListener() {
@Override
public void onDataFileLoaded(@Nullable String dataFile) {
// App is being used, i.e. in the foreground
AlarmManager alarmManager = (AlarmManager) dataFileService.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
ServiceScheduler.PendingIntentFactory pendingIntentFactory = new ServiceScheduler.PendingIntentFactory(dataFileService.getApplicationContext());
ServiceScheduler serviceScheduler = new ServiceScheduler(alarmManager, pendingIntentFactory, LoggerFactory.getLogger(ServiceScheduler.class));
if (dataFile != null) {
AndroidUserProfile userProfile =
(AndroidUserProfile) AndroidUserProfile.newInstance(optimizelyManager.getProjectId(), dataFileService.getApplicationContext());
optimizelyManager.injectOptimizely(dataFileService.getApplicationContext(), userProfile, serviceScheduler, dataFile);
} else {
// We should always call the callback even with the dummy
// instances. Devs might gate the rest of their app
// based on the loading of Optimizely
OptimizelyStartListener optimizelyStartListener = optimizelyManager.getOptimizelyStartListener();
if (optimizelyStartListener != null) {
optimizelyStartListener.onStart(optimizelyManager.getOptimizely());
}
}
}
});
}
bound = true;
}
/**
* @hide
* @see ServiceConnection#onServiceDisconnected(ComponentName)
*/
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
optimizelyManager.stop(context);
}
boolean isBound() {
return bound;
}
void setBound(boolean bound) {
this.bound = bound;
}
}
/**
* Builds instances of {@link OptimizelyManager}
*/
@SuppressWarnings("WeakerAccess")
public static class Builder {
@NonNull private final String projectId;
@NonNull private Long dataFileDownloadInterval = 1L;
@NonNull private TimeUnit dataFileDownloadIntervalTimeUnit = TimeUnit.DAYS;
@NonNull private Long eventHandlerDispatchInterval = 1L;
@NonNull private TimeUnit eventHandlerDispatchIntervalTimeUnit = TimeUnit.DAYS;
Builder(@NonNull String projectId) {
this.projectId = projectId;
}
/**
* Sets the interval which {@link com.optimizely.ab.android.event_handler.EventIntentService}
* will flush events.
*
* @param interval the interval
* @param timeUnit the unit of the interval
* @return this {@link Builder} instance
*/
public Builder withEventHandlerDispatchInterval(long interval, @NonNull TimeUnit timeUnit) {
this.eventHandlerDispatchInterval = interval;
this.eventHandlerDispatchIntervalTimeUnit = timeUnit;
return this;
}
/**
* Sets the interval which {@link DataFileService} will attempt to update the
* cached datafile.
*
* @param interval the interval
* @param timeUnit the unit of the interval
* @return this {@link Builder} instance
*/
public Builder withDataFileDownloadInterval(long interval, @NonNull TimeUnit timeUnit) {
this.dataFileDownloadInterval = interval;
this.dataFileDownloadIntervalTimeUnit = timeUnit;
return this;
}
/**
* Get a new {@link Builder} instance to create {@link OptimizelyManager} with.
*
* @return a {@link Builder} instance
*/
public OptimizelyManager build() {
Logger logger;
try {
logger = LoggerFactory.getLogger(OptimizelyManager.class);
} catch (Exception e) {
logger = LoggerFactory.getLogger("Optly.androidSdk");
logger.error("Unable to generate logger from class");
}
// AlarmManager doesn't allow intervals less than 60 seconds
if (dataFileDownloadIntervalTimeUnit.toMillis(dataFileDownloadInterval) < (60 * 1000)) {
dataFileDownloadIntervalTimeUnit = TimeUnit.SECONDS;
dataFileDownloadInterval = 60L;
logger.warn("Minimum datafile polling interval is 60 seconds. " +
"Defaulting to 60 seconds.");
}
return new OptimizelyManager(projectId,
eventHandlerDispatchInterval,
eventHandlerDispatchIntervalTimeUnit,
dataFileDownloadInterval,
dataFileDownloadIntervalTimeUnit,
Executors.newSingleThreadExecutor(),
logger);
}
}
}
| android-sdk/src/main/java/com/optimizely/ab/android/sdk/OptimizelyManager.java | /****************************************************************************
* Copyright 2016-2017, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
***************************************************************************/
package com.optimizely.ab.android.sdk;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.annotation.RequiresApi;
import android.support.annotation.VisibleForTesting;
import com.optimizely.ab.Optimizely;
import com.optimizely.ab.android.event_handler.OptlyEventHandler;
import com.optimizely.ab.android.shared.Cache;
import com.optimizely.ab.android.shared.Client;
import com.optimizely.ab.android.shared.OptlyStorage;
import com.optimizely.ab.android.shared.ServiceScheduler;
import com.optimizely.ab.bucketing.UserProfile;
import com.optimizely.ab.config.parser.ConfigParseException;
import com.optimizely.ab.event.internal.payload.Event;
import com.optimizely.ab.android.user_profile.AndroidUserProfile;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Handles loading the Optimizely data file
*/
public class OptimizelyManager {
@NonNull private OptimizelyClient optimizelyClient = new OptimizelyClient(null,
LoggerFactory.getLogger(OptimizelyClient.class));
@NonNull private final String projectId;
@NonNull private final Long eventHandlerDispatchInterval;
@NonNull private final TimeUnit eventHandlerDispatchIntervalTimeUnit;
@NonNull private final Long dataFileDownloadInterval;
@NonNull private final TimeUnit dataFileDownloadIntervalTimeUnit;
@NonNull private final Executor executor;
@NonNull private final Logger logger;
@Nullable private DataFileServiceConnection dataFileServiceConnection;
@Nullable private OptimizelyStartListener optimizelyStartListener;
@Nullable private UserProfile userProfile;
OptimizelyManager(@NonNull String projectId,
@NonNull Long eventHandlerDispatchInterval,
@NonNull TimeUnit eventHandlerDispatchIntervalTimeUnit,
@NonNull Long dataFileDownloadInterval,
@NonNull TimeUnit dataFileDownloadIntervalTimeUnit,
@NonNull Executor executor,
@NonNull Logger logger) {
this.projectId = projectId;
this.eventHandlerDispatchInterval = eventHandlerDispatchInterval;
this.eventHandlerDispatchIntervalTimeUnit = eventHandlerDispatchIntervalTimeUnit;
this.dataFileDownloadInterval = dataFileDownloadInterval;
this.dataFileDownloadIntervalTimeUnit = dataFileDownloadIntervalTimeUnit;
this.executor = executor;
this.logger = logger;
}
@NonNull
public Long getDataFileDownloadInterval() {
return dataFileDownloadInterval;
}
@NonNull
public TimeUnit getDataFileDownloadIntervalTimeUnit() {
return dataFileDownloadIntervalTimeUnit;
}
/**
* Returns the {@link OptimizelyManager} builder
*
* @param projectId your project's id
* @return a {@link OptimizelyManager.Builder}
*/
@NonNull
public static Builder builder(@NonNull String projectId) {
return new Builder(projectId);
}
@Nullable
DataFileServiceConnection getDataFileServiceConnection() {
return dataFileServiceConnection;
}
void setDataFileServiceConnection(@Nullable DataFileServiceConnection dataFileServiceConnection) {
this.dataFileServiceConnection = dataFileServiceConnection;
}
@Nullable
OptimizelyStartListener getOptimizelyStartListener() {
return optimizelyStartListener;
}
void setOptimizelyStartListener(@Nullable OptimizelyStartListener optimizelyStartListener) {
this.optimizelyStartListener = optimizelyStartListener;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance. Will also cache the instance
* for future lookups via getClient
*
* @param context any {@link Context} instance
* @param datafile the datafile
* @return an {@link OptimizelyClient} instance
*/
public OptimizelyClient initialize(@NonNull Context context, @NonNull String datafile) {
if (!isAndroidVersionSupported()) {
return optimizelyClient;
}
AndroidUserProfile userProfile =
(AndroidUserProfile) AndroidUserProfile.newInstance(getProjectId(), context);
// The User Profile is started on the main thread on an asynchronous start.
// Starting simply creates the file if it doesn't exist so it's not
// terribly expensive. Blocking the UI thread prevents touch input...
userProfile.start();
try {
optimizelyClient = buildOptimizely(context, datafile, userProfile);
} catch (ConfigParseException e) {
logger.error("Unable to parse compiled data file", e);
} catch (Exception e) {
logger.error("Unable to build OptimizelyClient instance", e);
}
// After instantiating the OptimizelyClient, we will begin the datafile sync so that next time
// the user can instantiate with the latest datafile
final Intent intent = new Intent(context.getApplicationContext(), DataFileService.class);
if (dataFileServiceConnection == null) {
this.dataFileServiceConnection = new DataFileServiceConnection(this, context);
context.getApplicationContext().bindService(intent, dataFileServiceConnection, Context.BIND_AUTO_CREATE);
}
return optimizelyClient;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance. Will also cache the instance
* for future lookups via getClient. The datafile should be stored in res/raw.
*
* @param context any {@link Context} instance
* @param dataFileRes the R id that the data file is located under.
* @return an {@link OptimizelyClient} instance
*/
@NonNull
public OptimizelyClient initialize(@NonNull Context context, @RawRes int dataFileRes) {
try {
String datafile = loadRawResource(context, dataFileRes);
return initialize(context, datafile);
} catch (IOException e) {
logger.error("Unable to load compiled data file", e);
}
// return dummy client if not able to initialize a valid one
return optimizelyClient;
}
/**
* Initialize Optimizely Synchronously
* <p>
* Instantiates and returns an {@link OptimizelyClient} instance using the datafile cached on disk
* if not available then it will return a dummy instance.
*
* @param context any {@link Context} instance
* @return an {@link OptimizelyClient} instance
*/
public OptimizelyClient initialize(@NonNull Context context) {
DataFileCache dataFileCache = new DataFileCache(
projectId,
new Cache(context, LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class)
);
JSONObject datafile = dataFileCache.load();
if (datafile != null) {
return initialize(context, datafile.toString());
}
// return dummy client if not able to initialize a valid one
return optimizelyClient;
}
/**
* Starts Optimizely asynchronously
* <p>
* An {@link OptimizelyClient} instance will be delivered to
* {@link OptimizelyStartListener#onStart(OptimizelyClient)}. The callback will only be hit
* once. If there is a cached datafile the returned instance will be built from it. The cached
* datafile will be updated from network if it is different from the cache. If there is no
* cached datafile the returned instance will always be built from the remote datafile.
*
* @param activity an Activity, used to automatically unbind {@link DataFileService}
* @param optimizelyStartListener callback that {@link OptimizelyClient} instances are sent to.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void initialize(@NonNull Activity activity, @NonNull OptimizelyStartListener optimizelyStartListener) {
if (!isAndroidVersionSupported()) {
return;
}
activity.getApplication().registerActivityLifecycleCallbacks(new OptlyActivityLifecycleCallbacks(this));
initialize(activity.getApplicationContext(), optimizelyStartListener);
}
/**
* @param context any type of context instance
* @param optimizelyStartListener callback that {@link OptimizelyClient} instances are sent to.
* @see #initialize(Activity, OptimizelyStartListener)
* <p>
* This method does the same thing except it can be used with a generic {@link Context}.
* When using this method be sure to call {@link #stop(Context)} to unbind {@link DataFileService}.
*/
public void initialize(@NonNull Context context, @NonNull OptimizelyStartListener optimizelyStartListener) {
if (!isAndroidVersionSupported()) {
return;
}
this.optimizelyStartListener = optimizelyStartListener;
final Intent intent = new Intent(context.getApplicationContext(), DataFileService.class);
if (dataFileServiceConnection == null) {
this.dataFileServiceConnection = new DataFileServiceConnection(this, context);
context.getApplicationContext().bindService(intent, dataFileServiceConnection, Context.BIND_AUTO_CREATE);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void stop(@NonNull Activity activity, @NonNull OptlyActivityLifecycleCallbacks optlyActivityLifecycleCallbacks) {
stop(activity);
activity.getApplication().unregisterActivityLifecycleCallbacks(optlyActivityLifecycleCallbacks);
}
/**
* Unbinds {@link DataFileService}
* <p>
* Calling this is not necessary if using {@link #initialize(Activity, OptimizelyStartListener)} which
* handles unbinding implicitly.
*
* @param context any {@link Context} instance
*/
@SuppressWarnings("WeakerAccess")
public void stop(@NonNull Context context) {
if (!isAndroidVersionSupported()) {
return;
}
if (dataFileServiceConnection != null && dataFileServiceConnection.isBound()) {
context.getApplicationContext().unbindService(dataFileServiceConnection);
dataFileServiceConnection = null;
}
this.optimizelyStartListener = null;
}
/**
* Gets a cached Optimizely instance
* <p>
* If {@link #initialize(Activity, OptimizelyStartListener)} or {@link #initialize(Context, OptimizelyStartListener)}
* has not been called yet the returned {@link OptimizelyClient} instance will be a dummy instance
* that logs warnings in order to prevent {@link NullPointerException}.
* <p>
* Using {@link #initialize(Activity, OptimizelyStartListener)} or {@link #initialize(Context, OptimizelyStartListener)}
* will update the cached instance with a new {@link OptimizelyClient} built from a cached local
* datafile on disk or a remote datafile on the CDN.
*
* @return the cached instance of {@link OptimizelyClient}
*/
@NonNull
public OptimizelyClient getOptimizely() {
isAndroidVersionSupported();
return optimizelyClient;
}
private String loadRawResource(Context context, @RawRes int rawRes) throws IOException {
Resources res = context.getResources();
InputStream in = res.openRawResource(rawRes);
byte[] b = new byte[in.available()];
int read = in.read(b);
if (read > -1) {
return new String(b);
} else {
throw new IOException("Couldn't parse raw res fixture, no bytes");
}
}
/**
* Check if the datafile is cached on the disk
*
* @param context any {@link Context} instance
* @return True if the datafile is cached on the disk
*/
public boolean isDatafileCached(Context context) {
DataFileCache dataFileCache = new DataFileCache(
projectId,
new Cache(context, LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class)
);
return dataFileCache.exists();
}
/**
* Returns the URL of the versioned datafile that this SDK expects to use
* @param projectId The id of the project for which we are getting the datafile
* @return the CDN location of the datafile
*/
public static @NonNull String getDatafileUrl(String projectId) {
return DataFileService.getDatafileUrl(projectId);
}
@NonNull
String getProjectId() {
return projectId;
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
void injectOptimizely(@NonNull final Context context, final @NonNull AndroidUserProfile userProfile, @NonNull final ServiceScheduler serviceScheduler, @NonNull final String dataFile) {
AsyncTask<Void, Void, UserProfile> initUserProfileTask = new AsyncTask<Void, Void, UserProfile>() {
@Override
protected UserProfile doInBackground(Void[] params) {
userProfile.start();
return userProfile;
}
@Override
protected void onPostExecute(UserProfile userProfile) {
Intent intent = new Intent(context, DataFileService.class);
intent.putExtra(DataFileService.EXTRA_PROJECT_ID, projectId);
serviceScheduler.schedule(intent, dataFileDownloadIntervalTimeUnit.toMillis(dataFileDownloadInterval));
try {
OptimizelyManager.this.optimizelyClient = buildOptimizely(context, dataFile, userProfile);
OptimizelyManager.this.userProfile = userProfile;
logger.info("Sending Optimizely instance to listener");
if (optimizelyStartListener != null) {
optimizelyStartListener.onStart(optimizelyClient);
} else {
logger.info("No listener to send Optimizely to");
}
} catch (Exception e) {
logger.error("Unable to build optimizely instance", e);
}
}
};
try {
initUserProfileTask.executeOnExecutor(executor);
} catch (Exception e) {
logger.error("Unable to initialize the user profile while injecting Optimizely", e);
}
}
private OptimizelyClient buildOptimizely(@NonNull Context context, @NonNull String dataFile, @NonNull UserProfile userProfile) throws ConfigParseException {
OptlyEventHandler eventHandler = OptlyEventHandler.getInstance(context);
eventHandler.setDispatchInterval(eventHandlerDispatchInterval, eventHandlerDispatchIntervalTimeUnit);
Event.ClientEngine clientEngine = OptimizelyClientEngine.getClientEngineFromContext(context);
Optimizely optimizely = Optimizely.builder(dataFile, eventHandler)
.withUserProfile(userProfile)
.withClientEngine(clientEngine)
.withClientVersion(BuildConfig.CLIENT_VERSION)
.build();
return new OptimizelyClient(optimizely, LoggerFactory.getLogger(OptimizelyClient.class));
}
@VisibleForTesting
public UserProfile getUserProfile() {
return userProfile;
}
private boolean isAndroidVersionSupported() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return true;
} else {
logger.warn("Optimizely will not work on this phone. It's Android version {} is less the minimum supported" +
"version {}", Build.VERSION.SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH);
return false;
}
}
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
static class OptlyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@NonNull private OptimizelyManager optimizelyManager;
OptlyActivityLifecycleCallbacks(@NonNull OptimizelyManager optimizelyManager) {
this.optimizelyManager = optimizelyManager;
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityCreated(Activity, Bundle)
*/
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityStarted(Activity)
*/
@Override
public void onActivityStarted(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityResumed(Activity)
*/
@Override
public void onActivityResumed(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityPaused(Activity)
*/
@Override
public void onActivityPaused(Activity activity) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityStopped(Activity)
*/
@Override
public void onActivityStopped(Activity activity) {
optimizelyManager.stop(activity, this);
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivitySaveInstanceState(Activity, Bundle)
*/
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// NO-OP
}
/**
* @hide
* @see android.app.Application.ActivityLifecycleCallbacks#onActivityDestroyed(Activity)
*/
@Override
public void onActivityDestroyed(Activity activity) {
// NO-OP
}
}
static class DataFileServiceConnection implements ServiceConnection {
@NonNull private final OptimizelyManager optimizelyManager;
@NonNull private final Context context;
private boolean bound = false;
DataFileServiceConnection(@NonNull OptimizelyManager optimizelyManager, @NonNull Context context) {
this.optimizelyManager = optimizelyManager;
this.context = context;
}
/**
* @hide
* @see ServiceConnection#onServiceConnected(ComponentName, IBinder)
*/
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
if (!(service instanceof DataFileService.LocalBinder)) {
return;
}
// We've bound to DataFileService, cast the IBinder and get DataFileService instance
DataFileService.LocalBinder binder = (DataFileService.LocalBinder) service;
final DataFileService dataFileService = binder.getService();
if (dataFileService != null) {
DataFileClient dataFileClient = new DataFileClient(
new Client(new OptlyStorage(dataFileService.getApplicationContext()), LoggerFactory.getLogger(OptlyStorage.class)),
LoggerFactory.getLogger(DataFileClient.class));
DataFileCache dataFileCache = new DataFileCache(
optimizelyManager.getProjectId(),
new Cache(dataFileService.getApplicationContext(), LoggerFactory.getLogger(Cache.class)),
LoggerFactory.getLogger(DataFileCache.class));
DataFileLoader dataFileLoader = new DataFileLoader(dataFileService,
dataFileClient,
dataFileCache,
Executors.newSingleThreadExecutor(),
LoggerFactory.getLogger(DataFileLoader.class));
dataFileService.getDataFile(optimizelyManager.getProjectId(), dataFileLoader, new DataFileLoadedListener() {
@Override
public void onDataFileLoaded(@Nullable String dataFile) {
// App is being used, i.e. in the foreground
AlarmManager alarmManager = (AlarmManager) dataFileService.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
ServiceScheduler.PendingIntentFactory pendingIntentFactory = new ServiceScheduler.PendingIntentFactory(dataFileService.getApplicationContext());
ServiceScheduler serviceScheduler = new ServiceScheduler(alarmManager, pendingIntentFactory, LoggerFactory.getLogger(ServiceScheduler.class));
if (dataFile != null) {
AndroidUserProfile userProfile =
(AndroidUserProfile) AndroidUserProfile.newInstance(optimizelyManager.getProjectId(), dataFileService.getApplicationContext());
optimizelyManager.injectOptimizely(dataFileService.getApplicationContext(), userProfile, serviceScheduler, dataFile);
} else {
// We should always call the callback even with the dummy
// instances. Devs might gate the rest of their app
// based on the loading of Optimizely
OptimizelyStartListener optimizelyStartListener = optimizelyManager.getOptimizelyStartListener();
if (optimizelyStartListener != null) {
optimizelyStartListener.onStart(optimizelyManager.getOptimizely());
}
}
}
});
}
bound = true;
}
/**
* @hide
* @see ServiceConnection#onServiceDisconnected(ComponentName)
*/
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
optimizelyManager.stop(context);
}
boolean isBound() {
return bound;
}
void setBound(boolean bound) {
this.bound = bound;
}
}
/**
* Builds instances of {@link OptimizelyManager}
*/
@SuppressWarnings("WeakerAccess")
public static class Builder {
@NonNull private final String projectId;
@NonNull private Long dataFileDownloadInterval = 1L;
@NonNull private TimeUnit dataFileDownloadIntervalTimeUnit = TimeUnit.DAYS;
@NonNull private Long eventHandlerDispatchInterval = 1L;
@NonNull private TimeUnit eventHandlerDispatchIntervalTimeUnit = TimeUnit.DAYS;
Builder(@NonNull String projectId) {
this.projectId = projectId;
}
/**
* Sets the interval which {@link com.optimizely.ab.android.event_handler.EventIntentService}
* will flush events.
*
* @param interval the interval
* @param timeUnit the unit of the interval
* @return this {@link Builder} instance
*/
public Builder withEventHandlerDispatchInterval(long interval, @NonNull TimeUnit timeUnit) {
this.eventHandlerDispatchInterval = interval;
this.eventHandlerDispatchIntervalTimeUnit = timeUnit;
return this;
}
/**
* Sets the interval which {@link DataFileService} will attempt to update the
* cached datafile.
*
* @param interval the interval
* @param timeUnit the unit of the interval
* @return this {@link Builder} instance
*/
public Builder withDataFileDownloadInterval(long interval, @NonNull TimeUnit timeUnit) {
this.dataFileDownloadInterval = interval;
this.dataFileDownloadIntervalTimeUnit = timeUnit;
return this;
}
/**
* Get a new {@link Builder} instance to create {@link OptimizelyManager} with.
*
* @return a {@link Builder} instance
*/
public OptimizelyManager build() {
final Logger logger = LoggerFactory.getLogger(OptimizelyManager.class);
// AlarmManager doesn't allow intervals less than 60 seconds
if (dataFileDownloadIntervalTimeUnit.toMillis(dataFileDownloadInterval) < (60 * 1000)) {
dataFileDownloadIntervalTimeUnit = TimeUnit.SECONDS;
dataFileDownloadInterval = 60L;
logger.warn("Minimum datafile polling interval is 60 seconds. " +
"Defaulting to 60 seconds.");
}
return new OptimizelyManager(projectId,
eventHandlerDispatchInterval,
eventHandlerDispatchIntervalTimeUnit,
dataFileDownloadInterval,
dataFileDownloadIntervalTimeUnit,
Executors.newSingleThreadExecutor(),
logger);
}
}
}
| Fix for crash #4
Summary: Fix for crash #2
Test Plan: automated
Reviewers: #oasis_team_review, mike.ng
JIRA Issues: OASIS-1235
Differential Revision: https://phabricator.optimizely.com/D15711
| android-sdk/src/main/java/com/optimizely/ab/android/sdk/OptimizelyManager.java | Fix for crash #4 | <ide><path>ndroid-sdk/src/main/java/com/optimizely/ab/android/sdk/OptimizelyManager.java
<ide> import com.optimizely.ab.android.shared.Client;
<ide> import com.optimizely.ab.android.shared.OptlyStorage;
<ide> import com.optimizely.ab.android.shared.ServiceScheduler;
<add>import com.optimizely.ab.android.user_profile.AndroidUserProfile;
<ide> import com.optimizely.ab.bucketing.UserProfile;
<ide> import com.optimizely.ab.config.parser.ConfigParseException;
<ide> import com.optimizely.ab.event.internal.payload.Event;
<del>import com.optimizely.ab.android.user_profile.AndroidUserProfile;
<ide>
<ide> import org.json.JSONObject;
<ide> import org.slf4j.Logger;
<ide> } catch (Exception e) {
<ide> logger.error("Unable to build OptimizelyClient instance", e);
<ide> }
<del>
<ide>
<ide> // After instantiating the OptimizelyClient, we will begin the datafile sync so that next time
<ide> // the user can instantiate with the latest datafile
<ide> * @return a {@link Builder} instance
<ide> */
<ide> public OptimizelyManager build() {
<del> final Logger logger = LoggerFactory.getLogger(OptimizelyManager.class);
<add> Logger logger;
<add> try {
<add> logger = LoggerFactory.getLogger(OptimizelyManager.class);
<add> } catch (Exception e) {
<add> logger = LoggerFactory.getLogger("Optly.androidSdk");
<add> logger.error("Unable to generate logger from class");
<add> }
<ide>
<ide> // AlarmManager doesn't allow intervals less than 60 seconds
<ide> if (dataFileDownloadIntervalTimeUnit.toMillis(dataFileDownloadInterval) < (60 * 1000)) {
<ide> dataFileDownloadIntervalTimeUnit,
<ide> Executors.newSingleThreadExecutor(),
<ide> logger);
<del>
<ide> }
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | faee87b30898a8ab638fb4a4c3efc05eb8b9baa4 | 0 | Esri/crowdsource-reporter,Esri/crowdsource-reporter | /*global define */
/*
| Copyright 2014 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
define({
root: ({
map: {
error: "Unable to create map",
zoomInTooltip: "Zoom in", // Command button to zoom in to the map
zoomOutTooltip: "Zoom out", // Command button to zoom out of the map
geolocationTooltip: "Current location" // Command button to navigate to the current geographical position
},
main: {
noGroup: "No group configured", // Shown when no group is configured in the configuration file
submitReportButtonText: "Submit a Report", //Submit report text for buttons on map and list
gotoListViewTooltip: "List view", // Go to List view tooltip text
noFeatureGeomtery: "Feature cannot be displayed" // Error message when geomtery is not available
},
signin: {
guestSigninText: "Proceed as Guest", // Shown in the 'Sign in' page below the icon for accessing application as an anonymous user
signInOrText: "Or", // Or text on sign in screen
signinOptionsText: "Sign in with:", // Shown in the 'Sign in' page above the icons for social media sign in
noGroupNameText: "Please sign in", // Shown when the group title is not available or the group is private
guestLoginTooltip: "Sign in as a guest", // Command button to access the application as an anonymous user
facebookLoginTooltip: "Sign in with Facebook", // Command button to access the application via Facebook login
twitterLoginTooltip: "Sign in with Twitter", // Command button to access the application via Twitter login
googlePlusLoginTooltip: "Sign in with Google+", // Command button to access the application via Google+ login
agolLoginTooltip: "Sign in with ArcGIS" // Command button to access the application via AGOL login
},
webMapList: {
owner: "Owner", // Shown in the 'Map information' section indicating the owner of the webmap
created: "Date created", // Shown in the 'Map information' section indicating the date when the webmap was created
modified: "Date modified", // Shown in the 'Map information' section indicating the date when the webmap was modified
description: "Description", // Shown in the 'Map information' section describing the webmap
snippet: "Summary", // Shown in the 'Map information' section providing the summary of the webmap
licenseInfo: "Access and use constraints", // Shown in the map information section indicating the webmap license information
accessInformation: "Credits", // Shown in the 'Map information' section indicating account credits
tags: "Tags", // Shown in the 'Map information' section indicating tags of the webmap
numViews: "Number of views", // Shown in the 'Map information' section indicating number of times the webmap has been viewed
avgRating: "Rating", // Shown in the 'Map information' section indicating webmap rating
noWebMapInGroup: "Configured group is invalid or no items have been shared with this group yet.", // Shown when the configured group is invalid/private or no items have been shared with the group
infoBtnToolTip: "Map information" // Command button to view the 'Map information'
},
issueWall: {
noResultsFound: "No features found", // Shown in the issue wall when no issues are present in layer
noResultsFoundInCurrentBuffer: "No features found near you", // Shown in the issue wall when no issues are present in the current buffer extent
unableToFetchFeatureError: "Unable to complete operation", // Shown in the issue wall when layer does not return any features and throws an error
gotoWebmapListTooltip: "Go to main list", // Tooltip for back icon in list header
gotoMapViewTooltip: "Map view" // Tooltip for map-it icon in list header
},
appHeader: {
myReport: "My Reports", // Command button shown in mobile menu list
signIn: "Sign In", // Command button shown in mobile menu list and in appheader
signOut: "Sign Out", // Command button shown in mobile menu list
signInTooltip: "Sign in", // Tooltip to 'Sign in' option
signOutTooltip: "Sign out", // Tooltip to 'Sign out' option
myReportTooltip: "View my reports" // Tooltip to 'My Reports' option
},
geoform: {
enterInformation: "Details", // Shown as the first section of the geoform, where the user can enter details of the issue
selectAttachments: "Attachments", // Appears above 'Select file' button indicating option to attach files
selectFileText: "Browse", // Command button to open a dialog box to select file(s) to be attached
enterLocation: "Location", // Shown as the second section of the geoform, where the user can select a location on the map
reportItButton: "Report It", // Command button to submit the geoform to report an issue
cancelButton: "Cancel", //Command button to close the geoform
requiredField: "(required)", // Shown next to the field in which the data is mandatory
selectDefaultText: "Select…", // Shown in the dropdown field indicating to select an option
invalidInputValue: "Please enter valid value.", // Shown when user clicks/taps the required field but does not enter the data and comes out of the required field
noFieldsConfiguredMessage: "Layer fields are not configured to capture data", // Shown when all the fields of the selected layer are disabled
invalidSmallNumber: "Please enter an integer", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -32768 and 32767.)
invalidNumber: "Please enter an integer", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -2147483648 and 2147483647.)
invalidFloat: "Please enter a number", // Shown when the entered value is beyond the specified range (valid ${openStrong}floating point${closeStrong} value between -3.4E38 and 1.2E38 )
invalidDouble: "Please enter a number", // Shown when the entered value is beyond the specified range (valid ${openStrong}double${closeStrong} value between -2.2E308 and 1.8E308)
requiredFields: "Please provide values for all required fields", // Shown when user submits the geoform without entering data in the mandatory field(s)
selectLocation: "Please select the location for your report", // Shown when user submits the geoform without selecting location on the map
numericRangeHintMessage: "${openStrong}Hint:${closeStrong} Minimum value ${minValue} and Maximum value ${maxValue}", // Shown as a pop over above the fields with numeric values, indicating the minimum and maximum range
dateRangeHintMessage: "${openStrong}Hint:${closeStrong} Minimum Date ${minValue} and Maximum Date ${maxValue}", // Shown as a pop over above the fields with date values, indicating the minimum and maximum date range
errorsInApplyEdits: "Report could not be submitted", // Shown when there is an error in any of the services while submitting the geoform
attachmentSelectedMsg: "attachment(s) selected", // Shown besides the select file button indicating the number of files attached
attachmentUploadStatus: "${failed} of ${total} attachment(s) failed to upload", // Shown when there is error while uploading the attachment, while submitting the geoform
geoLocationError: "Current location not available", // Shown when the browser returns an error instead of the current geographical position
geoLocationOutOfExtent: "Current location is out of basemap extent", // Shown when the current geographical position is out of the basemap extent
submitButtonTooltip: "Submit", // Command button to open the geoform
cancelButtonTooltip: "Cancel", //tooltip for cancel button
geoformBackButtonTooltip: "Return to the report list" //tooltip for Geoform back button
},
locator: {
addressText: "Address:", // Shown as a title for a group of addresses returned on performing unified search
usngText: "USNG", // Shown as a title for a group of USNG values returned on performing unified search
mgrsText: "MGRS", // Shown as a title for a group of MGRS values returned on performing unified search
latLongText: "Latitude/Longitude", // Shown as a title for a group of latitude longitude values returned on performing unified search
invalidSearch: "No results found", // Shown in the address container when no results are returned on performing unified search
locatorPlaceholder: "Enter an address to search", // Shown in the address container textbox as a placeholder
locationOutOfExtent: "Located address is out of basemap extent", // Shown as an alert when the selected address in the search result is out of basemap extent
searchButtonTooltip: "Search", // Tooltip for search button
clearButtonTooltip: "Clear search value" // Tooltip for Geocoder clear button
},
myIssues: {
title: "My Reports", // Shown as a title in 'My issues' panel
myIssuesTooltip: "My Reports", // Command button to access issues reported by the logged in user
noResultsFound: "No reports found" // Shown when no issues are reported by the logged in user
},
itemDetails: { // Detailed information about an item and a list of its comments
likeButtonLabel: "Vote", // Command button for up-voting a report
likeButtonTooltip: "Vote for this report", // Tooltip for Like button
commentButtonLabel: "Comment", // Command button for submitting feedback
commentButtonTooltip: "Comment on this report", // Tooltip for Comment button
galleryButtonLabel: "Gallery", // Command button for opening and closing attachment file gallery
galleryButtonTooltip: "See attached documents", // Tooltip for command button shown in details panel
mapButtonLabel: "View on Map", // Command button shown in details panel
mapButtonTooltip: "View the location of this report", // Tooltip for Gallery button
commentsListHeading: "Comments", // List heading for Comments section in details panel
unableToUpdateVoteField: "Your vote cannot be counted at this time.", // Error message for feature unable to update
gotoIssueListTooltip: "Go to the report list" // Tooltip for back icon in Issue list header
},
itemList: { // List of feature layer items shown in my-issues and issue-wall
likesForThisItemTooltip: "Votes for this report", //Shown on hovering of the like icon in my-issues and issue-wall
loadMoreButtonText: "Load More..." //Text for load more button
},
comment: {
commentsFormSubmitButton: "Submit Comment",
commentsFormCancelButton: "Cancel",
errorInSubmittingComment: "Comment could not be submitted.", // Shown when user is unable to add comments
emptyCommentMessage: "Please enter a comment.", // Shown when user submits a comment without any text/character
placeHolderText: "Type a comment", // Shown as a placeholder in comments textbox
noCommentsAvailableText: "No comments available", // Shown when no comments are available for the selected issue
remainingTextCount: "${0} character(s) remain", // Shown below the comments textbox indicating the number of characters that can be added
showNoText: "No" // Shown when comments character limit is exceeded
},
gallery: {
galleryHeaderText: "Gallery",
noAttachmentsAvailableText: "No attachments found" // Shown when no comments are available for the selected issue
}
}),
"ar": 1,
"cs": 1,
"da": 1,
"de": 1,
"el": 1,
"es": 1,
"et": 1,
"fi": 1,
"fr": 1,
"he": 1,
"hr": 1,
"it": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nb": 1,
"nl": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sr": 1,
"sv": 1,
"th": 1,
"tr": 1,
"vi": 1,
"zh-cn": 1,
"zh-hk": 1,
"zh-tw": 1
});
| js/nls/resources.js | /*global define */
/*
| Copyright 2014 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
define({
root: ({
map: {
error: "Unable to create map",
zoomInTooltip: "Zoom in", // Command button to zoom in to the map
zoomOutTooltip: "Zoom out", // Command button to zoom out of the map
geolocationTooltip: "Current location" // Command button to navigate to the current geographical position
},
main: {
noGroup: "No group configured", // Shown when no group is configured in the configuration file
submitReportButtonText: "Submit a Report", //Submit report text for buttons on map and list
gotoListViewTooltip: "List view", // Go to List view tooltip text
noFeatureGeomtery: "Feature cannot be displayed" // Error message when geomtery is not available
},
signin: {
guestSigninText: "Proceed as Guest", // Shown in the 'Sign in' page below the icon for accessing application as an anonymous user
signInOrText: "Or", // Or text on sign in screen
signinOptionsText: "Sign in with:", // Shown in the 'Sign in' page above the icons for social media sign in
noGroupNameText: "Please sign in", // Shown when the group title is not available or the group is private
guestLoginTooltip: "Sign in as a guest", // Command button to access the application as an anonymous user
facebookLoginTooltip: "Sign in with Facebook", // Command button to access the application via Facebook login
twitterLoginTooltip: "Sign in with Twitter", // Command button to access the application via Twitter login
googlePlusLoginTooltip: "Sign in with Google+", // Command button to access the application via Google+ login
agolLoginTooltip: "Sign in with ArcGIS" // Command button to access the application via AGOL login
},
webMapList: {
owner: "Owner", // Shown in the 'Map information' section indicating the owner of the webmap
created: "Date created", // Shown in the 'Map information' section indicating the date when the webmap was created
modified: "Date modified", // Shown in the 'Map information' section indicating the date when the webmap was modified
description: "Description", // Shown in the 'Map information' section describing the webmap
snippet: "Summary", // Shown in the 'Map information' section providing the summary of the webmap
licenseInfo: "Access and use constraints", // Shown in the map information section indicating the webmap license information
accessInformation: "Credits", // Shown in the 'Map information' section indicating account credits
tags: "Tags", // Shown in the 'Map information' section indicating tags of the webmap
numViews: "Number of views", // Shown in the 'Map information' section indicating number of times the webmap has been viewed
avgRating: "Rating", // Shown in the 'Map information' section indicating webmap rating
noWebMapInGroup: "Configured group is invalid or no items have been shared with this group yet.", // Shown when the configured group is invalid/private or no items have been shared with the group
infoBtnToolTip: "Map information" // Command button to view the 'Map information'
},
issueWall: {
noResultsFound: "No features found", // Shown in the issue wall when no issues are present in layer
noResultsFoundInCurrentBuffer: "No features found near you", // Shown in the issue wall when no issues are present in the current buffer extent
unableToFetchFeatureError: "Unable to complete operation", // Shown in the issue wall when layer does not return any features and throws an error
gotoWebmapListTooltip: "Go to main list", // Tooltip for back icon in list header
gotoMapViewTooltip: "Map view" // Tooltip for map-it icon in list header
},
appHeader: {
myReport: "My Reports", // Command button shown in mobile menu list
signIn: "Sign In", // Command button shown in mobile menu list and in appheader
signOut: "Sign Out", // Command button shown in mobile menu list
signInTooltip: "Sign in", // Tooltip to 'Sign in' option
signOutTooltip: "Sign out", // Tooltip to 'Sign out' option
myReportTooltip: "View my reports" // Tooltip to 'My Reports' option
},
geoform: {
enterInformation: "Details", // Shown as the first section of the geoform, where the user can enter details of the issue
selectAttachments: "Attachments", // Appears above 'Select file' button indicating option to attach files
selectFileText: "Browse", // Command button to open a dialog box to select file(s) to be attached
enterLocation: "Location", // Shown as the second section of the geoform, where the user can select a location on the map
reportItButton: "Report It", // Command button to submit the geoform to report an issue
cancelButton: "Cancel", //Command button to close the geoform
requiredField: "(required)", // Shown next to the field in which the data is mandatory
selectDefaultText: "Select…", // Shown in the dropdown field indicating to select an option
invalidInputValue: "Please enter valid value.", // Shown when user clicks/taps the required field but does not enter the data and comes out of the required field
noFieldsConfiguredMessage: "Layer fields are not configured to capture data", // Shown when all the fields of the selected layer are disabled
invalidSmallNumber: "Please enter an integer", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -32768 and 32767.)
invalidNumber: "Please enter an integer", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -2147483648 and 2147483647.)
invalidFloat: "Please enter a number", // Shown when the entered value is beyond the specified range (valid ${openStrong}floating point${closeStrong} value between -3.4E38 and 1.2E38 )
invalidDouble: "Please enter a number", // Shown when the entered value is beyond the specified range (valid ${openStrong}double${closeStrong} value between -2.2E308 and 1.8E308)
requiredFields: "Please provide values for all required fields", // Shown when user submits the geoform without entering data in the mandatory field(s)
selectLocation: "Please select the location for your report", // Shown when user submits the geoform without selecting location on the map
numericRangeHintMessage: "${openStrong}Hint:${closeStrong} Minimum value ${minValue} and Maximum value ${maxValue}", // Shown as a pop over above the fields with numeric values, indicating the minimum and maximum range
dateRangeHintMessage: "${openStrong}Hint:${closeStrong} Minimum Date ${minValue} and Maximum Date ${maxValue}", // Shown as a pop over above the fields with date values, indicating the minimum and maximum date range
errorsInApplyEdits: "Report could not be submitted", // Shown when there is an error in any of the services while submitting the geoform
attachmentSelectedMsg: "attachment(s) selected", // Shown besides the select file button indicating the number of files attached
attachmentUploadStatus: "${failed} of ${total} attachment(s) failed to upload", // Shown when there is error while uploading the attachment, while submitting the geoform
geoLocationError: "Current location not available", // Shown when the browser returns an error instead of the current geographical position
geoLocationOutOfExtent: "Current location is out of basemap extent", // Shown when the current geographical position is out of the basemap extent
submitButtonTooltip: "Submit", // Command button to open the geoform
cancelButtonTooltip: "Cancel", //tooltip for cancel button
geoformBackButtonTooltip: "Return to the report list" //tooltip for Geoform back button
},
locator: {
addressText: "Address:", // Shown as a title for a group of addresses returned on performing unified search
usngText: "USNG", // Shown as a title for a group of USNG values returned on performing unified search
mgrsText: "MGRS", // Shown as a title for a group of MGRS values returned on performing unified search
latLongText: "Latitude/Longitude", // Shown as a title for a group of latitude longitude values returned on performing unified search
invalidSearch: "No results found", // Shown in the address container when no results are returned on performing unified search
locatorPlaceholder: "Enter an address to search", // Shown in the address container textbox as a placeholder
locationOutOfExtent: "Located address is out of basemap extent", // Shown as an alert when the selected address in the search result is out of basemap extent
searchButtonTooltip: "Search", // Tooltip for search button
clearButtonTooltip: "Clear search value" // Tooltip for Geocoder clear button
},
myIssues: {
title: "My Reports", // Shown as a title in 'My issues' panel
myIssuesTooltip: "My Reports", // Command button to access issues reported by the logged in user
noResultsFound: "No reports found" // Shown when no issues are reported by the logged in user
},
itemDetails: { // Detailed information about an item and a list of its comments
likeButtonLabel: "Vote", // Command button for up-voting a report
likeButtonTooltip: "Vote for this report", // Tooltip for Like button
commentButtonLabel: "Comment", // Command button for submitting feedback
commentButtonTooltip: "Comment on this report", // Tooltip for Comment button
galleryButtonLabel: "Gallery", // Command button for opening and closing attachment file gallery
galleryButtonTooltip: "See attached documents", // Tooltip for command button shown in details panel
mapButtonLabel: "View on Map", // Command button shown in details panel
mapButtonTooltip: "View the location of this report", // Tooltip for Gallery button
commentsListHeading: "Comments", // List heading for Comments section in details panel
unableToUpdateVoteField: "Your vote cannot be counted at this time.", // Error message for feature unable to update
gotoIssueListTooltip: "Go to the report list" // Tooltip for back icon in Issue list header
},
itemList: { // List of feature layer items shown in my-issues and issue-wall
likesForThisItemTooltip: "Votes for this report", //Shown on hovering of the like icon in my-issues and issue-wall
loadMoreButtonText: "Load More..." //Text for load more button
},
comment: {
commentsFormSubmitButton: "Submit Comment",
commentsFormCancelButton: "Cancel",
errorInSubmittingComment: "Comment could not be submitted.", // Shown when user is unable to add comments
emptyCommentMessage: "Please enter a comment.", // Shown when user submits a comment without any text/character
placeHolderText: "Type a comment", // Shown as a placeholder in comments textbox
noCommentsAvailableText: "No comments available", // Shown when no comments are available for the selected issue
remainingTextCount: "${0} character(s) remain", // Shown below the comments textbox indicating the number of characters that can be added
showNoText: "No" // Shown when comments character limit is exceeded
},
gallery: {
galleryHeaderText: "Gallery",
noAttachmentsAvailableText: "No attachments found" // Shown when no comments are available for the selected issue
}
}),
"ar": 1,
"cr": 1,
"cs": 1,
"da": 1,
"de": 1,
"el": 1,
"es": 1,
"et": 1,
"fi": 1,
"fr": 1,
"he": 1,
"it": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nb": 1,
"nl": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sr": 1,
"sv": 1,
"th": 1,
"tr": 1,
"vi": 1,
"zh-cn": 1,
"zh-hk": 1,
"zh-tw": 1
});
| fixed croatian key
| js/nls/resources.js | fixed croatian key | <ide><path>s/nls/resources.js
<ide> }
<ide> }),
<ide> "ar": 1,
<del> "cr": 1,
<ide> "cs": 1,
<ide> "da": 1,
<ide> "de": 1,
<ide> "fi": 1,
<ide> "fr": 1,
<ide> "he": 1,
<add> "hr": 1,
<ide> "it": 1,
<ide> "ja": 1,
<ide> "ko": 1, |
|
Java | mit | 7d1ed494e874d7bb66121f043d6451278abb30d1 | 0 | wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav | package de.wellenvogel.avnav.charts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.ParcelFileDescriptor;
import android.support.v4.provider.DocumentFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import de.wellenvogel.avnav.util.AvnLog;
public class MbTilesFile extends ChartFile {
private boolean schemeXyz=true;
SQLiteDatabase db=null;
Object lock=new Object();
Object writerLock=new Object();
long sequence=System.currentTimeMillis();
public MbTilesFile(File pLocation) throws Exception {
super(pLocation);
initialize();
}
@Override
public String getScheme() {
return schemeXyz?"xyz":"tms";
}
@Override
public boolean setScheme(String newScheme) throws Exception {
newScheme=newScheme.toLowerCase();
if (!newScheme.equals("xyz") && ! newScheme.equals("tms")){
throw new Exception("invalid scheme");
}
if (newScheme.equals("xyz")){
if (schemeXyz) return false;
schemeXyz=true;
}
else{
if (!schemeXyz) return false;
schemeXyz=false;
}
synchronized (writerLock) {
SQLiteDatabase dbrw = SQLiteDatabase.openDatabase(mRealFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
Cursor cu=null;
try {
cu = dbrw.rawQuery("select value from metadata where name='scheme'", null);
ContentValues update = new ContentValues();
update.put("value", newScheme);
if (cu.moveToFirst()) {
cu.close();
dbrw.update("metadata", update, "name='scheme'", null);
} else {
cu.close();
update.put("name","scheme");
dbrw.insert("metadata", null, update);
}
}finally{
if (cu != null){
try{
cu.close();
}catch (Throwable t){}
}
dbrw.close();
}
}
readHeader();
return true;
}
@Override
public long getSequence() {
return sequence;
}
@Override
public void close() throws IOException {
synchronized (lock) {
if (db != null) db.close();
}
}
@Override
public int numFiles() {
return 1;
}
class Tile{
int x; //tile_column
int y; //tile_row
int z; //zoom_level
Tile(int z, int x, int y){
this.x=x;
this.y=y;
this.z=z;
}
String[] toQueryArgs(){
return new String[]{
Integer.toString(z),
Integer.toString(x),
Integer.toString(y)
};
}
}
//tile is (z,x,y)
private Tile zxyToZoomColRow(int z,int x, int y) {
if (schemeXyz) {
return new Tile(z, x, (1 << z) - 1 - y);
}
else {
return new Tile(z, x, y);
}
}
private int rowToY(int z, int row) {
if (schemeXyz){
return (1<< z) - 1 - row;
}
else {
return row;
}
}
private int colToX(int z, int col) {
return col;
}
@Override
protected void openFiles() throws FileNotFoundException {
}
@Override
protected void openFilesUri() throws IOException {
throw new IOException("unable to read mbtiles from external dir");
}
@Override
protected void readHeader() throws Exception {
mSources.put(0,"mbtiles");
Cursor cu=null;
if (db != null){
try{
db.close();
db=null;
}catch (Throwable e){}
}
db=SQLiteDatabase.openDatabase(mRealFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
try {
cu = db.rawQuery("select value from metadata where name=?", new String[]{"scheme"});
if (cu.moveToFirst()){
String scheme=cu.getString(0);
AvnLog.i("found schema for "+mRealFile.getPath()+": "+scheme);
if (scheme.equalsIgnoreCase("tms")) schemeXyz=false;
}
cu.close();
cu=db.rawQuery("select distinct zoom_level from tiles",null);
ArrayList<Integer> zoomlevels=new ArrayList<Integer>();
while(cu.moveToNext()){
zoomlevels.add(cu.getInt(0));
}
AvnLog.i("read "+zoomlevels.size()+" zoomlevels");
cu.close();
for (int zl : zoomlevels){
ChartRange range=new ChartRange();
range.zoom=zl;
range.sourceIndex=0;
range.offset=0L; //not used
cu=db.rawQuery("select min(tile_row),max(tile_row) from tiles where zoom_level=?",
new String[]{Integer.toString(zl)});
if (cu.moveToFirst()){
if (schemeXyz) {
range.yMin=rowToY(zl,cu.getInt(1));
range.yMax=rowToY(zl,cu.getInt(0));
}
else{
range.yMin=rowToY(zl,cu.getInt(0));
range.yMax=rowToY(zl,cu.getInt(1));
}
}
cu.close();
cu=db.rawQuery("select min(tile_column),max(tile_column) from tiles where zoom_level=?",
new String[]{Integer.toString(zl)});
if (cu.moveToFirst()){
range.xMin=colToX(zl,cu.getInt(0));
range.xMax=colToX(zl,cu.getInt(1));
}
mRangeData.add(range);
}
}finally {
if (cu != null) {
try {
cu.close();
}catch (Throwable t){}
}
}
sequence=System.currentTimeMillis();
}
@Override
public ChartInputStream getInputStream(int pX, int pY, int pZ, int sourceIndex) throws IOException {
if (db == null) return null;
synchronized (lock) {
Tile param=zxyToZoomColRow(pZ,pX,pY);
Cursor cu=db.query("tiles",
new String[]{"tile_data"},
"zoom_level=? and tile_column=? and tile_row=?",
param.toQueryArgs(),null,null,null);
if (cu.moveToFirst()) {
byte data[] = cu.getBlob(0);
cu.close();
return new ChartInputStream(new ByteArrayInputStream(data),data.length);
}
cu.close();
}
return null;
}
}
| android/src/main/java/de/wellenvogel/avnav/charts/MbTilesFile.java | package de.wellenvogel.avnav.charts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.ParcelFileDescriptor;
import android.support.v4.provider.DocumentFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import de.wellenvogel.avnav.util.AvnLog;
public class MbTilesFile extends ChartFile {
private boolean schemeXyz=true;
SQLiteDatabase db=null;
Object lock=new Object();
Object writerLock=new Object();
long sequence=System.currentTimeMillis();
public MbTilesFile(File pLocation) throws Exception {
super(pLocation);
initialize();
}
@Override
public String getScheme() {
return schemeXyz?"xyz":"tms";
}
@Override
public boolean setScheme(String newScheme) throws Exception {
newScheme=newScheme.toLowerCase();
if (!newScheme.equals("xyz") && ! newScheme.equals("tms")){
throw new Exception("invalid scheme");
}
if (newScheme.equals("xyz")){
if (schemeXyz) return false;
}
else{
if (!schemeXyz) return false;
}
synchronized (writerLock) {
SQLiteDatabase dbrw = SQLiteDatabase.openDatabase(mRealFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
Cursor cu=null;
try {
cu = dbrw.rawQuery("select value from metadata where name='scheme'", null);
ContentValues update = new ContentValues();
update.put("value", newScheme);
if (cu.moveToFirst()) {
cu.close();
dbrw.update("metadata", update, "name='scheme'", null);
} else {
cu.close();
update.put("name","scheme");
dbrw.insert("metadata", null, update);
}
}finally{
if (cu != null){
try{
cu.close();
}catch (Throwable t){}
}
dbrw.close();
}
}
readHeader();
return false;
}
@Override
public long getSequence() {
return sequence;
}
@Override
public void close() throws IOException {
synchronized (lock) {
if (db != null) db.close();
}
}
@Override
public int numFiles() {
return 1;
}
class Tile{
int x; //tile_column
int y; //tile_row
int z; //zoom_level
Tile(int z, int x, int y){
this.x=x;
this.y=y;
this.z=z;
}
String[] toQueryArgs(){
return new String[]{
Integer.toString(z),
Integer.toString(x),
Integer.toString(y)
};
}
}
//tile is (z,x,y)
private Tile zxyToZoomColRow(int z,int x, int y) {
if (schemeXyz) {
return new Tile(z, x, (1 << z) - 1 - y);
}
else {
return new Tile(z, x, y);
}
}
private int rowToY(int z, int row) {
if (schemeXyz){
return (1<< z) - 1 - row;
}
else {
return row;
}
}
private int colToX(int z, int col) {
return col;
}
@Override
protected void openFiles() throws FileNotFoundException {
}
@Override
protected void openFilesUri() throws IOException {
throw new IOException("unable to read mbtiles from external dir");
}
@Override
protected void readHeader() throws Exception {
mSources.put(0,"mbtiles");
Cursor cu=null;
if (db != null){
try{
db.close();
db=null;
}catch (Throwable e){}
}
db=SQLiteDatabase.openDatabase(mRealFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
try {
cu = db.rawQuery("select value from metadata where name=?", new String[]{"scheme"});
if (cu.moveToFirst()){
String scheme=cu.getString(0);
AvnLog.i("found schema for "+mRealFile.getPath()+": "+scheme);
if (scheme.equalsIgnoreCase("tms")) schemeXyz=false;
}
cu.close();
cu=db.rawQuery("select distinct zoom_level from tiles",null);
ArrayList<Integer> zoomlevels=new ArrayList<Integer>();
while(cu.moveToNext()){
zoomlevels.add(cu.getInt(0));
}
AvnLog.i("read "+zoomlevels.size()+" zoomlevels");
cu.close();
for (int zl : zoomlevels){
ChartRange range=new ChartRange();
range.zoom=zl;
range.sourceIndex=0;
range.offset=0L; //not used
cu=db.rawQuery("select min(tile_row),max(tile_row) from tiles where zoom_level=?",
new String[]{Integer.toString(zl)});
if (cu.moveToFirst()){
if (schemeXyz) {
range.yMin=rowToY(zl,cu.getInt(1));
range.yMax=rowToY(zl,cu.getInt(0));
}
else{
range.yMin=rowToY(zl,cu.getInt(0));
range.yMax=rowToY(zl,cu.getInt(1));
}
}
cu.close();
cu=db.rawQuery("select min(tile_column),max(tile_column) from tiles where zoom_level=?",
new String[]{Integer.toString(zl)});
if (cu.moveToFirst()){
range.xMin=colToX(zl,cu.getInt(0));
range.xMax=colToX(zl,cu.getInt(1));
}
mRangeData.add(range);
}
}finally {
if (cu != null) {
try {
cu.close();
}catch (Throwable t){}
}
}
sequence=System.currentTimeMillis();
}
@Override
public ChartInputStream getInputStream(int pX, int pY, int pZ, int sourceIndex) throws IOException {
if (db == null) return null;
synchronized (lock) {
Tile param=zxyToZoomColRow(pZ,pX,pY);
Cursor cu=db.query("tiles",
new String[]{"tile_data"},
"zoom_level=? and tile_column=? and tile_row=?",
param.toQueryArgs(),null,null,null);
if (cu.moveToFirst()) {
byte data[] = cu.getBlob(0);
cu.close();
return new ChartInputStream(new ByteArrayInputStream(data),data.length);
}
cu.close();
}
return null;
}
}
| correctly switch scheme for tms back to xyz
| android/src/main/java/de/wellenvogel/avnav/charts/MbTilesFile.java | correctly switch scheme for tms back to xyz | <ide><path>ndroid/src/main/java/de/wellenvogel/avnav/charts/MbTilesFile.java
<ide> }
<ide> if (newScheme.equals("xyz")){
<ide> if (schemeXyz) return false;
<add> schemeXyz=true;
<ide> }
<ide> else{
<ide> if (!schemeXyz) return false;
<add> schemeXyz=false;
<ide> }
<ide> synchronized (writerLock) {
<ide> SQLiteDatabase dbrw = SQLiteDatabase.openDatabase(mRealFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
<ide> }
<ide> }
<ide> readHeader();
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> @Override |
|
Java | mit | f4763d800472fd3f5c4ce1913ee01cf46bf2a6d4 | 0 | tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus | /*******************************************************************************
* Copyright (c) 2018 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package util;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.junit.runners.model.InitializationError;
public class IsolatedTestCaseRunner extends Runner {
private final JUnit4 delegate;
public IsolatedTestCaseRunner(final Class<?> testFileClass)
throws InitializationError, ClassNotFoundException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
// Since IsolatedTestCaseRunner runs several isolated tests in a single VM, it
// is good practice to clean resources before each new test.
System.gc();
ClassLoader classLoader = IsolatedTestCaseRunner.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
// When run within e.g. Eclipse, the classloader might not be of instance
// URLClassLoader. In this case, just use the provided class loader which won't
// isolate tests. A set of tests can thus only be run in a single VM from ant
// or maven which pass a URLClassLoader.
classLoader = new IsolatedTestCaseClassLoader((URLClassLoader) classLoader);
}
delegate = new JUnit4(classLoader.loadClass(testFileClass.getName()));
}
@Override
public Description getDescription() {
return delegate.getDescription();
}
@Override
public void run(RunNotifier notifier) {
delegate.run(notifier);
}
private class IsolatedTestCaseClassLoader extends URLClassLoader {
private final Map<String, Class<?>> cache = new HashMap<>();
private final Set<String> packages = new HashSet<>();
public IsolatedTestCaseClassLoader(URLClassLoader classLoader) {
super(classLoader.getURLs());
// All of TLC's java packages.
packages.add("tla2sany");
packages.add("pcal");
packages.add("util");
packages.add("tla2tex");
packages.add("tlc2");
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (cache.containsKey(name)) {
// Cache to not load classes twice for a single test case which results in a
// LinkageError.
return cache.get(name);
}
for (final String pkg : packages) {
if (name.startsWith(pkg)) {
final Class<?> findClass = findClass(name);
cache.put(name, findClass);
return findClass;
}
}
return super.loadClass(name);
}
}
}
| tlatools/test/util/IsolatedTestCaseRunner.java | package util;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.junit.runners.model.InitializationError;
public class IsolatedTestCaseRunner extends Runner {
private final JUnit4 delegate;
public IsolatedTestCaseRunner(final Class<?> testFileClass)
throws InitializationError, ClassNotFoundException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
ClassLoader classLoader = IsolatedTestCaseRunner.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
classLoader = new IsolatedTestCaseClassLoader((URLClassLoader) classLoader);
}
delegate = new JUnit4(classLoader.loadClass(testFileClass.getName()));
}
@Override
public Description getDescription() {
return delegate.getDescription();
}
@Override
public void run(RunNotifier notifier) {
delegate.run(notifier);
}
private class IsolatedTestCaseClassLoader extends URLClassLoader {
private final Map<String, Object> cache = new HashMap<>();
private final Set<String> packages = new HashSet<>();
public IsolatedTestCaseClassLoader(URLClassLoader classLoader) {
super(classLoader.getURLs());
packages.add("tla2sany");
packages.add("pcal");
packages.add("util");
packages.add("tla2tex");
packages.add("tlc2");
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (cache.containsKey(name)) {
// Cache to not load classes twice which results in a LinkageError.
return (Class<?>) cache.get(name);
}
for (final String pkg : packages) {
if (name.startsWith(pkg)) {
final Class<?> findClass = findClass(name);
cache.put(name, findClass);
return findClass;
}
}
return super.loadClass(name);
}
}
}
| Run garbage collection prior to each test invocation to free up
resources in a single VM run.
[Tests] | tlatools/test/util/IsolatedTestCaseRunner.java | Run garbage collection prior to each test invocation to free up resources in a single VM run. | <ide><path>latools/test/util/IsolatedTestCaseRunner.java
<add>/*******************************************************************************
<add> * Copyright (c) 2018 Microsoft Research. All rights reserved.
<add> *
<add> * The MIT License (MIT)
<add> *
<add> * Permission is hereby granted, free of charge, to any person obtaining a copy
<add> * of this software and associated documentation files (the "Software"), to deal
<add> * in the Software without restriction, including without limitation the rights
<add> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
<add> * of the Software, and to permit persons to whom the Software is furnished to do
<add> * so, subject to the following conditions:
<add> *
<add> * The above copyright notice and this permission notice shall be included in all
<add> * copies or substantial portions of the Software.
<add> *
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
<add> * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
<add> * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
<add> * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<add> *
<add> * Contributors:
<add> * Markus Alexander Kuppe - initial API and implementation
<add> ******************************************************************************/
<ide> package util;
<ide>
<ide> import java.lang.reflect.InvocationTargetException;
<ide> throws InitializationError, ClassNotFoundException, InstantiationException, IllegalAccessException,
<ide> IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
<ide>
<add> // Since IsolatedTestCaseRunner runs several isolated tests in a single VM, it
<add> // is good practice to clean resources before each new test.
<add> System.gc();
<ide>
<ide> ClassLoader classLoader = IsolatedTestCaseRunner.class.getClassLoader();
<ide> if (classLoader instanceof URLClassLoader) {
<add> // When run within e.g. Eclipse, the classloader might not be of instance
<add> // URLClassLoader. In this case, just use the provided class loader which won't
<add> // isolate tests. A set of tests can thus only be run in a single VM from ant
<add> // or maven which pass a URLClassLoader.
<ide> classLoader = new IsolatedTestCaseClassLoader((URLClassLoader) classLoader);
<ide> }
<ide> delegate = new JUnit4(classLoader.loadClass(testFileClass.getName()));
<ide>
<ide> private class IsolatedTestCaseClassLoader extends URLClassLoader {
<ide>
<del> private final Map<String, Object> cache = new HashMap<>();
<add> private final Map<String, Class<?>> cache = new HashMap<>();
<ide> private final Set<String> packages = new HashSet<>();
<ide>
<ide> public IsolatedTestCaseClassLoader(URLClassLoader classLoader) {
<ide> super(classLoader.getURLs());
<ide>
<add> // All of TLC's java packages.
<ide> packages.add("tla2sany");
<ide> packages.add("pcal");
<ide> packages.add("util");
<ide> @Override
<ide> public Class<?> loadClass(String name) throws ClassNotFoundException {
<ide> if (cache.containsKey(name)) {
<del> // Cache to not load classes twice which results in a LinkageError.
<del> return (Class<?>) cache.get(name);
<add> // Cache to not load classes twice for a single test case which results in a
<add> // LinkageError.
<add> return cache.get(name);
<ide> }
<ide> for (final String pkg : packages) {
<ide> if (name.startsWith(pkg)) { |
|
JavaScript | mit | 64ea97adfb760fce72bbaa656bc3a77568150517 | 0 | chessfish/chesslib | import { PAWN } from '../../brands'
import { Piece } from '../piece'
import { squareName } from '../../util'
export class Pawn extends Piece {
get brand() {
return PAWN;
}
get unicode() {
return this.isWhite ? '♙' : '♟';
}
get fenEncoding() {
return this.isWhite ? 'P' : 'p';
}
get startRow() {
return this.isWhite ? 6 : 1;
}
get reach() {
return this.isWhite ? -1 : 1;
}
canMove(position, from, to) {
// pawns can only move forwards:
if (from.x !== to.x) {
return false;
}
const reach = this.reach;
// pawns can move two squares on their first move.
if (from.y === this.startRow) {
return to.y === from.y + reach || to.y === from.y + reach * 2;
}
return to.y === from.y + reach;
}
canCapture(position, from, to) {
return (
// it's one rank "below" the pawn to be captured:
to.y === from.y + this.reach &&
// it's a from a neighboring file:
(from.x === to.x + 1 || from.x === to.x - 1)
);
}
}
| src/piece/pawn/index.js | import { PAWN } from '../../brands'
import { Piece } from '../piece'
import { squareName } from '../../util'
export class Pawn extends Piece {
get brand() {
return PAWN;
}
get unicode() {
return this.isWhite ? '♙' : '♟';
}
get fenEncoding() {
return this.isWhite ? 'P' : 'p';
}
get startRow() {
return this.isWhite ? 6 : 1;
}
get reach() {
return this.isWhite ? -1 : 1;
}
canMove(position, from, to) {
// pawns can only move forwards:
if (from.x !== to.x) {
return false;
}
const reach = this.reach;
// pawns can move two squares on their first move.
if (from.y === this.startRow) {
return to.y === from.y + reach || to.y === from.y + reach * 2;
}
return to.y === from.y + reach;
}
canCapture(position, from, to) {
return (
from.x === to.x + 1 || from.x === to.x -1 &&
(
to.y === from.y + this.reach ||
position.enPassantTarget.equal(squareName(to))
)
);
}
}
| working en passant
| src/piece/pawn/index.js | working en passant | <ide><path>rc/piece/pawn/index.js
<ide>
<ide> canCapture(position, from, to) {
<ide> return (
<del> from.x === to.x + 1 || from.x === to.x -1 &&
<del> (
<del> to.y === from.y + this.reach ||
<del> position.enPassantTarget.equal(squareName(to))
<del> )
<add> // it's one rank "below" the pawn to be captured:
<add> to.y === from.y + this.reach &&
<add> // it's a from a neighboring file:
<add> (from.x === to.x + 1 || from.x === to.x - 1)
<ide> );
<ide> }
<ide> } |
|
Java | bsd-3-clause | 101d4b8d667c57673c44e84e689f83e7cdd9c573 | 0 | Praesidio/LiveStats | package io.praesid.livestats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.ToString;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.DoubleConsumer;
@ThreadSafe
@ToString
public final class LiveStats implements DoubleConsumer {
private static final double[] DEFAULT_TILES = {0.5};
private final AtomicDouble average = new AtomicDouble(0);
private final AtomicDouble sumCentralMoment2 = new AtomicDouble(0);
private final AtomicDouble sumCentralMoment3 = new AtomicDouble(0);
private final AtomicDouble sumCentralMoment4 = new AtomicDouble(0);
private final AtomicInteger count = new AtomicInteger(0);
private final ImmutableList<Quantile> tiles;
/**
* Constructs a LiveStats object
*
* @param p An array of quantiles to track (default {0.5})
*/
public LiveStats(final double... p) {
final Builder<Quantile> tilesBuilder = ImmutableList.builder();
final double[] tiles = p.length == 0 ? DEFAULT_TILES : p;
for (final double tile : tiles) {
tilesBuilder.add(new Quantile(tile));
}
this.tiles = tilesBuilder.build();
}
/**
* Adds another datum
*
* @param item the value to add
*/
@Override
public void accept(final double item) {
add(item);
}
/**
* Adds another datum
*
* @param item the value to add
*/
public void add(double item) {
tiles.forEach(tile -> tile.add(item));
final int myCount = count.incrementAndGet();
final double preDelta = item - average.get();
final double delta = item - average.addAndGet(preDelta / myCount);
final double delta2 = delta * delta;
sumCentralMoment2.addAndGet(delta2);
final double delta3 = delta2 * delta;
sumCentralMoment3.addAndGet(delta3);
final double delta4 = delta3 * delta;
sumCentralMoment4.addAndGet(delta4);
}
/**
* @return a Map of quantile to approximate value
*/
public Map<Double, Double> quantiles() {
final ImmutableMap.Builder<Double, Double> builder = ImmutableMap.builder();
for (final Quantile tile : tiles) {
builder.put(tile.p, tile.quantile());
}
return builder.build();
}
public double maximum() {
return tiles.get(0).maximum();
}
public double mean() {
return average.get();
}
public double minimum() {
return tiles.get(0).minimum();
}
public int num() {
return count.get();
}
public double variance() {
return sumCentralMoment2.get() / count.get();
}
public double kurtosis() {
// u4 / u2^2 - 3
// (s4/c) / (s2/c)^2 - 3
// s4 / (c * (s2/c)^2) - 3
// s4 / (c * (s2/c) * (s2/c)) - 3
// s4 / (s2^2 / c) - 3
// s4 * c / s2^2 - 3
return sumCentralMoment4.get() * count.get() / Math.pow(sumCentralMoment2.get(), 2) - 3;
}
public double skewness() {
// u3 / u2^(3/2)
// (s3/c) / (s2/c)^(3/2)
// s3 / (c * (s2/c)^(3/2))
// s3 / (c * (s2/c) * (s2/c)^(1/2))
// s3 / (s2 * sqrt(s2/c))
// s3 * sqrt(c/s2) / s2
final double mySumCentralMoment2 = sumCentralMoment2.get();
return sumCentralMoment3.get() * Math.sqrt(count.get() / mySumCentralMoment2) / mySumCentralMoment2;
}
@ThreadSafe
@ToString
private static final class Quantile {
private static final int N_MARKERS = 5; // dn and npos must be updated if this is changed
private final double[] dn; // Immutable
private final double[] npos;
private final int[] pos = {1, 2, 3, 4, 5};
private final double[] heights;
private int initialized;
public final double p;
/**
* Constructs a single quantile object
*/
public Quantile(double p) {
this.p = p;
dn = new double[]{0, p / 2, p, (1 + p) / 2, 1};
npos = new double[]{1, 1 + 2 * p, 1 + 4 * p, 3 + 2 * p, 5};
initialized = 0;
heights = new double[N_MARKERS];
}
public synchronized double minimum() {
if (initialized < N_MARKERS) {
Arrays.sort(heights);
}
return heights[0];
}
public synchronized double maximum() {
if (initialized != N_MARKERS) {
Arrays.sort(heights);
}
return heights[initialized - 1];
}
public synchronized double quantile() {
if (initialized != N_MARKERS) {
Arrays.sort(heights); // Not fully initialized, probably not in order
// make sure we don't overflow on p == 1 or underflow on p == 0
return heights[Math.min(Math.max(initialized - 1, 0), (int)(initialized * p))];
}
return heights[2];
}
/**
* Adds another datum
*/
public synchronized void add(double item) {
if (initialized < N_MARKERS) {
heights[initialized] = item;
initialized++;
if (initialized == N_MARKERS) {
Arrays.sort(heights);
}
return;
}
// find cell k
final int k;
if (item < heights[0]) {
heights[0] = item;
k = 1;
} else if (item >= heights[N_MARKERS - 1]) {
heights[N_MARKERS - 1] = item;
k = N_MARKERS - 1;
} else {
int i = 1; // Linear search is fastest because N_MARKERS is small
while (item >= heights[i]) {
i++;
}
k = i;
}
for (int i = k; i < pos.length; i++) {
pos[i]++; // increment all positions greater than k
}
for (int i = 1; i < npos.length; i++) {
npos[i] += dn[i]; // updated desired positions
}
adjust();
}
private void adjust() {
for (int i = 1; i < N_MARKERS - 1; i++) {
final int n = pos[i];
final double d0 = npos[i] - n;
if ((d0 >= 1 && pos[i + 1] > n + 1) || (d0 <= -1 && pos[i - 1] < n - 1)) {
final int d = d0 > 0 ? 1 : -1;
final double q = heights[i];
final double qp1 = heights[i + 1];
final double qm1 = heights[i - 1];
final int np1 = pos[i + 1];
final int nm1 = pos[i - 1];
final double qn = calcP2(d, q, qp1, qm1, n, np1, nm1);
if (qm1 < qn && qn < qp1) {
heights[i] = qn;
} else {
// use linear form
heights[i] = q + Math.copySign((heights[i + d] - q) / (pos[i + d] - n), d);
}
pos[i] = n + d;
}
}
}
private static double calcP2(int d, double q, double qp1, double qm1, int n, int np1, int nm1) {
// q + d / (np1 - nm1) * ((n - nm1 + d) * (qp1 - q) / (np1 - n) + (np1 - n - d) * (q - qm1) / (n - nm1))
final int leftX = n - nm1;
final int rightX = np1 - n;
final double rightScale = (leftX + d) / (double)rightX;
final double leftScale = (rightX - d) / (double)leftX;
final double leftHalf = leftScale * (q - qm1);
final double rightHalf = rightScale * (qp1 - q);
return q + Math.copySign((leftHalf + rightHalf) / (np1 - nm1), d);
}
}
}
| src/main/java/io/praesid/livestats/LiveStats.java | package io.praesid.livestats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.ToString;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.DoubleConsumer;
@ThreadSafe
@ToString
public final class LiveStats implements DoubleConsumer {
private static final double[] DEFAULT_TILES = {0.5};
private final AtomicDouble cumulant2 = new AtomicDouble(0);
private final AtomicDouble cumulant4 = new AtomicDouble(0);
private final AtomicDouble cumulant3 = new AtomicDouble(0);
private final AtomicDouble average = new AtomicDouble(0);
private final AtomicInteger count = new AtomicInteger(0);
private final ImmutableList<Quantile> tiles;
/**
* Constructs a LiveStats object
*
* @param p An array of quantiles to track (default {0.5})
*/
public LiveStats(final double... p) {
final Builder<Quantile> tilesBuilder = ImmutableList.builder();
final double[] tiles = p.length == 0 ? DEFAULT_TILES : p;
for (final double tile : tiles) {
tilesBuilder.add(new Quantile(tile));
}
this.tiles = tilesBuilder.build();
}
/**
* Adds another datum
*
* @param item the value to add
*/
@Override
public void accept(final double item) {
add(item);
}
/**
* Adds another datum
*
* @param item the value to add
*/
public void add(double item) {
tiles.forEach(tile -> tile.add(item));
final int myCount = count.incrementAndGet();
final double preDelta = item - average.get();
final double delta = item - average.addAndGet(preDelta / myCount);
final double delta2 = delta * delta;
cumulant2.addAndGet(delta2);
final double delta3 = delta2 * delta;
cumulant3.addAndGet(delta3);
final double delta4 = delta3 * delta;
cumulant4.addAndGet(delta4);
}
/**
* @return a Map of quantile to approximate value
*/
public Map<Double, Double> quantiles() {
final ImmutableMap.Builder<Double, Double> builder = ImmutableMap.builder();
for (final Quantile tile : tiles) {
builder.put(tile.p, tile.quantile());
}
return builder.build();
}
public double maximum() {
return tiles.get(0).maximum();
}
public double mean() {
return average.get();
}
public double minimum() {
return tiles.get(0).minimum();
}
public int num() {
return count.get();
}
public double variance() {
return cumulant2.get() / count.get();
}
public double kurtosis() {
// k / (c * (v/c)^2) - 3
// k / (c * (v/c) * (v/c)) - 3
// k / (v * v / c) - 3
// k * c / (v * v) - 3
final double myCumulant2 = cumulant2.get();
return cumulant4.get() * count.get() / (myCumulant2 * myCumulant2) - 3;
}
public double skewness() {
// s / (c * (v/c)^(3/2))
// s / (c * (v/c) * (v/c)^(1/2))
// s / (v * sqrt(v/c))
// s * sqrt(c/v) / v
final double myCumulant2 = cumulant2.get();
return cumulant3.get() * Math.sqrt(count.get() / myCumulant2) / myCumulant2;
}
@ThreadSafe
@ToString
private static final class Quantile {
private static final int N_MARKERS = 5; // dn and npos must be updated if this is changed
private final double[] dn; // Immutable
private final double[] npos;
private final int[] pos = {1, 2, 3, 4, 5};
private final double[] heights;
private int initialized;
public final double p;
/**
* Constructs a single quantile object
*/
public Quantile(double p) {
this.p = p;
dn = new double[]{0, p / 2, p, (1 + p) / 2, 1};
npos = new double[]{1, 1 + 2 * p, 1 + 4 * p, 3 + 2 * p, 5};
initialized = 0;
heights = new double[N_MARKERS];
}
public synchronized double minimum() {
if (initialized < N_MARKERS) {
Arrays.sort(heights);
}
return heights[0];
}
public synchronized double maximum() {
if (initialized != N_MARKERS) {
Arrays.sort(heights);
}
return heights[initialized - 1];
}
public synchronized double quantile() {
if (initialized != N_MARKERS) {
Arrays.sort(heights); // Not fully initialized, probably not in order
// make sure we don't overflow on p == 1 or underflow on p == 0
return heights[Math.min(Math.max(initialized - 1, 0), (int)(initialized * p))];
}
return heights[2];
}
/**
* Adds another datum
*/
public synchronized void add(double item) {
if (initialized < N_MARKERS) {
heights[initialized] = item;
initialized++;
if (initialized == N_MARKERS) {
Arrays.sort(heights);
}
return;
}
// find cell k
final int k;
if (item < heights[0]) {
heights[0] = item;
k = 1;
} else if (item >= heights[N_MARKERS - 1]) {
heights[N_MARKERS - 1] = item;
k = N_MARKERS - 1;
} else {
int i = 1; // Linear search is fastest because N_MARKERS is small
while (item >= heights[i]) {
i++;
}
k = i;
}
for (int i = k; i < pos.length; i++) {
pos[i]++; // increment all positions greater than k
}
for (int i = 1; i < npos.length; i++) {
npos[i] += dn[i]; // updated desired positions
}
adjust();
}
private void adjust() {
for (int i = 1; i < N_MARKERS - 1; i++) {
final int n = pos[i];
final double d0 = npos[i] - n;
if ((d0 >= 1 && pos[i + 1] > n + 1) || (d0 <= -1 && pos[i - 1] < n - 1)) {
final int d = d0 > 0 ? 1 : -1;
final double q = heights[i];
final double qp1 = heights[i + 1];
final double qm1 = heights[i - 1];
final int np1 = pos[i + 1];
final int nm1 = pos[i - 1];
final double qn = calcP2(d, q, qp1, qm1, n, np1, nm1);
if (qm1 < qn && qn < qp1) {
heights[i] = qn;
} else {
// use linear form
heights[i] = q + Math.copySign((heights[i + d] - q) / (pos[i + d] - n), d);
}
pos[i] = n + d;
}
}
}
private static double calcP2(int d, double q, double qp1, double qm1, int n, int np1, int nm1) {
// q + d / (np1 - nm1) * ((n - nm1 + d) * (qp1 - q) / (np1 - n) + (np1 - n - d) * (q - qm1) / (n - nm1))
final int leftX = n - nm1;
final int rightX = np1 - n;
final double rightScale = (leftX + d) / (double)rightX;
final double leftScale = (rightX - d) / (double)leftX;
final double leftHalf = leftScale * (q - qm1);
final double rightHalf = rightScale * (qp1 - q);
return q + Math.copySign((leftHalf + rightHalf) / (np1 - nm1), d);
}
}
}
| Further improve naming of variables and comments
| src/main/java/io/praesid/livestats/LiveStats.java | Further improve naming of variables and comments | <ide><path>rc/main/java/io/praesid/livestats/LiveStats.java
<ide>
<ide> private static final double[] DEFAULT_TILES = {0.5};
<ide>
<del> private final AtomicDouble cumulant2 = new AtomicDouble(0);
<del> private final AtomicDouble cumulant4 = new AtomicDouble(0);
<del> private final AtomicDouble cumulant3 = new AtomicDouble(0);
<ide> private final AtomicDouble average = new AtomicDouble(0);
<add> private final AtomicDouble sumCentralMoment2 = new AtomicDouble(0);
<add> private final AtomicDouble sumCentralMoment3 = new AtomicDouble(0);
<add> private final AtomicDouble sumCentralMoment4 = new AtomicDouble(0);
<ide> private final AtomicInteger count = new AtomicInteger(0);
<ide> private final ImmutableList<Quantile> tiles;
<ide>
<ide> final double delta = item - average.addAndGet(preDelta / myCount);
<ide>
<ide> final double delta2 = delta * delta;
<del> cumulant2.addAndGet(delta2);
<add> sumCentralMoment2.addAndGet(delta2);
<ide>
<ide> final double delta3 = delta2 * delta;
<del> cumulant3.addAndGet(delta3);
<add> sumCentralMoment3.addAndGet(delta3);
<ide>
<ide> final double delta4 = delta3 * delta;
<del> cumulant4.addAndGet(delta4);
<add> sumCentralMoment4.addAndGet(delta4);
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> public double variance() {
<del> return cumulant2.get() / count.get();
<add> return sumCentralMoment2.get() / count.get();
<ide> }
<ide>
<ide> public double kurtosis() {
<del> // k / (c * (v/c)^2) - 3
<del> // k / (c * (v/c) * (v/c)) - 3
<del> // k / (v * v / c) - 3
<del> // k * c / (v * v) - 3
<del> final double myCumulant2 = cumulant2.get();
<del> return cumulant4.get() * count.get() / (myCumulant2 * myCumulant2) - 3;
<add> // u4 / u2^2 - 3
<add> // (s4/c) / (s2/c)^2 - 3
<add> // s4 / (c * (s2/c)^2) - 3
<add> // s4 / (c * (s2/c) * (s2/c)) - 3
<add> // s4 / (s2^2 / c) - 3
<add> // s4 * c / s2^2 - 3
<add> return sumCentralMoment4.get() * count.get() / Math.pow(sumCentralMoment2.get(), 2) - 3;
<ide> }
<ide>
<ide> public double skewness() {
<del> // s / (c * (v/c)^(3/2))
<del> // s / (c * (v/c) * (v/c)^(1/2))
<del> // s / (v * sqrt(v/c))
<del> // s * sqrt(c/v) / v
<del> final double myCumulant2 = cumulant2.get();
<del> return cumulant3.get() * Math.sqrt(count.get() / myCumulant2) / myCumulant2;
<add> // u3 / u2^(3/2)
<add> // (s3/c) / (s2/c)^(3/2)
<add> // s3 / (c * (s2/c)^(3/2))
<add> // s3 / (c * (s2/c) * (s2/c)^(1/2))
<add> // s3 / (s2 * sqrt(s2/c))
<add> // s3 * sqrt(c/s2) / s2
<add> final double mySumCentralMoment2 = sumCentralMoment2.get();
<add> return sumCentralMoment3.get() * Math.sqrt(count.get() / mySumCentralMoment2) / mySumCentralMoment2;
<ide> }
<ide>
<ide> @ThreadSafe |
|
Java | lgpl-2.1 | 67989a993270e78d76993631fb049b91745c500c | 0 | DravitLochan/susi_server,DravitLochan/susi_server,DravitLochan/susi_server,DravitLochan/susi_server | /**
* SusiIntent
* Copyright 29.06.2016 by Michael Peter Christen, @0rb1t3r
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package ai.susi.mind;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.json.JSONArray;
import org.json.JSONObject;
import ai.susi.DAO;
import ai.susi.tools.TimeoutMatcher;
/**
* An intent in the Susi AI framework is a collection of utterances, inference processes and actions that are applied
* on external sense data if the utterances identify that this intent set would be applicable on the sense data.
* A set of intent would is a intent on how to handle activities from the outside of the AI and react on
* such activities.
*/
public class SusiIntent {
public final static String CATCHALL_KEY = "*";
public final static int DEFAULT_SCORE = 10;
private final List<SusiUtterance> utterances;
private final List<SusiInference> inferences;
private final List<SusiAction> actions;
private final Set<String> keys;
private final String comment;
private final int user_subscore;
private Score score;
private final int id;
private final String skill, example, expect;
private SusiLanguage language;
/**
* Generate a set of intents from a single intent definition. This may be possible if the intent contains an 'options'
* object which creates a set of intents, one for each option. The options combine with one set of utterances
* @param json - a multi-intent definition
* @return a set of intents
*/
public static List<SusiIntent> getIntents(SusiLanguage language, JSONObject json, String skillpath) {
if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0);
final List<SusiIntent> intents = new ArrayList<>();
if (json.has("options")) {
JSONArray options = json.getJSONArray("options");
for (int i = 0; i < options.length(); i++) {
JSONObject option = new JSONObject();
option.put("phrases", json.get("phrases"));
JSONObject or = options.getJSONObject(i);
for (String k: or.keySet()) option.put(k, or.get(k));
intents.add(new SusiIntent(language, option, skillpath));
}
} else {
try {
SusiIntent intent = new SusiIntent(language, json, skillpath);
intents.add(intent);
} catch (PatternSyntaxException e) {
Logger.getLogger("SusiIntent").warning("Regular Expression error in Susi Intent " + skillpath + ": " + json.toString(2));
}
}
return intents;
}
/**
* Create an intent by parsing of the intent description
* @param json the intent description
* @throws PatternSyntaxException
*/
private SusiIntent(SusiLanguage language, JSONObject json, String skillpath) throws PatternSyntaxException {
// extract the utterances and the utterances subscore
if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0);
JSONArray p = (JSONArray) json.remove("phrases");
this.utterances = new ArrayList<>(p.length());
p.forEach(q -> this.utterances.add(new SusiUtterance((JSONObject) q)));
// extract the actions and the action subscore
if (!json.has("actions")) throw new PatternSyntaxException("actions missing", "", 0);
p = (JSONArray) json.remove("actions");
this.actions = new ArrayList<>(p.length());
p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));
// extract the inferences and the process subscore; there may be no inference at all
if (json.has("process")) {
p = (JSONArray) json.remove("process");
this.inferences = new ArrayList<>(p.length());
p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
} else {
this.inferences = new ArrayList<>(0);
}
// extract (or compute) the keys; there may be none key given, then they will be computed
this.keys = new HashSet<>();
JSONArray k;
if (json.has("keys")) {
k = json.getJSONArray("keys");
if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0)) k = computeKeysFromUtterance(this.utterances);
} else {
k = computeKeysFromUtterance(this.utterances);
}
k.forEach(o -> this.keys.add((String) o));
this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
this.score = null; // calculate this later if required
// extract the comment
this.comment = json.has("comment") ? json.getString("comment") : "";
// remember the origin
this.skill = skillpath;
// compute the language from the origin
this.language = language;
// quality control
this.example = json.has("example") ? json.getString("example") : "";
this.expect = json.has("expect") ? json.getString("expect") : "";
// calculate the id
String ids0 = this.actions.toString();
String ids1 = this.utterances.toString();
this.id = ids0.hashCode() + ids1.hashCode();
}
public String getSkill() {
return this.skill == null || this.skill.length() == 0 ? null : this.skill;
}
public String getExpect() {
return this.expect == null || this.expect.length() == 0 ? null : this.expect;
}
public String getExample() {
return this.example == null || this.example.length() == 0 ? null : this.example;
}
public int hashCode() {
return this.id;
}
public JSONObject toJSON() {
JSONObject json = new JSONObject(true);
json.put("id", this.id);
if (this.keys != null && this.keys.size() > 0) json.put("keys", new JSONArray(this.keys));
JSONArray p = new JSONArray(); this.utterances.forEach(utterance -> p.put(utterance.toJSON()));
json.put("phrases", p);
JSONArray i = new JSONArray(); this.inferences.forEach(inference -> i.put(inference.getJSON()));
json.put("process", i);
JSONArray a = new JSONArray(); this.getActionsClone().forEach(action ->a.put(action.toJSONClone()));
json.put("actions", a);
if (this.comment != null && this.comment.length() > 0) json.put("comment", this.comment);
if (this.score != null) json.put("score", this.score.score);
if (this.skill != null && this.skill.length() > 0) json.put("skill", this.skill);
if (this.example != null && this.example.length() > 0) json.put("example", example);
if (this.expect != null && this.expect.length() > 0) json.put("expect", expect);
return json;
}
public static JSONObject answerIntent(
String[] utterances,
String condition,
String[] answers,
boolean prior,
String example,
String expect) {
JSONObject intent = new JSONObject(true);
// write utterances
JSONArray p = new JSONArray();
intent.put("phrases", p);
for (String utterance: utterances) p.put(SusiUtterance.simplePhrase(utterance.trim(), prior));
// write conditions (if any)
if (condition != null && condition.length() > 0) {
JSONArray c = new JSONArray();
intent.put("process", c);
c.put(SusiInference.simpleMemoryProcess(condition));
}
// quality control
if (example != null && example.length() > 0) intent.put("example", example);
if (expect != null && expect.length() > 0) intent.put("expect", expect);
// write actions
JSONArray a = new JSONArray();
intent.put("actions", a);
a.put(SusiAction.answerAction(answers));
return intent;
}
public String toString() {
return this.toJSON().toString(2);
}
public long getID() {
return this.id;
}
private final static Pattern SPACE_PATTERN = Pattern.compile(" ");
/**
* if no keys are given, we compute them from the given utterances
* @param utterances
* @return
*/
private static JSONArray computeKeysFromUtterance(List<SusiUtterance> utterances) {
Set<String> t = new LinkedHashSet<>();
// create a list of token sets from the utterances
List<Set<String>> ptl = new ArrayList<>();
final AtomicBoolean needsCatchall = new AtomicBoolean(false);
utterances.forEach(utterance -> {
Set<String> s = new HashSet<>();
for (String token: SPACE_PATTERN.split(utterance.getPattern().toString())) {
String m = SusiUtterance.extractMeat(token.toLowerCase());
if (m.length() > 1) s.add(m);
}
// if there is no meat inside, it will not be possible to access the intent without the catchall intent, so remember that
if (s.size() == 0) needsCatchall.set(true);
ptl.add(s);
});
// this is a kind of emergency case where we need a catchall intent because otherwise we cannot access one of the utterances
JSONArray a = new JSONArray();
if (needsCatchall.get()) return a.put(CATCHALL_KEY);
// collect all token
ptl.forEach(set -> set.forEach(token -> t.add(token)));
// if no tokens are available, return the catchall key
if (t.size() == 0) return a.put(CATCHALL_KEY);
// make a copy to make it possible to use the original key set again
Set<String> tc = new LinkedHashSet<>();
t.forEach(c -> tc.add(c));
// remove all token that do not appear in all utterances
ptl.forEach(set -> {
Iterator<String> i = t.iterator();
while (i.hasNext()) if (!set.contains(i.next())) i.remove();
});
// if no token is left, use the original tc set and add all keys
if (t.size() == 0) {
tc.forEach(c -> a.put(c));
return a;
}
// use only the first token, because that appears in all the utterances
return new JSONArray().put(t.iterator().next());
}
/**
* To simplify the check weather or not a intent could be applicable, a key set is provided which
* must match with input tokens literally. This key check prevents too large numbers of utterance checks
* thus increasing performance.
* @return the keys which must appear in an input to allow that this intent can be applied
*/
public Set<String> getKeys() {
return this.keys;
}
/**
* An intent may have a comment which describes what the intent means. It never has any computational effect.
* @return the intent comment
*/
public String getComment() {
return this.comment;
}
/**
* get the intent score
* @param language this is the language the user is speaking
* @return an intent score: the higher, the better
*/
public Score getScore(SusiLanguage language) {
if (this.score != null) return score;
this.score = new Score(language);
return this.score;
}
/**
* The score is used to prefer one intent over another if that other intent has a lower score.
* The reason that this score is used is given by the fact that we need intents which have
* fuzzy utterance definitions and several intents might be selected because these fuzzy utterances match
* on the same input sequence. One example is the catch-all intent which fires always but has
* lowest priority.
* In the context of artificial mind modeling the score plays the role of a positive emotion.
* If the AI learns that a intent was applied and caused a better situation (see also: game playing gamefield
* evaluation) then the intent might get the score increased. Having many intents which have a high score
* therefore might induce a 'good feeling' because it is known that the outcome will be good.
* @return a score which is used for sorting of the intents. The higher the better. Highest score wins.
*/
public class Score {
public int score;
public String log;
public Score(SusiLanguage userLanguage) {
if (SusiIntent.this.score != null) return;
/*
* Score Computation:
* see: https://github.com/loklak/loklak_server/issues/767
* Criteria:
* (0) the language
* We do not want to switch skills for languages because people sometimes
* speak several languages. Therefore we use a likelihood that someone who speaks language A
* also speaks language B.
* (1) the existence of a pattern where we decide between prior and minor intents
* pattern: {false, true} with/without pattern could be computed from the intent string
* all intents with pattern are ordered in the middle between prior and minor
* this is combined with
* prior: {false, true} overruling (prior=true) or default (prior=false) would have to be defined
* The prior attribute can also be expressed as an replacement of a pattern type because it is only relevant if the query is not a pattern or regular expression.
* The resulting criteria is a property with three possible values: {minor, pattern, major}
* (2) the meatsize (number of characters that are non-patterns)
* (3) the whole size (total number of characters)
* (4) the conversation plan:
* purpose: {answer, question, reply} purpose would have to be defined
* The purpose can be computed using a pattern on the answer expression: is there a '?' at the end, is it a question. Is there also a '. ' (end of sentence) in the text, is it a reply.
* (5) the operation type
* op: {retrieval, computation, storage} the operation could be computed from the intent string
* (6) the IO activity (-location)
* io: {remote, local, ram} the storage location can be computed from the intent string
* (7) finally the subscore can be assigned manually
* subscore a score in a small range which can be used to distinguish intents within the same categories
*/
// compute the score
// (0) language
final int language_subscore = (int) (100 * SusiIntent.this.language.likelihoodCanSpeak(userLanguage));
this.score = language_subscore;
// (1) pattern score
final AtomicInteger utterances_subscore = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_subscore.set(Math.min(utterances_subscore.get(), utterance.getSubscore())));
this.score = this.score * SusiUtterance.Type.values().length + utterances_subscore.get();
// (2) meatsize: length of a utterance (counts letters)
final AtomicInteger utterances_meatscore = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_meatscore.set(Math.max(utterances_meatscore.get(), utterance.getMeatsize())));
this.score = this.score * 100 + utterances_meatscore.get();
// (3) whole size: length of the pattern
final AtomicInteger utterances_wholesize = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_wholesize.set(Math.max(utterances_wholesize.get(), utterance.getPattern().toString().length())));
this.score = this.score * 100 + utterances_wholesize.get();
// (4) conversation plan from the answer purpose
final AtomicInteger dialogType_subscore = new AtomicInteger(0);
if (!(utterances.size() == 1 && utterances.get(0).equals("(.*)"))) {
SusiIntent.this.actions.forEach(action -> dialogType_subscore.set(Math.max(dialogType_subscore.get(), action.getDialogType().getSubscore())));
}
this.score = this.score * SusiAction.DialogType.values().length + dialogType_subscore.get();
// (5) operation type - there may be no operation at all
final AtomicInteger inference_subscore = new AtomicInteger(0);
SusiIntent.this.inferences.forEach(inference -> inference_subscore.set(Math.max(inference_subscore.get(), inference.getType().getSubscore())));
this.score = this.score * (1 + SusiInference.Type.values().length) + inference_subscore.get();
// (6) subscore from the user
this.score += this.score * 1000 + Math.min(1000, SusiIntent.this.user_subscore);
this.log =
"language=" + language_subscore +
", dialog=" + dialogType_subscore.get() +
", utterance=" + utterances_subscore.get() +
", meatscore=" + utterances_meatscore.get() +
", wholesize=" + utterances_wholesize.get() +
", inference=" + inference_subscore.get() +
", subscore=" + user_subscore +
", pattern=" + utterances.get(0).toString() + (SusiIntent.this.inferences.size() > 0 ? (", inference=" + SusiIntent.this.inferences.get(0).getExpression()) : "");
}
}
/**
* The utterances of an intent are the matching intents which must apply to make it possible that the utterance is applied.
* This returns the utterances of the intent.
* @return the utterances of the intent. The intent fires if ANY of the utterances apply
*/
public List<SusiUtterance> getUtterances() {
return this.utterances;
}
/**
* The inferences of a intent are a set of operations that are applied if the intent is selected as response
* mechanism. The inferences are feeded by the matching parts of the utterances to have an initial data set.
* Inferences are lists because they represent a set of lambda operations on the data stream. The last
* Data set is the response. The stack of data sets which are computed during the inference processing
* is the thought argument, a list of thoughts in between of the inferences.
* @return the (ordered) list of inferences to be applied for this intent
*/
public List<SusiInference> getInferences() {
return this.inferences;
}
/**
* Actions are operations that are activated when inferences terminate and something should be done with the
* result. Actions describe how data should be presented, i.e. painted in graphs or just answer lines.
* Because actions may get changed during computation, we return a clone here
* @return a list of possible actions. It might be possible to use only a subset, but it is recommended to activate all of them
*/
public List<SusiAction> getActionsClone() {
List<SusiAction> clonedList = new ArrayList<>();
this.actions.forEach(action -> {
JSONObject actionJson = action.toJSONClone();
if (this.language != SusiLanguage.unknown) actionJson.put("language", this.language.name());
clonedList.add(new SusiAction(actionJson));
});
return clonedList;
}
/**
* The matcher of a intent is the result of the application of the intent's utterances,
* the pattern which allow to apply the intent
* @param s the string which should match
* @return a matcher on the intent utterances
*/
public Collection<Matcher> matcher(String s) {
List<Matcher> l = new ArrayList<>();
s = s.toLowerCase();
for (SusiUtterance p: this.utterances) {
Matcher m = p.getPattern().matcher(s);
if (new TimeoutMatcher(m).find()) {
//System.out.println("MATCHERGROUP=" + m.group().toString());
l.add(m); // TODO: exclude double-entries
}
}
return l;
}
/**
* If a intent is applied to an input stream, it must follow a specific process which is implemented
* in this consideration method. It is called a consideration in the context of an AI process which
* tries different procedures to get the optimum result, thus considering different intents.
* @param query the user input
* @param token the key from the user query which matched the intent tokens (also considering category matching)
* @return the result of the application of the intent, a thought argument containing the thoughts which terminated into a final mindstate or NULL if the consideration should be rejected
*/
public SusiArgument consideration(final String query, SusiThought recall, SusiLinguistics.Token token, SusiMind mind, String client) {
// we start with the recall from previous interactions as new flow
final SusiArgument flow = new SusiArgument().think(recall);
// that argument is filled with an idea which consist of the query where we extract the identified data entities
alternatives: for (Matcher matcher: this.matcher(query)) {
if (!new TimeoutMatcher(matcher).matches()) continue;
SusiThought keynote = new SusiThought(matcher);
if (token != null) {
keynote.addObservation("token_original", token.original);
keynote.addObservation("token_canonical", token.canonical);
keynote.addObservation("token_categorized", token.categorized);
}
DAO.log("Susi has an idea: on " + keynote.toString() + " apply " + this.toJSON());
flow.think(keynote);
// lets apply the intents that belong to this specific consideration
for (SusiInference inference: this.getInferences()) {
SusiThought implication = inference.applyProcedures(flow);
DAO.log("Susi is thinking about: " + implication.toString());
// make sure that we are not stuck:
// in case that we are stuck (== no progress was made) we terminate and return null
if ((flow.mindstate().equals(implication) || implication.isFailed())) continue alternatives; // TODO: do this only if specific marker is in intent
// think
flow.think(implication);
}
// we deduced thoughts from the inferences in the intents. Now apply the actions of intent to produce results
this.getActionsClone().forEach(action -> flow.addAction(action/*.execution(flow, mind, client)*/));
// add skill source
if (this.skill != null && this.skill.length() > 0) flow.addSkill(this.skill);
return flow;
}
// fail, no alternative was successful
return null;
}
}
| src/ai/susi/mind/SusiIntent.java | /**
* SusiIntent
* Copyright 29.06.2016 by Michael Peter Christen, @0rb1t3r
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package ai.susi.mind;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.json.JSONArray;
import org.json.JSONObject;
import ai.susi.DAO;
import ai.susi.tools.TimeoutMatcher;
/**
* An intent in the Susi AI framework is a collection of utterances, inference processes and actions that are applied
* on external sense data if the utterances identify that this intent set would be applicable on the sense data.
* A set of intent would is a intent on how to handle activities from the outside of the AI and react on
* such activities.
*/
public class SusiIntent {
public final static String CATCHALL_KEY = "*";
public final static int DEFAULT_SCORE = 10;
private final List<SusiUtterance> utterances;
private final List<SusiInference> inferences;
private final List<SusiAction> actions;
private final Set<String> keys;
private final String comment;
private final int user_subscore;
private Score score;
private final int id;
private final String skill, example, expect;
private SusiLanguage language;
/**
* Generate a set of intents from a single intent definition. This may be possible if the intent contains an 'options'
* object which creates a set of intents, one for each option. The options combine with one set of utterances
* @param json - a multi-intent definition
* @return a set of intents
*/
public static List<SusiIntent> getIntents(SusiLanguage language, JSONObject json, String skillpath) {
if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0);
final List<SusiIntent> intents = new ArrayList<>();
if (json.has("options")) {
JSONArray options = json.getJSONArray("options");
for (int i = 0; i < options.length(); i++) {
JSONObject option = new JSONObject();
option.put("phrases", json.get("phrases"));
JSONObject or = options.getJSONObject(i);
for (String k: or.keySet()) option.put(k, or.get(k));
intents.add(new SusiIntent(language, option, skillpath));
}
} else {
try {
SusiIntent intent = new SusiIntent(language, json, skillpath);
intents.add(intent);
} catch (PatternSyntaxException e) {
Logger.getLogger("SusiIntent").warning("Regular Expression error in Susi Intent: " + json.toString(2));
}
}
return intents;
}
/**
* Create an intent by parsing of the intent description
* @param json the intent description
* @throws PatternSyntaxException
*/
private SusiIntent(SusiLanguage language, JSONObject json, String skillpath) throws PatternSyntaxException {
// extract the utterances and the utterances subscore
if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0);
JSONArray p = (JSONArray) json.remove("phrases");
this.utterances = new ArrayList<>(p.length());
p.forEach(q -> this.utterances.add(new SusiUtterance((JSONObject) q)));
// extract the actions and the action subscore
if (!json.has("actions")) throw new PatternSyntaxException("actions missing", "", 0);
p = (JSONArray) json.remove("actions");
this.actions = new ArrayList<>(p.length());
p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));
// extract the inferences and the process subscore; there may be no inference at all
if (json.has("process")) {
p = (JSONArray) json.remove("process");
this.inferences = new ArrayList<>(p.length());
p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
} else {
this.inferences = new ArrayList<>(0);
}
// extract (or compute) the keys; there may be none key given, then they will be computed
this.keys = new HashSet<>();
JSONArray k;
if (json.has("keys")) {
k = json.getJSONArray("keys");
if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0)) k = computeKeysFromUtterance(this.utterances);
} else {
k = computeKeysFromUtterance(this.utterances);
}
k.forEach(o -> this.keys.add((String) o));
this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
this.score = null; // calculate this later if required
// extract the comment
this.comment = json.has("comment") ? json.getString("comment") : "";
// remember the origin
this.skill = skillpath;
// compute the language from the origin
this.language = language;
// quality control
this.example = json.has("example") ? json.getString("example") : "";
this.expect = json.has("expect") ? json.getString("expect") : "";
// calculate the id
String ids0 = this.actions.toString();
String ids1 = this.utterances.toString();
this.id = ids0.hashCode() + ids1.hashCode();
}
public String getSkill() {
return this.skill == null || this.skill.length() == 0 ? null : this.skill;
}
public String getExpect() {
return this.expect == null || this.expect.length() == 0 ? null : this.expect;
}
public String getExample() {
return this.example == null || this.example.length() == 0 ? null : this.example;
}
public int hashCode() {
return this.id;
}
public JSONObject toJSON() {
JSONObject json = new JSONObject(true);
json.put("id", this.id);
if (this.keys != null && this.keys.size() > 0) json.put("keys", new JSONArray(this.keys));
JSONArray p = new JSONArray(); this.utterances.forEach(utterance -> p.put(utterance.toJSON()));
json.put("phrases", p);
JSONArray i = new JSONArray(); this.inferences.forEach(inference -> i.put(inference.getJSON()));
json.put("process", i);
JSONArray a = new JSONArray(); this.getActionsClone().forEach(action ->a.put(action.toJSONClone()));
json.put("actions", a);
if (this.comment != null && this.comment.length() > 0) json.put("comment", this.comment);
if (this.score != null) json.put("score", this.score.score);
if (this.skill != null && this.skill.length() > 0) json.put("skill", this.skill);
if (this.example != null && this.example.length() > 0) json.put("example", example);
if (this.expect != null && this.expect.length() > 0) json.put("expect", expect);
return json;
}
public static JSONObject answerIntent(
String[] utterances,
String condition,
String[] answers,
boolean prior,
String example,
String expect) {
JSONObject intent = new JSONObject(true);
// write utterances
JSONArray p = new JSONArray();
intent.put("phrases", p);
for (String utterance: utterances) p.put(SusiUtterance.simplePhrase(utterance.trim(), prior));
// write conditions (if any)
if (condition != null && condition.length() > 0) {
JSONArray c = new JSONArray();
intent.put("process", c);
c.put(SusiInference.simpleMemoryProcess(condition));
}
// quality control
if (example != null && example.length() > 0) intent.put("example", example);
if (expect != null && expect.length() > 0) intent.put("expect", expect);
// write actions
JSONArray a = new JSONArray();
intent.put("actions", a);
a.put(SusiAction.answerAction(answers));
return intent;
}
public String toString() {
return this.toJSON().toString(2);
}
public long getID() {
return this.id;
}
private final static Pattern SPACE_PATTERN = Pattern.compile(" ");
/**
* if no keys are given, we compute them from the given utterances
* @param utterances
* @return
*/
private static JSONArray computeKeysFromUtterance(List<SusiUtterance> utterances) {
Set<String> t = new LinkedHashSet<>();
// create a list of token sets from the utterances
List<Set<String>> ptl = new ArrayList<>();
final AtomicBoolean needsCatchall = new AtomicBoolean(false);
utterances.forEach(utterance -> {
Set<String> s = new HashSet<>();
for (String token: SPACE_PATTERN.split(utterance.getPattern().toString())) {
String m = SusiUtterance.extractMeat(token.toLowerCase());
if (m.length() > 1) s.add(m);
}
// if there is no meat inside, it will not be possible to access the intent without the catchall intent, so remember that
if (s.size() == 0) needsCatchall.set(true);
ptl.add(s);
});
// this is a kind of emergency case where we need a catchall intent because otherwise we cannot access one of the utterances
JSONArray a = new JSONArray();
if (needsCatchall.get()) return a.put(CATCHALL_KEY);
// collect all token
ptl.forEach(set -> set.forEach(token -> t.add(token)));
// if no tokens are available, return the catchall key
if (t.size() == 0) return a.put(CATCHALL_KEY);
// make a copy to make it possible to use the original key set again
Set<String> tc = new LinkedHashSet<>();
t.forEach(c -> tc.add(c));
// remove all token that do not appear in all utterances
ptl.forEach(set -> {
Iterator<String> i = t.iterator();
while (i.hasNext()) if (!set.contains(i.next())) i.remove();
});
// if no token is left, use the original tc set and add all keys
if (t.size() == 0) {
tc.forEach(c -> a.put(c));
return a;
}
// use only the first token, because that appears in all the utterances
return new JSONArray().put(t.iterator().next());
}
/**
* To simplify the check weather or not a intent could be applicable, a key set is provided which
* must match with input tokens literally. This key check prevents too large numbers of utterance checks
* thus increasing performance.
* @return the keys which must appear in an input to allow that this intent can be applied
*/
public Set<String> getKeys() {
return this.keys;
}
/**
* An intent may have a comment which describes what the intent means. It never has any computational effect.
* @return the intent comment
*/
public String getComment() {
return this.comment;
}
/**
* get the intent score
* @param language this is the language the user is speaking
* @return an intent score: the higher, the better
*/
public Score getScore(SusiLanguage language) {
if (this.score != null) return score;
this.score = new Score(language);
return this.score;
}
/**
* The score is used to prefer one intent over another if that other intent has a lower score.
* The reason that this score is used is given by the fact that we need intents which have
* fuzzy utterance definitions and several intents might be selected because these fuzzy utterances match
* on the same input sequence. One example is the catch-all intent which fires always but has
* lowest priority.
* In the context of artificial mind modeling the score plays the role of a positive emotion.
* If the AI learns that a intent was applied and caused a better situation (see also: game playing gamefield
* evaluation) then the intent might get the score increased. Having many intents which have a high score
* therefore might induce a 'good feeling' because it is known that the outcome will be good.
* @return a score which is used for sorting of the intents. The higher the better. Highest score wins.
*/
public class Score {
public int score;
public String log;
public Score(SusiLanguage userLanguage) {
if (SusiIntent.this.score != null) return;
/*
* Score Computation:
* see: https://github.com/loklak/loklak_server/issues/767
* Criteria:
* (0) the language
* We do not want to switch skills for languages because people sometimes
* speak several languages. Therefore we use a likelihood that someone who speaks language A
* also speaks language B.
* (1) the existence of a pattern where we decide between prior and minor intents
* pattern: {false, true} with/without pattern could be computed from the intent string
* all intents with pattern are ordered in the middle between prior and minor
* this is combined with
* prior: {false, true} overruling (prior=true) or default (prior=false) would have to be defined
* The prior attribute can also be expressed as an replacement of a pattern type because it is only relevant if the query is not a pattern or regular expression.
* The resulting criteria is a property with three possible values: {minor, pattern, major}
* (2) the meatsize (number of characters that are non-patterns)
* (3) the whole size (total number of characters)
* (4) the conversation plan:
* purpose: {answer, question, reply} purpose would have to be defined
* The purpose can be computed using a pattern on the answer expression: is there a '?' at the end, is it a question. Is there also a '. ' (end of sentence) in the text, is it a reply.
* (5) the operation type
* op: {retrieval, computation, storage} the operation could be computed from the intent string
* (6) the IO activity (-location)
* io: {remote, local, ram} the storage location can be computed from the intent string
* (7) finally the subscore can be assigned manually
* subscore a score in a small range which can be used to distinguish intents within the same categories
*/
// compute the score
// (0) language
final int language_subscore = (int) (100 * SusiIntent.this.language.likelihoodCanSpeak(userLanguage));
this.score = language_subscore;
// (1) pattern score
final AtomicInteger utterances_subscore = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_subscore.set(Math.min(utterances_subscore.get(), utterance.getSubscore())));
this.score = this.score * SusiUtterance.Type.values().length + utterances_subscore.get();
// (2) meatsize: length of a utterance (counts letters)
final AtomicInteger utterances_meatscore = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_meatscore.set(Math.max(utterances_meatscore.get(), utterance.getMeatsize())));
this.score = this.score * 100 + utterances_meatscore.get();
// (3) whole size: length of the pattern
final AtomicInteger utterances_wholesize = new AtomicInteger(0);
SusiIntent.this.utterances.forEach(utterance -> utterances_wholesize.set(Math.max(utterances_wholesize.get(), utterance.getPattern().toString().length())));
this.score = this.score * 100 + utterances_wholesize.get();
// (4) conversation plan from the answer purpose
final AtomicInteger dialogType_subscore = new AtomicInteger(0);
if (!(utterances.size() == 1 && utterances.get(0).equals("(.*)"))) {
SusiIntent.this.actions.forEach(action -> dialogType_subscore.set(Math.max(dialogType_subscore.get(), action.getDialogType().getSubscore())));
}
this.score = this.score * SusiAction.DialogType.values().length + dialogType_subscore.get();
// (5) operation type - there may be no operation at all
final AtomicInteger inference_subscore = new AtomicInteger(0);
SusiIntent.this.inferences.forEach(inference -> inference_subscore.set(Math.max(inference_subscore.get(), inference.getType().getSubscore())));
this.score = this.score * (1 + SusiInference.Type.values().length) + inference_subscore.get();
// (6) subscore from the user
this.score += this.score * 1000 + Math.min(1000, SusiIntent.this.user_subscore);
this.log =
"language=" + language_subscore +
", dialog=" + dialogType_subscore.get() +
", utterance=" + utterances_subscore.get() +
", meatscore=" + utterances_meatscore.get() +
", wholesize=" + utterances_wholesize.get() +
", inference=" + inference_subscore.get() +
", subscore=" + user_subscore +
", pattern=" + utterances.get(0).toString() + (SusiIntent.this.inferences.size() > 0 ? (", inference=" + SusiIntent.this.inferences.get(0).getExpression()) : "");
}
}
/**
* The utterances of an intent are the matching intents which must apply to make it possible that the utterance is applied.
* This returns the utterances of the intent.
* @return the utterances of the intent. The intent fires if ANY of the utterances apply
*/
public List<SusiUtterance> getUtterances() {
return this.utterances;
}
/**
* The inferences of a intent are a set of operations that are applied if the intent is selected as response
* mechanism. The inferences are feeded by the matching parts of the utterances to have an initial data set.
* Inferences are lists because they represent a set of lambda operations on the data stream. The last
* Data set is the response. The stack of data sets which are computed during the inference processing
* is the thought argument, a list of thoughts in between of the inferences.
* @return the (ordered) list of inferences to be applied for this intent
*/
public List<SusiInference> getInferences() {
return this.inferences;
}
/**
* Actions are operations that are activated when inferences terminate and something should be done with the
* result. Actions describe how data should be presented, i.e. painted in graphs or just answer lines.
* Because actions may get changed during computation, we return a clone here
* @return a list of possible actions. It might be possible to use only a subset, but it is recommended to activate all of them
*/
public List<SusiAction> getActionsClone() {
List<SusiAction> clonedList = new ArrayList<>();
this.actions.forEach(action -> {
JSONObject actionJson = action.toJSONClone();
if (this.language != SusiLanguage.unknown) actionJson.put("language", this.language.name());
clonedList.add(new SusiAction(actionJson));
});
return clonedList;
}
/**
* The matcher of a intent is the result of the application of the intent's utterances,
* the pattern which allow to apply the intent
* @param s the string which should match
* @return a matcher on the intent utterances
*/
public Collection<Matcher> matcher(String s) {
List<Matcher> l = new ArrayList<>();
s = s.toLowerCase();
for (SusiUtterance p: this.utterances) {
Matcher m = p.getPattern().matcher(s);
if (new TimeoutMatcher(m).find()) {
//System.out.println("MATCHERGROUP=" + m.group().toString());
l.add(m); // TODO: exclude double-entries
}
}
return l;
}
/**
* If a intent is applied to an input stream, it must follow a specific process which is implemented
* in this consideration method. It is called a consideration in the context of an AI process which
* tries different procedures to get the optimum result, thus considering different intents.
* @param query the user input
* @param token the key from the user query which matched the intent tokens (also considering category matching)
* @return the result of the application of the intent, a thought argument containing the thoughts which terminated into a final mindstate or NULL if the consideration should be rejected
*/
public SusiArgument consideration(final String query, SusiThought recall, SusiLinguistics.Token token, SusiMind mind, String client) {
// we start with the recall from previous interactions as new flow
final SusiArgument flow = new SusiArgument().think(recall);
// that argument is filled with an idea which consist of the query where we extract the identified data entities
alternatives: for (Matcher matcher: this.matcher(query)) {
if (!new TimeoutMatcher(matcher).matches()) continue;
SusiThought keynote = new SusiThought(matcher);
if (token != null) {
keynote.addObservation("token_original", token.original);
keynote.addObservation("token_canonical", token.canonical);
keynote.addObservation("token_categorized", token.categorized);
}
DAO.log("Susi has an idea: on " + keynote.toString() + " apply " + this.toJSON());
flow.think(keynote);
// lets apply the intents that belong to this specific consideration
for (SusiInference inference: this.getInferences()) {
SusiThought implication = inference.applyProcedures(flow);
DAO.log("Susi is thinking about: " + implication.toString());
// make sure that we are not stuck:
// in case that we are stuck (== no progress was made) we terminate and return null
if ((flow.mindstate().equals(implication) || implication.isFailed())) continue alternatives; // TODO: do this only if specific marker is in intent
// think
flow.think(implication);
}
// we deduced thoughts from the inferences in the intents. Now apply the actions of intent to produce results
this.getActionsClone().forEach(action -> flow.addAction(action/*.execution(flow, mind, client)*/));
// add skill source
if (this.skill != null && this.skill.length() > 0) flow.addSkill(this.skill);
return flow;
}
// fail, no alternative was successful
return null;
}
}
| log output | src/ai/susi/mind/SusiIntent.java | log output | <ide><path>rc/ai/susi/mind/SusiIntent.java
<ide> SusiIntent intent = new SusiIntent(language, json, skillpath);
<ide> intents.add(intent);
<ide> } catch (PatternSyntaxException e) {
<del> Logger.getLogger("SusiIntent").warning("Regular Expression error in Susi Intent: " + json.toString(2));
<add> Logger.getLogger("SusiIntent").warning("Regular Expression error in Susi Intent " + skillpath + ": " + json.toString(2));
<ide> }
<ide> }
<ide> return intents; |
|
Java | apache-2.0 | 19c53277ab4ad1ae02fd1c6c4d1677053542a60e | 0 | infobip/mobile-messaging-sdk-android,infobip/mobile-messaging-sdk-android,infobip/mobile-messaging-sdk-android | package org.infobip.mobile.messaging.util;
import android.content.Context;
import android.telephony.TelephonyManager;
import org.infobip.mobile.messaging.tools.MobileMessagingTestCase;
import org.junit.Test;
import org.mockito.BDDMockito;
import static junit.framework.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
/**
* @author sslavin
* @since 29/03/2018.
*/
public class MobileNetworkInformationTest extends MobileMessagingTestCase {
private TelephonyManager telephonyManager = mock(TelephonyManager.class);
private Context context = mock(Context.class);
private String invalidOperatorCodes[] = new String[]{null, "", "1", "12"};
@Override
public void setUp() throws Exception {
super.setUp();
given(context.getSystemService(eq(Context.TELEPHONY_SERVICE))).willReturn(telephonyManager);
reset(telephonyManager);
}
@Test
public void shouldReturnUnknown_whenReadingMobileCountryCode_ifNetworkOperatorIsInvalid() {
givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getMobileCountryCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingSIMCountryCode_ifNetworkOperatorIsInvalid() {
givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getSIMCountryCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingMobileNetworkCode_ifNetworkOperatorIsInvalid() {
givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getMobileNetworkCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingSIMNetworkCode_ifNetworkOperatorIsInvalid() {
givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getSIMNetworkCode(context));
}
}
private void givenMethodWillReturn(String method, String values[]) {
BDDMockito.BDDMyOngoingStubbing<String> stubbing = given(method);
for (String value : values) {
stubbing = stubbing.willReturn(value);
}
}
}
| infobip-mobile-messaging-android-sdk/src/androidTest/java/org/infobip/mobile/messaging/util/MobileNetworkInformationTest.java | package org.infobip.mobile.messaging.util;
import android.content.Context;
import android.telephony.TelephonyManager;
import org.infobip.mobile.messaging.tools.MobileMessagingTestCase;
import org.junit.Test;
import org.mockito.BDDMockito;
import static junit.framework.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
/**
* @author sslavin
* @since 29/03/2018.
*/
public class MobileNetworkInformationTest extends MobileMessagingTestCase {
private TelephonyManager telephonyManager = mock(TelephonyManager.class);
private Context context = mock(Context.class);
private String invalidOperatorCodes[] = new String[]{null, "", "1", "12"};
@Override
public void setUp() throws Exception {
super.setUp();
given(context.getSystemService(eq(Context.TELEPHONY_SERVICE))).willReturn(telephonyManager);
reset(telephonyManager);
}
@Test
public void shouldReturnUnknown_whenReadingMobileCountryCode_ifNetworkOperatorLengthIsLessThan3() {
givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getMobileCountryCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingSIMCountryCode_ifNetworkOperatorLengthIsLessThan3() {
givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getSIMCountryCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingMobileNetworkCode_ifNetworkOperatorLengthIsLessThan6() {
givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getMobileNetworkCode(context));
}
}
@Test
public void shouldReturnUnknown_whenReadingSIMNetworkCode_ifNetworkOperatorLengthIsLessThan3() {
givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
for (String ignored : invalidOperatorCodes) {
assertEquals("unknown", MobileNetworkInformation.getSIMNetworkCode(context));
}
}
private void givenMethodWillReturn(String method, String values[]) {
BDDMockito.BDDMyOngoingStubbing<String> stubbing = given(method);
for (String value : values) {
stubbing = stubbing.willReturn(value);
}
}
}
| Fixed test namings
| infobip-mobile-messaging-android-sdk/src/androidTest/java/org/infobip/mobile/messaging/util/MobileNetworkInformationTest.java | Fixed test namings | <ide><path>nfobip-mobile-messaging-android-sdk/src/androidTest/java/org/infobip/mobile/messaging/util/MobileNetworkInformationTest.java
<ide> }
<ide>
<ide> @Test
<del> public void shouldReturnUnknown_whenReadingMobileCountryCode_ifNetworkOperatorLengthIsLessThan3() {
<add> public void shouldReturnUnknown_whenReadingMobileCountryCode_ifNetworkOperatorIsInvalid() {
<ide> givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
<ide>
<ide> for (String ignored : invalidOperatorCodes) {
<ide> }
<ide>
<ide> @Test
<del> public void shouldReturnUnknown_whenReadingSIMCountryCode_ifNetworkOperatorLengthIsLessThan3() {
<add> public void shouldReturnUnknown_whenReadingSIMCountryCode_ifNetworkOperatorIsInvalid() {
<ide> givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
<ide>
<ide> for (String ignored : invalidOperatorCodes) {
<ide> }
<ide>
<ide> @Test
<del> public void shouldReturnUnknown_whenReadingMobileNetworkCode_ifNetworkOperatorLengthIsLessThan6() {
<add> public void shouldReturnUnknown_whenReadingMobileNetworkCode_ifNetworkOperatorIsInvalid() {
<ide> givenMethodWillReturn(telephonyManager.getNetworkOperator(), invalidOperatorCodes);
<ide>
<ide> for (String ignored : invalidOperatorCodes) {
<ide> }
<ide>
<ide> @Test
<del> public void shouldReturnUnknown_whenReadingSIMNetworkCode_ifNetworkOperatorLengthIsLessThan3() {
<add> public void shouldReturnUnknown_whenReadingSIMNetworkCode_ifNetworkOperatorIsInvalid() {
<ide> givenMethodWillReturn(telephonyManager.getSimOperator(), invalidOperatorCodes);
<ide>
<ide> for (String ignored : invalidOperatorCodes) { |
|
Java | lgpl-2.1 | e34dcc2d6611c96d187de40e131bc57d833bc663 | 0 | tomck/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,tomck/intermine,elsiklab/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,joshkh/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,joshkh/intermine,drhee/toxoMine,joshkh/intermine,justincc/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,kimrutherford/intermine,JoeCarlson/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,joshkh/intermine,JoeCarlson/intermine,drhee/toxoMine,tomck/intermine,JoeCarlson/intermine,drhee/toxoMine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,zebrafishmine/intermine,kimrutherford/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,tomck/intermine,elsiklab/intermine,drhee/toxoMine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,drhee/toxoMine,justincc/intermine,JoeCarlson/intermine,justincc/intermine,tomck/intermine,drhee/toxoMine,justincc/intermine,elsiklab/intermine | package org.intermine.api.template;
/*
* Copyright (C) 2002-2009 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
/**
* Exception thrown when errors occur populating a template query with values.
* @author Richard Smith
*
*/
public class TemplatePopulatorException extends RuntimeException
{
/**
* Constructs an TemplatePopulatorException with the specified detail message.
*
* @param msg the detail message
*/
public TemplatePopulatorException(String msg) {
super(msg);
}
/**
* Constructs an TemplatePopulatorException with the specified nested throwable.
*
* @param t the nested throwable
*/
public TemplatePopulatorException(Throwable t) {
super(t);
}
/**
* Constructs an TemplatePopulatorException with the specified detail message and
* nested throwable.
*
* @param msg the detail message
* @param t the nested throwable
*/
public TemplatePopulatorException(String msg, Throwable t) {
super(msg, t);
}
}
| intermine/api/main/src/org/intermine/api/template/TemplatePopulatorException.java | package org.intermine.api.template;
/*
* Copyright (C) 2002-2009 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
/**
* Exception thrown when errors occuer populating a template query with values.
* @author Richard Smith
*
*/
public class TemplatePopulatorException extends RuntimeException
{
/**
* Constructs an TemplatePopulationException with the specified detail message.
*
* @param msg the detail message
*/
public TemplatePopulatorException(String msg) {
super(msg);
}
/**
* Constructs an TemplatePopulationException with the specified nested throwable.
*
* @param t the nested throwable
*/
public TemplatePopulatorException(Throwable t) {
super(t);
}
/**
* Constructs an TemplatePopulationException with the specified detail message and
* nested throwable.
*
* @param msg the detail message
* @param t the nested throwable
*/
public TemplatePopulatorException(String msg, Throwable t) {
super(msg, t);
}
}
| Text fixes.
| intermine/api/main/src/org/intermine/api/template/TemplatePopulatorException.java | Text fixes. | <ide><path>ntermine/api/main/src/org/intermine/api/template/TemplatePopulatorException.java
<ide> */
<ide>
<ide> /**
<del> * Exception thrown when errors occuer populating a template query with values.
<add> * Exception thrown when errors occur populating a template query with values.
<ide> * @author Richard Smith
<ide> *
<ide> */
<del>public class TemplatePopulatorException extends RuntimeException
<add>public class TemplatePopulatorException extends RuntimeException
<ide> {
<ide>
<ide> /**
<del> * Constructs an TemplatePopulationException with the specified detail message.
<add> * Constructs an TemplatePopulatorException with the specified detail message.
<ide> *
<ide> * @param msg the detail message
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Constructs an TemplatePopulationException with the specified nested throwable.
<add> * Constructs an TemplatePopulatorException with the specified nested throwable.
<ide> *
<ide> * @param t the nested throwable
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Constructs an TemplatePopulationException with the specified detail message and
<add> * Constructs an TemplatePopulatorException with the specified detail message and
<ide> * nested throwable.
<ide> *
<ide> * @param msg the detail message |
|
Java | mit | error: pathspec 'src/cn/simastudio/charkey/codinginterview/MinNumberInRotateArray.java' did not match any file(s) known to git
| 641e68a929c3c425e8aa1299c19c3d1917c6567a | 1 | CharkeyQK/AlgorithmDataStructure | /*
* Copyright (c) 2013-2015 Charkey. All rights reserved.
*
* This software is the confidential and proprietary information of Charkey.
* You shall not disclose such Confidential Information and shall use it only
* in accordance with the terms of the agreements you entered into with Charkey.
*
* Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
*
* Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
* MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package cn.simastudio.charkey.codinginterview;
/**
* Created by Qikai on 2016/8/5.
*/
public class MinNumberInRotateArray {
public int minNumberInRotateArray(int [] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int index = start + (end - start) / 2;
if (array[index] > array[end]) {
start = index + 1;
} else if (array[index] < array[end]) {
end = index;
} else if (array[index] == array[end]) {
end = end - 1;
}
}
return array[start];
}
public static void main(String[] args) {
int[] array = {7877,7878,7879,7880,7881,7882,7884,7884,7884,7885,7887,7888,7889,7891,7892,7893,7894,7895,7895,7896,7897,7897,7904,7904,7904,7905,7906,7907,7909,7910,7911,7912,7913,7916,7917,7918,7918,7918,7919,7919,7922,7924,7926,7926,7926,7930,7931,7935,7936,7937,7939,7939,7942,7943,7944,7946,7947,7949,7951,7960,7965,7965,7971,7973,7974,7976,7976,7977,7978,7978,7980,7981,7982,7983,7984,7986,7986,7994,7995,7996,7997,7998,7998,8000,8001,8008,8008,8009,8009,8010,8011,8011,8013,8013,8014,8016,8019,8020,8020,8022,8023,8026,8029,8033,8035,8036,8038,8039,8040,8040,8041,8047,8050,8053,8055,8057,8057,8058,8065,8065,8065,8066,8068,8068,8070,8074,8074,8074,8076,8077,8078,8079,8080,8082,8083,8084,8087,8090,8092,8092,8092,8094,8099,8099,8102,8107,8108,8109,8109,8114,8115,8116,8118,8120,8125,8125,8126,8127,8128,8130,8131,8133,8136,8137,8139,8142,8142,8146,8147,8147,8148,8149,8150,8153,8153,8154,8155,8158,8161,8162,8163,8167,8171,8173,8182,8183,8183,8185,8189,8190,8190,8191,8192,8193,8193,8194,8195,8196,8198,8198,8198,8198,8199,8199,8199,8199,8200,8200,8200,8201,8202,8205,8206,8207,8209,8210,8211,8211,8212,8214,8218,8219,8220,8220,8222,8223,8224,8224,8225,8225,8227,8229,8229,8234,8234,8237,8242,8253,8255,8256,8262,8265,8275,8277,8279,8283,8284,8285,8288,8289,8291,8295,8299,8299,8301,8301,8305,8307,8308,8308,8308,8313,8313,8314,8314,8317,8317,8320,8322,8322,8324,8327,8328,8329,8331,8331,8335,8338,8339,8340,8340,8343,8344,8344,8346,8346,8350,8353,8360,8360,8360,8360,8361,8362,8363,8366,8368,8369,8369,8372,8374,8374,8375,8379,8381,8386,8386,8389,8391,8394,8395,8397,8402,8403,8408,8411,8412,8414,8415,8416,8416,8416,8419,8420,8420,8420,8422,8423,8426,8426,8429,8434,8439,8443,8443,8444,8444,8445,8445,8446,8446,8447,8447,8449,8452,8453,8453,8456,8457,8461,8463,8464,8465,8467,8469,8469,8469,8469,8470,8473,8475,8476,8476,8477,8479,8482,8482,8485,8485,8489,8489,8490,8491,8492,8494,8494,8497,8499,8501,8501,8501,8504,8505,8506,8506,8512,8514,8514,8515,8517,8517,8518,8523,8524,8526,8529,8533,8534,8535,8535,8537,8538,8539,8541,8541,8542,8545,8545,8546,8546,8547,8549,8549,8550,8551,8552,8553,8553,8558,8561,8561,8567,8569,8575,8580,8582,8583,8584,8584,8585,8588,8591,8592,8596,8597,8597,8597,8599,8606,8608,8608,8610,8611,8613,8614,8616,8622,8622,8626,8628,8635,8639,8642,8644,8646,8647,8648,8651,8652,8654,8656,8656,8656,8658,8659,8661,8662,8663,8665,8665,8667,8668,8668,8669,8671,8675,8675,8680,8683,8684,8684,8685,8686,8686,8688,8688,8691,8693,8697,8699,8701,8703,8705,8707,8709,8710,8711,8712,8718,8718,8718,8725,8726,8727,8728,8728,8729,8731,8733,8733,8735,8737,8741,8744,8746,8747,8748,8748,8752,8753,8753,8754,8757,8757,8760,8761,8762,8764,8764,8766,8770,8771,8772,8774,8774,8775,8779,8780,8782,8782,8783,8783,8784,8786,8786,8786,8787,8788,8788,8790,8798,8798,8800,8801,8802,8804,8805,8812,8813,8815,8817,8820,8823,8824,8826,8829,8831,8833,8835,8836,8837,8840,8840,8842,8842,8847,8848,8848,8850,8853,8854,8854,8855,8856,8859,8861,8869,8875,8876,8878,8880,8881,8883,8884,8887,8887,8887,8888,8889,8890,8890,8893,8896,8898,8899,8900,8900,8901,8901,8903,8904,8904,8905,8906,8909,8909,8909,8911,8914,8915,8918,8919,8926,8929,8929,8930,8931,8934,8935,8935,8939,8939,8942,8942,8943,8943,8943,8944,8944,8945,8947,8953,8955,8955,8956,8958,8960,8962,8964,8964,8965,8966,8969,8972,8973,8979,8979,8986,8990,8992,8995,9002,9004,9005,9005,9008,9008,9010,9010,9013,9018,9018,9018,9019,9023,9026,9026,9031,9032,9033,9033,9034,9048,9056,9057,9058,9063,9063,9065,9066,9068,9068,9071,9072,9073,9073,9074,9079,9085,9085,9086,9088,9097,9098,9103,9103,9104,9108,9110,9111,9117,9117,9124,9126,9135,9143,9144,9144,9148,9150,9151,9158,9159,9161,9165,9165,9165,9167,9169,9169,9171,9172,9173,9184,9185,9185,9189,9189,9191,9192,9193,9194,9196,9196,9197,9197,9197,9197,9198,9200,9203,9203,9204,9205,9207,9210,9216,9218,9218,9221,9222,9226,9227,9229,9229,9229,9231,9235,9237,9240,9240,9241,9241,9242,9243,9245,9246,9246,9247,9247,9247,9248,9248,9250,9252,9252,9260,9261,9268,9272,9273,9275,9277,9278,9283,9285,9287,9288,9288,9288,9289,9290,9292,9292,9293,9294,9294,9294,9294,9295,9298,9304,9309,9312,9313,9313,9317,9317,9318,9318,9320,9322,9327,9329,9329,9330,9332,9333,9334,9339,9340,9341,9345,9348,9350,9351,9351,9353,9353,9354,9354,9356,9357,9357,9358,9360,9362,9365,9368,9371,9371,9372,9373,9374,9375,9376,9376,9377,9379,9381,9384,9385,9387,9387,9387,9388,9390,9391,9396,9399,9399,9403,9405,9408,9411,9412,9414,9414,9415,9416,9417,9419,9419,9421,9422,9423,9428,9428,9429,9429,9429,9430,9431,9432,9432,9435,9435,9435,9436,9437,9442,9443,9444,9445,9446,9450,9450,9451,9453,9456,9459,9461,9462,9462,9466,9466,9468,9470,9473,9474,9479,9480,9480,9481,9486,9486,9488,9491,9495,9496,9497,9499,9500,9500,9502,9503,9509,9510,9515,9518,9520,9524,9524,9533,9535,9536,9539,9539,9539,9540,9540,9542,9546,9547,9548,9550,9550,9551,9552,9553,9554,9555,9555,9557,9557,9557,9561,9562,9563,9564,9564,9565,9566,9567,9570,9570,9571,9571,9572,9573,9574,9576,9580,9581,9587,9588,9591,9591,9592,9593,9599,9599,9600,9600,9601,9602,9604,9605,9606,9606,9607,9613,9615,9622,9623,9625,9625,9625,9625,9629,9630,9630,9634,9635,9637,9639,9640,9641,9642,9644,9645,9649,9650,9650,9652,9653,9655,9655,9661,9661,9663,9663,9666,9668,9671,9671,9672,9673,9674,9680,9683,9686,9688,9690,9691,9691,9691,9692,9692,9697,9698,9700,9700,9701,9703,9704,9705,9705,9708,9710,9711,9712,9712,9713,9714,9714,9717,9717,9718,9722,9722,9726,9728,9728,9733,9737,9739,9740,9741,9743,9743,9745,9746,9746,9746,9747,9748,9748,9752,9754,9754,9755,9757,9757,9757,9761,9768,9774,9775,9779,9780,9782,9791,9793,9794,9803,9806,9806,9807,9807,9807,9815,9818,9818,9819,9823,9823,9827,9828,9828,9831,9833,9836,9837,9837,9848,9849,9852,9853,9860,9862,9866,9868,9870,9876,9880,9882,9882,9882,9883,9883,9886,9892,9895,9895,9900,9906,9907,9908,9911,9911,9914,9915,9915,9917,9919,9921,9921,9923,9926,9930,9931,9936,9939,9939,9939,9941,9943,9944,9947,9948,9949,9950,9952,9954,9954,9955,9955,9958,9958,9958,9960,9964,9969,9969,9970,9970,9971,9972,9973,9974,9975,9975,9977,9978,9979,9980,9981,9982,9982,9982,9985,9990,9990,9991,9994,9995,9997,9999,10000,10000,1,1,1,2,2,3,3,3,6,11,15,16,19,19,19,21,23,23,24,24,24,26,28,29,31,32,32,33,38,39,40,40,42,43,44,47,48,48,50,50,51,54,55,57,57,61,69,69,70,73,74,77,79,79,80,83,83,84,85,87,89,90,91,91,91,91,92,94,94,95,96,99,99,101,101,104,104,114,115,116,116,117,117,120,121,122,123,125,126,126,128,128,132,134,138,140,142,142,146,146,146,148,150,150,151,152,158,159,159,159,161,161,161,162,162,165,165,166,166,168,171,173,173,174,176,177,177,177,178,178,179,180,180,180,181,182,183,184,185,189,190,193,194,194,194,196,196,198,198,200,203,204,206,210,211,213,216,216,216,218,218,219,220,220,220,220,221,221,221,221,223,227,228,230,232,232,233,233,234,235,237,239,241,241,242,249,251,251,252,255,256,258,258,258,259,260,260,260,260,262,263,263,265,265,266,269,270,270,271,272,274,275,276,277,278,279,283,283,288,292,293,294,295,297,298,298,299,300,300,302,302,302,302,304,305,305,307,315,318,318,318,319,320,320,322,323,323,325,325,326,326,331,331,333,334,334,335,335,337,340,344,344,345,345,346,347,348,349,353,357,361,364,365,365,366,367,368,368,369,369,369,372,372,372,375,378,378,378,379,380,385,389,389,395,395};
System.out.println(new MinNumberInRotateArray().minNumberInRotateArray(array));
}
}
| src/cn/simastudio/charkey/codinginterview/MinNumberInRotateArray.java | minNumberInRotateArray
| src/cn/simastudio/charkey/codinginterview/MinNumberInRotateArray.java | minNumberInRotateArray | <ide><path>rc/cn/simastudio/charkey/codinginterview/MinNumberInRotateArray.java
<add>/*
<add> * Copyright (c) 2013-2015 Charkey. All rights reserved.
<add> *
<add> * This software is the confidential and proprietary information of Charkey.
<add> * You shall not disclose such Confidential Information and shall use it only
<add> * in accordance with the terms of the agreements you entered into with Charkey.
<add> *
<add> * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
<add> * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
<add> * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
<add> *
<add> * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
<add> * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
<add> */
<add>
<add>package cn.simastudio.charkey.codinginterview;
<add>
<add>/**
<add> * Created by Qikai on 2016/8/5.
<add> */
<add>public class MinNumberInRotateArray {
<add>
<add> public int minNumberInRotateArray(int [] array) {
<add> int start = 0;
<add> int end = array.length - 1;
<add> while (start < end) {
<add> int index = start + (end - start) / 2;
<add> if (array[index] > array[end]) {
<add> start = index + 1;
<add> } else if (array[index] < array[end]) {
<add> end = index;
<add> } else if (array[index] == array[end]) {
<add> end = end - 1;
<add> }
<add> }
<add> return array[start];
<add> }
<add>
<add> public static void main(String[] args) {
<add> int[] array = {7877,7878,7879,7880,7881,7882,7884,7884,7884,7885,7887,7888,7889,7891,7892,7893,7894,7895,7895,7896,7897,7897,7904,7904,7904,7905,7906,7907,7909,7910,7911,7912,7913,7916,7917,7918,7918,7918,7919,7919,7922,7924,7926,7926,7926,7930,7931,7935,7936,7937,7939,7939,7942,7943,7944,7946,7947,7949,7951,7960,7965,7965,7971,7973,7974,7976,7976,7977,7978,7978,7980,7981,7982,7983,7984,7986,7986,7994,7995,7996,7997,7998,7998,8000,8001,8008,8008,8009,8009,8010,8011,8011,8013,8013,8014,8016,8019,8020,8020,8022,8023,8026,8029,8033,8035,8036,8038,8039,8040,8040,8041,8047,8050,8053,8055,8057,8057,8058,8065,8065,8065,8066,8068,8068,8070,8074,8074,8074,8076,8077,8078,8079,8080,8082,8083,8084,8087,8090,8092,8092,8092,8094,8099,8099,8102,8107,8108,8109,8109,8114,8115,8116,8118,8120,8125,8125,8126,8127,8128,8130,8131,8133,8136,8137,8139,8142,8142,8146,8147,8147,8148,8149,8150,8153,8153,8154,8155,8158,8161,8162,8163,8167,8171,8173,8182,8183,8183,8185,8189,8190,8190,8191,8192,8193,8193,8194,8195,8196,8198,8198,8198,8198,8199,8199,8199,8199,8200,8200,8200,8201,8202,8205,8206,8207,8209,8210,8211,8211,8212,8214,8218,8219,8220,8220,8222,8223,8224,8224,8225,8225,8227,8229,8229,8234,8234,8237,8242,8253,8255,8256,8262,8265,8275,8277,8279,8283,8284,8285,8288,8289,8291,8295,8299,8299,8301,8301,8305,8307,8308,8308,8308,8313,8313,8314,8314,8317,8317,8320,8322,8322,8324,8327,8328,8329,8331,8331,8335,8338,8339,8340,8340,8343,8344,8344,8346,8346,8350,8353,8360,8360,8360,8360,8361,8362,8363,8366,8368,8369,8369,8372,8374,8374,8375,8379,8381,8386,8386,8389,8391,8394,8395,8397,8402,8403,8408,8411,8412,8414,8415,8416,8416,8416,8419,8420,8420,8420,8422,8423,8426,8426,8429,8434,8439,8443,8443,8444,8444,8445,8445,8446,8446,8447,8447,8449,8452,8453,8453,8456,8457,8461,8463,8464,8465,8467,8469,8469,8469,8469,8470,8473,8475,8476,8476,8477,8479,8482,8482,8485,8485,8489,8489,8490,8491,8492,8494,8494,8497,8499,8501,8501,8501,8504,8505,8506,8506,8512,8514,8514,8515,8517,8517,8518,8523,8524,8526,8529,8533,8534,8535,8535,8537,8538,8539,8541,8541,8542,8545,8545,8546,8546,8547,8549,8549,8550,8551,8552,8553,8553,8558,8561,8561,8567,8569,8575,8580,8582,8583,8584,8584,8585,8588,8591,8592,8596,8597,8597,8597,8599,8606,8608,8608,8610,8611,8613,8614,8616,8622,8622,8626,8628,8635,8639,8642,8644,8646,8647,8648,8651,8652,8654,8656,8656,8656,8658,8659,8661,8662,8663,8665,8665,8667,8668,8668,8669,8671,8675,8675,8680,8683,8684,8684,8685,8686,8686,8688,8688,8691,8693,8697,8699,8701,8703,8705,8707,8709,8710,8711,8712,8718,8718,8718,8725,8726,8727,8728,8728,8729,8731,8733,8733,8735,8737,8741,8744,8746,8747,8748,8748,8752,8753,8753,8754,8757,8757,8760,8761,8762,8764,8764,8766,8770,8771,8772,8774,8774,8775,8779,8780,8782,8782,8783,8783,8784,8786,8786,8786,8787,8788,8788,8790,8798,8798,8800,8801,8802,8804,8805,8812,8813,8815,8817,8820,8823,8824,8826,8829,8831,8833,8835,8836,8837,8840,8840,8842,8842,8847,8848,8848,8850,8853,8854,8854,8855,8856,8859,8861,8869,8875,8876,8878,8880,8881,8883,8884,8887,8887,8887,8888,8889,8890,8890,8893,8896,8898,8899,8900,8900,8901,8901,8903,8904,8904,8905,8906,8909,8909,8909,8911,8914,8915,8918,8919,8926,8929,8929,8930,8931,8934,8935,8935,8939,8939,8942,8942,8943,8943,8943,8944,8944,8945,8947,8953,8955,8955,8956,8958,8960,8962,8964,8964,8965,8966,8969,8972,8973,8979,8979,8986,8990,8992,8995,9002,9004,9005,9005,9008,9008,9010,9010,9013,9018,9018,9018,9019,9023,9026,9026,9031,9032,9033,9033,9034,9048,9056,9057,9058,9063,9063,9065,9066,9068,9068,9071,9072,9073,9073,9074,9079,9085,9085,9086,9088,9097,9098,9103,9103,9104,9108,9110,9111,9117,9117,9124,9126,9135,9143,9144,9144,9148,9150,9151,9158,9159,9161,9165,9165,9165,9167,9169,9169,9171,9172,9173,9184,9185,9185,9189,9189,9191,9192,9193,9194,9196,9196,9197,9197,9197,9197,9198,9200,9203,9203,9204,9205,9207,9210,9216,9218,9218,9221,9222,9226,9227,9229,9229,9229,9231,9235,9237,9240,9240,9241,9241,9242,9243,9245,9246,9246,9247,9247,9247,9248,9248,9250,9252,9252,9260,9261,9268,9272,9273,9275,9277,9278,9283,9285,9287,9288,9288,9288,9289,9290,9292,9292,9293,9294,9294,9294,9294,9295,9298,9304,9309,9312,9313,9313,9317,9317,9318,9318,9320,9322,9327,9329,9329,9330,9332,9333,9334,9339,9340,9341,9345,9348,9350,9351,9351,9353,9353,9354,9354,9356,9357,9357,9358,9360,9362,9365,9368,9371,9371,9372,9373,9374,9375,9376,9376,9377,9379,9381,9384,9385,9387,9387,9387,9388,9390,9391,9396,9399,9399,9403,9405,9408,9411,9412,9414,9414,9415,9416,9417,9419,9419,9421,9422,9423,9428,9428,9429,9429,9429,9430,9431,9432,9432,9435,9435,9435,9436,9437,9442,9443,9444,9445,9446,9450,9450,9451,9453,9456,9459,9461,9462,9462,9466,9466,9468,9470,9473,9474,9479,9480,9480,9481,9486,9486,9488,9491,9495,9496,9497,9499,9500,9500,9502,9503,9509,9510,9515,9518,9520,9524,9524,9533,9535,9536,9539,9539,9539,9540,9540,9542,9546,9547,9548,9550,9550,9551,9552,9553,9554,9555,9555,9557,9557,9557,9561,9562,9563,9564,9564,9565,9566,9567,9570,9570,9571,9571,9572,9573,9574,9576,9580,9581,9587,9588,9591,9591,9592,9593,9599,9599,9600,9600,9601,9602,9604,9605,9606,9606,9607,9613,9615,9622,9623,9625,9625,9625,9625,9629,9630,9630,9634,9635,9637,9639,9640,9641,9642,9644,9645,9649,9650,9650,9652,9653,9655,9655,9661,9661,9663,9663,9666,9668,9671,9671,9672,9673,9674,9680,9683,9686,9688,9690,9691,9691,9691,9692,9692,9697,9698,9700,9700,9701,9703,9704,9705,9705,9708,9710,9711,9712,9712,9713,9714,9714,9717,9717,9718,9722,9722,9726,9728,9728,9733,9737,9739,9740,9741,9743,9743,9745,9746,9746,9746,9747,9748,9748,9752,9754,9754,9755,9757,9757,9757,9761,9768,9774,9775,9779,9780,9782,9791,9793,9794,9803,9806,9806,9807,9807,9807,9815,9818,9818,9819,9823,9823,9827,9828,9828,9831,9833,9836,9837,9837,9848,9849,9852,9853,9860,9862,9866,9868,9870,9876,9880,9882,9882,9882,9883,9883,9886,9892,9895,9895,9900,9906,9907,9908,9911,9911,9914,9915,9915,9917,9919,9921,9921,9923,9926,9930,9931,9936,9939,9939,9939,9941,9943,9944,9947,9948,9949,9950,9952,9954,9954,9955,9955,9958,9958,9958,9960,9964,9969,9969,9970,9970,9971,9972,9973,9974,9975,9975,9977,9978,9979,9980,9981,9982,9982,9982,9985,9990,9990,9991,9994,9995,9997,9999,10000,10000,1,1,1,2,2,3,3,3,6,11,15,16,19,19,19,21,23,23,24,24,24,26,28,29,31,32,32,33,38,39,40,40,42,43,44,47,48,48,50,50,51,54,55,57,57,61,69,69,70,73,74,77,79,79,80,83,83,84,85,87,89,90,91,91,91,91,92,94,94,95,96,99,99,101,101,104,104,114,115,116,116,117,117,120,121,122,123,125,126,126,128,128,132,134,138,140,142,142,146,146,146,148,150,150,151,152,158,159,159,159,161,161,161,162,162,165,165,166,166,168,171,173,173,174,176,177,177,177,178,178,179,180,180,180,181,182,183,184,185,189,190,193,194,194,194,196,196,198,198,200,203,204,206,210,211,213,216,216,216,218,218,219,220,220,220,220,221,221,221,221,223,227,228,230,232,232,233,233,234,235,237,239,241,241,242,249,251,251,252,255,256,258,258,258,259,260,260,260,260,262,263,263,265,265,266,269,270,270,271,272,274,275,276,277,278,279,283,283,288,292,293,294,295,297,298,298,299,300,300,302,302,302,302,304,305,305,307,315,318,318,318,319,320,320,322,323,323,325,325,326,326,331,331,333,334,334,335,335,337,340,344,344,345,345,346,347,348,349,353,357,361,364,365,365,366,367,368,368,369,369,369,372,372,372,375,378,378,378,379,380,385,389,389,395,395};
<add> System.out.println(new MinNumberInRotateArray().minNumberInRotateArray(array));
<add> }
<add>} |
|
JavaScript | agpl-3.0 | b69b2c19e5c06c5e7e6903b81232f2ec5079a5bb | 0 | 1lann/LoL-Cruncher,1lann/LoL-Cruncher,1lann/LoL-Cruncher,tromp91/LoL-Cruncher,tromp91/LoL-Cruncher,tromp91/LoL-Cruncher |
// LoL Cruncher - A Historical League of Legends Statistics Tracker
// Copyright (C) 2015 Jason Chu (1lann) [email protected]
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// jscs: disable
var statsSource = '\
<table class="stats-table">\
<tbody>\
{{#each statsRow}}\
<tr>\
<td class="stats-data">{{data}}</td>\
<td class="stats-label">{{label}}</td>\
</tr>\
{{/each}}\
</tbody>\
</table>'
var statsTemplate = Handlebars.compile(statsSource);
var timePlayingSource = '\
<span class="time-playing">{{time}}</span>\
<span class="spent-playing"> spent playing</span>\
'
var timePlayingTemplate = Handlebars.compile(timePlayingSource);
var filtersAreaSource = '\
<span>\
<div class="ui inline dropdown" id="general-dropdown">\
<input type="hidden" name="data-type">\
<div class="text">All</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="All">All</div>\
<div class="item" data-text="Rates/average">Rates/Averages</div>\
</div>\
</div>\
statistics\
<div class="ui inline dropdown" id="date-dropdown">\
<input type="hidden" name="timeframe">\
<div class="text">since {{start}}</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="since {{start}}">since {{start}}</div>\
{{#each month}}\
<div class="item" data-text="{{text}}">{{text}}</div>\
{{/each}}\
</div>\
</div>\
for\
<div class="ui inline dropdown" id="queue-dropdown">\
<input type="hidden" name="queue-type">\
<div class="text">all queues</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="all queues">all queues</div>\
{{#each queueTypes}}\
<div class="item" data-text="{{name}}">{{name}}</div>\
{{/each}}\
</div>\
</div>\
<span class="glyphicon glyphicon-info-sign" data-container="body" data-toggle="popover"\
data-trigger="hover" data-placement="top" data-content="Customs, Dominion and featured gamemodes\'\
statistics will not be recorded."></span>\
</span>\
<br>\
<span>\
Display statistics as\
<div class="ui inline dropdown" id="display-dropdown">\
<input type="hidden" name="display-type">\
<div class="text">cards</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="cards">cards</div>\
<div class="item" data-text="a table">a table</div>\
</div>\
</div>\
</span>\
<p class="delay">Statistics may be delayed by up to 24 hours</p>'
var filtersAreaTemplate = Handlebars.compile(filtersAreaSource);
var championCardSource = '\
<div class="stats-card">\
<img class="champion-image" src="//ddragon.leagueoflegends.com/cdn/5.5.1/img/champion/{{imageName}}">\
<div class="champion-label">\
<p class="title">Stats for {{displayName}}</p>\
<p class="subheading">{{dateFilter}}</p>\
</div>\
<div class="stats-area">\
{{{stats}}}\
</div>\
</div>\
'
var championCardTemplate = Handlebars.compile(championCardSource);
var generalCardSource = '\
<div class="stats-card">\
<div class="title">All champions stats</div>\
<p class="subheading">{{dateFilter}}</p>\
<div class="stats-area">\
{{{stats}}}\
</div>\
</div>'
var generalCardTemplate = Handlebars.compile(generalCardSource);
var profileSource = '\
<img src="//avatar.leagueoflegends.com/{{regionCode}}/{{{imageName}}}.png">\
<div class="profile-info">\
<p class="username">{{username}}</p>\
<p class="region">{{region}}</p>\
</div>'
var profileTemplate = Handlebars.compile(profileSource);
var tableAllHeader = '\
<th class="no-pointer"></th> <!-- Image -->\
<th>Champion</th>\
<th>Played</th>\
<th class="won">Won</th>\
<th class="lost">Lost</th>\
<th class="minions">Minions</th>\
<th class="jungle">Jungle</th>\
<th class="gold">Gold</th>\
<th class="wards">Wards</th>\
<th class="kills">Kills</th>\
<th class="deaths">Deaths</th>\
<th class="assists">Assists</th>'
var tableRatesHeader = '\
<th class="no-pointer"></th> <!-- Image -->\
<th>Champion</th>\
<th>Played</th>\
<th class="won">Winrate</th>\
<th class="minions">Minions/10m</th>\
<th class="jungle">Jungle/10m</th>\
<th class="gold">Gold/10m</th>\
<th class="wards">Wards</th>\
<th class="kills">Kills</th>\
<th class="deaths">Deaths</th>\
<th class="assists">Assists</th>'
var tableStatsSource = '\
<table class="table" id="stats-table">\
<thead>\
<tr>\
{{{tableHeader}}}\
</tr>\
</thead>\
<tbody>\
{{#each championStats}}\
<tr>\
{{{stats}}}\
</tr>\
{{/each}}\
</tbody>\
{{{tableFooter}}}\
</table>'
var tableStatsTemplate = Handlebars.compile(tableStatsSource);
var tableRowSource = '\
<td><img src="//ddragon.leagueoflegends.com/cdn/5.5.1/img/champion/{{imageName}}"></td>\
<td>{{championName}}</td>\
<td>{{games}}</td>\
<td class="won">{{wins}}</td>\
{{#if losses}}\
<td class="lost">{{losses}}</td>\
{{/if}}\
<td class="minions">{{minions}}</td>\
<td class="jungle">{{jungle}}</td>\
<td class="gold">{{gold}}</td>\
<td class="wards">{{wards}}</td>\
<td class="kills">{{kills}}</td>\
<td class="deaths">{{deaths}}</td>\
<td class="assists">{{assists}}</td>'
var tableRowTemplate = Handlebars.compile(tableRowSource);
tableFooterSource = '\
<tfoot>\
<tr>\
<td></td>\
<td>Total</td>\
<td>{{games}}</td>\
<td class="won">{{wins}}</td>\
{{#if losses}}\
<td class="lost">{{losses}}</td>\
{{/if}}\
<td class="minions">{{minions}}</td>\
<td class="jungle">{{jungle}}</td>\
<td class="gold">{{gold}}</td>\
<td class="wards">{{wards}}</td>\
<td class="kills">{{kills}}</td>\
<td class="deaths">{{deaths}}</td>\
<td class="assists">{{assists}}</td>\
</tr>\
</tfoot>\
'
var tableFooterTemplate = Handlebars.compile(tableFooterSource);
| public/js/stats-templates.js |
// LoL Cruncher - A Historical League of Legends Statistics Tracker
// Copyright (C) 2015 Jason Chu (1lann) [email protected]
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// jscs: disable
var statsSource = '\
<table class="stats-table">\
<tbody>\
{{#each statsRow}}\
<tr>\
<td class="stats-data">{{data}}</td>\
<td class="stats-label">{{label}}</td>\
</tr>\
{{/each}}\
</tbody>\
</table>'
var statsTemplate = Handlebars.compile(statsSource);
var timePlayingSource = '\
<span class="time-playing">{{time}}</span>\
<span class="spent-playing"> spent playing</span>\
'
var timePlayingTemplate = Handlebars.compile(timePlayingSource);
var filtersAreaSource = '\
<span>\
<div class="ui inline dropdown" id="general-dropdown">\
<input type="hidden" name="data-type">\
<div class="text">All</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="All">All</div>\
<div class="item" data-text="Rates/average">Rates/Averages</div>\
</div>\
</div>\
statistics\
<div class="ui inline dropdown" id="date-dropdown">\
<input type="hidden" name="timeframe">\
<div class="text">since {{start}}</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="since {{start}}">since {{start}}</div>\
{{#each month}}\
<div class="item" data-text="{{text}}">{{text}}</div>\
{{/each}}\
</div>\
</div>\
for\
<div class="ui inline dropdown" id="queue-dropdown">\
<input type="hidden" name="queue-type">\
<div class="text">all queues</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="all queues">all queues</div>\
{{#each queueTypes}}\
<div class="item" data-text="{{name}}">{{name}}</div>\
{{/each}}\
</div>\
</div>\
<span class="glyphicon glyphicon-info-sign" data-container="body" data-toggle="popover"\
data-trigger="hover" data-placement="top" data-content="Customs, Dominion and featured gamemodes\'\
statistics will not be recorded."></span>\
</span>\
<br>\
<span>\
Display statistics as\
<div class="ui inline dropdown" id="display-dropdown">\
<input type="hidden" name="display-type">\
<div class="text">cards</div>\
<i class="dropdown icon"></i>\
<div class="menu">\
<div class="item active selected" data-text="cards">cards</div>\
<div class="item" data-text="a table">a table</div>\
</div>\
</div>\
</span>\
<p class="delay">Statistics may be delayed by up to 24 hours</p>'
var filtersAreaTemplate = Handlebars.compile(filtersAreaSource);
var championCardSource = '\
<div class="stats-card">\
<img class="champion-image" src="//ddragon.leagueoflegends.com/cdn/5.1.1/img/champion/{{imageName}}">\
<div class="champion-label">\
<p class="title">Stats for {{displayName}}</p>\
<p class="subheading">{{dateFilter}}</p>\
</div>\
<div class="stats-area">\
{{{stats}}}\
</div>\
</div>\
'
var championCardTemplate = Handlebars.compile(championCardSource);
var generalCardSource = '\
<div class="stats-card">\
<div class="title">All champions stats</div>\
<p class="subheading">{{dateFilter}}</p>\
<div class="stats-area">\
{{{stats}}}\
</div>\
</div>'
var generalCardTemplate = Handlebars.compile(generalCardSource);
var profileSource = '\
<img src="//avatar.leagueoflegends.com/{{regionCode}}/{{{imageName}}}.png">\
<div class="profile-info">\
<p class="username">{{username}}</p>\
<p class="region">{{region}}</p>\
</div>'
var profileTemplate = Handlebars.compile(profileSource);
var tableAllHeader = '\
<th class="no-pointer"></th> <!-- Image -->\
<th>Champion</th>\
<th>Played</th>\
<th class="won">Won</th>\
<th class="lost">Lost</th>\
<th class="minions">Minions</th>\
<th class="jungle">Jungle</th>\
<th class="gold">Gold</th>\
<th class="wards">Wards</th>\
<th class="kills">Kills</th>\
<th class="deaths">Deaths</th>\
<th class="assists">Assists</th>'
var tableRatesHeader = '\
<th class="no-pointer"></th> <!-- Image -->\
<th>Champion</th>\
<th>Played</th>\
<th class="won">Winrate</th>\
<th class="minions">Minions/10m</th>\
<th class="jungle">Jungle/10m</th>\
<th class="gold">Gold/10m</th>\
<th class="wards">Wards</th>\
<th class="kills">Kills</th>\
<th class="deaths">Deaths</th>\
<th class="assists">Assists</th>'
var tableStatsSource = '\
<table class="table" id="stats-table">\
<thead>\
<tr>\
{{{tableHeader}}}\
</tr>\
</thead>\
<tbody>\
{{#each championStats}}\
<tr>\
{{{stats}}}\
</tr>\
{{/each}}\
</tbody>\
{{{tableFooter}}}\
</table>'
var tableStatsTemplate = Handlebars.compile(tableStatsSource);
var tableRowSource = '\
<td><img src="//ddragon.leagueoflegends.com/cdn/5.1.1/img/champion/{{imageName}}"></td>\
<td>{{championName}}</td>\
<td>{{games}}</td>\
<td class="won">{{wins}}</td>\
{{#if losses}}\
<td class="lost">{{losses}}</td>\
{{/if}}\
<td class="minions">{{minions}}</td>\
<td class="jungle">{{jungle}}</td>\
<td class="gold">{{gold}}</td>\
<td class="wards">{{wards}}</td>\
<td class="kills">{{kills}}</td>\
<td class="deaths">{{deaths}}</td>\
<td class="assists">{{assists}}</td>'
var tableRowTemplate = Handlebars.compile(tableRowSource);
tableFooterSource = '\
<tfoot>\
<tr>\
<td></td>\
<td>Total</td>\
<td>{{games}}</td>\
<td class="won">{{wins}}</td>\
{{#if losses}}\
<td class="lost">{{losses}}</td>\
{{/if}}\
<td class="minions">{{minions}}</td>\
<td class="jungle">{{jungle}}</td>\
<td class="gold">{{gold}}</td>\
<td class="wards">{{wards}}</td>\
<td class="kills">{{kills}}</td>\
<td class="deaths">{{deaths}}</td>\
<td class="assists">{{assists}}</td>\
</tr>\
</tfoot>\
'
var tableFooterTemplate = Handlebars.compile(tableFooterSource);
| Updated templates for patch 5.5
| public/js/stats-templates.js | Updated templates for patch 5.5 | <ide><path>ublic/js/stats-templates.js
<ide>
<ide> var championCardSource = '\
<ide> <div class="stats-card">\
<del> <img class="champion-image" src="//ddragon.leagueoflegends.com/cdn/5.1.1/img/champion/{{imageName}}">\
<add> <img class="champion-image" src="//ddragon.leagueoflegends.com/cdn/5.5.1/img/champion/{{imageName}}">\
<ide> <div class="champion-label">\
<ide> <p class="title">Stats for {{displayName}}</p>\
<ide> <p class="subheading">{{dateFilter}}</p>\
<ide> var tableStatsTemplate = Handlebars.compile(tableStatsSource);
<ide>
<ide> var tableRowSource = '\
<del><td><img src="//ddragon.leagueoflegends.com/cdn/5.1.1/img/champion/{{imageName}}"></td>\
<add><td><img src="//ddragon.leagueoflegends.com/cdn/5.5.1/img/champion/{{imageName}}"></td>\
<ide> <td>{{championName}}</td>\
<ide> <td>{{games}}</td>\
<ide> <td class="won">{{wins}}</td>\ |
|
Java | apache-2.0 | 99860fdea5e8c0de0f63a98b94d7acc65d7f49a8 | 0 | ibinti/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,asedunov/intellij-community,allotria/intellij-community,da1z/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,apixandru/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,hurricup/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,signed/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,asedunov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,signed/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ibinti/intellij-community,da1z/intellij-community,apixandru/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,semonte/intellij-community,retomerz/intellij-community,semonte/intellij-community,retomerz/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,retomerz/intellij-community,semonte/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,retomerz/intellij-community,semonte/intellij-community,semonte/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,signed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,allotria/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,semonte/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl.welcomeScreen;
import com.intellij.ide.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.util.io.UniqueNameBuilder;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.speedSearch.ListWithFilter;
import com.intellij.ui.speedSearch.NameFilteringListModel;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBDimension;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class NewRecentProjectPanel extends RecentProjectPanel {
public NewRecentProjectPanel(Disposable parentDisposable) {
super(parentDisposable);
setBorder(null);
setBackground(FlatWelcomeFrame.getProjectsBackground());
JScrollPane scrollPane = UIUtil.findComponentOfType(this, JScrollPane.class);
if (scrollPane != null) {
scrollPane.setBackground(FlatWelcomeFrame.getProjectsBackground());
JBDimension size = JBUI.size(300, 460);
scrollPane.setSize(size);
scrollPane.setMinimumSize(size);
scrollPane.setPreferredSize(size);
}
ListWithFilter panel = UIUtil.findComponentOfType(this, ListWithFilter.class);
if (panel != null) {
panel.setBackground(FlatWelcomeFrame.getProjectsBackground());
}
}
protected Dimension getPreferredScrollableViewportSize() {
return null;
}
@Override
public void addNotify() {
super.addNotify();
final JList list = UIUtil.findComponentOfType(this, JList.class);
if (list != null) {
list.updateUI();
}
}
@Override
protected JBList createList(AnAction[] recentProjectActions, Dimension size) {
final JBList list = super.createList(recentProjectActions, size);
list.setBackground(FlatWelcomeFrame.getProjectsBackground());
list.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Object selected = list.getSelectedValue();
final ProjectGroup group;
if (selected instanceof ProjectGroupActionGroup) {
group = ((ProjectGroupActionGroup)selected).getGroup();
} else {
group = null;
}
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
if (group != null) {
if (!group.isExpanded()) {
group.setExpanded(true);
ListModel model = ((NameFilteringListModel)list.getModel()).getOriginalModel();
int index = list.getSelectedIndex();
RecentProjectsWelcomeScreenActionBase.rebuildRecentProjectDataModel((DefaultListModel)model);
list.setSelectedIndex(group.getProjects().isEmpty() ? index : index + 1);
}
} else {
FlatWelcomeFrame frame = UIUtil.getParentOfType(FlatWelcomeFrame.class, list);
if (frame != null) {
FocusTraversalPolicy policy = frame.getFocusTraversalPolicy();
if (policy != null) {
Component next = policy.getComponentAfter(frame, list);
if (next != null) {
next.requestFocus();
}
}
}
}
} else if (keyCode == KeyEvent.VK_LEFT ) {
if (group != null && group.isExpanded()) {
group.setExpanded(false);
int index = list.getSelectedIndex();
ListModel model = ((NameFilteringListModel)list.getModel()).getOriginalModel();
RecentProjectsWelcomeScreenActionBase.rebuildRecentProjectDataModel((DefaultListModel)model);
list.setSelectedIndex(index);
}
}
}
});
list.addMouseListener(new PopupHandler() {
@Override
public void invokePopup(Component comp, int x, int y) {
final int index = list.locationToIndex(new Point(x, y));
if (index != -1 && Arrays.binarySearch(list.getSelectedIndices(), index) < 0) {
list.setSelectedIndex(index);
}
final ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("WelcomeScreenRecentProjectActionGroup");
if (group != null) {
ActionManager.getInstance().createActionPopupMenu(ActionPlaces.WELCOME_SCREEN, group).getComponent().show(comp, x, y);
}
}
});
return list;
}
@Override
protected boolean isUseGroups() {
return FlatWelcomeFrame.isUseProjectGroups();
}
@Override
protected ListCellRenderer createRenderer(UniqueNameBuilder<ReopenProjectAction> pathShortener) {
return new RecentProjectItemRenderer(myPathShortener) {
private GridBagConstraints nameCell;
private GridBagConstraints pathCell;
private GridBagConstraints closeButtonCell;
private void initConstraints () {
nameCell = new GridBagConstraints();
pathCell = new GridBagConstraints();
closeButtonCell = new GridBagConstraints();
nameCell.gridx = 0;
nameCell.gridy = 0;
nameCell.weightx = 1.0;
nameCell.weighty = 1.0;
nameCell.anchor = GridBagConstraints.FIRST_LINE_START;
nameCell.insets = JBUI.insets(6, 5, 1, 5);
pathCell.gridx = 0;
pathCell.gridy = 1;
pathCell.insets = JBUI.insets(1, 5, 6, 5);
pathCell.anchor = GridBagConstraints.LAST_LINE_START;
closeButtonCell.gridx = 1;
closeButtonCell.gridy = 0;
closeButtonCell.anchor = GridBagConstraints.FIRST_LINE_END;
closeButtonCell.insets = JBUI.insets(7, 7, 7, 7);
closeButtonCell.gridheight = 2;
//closeButtonCell.anchor = GridBagConstraints.WEST;
}
@Override
protected Color getListBackground(boolean isSelected, boolean hasFocus) {
return isSelected ? FlatWelcomeFrame.getListSelectionColor(hasFocus) : FlatWelcomeFrame.getProjectsBackground();
}
@Override
protected Color getListForeground(boolean isSelected, boolean hasFocus) {
return UIUtil.getListForeground(isSelected && hasFocus);
}
@Override
protected void layoutComponents() {
setLayout(new GridBagLayout());
initConstraints();
add(myName, nameCell);
add(myPath, pathCell);
}
JComponent spacer = new NonOpaquePanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(JBUI.scale(22), super.getPreferredSize().height);
}
};
@Override
public Component getListCellRendererComponent(JList list, final Object value, int index, final boolean isSelected, boolean cellHasFocus) {
final Color fore = getListForeground(isSelected, list.hasFocus());
final Color back = getListBackground(isSelected, list.hasFocus());
final JLabel name = new JLabel();
final JLabel path = new JLabel();
name.setForeground(fore);
path.setForeground(isSelected ? fore : UIUtil.getInactiveTextColor());
setBackground(back);
return new JPanel() {
{
setLayout(new BorderLayout());
setBackground(back);
boolean isGroup = value instanceof ProjectGroupActionGroup;
boolean isInsideGroup = false;
if (value instanceof ReopenProjectAction) {
final String path = ((ReopenProjectAction)value).getProjectPath();
for (ProjectGroup group : RecentProjectsManager.getInstance().getGroups()) {
final List<String> projects = group.getProjects();
if (projects.contains(path)) {
isInsideGroup = true;
break;
}
}
}
setBorder(JBUI.Borders.empty(5, 7));
if (isInsideGroup) {
add(spacer, BorderLayout.WEST);
}
if (isGroup) {
final ProjectGroup group = ((ProjectGroupActionGroup)value).getGroup();
name.setText(" " + group.getName());
name.setIcon(IconUtil.toSize(group.isExpanded() ? UIUtil.getTreeExpandedIcon() : UIUtil.getTreeCollapsedIcon(), JBUI.scale(16), JBUI.scale(16)));
name.setFont(name.getFont().deriveFont(Font.BOLD));
add(name);
} else if (value instanceof ReopenProjectAction) {
final NonOpaquePanel p = new NonOpaquePanel(new BorderLayout());
name.setText(((ReopenProjectAction)value).getTemplatePresentation().getText());
path.setText(getTitle2Text((ReopenProjectAction)value, path, JBUI.scale(isInsideGroup ? 80 : 60)));
p.add(name, BorderLayout.NORTH);
p.add(path, BorderLayout.SOUTH);
String projectPath = ((ReopenProjectAction)value).getProjectPath();
Icon icon = RecentProjectsManagerBase.getProjectIcon(projectPath, UIUtil.isUnderDarcula());
if (icon == null) {
if (UIUtil.isUnderDarcula()) {
//No dark icon for this project
icon = RecentProjectsManagerBase.getProjectIcon(projectPath, false);
}
}
if (icon == null) {
icon = EmptyIcon.ICON_16;
}
final JLabel projectIcon = new JLabel("", icon, SwingConstants.LEFT) {
@Override
protected void paintComponent(Graphics g) {
getIcon().paintIcon(this, g, 0, (getHeight() - getIcon().getIconHeight()) / 2);
}
};
projectIcon.setBorder(JBUI.Borders.emptyRight(8));
projectIcon.setVerticalAlignment(SwingConstants.CENTER);
final NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout());
panel.add(p);
panel.add(projectIcon, BorderLayout.WEST);
add(panel);
}
AccessibleContextUtil.setCombinedName(this, name, " - ", path);
AccessibleContextUtil.setCombinedDescription(this, name, " - ", path);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(super.getPreferredSize().width, JBUI.scale(44));
}
};
}
};
}
@Nullable
@Override
protected JPanel createTitle() {
return null;
}
}
| platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/NewRecentProjectPanel.java | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl.welcomeScreen;
import com.intellij.ide.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.util.io.UniqueNameBuilder;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.speedSearch.ListWithFilter;
import com.intellij.ui.speedSearch.NameFilteringListModel;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class NewRecentProjectPanel extends RecentProjectPanel {
public NewRecentProjectPanel(Disposable parentDisposable) {
super(parentDisposable);
setBorder(null);
setBackground(FlatWelcomeFrame.getProjectsBackground());
JScrollPane scrollPane = UIUtil.findComponentOfType(this, JScrollPane.class);
if (scrollPane != null) {
scrollPane.setBackground(FlatWelcomeFrame.getProjectsBackground());
final int width = 300;
final int height = 460;
scrollPane.setSize(JBUI.size(width, height));
scrollPane.setMinimumSize(JBUI.size(width, height));
scrollPane.setPreferredSize(JBUI.size(width, height));
}
ListWithFilter panel = UIUtil.findComponentOfType(this, ListWithFilter.class);
if (panel != null) {
panel.setBackground(FlatWelcomeFrame.getProjectsBackground());
}
}
protected Dimension getPreferredScrollableViewportSize() {
return null;//new Dimension(250, 430);
}
@Override
public void addNotify() {
super.addNotify();
final JList list = UIUtil.findComponentOfType(this, JList.class);
if (list != null) {
list.updateUI();
}
}
@Override
protected JBList createList(AnAction[] recentProjectActions, Dimension size) {
final JBList list = super.createList(recentProjectActions, size);
list.setBackground(FlatWelcomeFrame.getProjectsBackground());
list.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Object selected = list.getSelectedValue();
final ProjectGroup group;
if (selected instanceof ProjectGroupActionGroup) {
group = ((ProjectGroupActionGroup)selected).getGroup();
} else {
group = null;
}
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
if (group != null) {
if (!group.isExpanded()) {
group.setExpanded(true);
ListModel model = ((NameFilteringListModel)list.getModel()).getOriginalModel();
int index = list.getSelectedIndex();
RecentProjectsWelcomeScreenActionBase.rebuildRecentProjectDataModel((DefaultListModel)model);
list.setSelectedIndex(group.getProjects().isEmpty() ? index : index + 1);
}
} else {
FlatWelcomeFrame frame = UIUtil.getParentOfType(FlatWelcomeFrame.class, list);
if (frame != null) {
FocusTraversalPolicy policy = frame.getFocusTraversalPolicy();
if (policy != null) {
Component next = policy.getComponentAfter(frame, list);
if (next != null) {
next.requestFocus();
}
}
}
}
} else if (keyCode == KeyEvent.VK_LEFT ) {
if (group != null && group.isExpanded()) {
group.setExpanded(false);
int index = list.getSelectedIndex();
ListModel model = ((NameFilteringListModel)list.getModel()).getOriginalModel();
RecentProjectsWelcomeScreenActionBase.rebuildRecentProjectDataModel((DefaultListModel)model);
list.setSelectedIndex(index);
}
}
}
});
list.addMouseListener(new PopupHandler() {
@Override
public void invokePopup(Component comp, int x, int y) {
final int index = list.locationToIndex(new Point(x, y));
if (index != -1 && Arrays.binarySearch(list.getSelectedIndices(), index) < 0) {
list.setSelectedIndex(index);
}
final ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("WelcomeScreenRecentProjectActionGroup");
if (group != null) {
ActionManager.getInstance().createActionPopupMenu(ActionPlaces.WELCOME_SCREEN, group).getComponent().show(comp, x, y);
}
}
});
return list;
}
@Override
protected boolean isUseGroups() {
return FlatWelcomeFrame.isUseProjectGroups();
}
@Override
protected ListCellRenderer createRenderer(UniqueNameBuilder<ReopenProjectAction> pathShortener) {
return new RecentProjectItemRenderer(myPathShortener) {
private GridBagConstraints nameCell;
private GridBagConstraints pathCell;
private GridBagConstraints closeButtonCell;
private void initConstraints () {
nameCell = new GridBagConstraints();
pathCell = new GridBagConstraints();
closeButtonCell = new GridBagConstraints();
nameCell.gridx = 0;
nameCell.gridy = 0;
nameCell.weightx = 1.0;
nameCell.weighty = 1.0;
nameCell.anchor = GridBagConstraints.FIRST_LINE_START;
nameCell.insets = JBUI.insets(6, 5, 1, 5);
pathCell.gridx = 0;
pathCell.gridy = 1;
pathCell.insets = JBUI.insets(1, 5, 6, 5);
pathCell.anchor = GridBagConstraints.LAST_LINE_START;
closeButtonCell.gridx = 1;
closeButtonCell.gridy = 0;
closeButtonCell.anchor = GridBagConstraints.FIRST_LINE_END;
closeButtonCell.insets = JBUI.insets(7, 7, 7, 7);
closeButtonCell.gridheight = 2;
//closeButtonCell.anchor = GridBagConstraints.WEST;
}
@Override
protected Color getListBackground(boolean isSelected, boolean hasFocus) {
return isSelected ? FlatWelcomeFrame.getListSelectionColor(hasFocus) : FlatWelcomeFrame.getProjectsBackground();
}
@Override
protected Color getListForeground(boolean isSelected, boolean hasFocus) {
return UIUtil.getListForeground(isSelected && hasFocus);
}
@Override
protected void layoutComponents() {
setLayout(new GridBagLayout());
initConstraints();
add(myName, nameCell);
add(myPath, pathCell);
}
JComponent spacer = new NonOpaquePanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(JBUI.scale(22), super.getPreferredSize().height);
}
};
@Override
public Component getListCellRendererComponent(JList list, final Object value, int index, final boolean isSelected, boolean cellHasFocus) {
final Color fore = getListForeground(isSelected, list.hasFocus());
final Color back = getListBackground(isSelected, list.hasFocus());
final JLabel name = new JLabel();
final JLabel path = new JLabel();
name.setForeground(fore);
path.setForeground(isSelected ? fore : UIUtil.getInactiveTextColor());
setBackground(back);
return new JPanel() {
{
setLayout(new BorderLayout());
setBackground(back);
boolean isGroup = value instanceof ProjectGroupActionGroup;
boolean isInsideGroup = false;
boolean isLastInGroup = false;
if (value instanceof ReopenProjectAction) {
final String path = ((ReopenProjectAction)value).getProjectPath();
for (ProjectGroup group : RecentProjectsManager.getInstance().getGroups()) {
final List<String> projects = group.getProjects();
if (projects.contains(path)) {
isInsideGroup = true;
isLastInGroup = path.equals(projects.get(projects.size() - 1));
break;
}
}
}
setBorder(JBUI.Borders.empty(5, 7));
if (isInsideGroup) {
add(spacer, BorderLayout.WEST);
}
if (isGroup) {
final ProjectGroup group = ((ProjectGroupActionGroup)value).getGroup();
name.setText(" " + group.getName());
name.setIcon(IconUtil.toSize(group.isExpanded() ? UIUtil.getTreeExpandedIcon() : UIUtil.getTreeCollapsedIcon(), JBUI.scale(16), JBUI.scale(16)));
name.setFont(name.getFont().deriveFont(Font.BOLD));
add(name);
} else if (value instanceof ReopenProjectAction) {
final NonOpaquePanel p = new NonOpaquePanel(new BorderLayout());
name.setText(((ReopenProjectAction)value).getTemplatePresentation().getText());
path.setText(getTitle2Text((ReopenProjectAction)value, path, JBUI.scale(isInsideGroup ? 80 : 60)));
p.add(name, BorderLayout.NORTH);
p.add(path, BorderLayout.SOUTH);
String projectPath = ((ReopenProjectAction)value).getProjectPath();
Icon icon = RecentProjectsManagerBase.getProjectIcon(projectPath, UIUtil.isUnderDarcula());
if (icon == null) {
if (UIUtil.isUnderDarcula()) {
//No dark icon for this project
icon = RecentProjectsManagerBase.getProjectIcon(projectPath, false);
}
}
if (icon == null) {
icon = EmptyIcon.ICON_16;
}
final JLabel projectIcon = new JLabel("", icon, SwingConstants.LEFT) {
@Override
protected void paintComponent(Graphics g) {
getIcon().paintIcon(this, g, 0, (getHeight() - getIcon().getIconHeight()) / 2);
}
};
projectIcon.setBorder(JBUI.Borders.emptyRight(8));
projectIcon.setVerticalAlignment(SwingConstants.CENTER);
final NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout());
panel.add(p);
panel.add(projectIcon, BorderLayout.WEST);
add(panel);
}
AccessibleContextUtil.setCombinedName(this, name, " - ", path);
AccessibleContextUtil.setCombinedDescription(this, name, " - ", path);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(super.getPreferredSize().width, JBUI.scale(44));
}
};
}
};
}
@Nullable
@Override
protected JPanel createTitle() {
return null;
}
}
| cleanup
| platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/NewRecentProjectPanel.java | cleanup | <ide><path>latform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/NewRecentProjectPanel.java
<ide> /*
<del> * Copyright 2000-2015 JetBrains s.r.o.
<add> * Copyright 2000-2016 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import com.intellij.ui.speedSearch.NameFilteringListModel;
<ide> import com.intellij.util.IconUtil;
<ide> import com.intellij.util.ui.EmptyIcon;
<add>import com.intellij.util.ui.JBDimension;
<ide> import com.intellij.util.ui.JBUI;
<ide> import com.intellij.util.ui.UIUtil;
<ide> import com.intellij.util.ui.accessibility.AccessibleContextUtil;
<ide> JScrollPane scrollPane = UIUtil.findComponentOfType(this, JScrollPane.class);
<ide> if (scrollPane != null) {
<ide> scrollPane.setBackground(FlatWelcomeFrame.getProjectsBackground());
<del> final int width = 300;
<del> final int height = 460;
<del> scrollPane.setSize(JBUI.size(width, height));
<del> scrollPane.setMinimumSize(JBUI.size(width, height));
<del> scrollPane.setPreferredSize(JBUI.size(width, height));
<add> JBDimension size = JBUI.size(300, 460);
<add> scrollPane.setSize(size);
<add> scrollPane.setMinimumSize(size);
<add> scrollPane.setPreferredSize(size);
<ide> }
<ide> ListWithFilter panel = UIUtil.findComponentOfType(this, ListWithFilter.class);
<ide> if (panel != null) {
<ide> }
<ide>
<ide> protected Dimension getPreferredScrollableViewportSize() {
<del> return null;//new Dimension(250, 430);
<add> return null;
<ide> }
<ide>
<ide> @Override
<ide>
<ide> boolean isGroup = value instanceof ProjectGroupActionGroup;
<ide> boolean isInsideGroup = false;
<del> boolean isLastInGroup = false;
<ide> if (value instanceof ReopenProjectAction) {
<ide> final String path = ((ReopenProjectAction)value).getProjectPath();
<ide> for (ProjectGroup group : RecentProjectsManager.getInstance().getGroups()) {
<ide> final List<String> projects = group.getProjects();
<ide> if (projects.contains(path)) {
<ide> isInsideGroup = true;
<del> isLastInGroup = path.equals(projects.get(projects.size() - 1));
<ide> break;
<ide> }
<ide> } |
|
JavaScript | mit | 7761800d1e4721f0955016c4ae97ba8a55ac9e5c | 0 | ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing | ///<reference path="Order.js"/>
//Self-Executing Anonymous Function
//Adding New Functionality to Purchasing for Edit
(function (purchasing, $, undefined) {
"use strict";
//Private Property
var lineItemAndSplitSections = "#line-items-section, #order-split-section, #order-account-section";
//Public Method
purchasing.initEdit = function () {
loadLineItemsAndSplits({ disableModification: true });
attachModificationEvents();
};
//Public Method
purchasing.initCopy = function () {
loadLineItemsAndSplits({ disableModification: false });
};
function loadLineItemsAndSplits(options) {
$.getJSON(purchasing._getOption("GetLineItemsAndSplitsUrl"), null, function (result) {
//manual mapping for now. can look into mapping plugin later
var model = purchasing.OrderModel;
model.items.removeAll();
model.splitType(result.splitType);
model.shipping(purchasing.displayAmount(result.orderDetail.Shipping));
model.freight(purchasing.displayAmount(result.orderDetail.Freight));
model.tax(purchasing.displayPercent(result.orderDetail.Tax));
purchasing.OrderModel.disableSubaccountLoading = true; //Don't search subaccounts when loading existing selections
$.each(result.lineItems, function (index, lineResult) {
var lineItem = new purchasing.LineItem(index, model);
lineItem.quantity(lineResult.Quantity);
lineItem.unit(lineResult.Units);
lineItem.desc(lineResult.Description);
lineItem.price(lineResult.Price);
lineItem.catalogNumber(lineResult.CatalogNumber);
lineItem.commodity(lineResult.CommodityCode);
lineItem.url(lineResult.Url);
lineItem.note(lineResult.Notes);
if (lineItem.hasDetails()) {
lineItem.showDetails(true);
}
if (model.splitType() === "Line") {
var lineSplitCount = model.lineSplitCount(); //keep starting split count, and increment until we push the lineItem
$.each(result.splits, function (i, split) {
if (split.LineItemId === lineResult.Id) {
//Add split because it's for this line
var newSplit = new purchasing.LineSplit(lineSplitCount++, lineItem);
addAccountIfNeeded(split.Account, split.AccountName);
addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);
newSplit.amountComputed(split.Amount);
newSplit.account(split.Account);
newSplit.subAccount(split.SubAccount);
newSplit.project(split.Project);
lineItem.splits.push(newSplit);
}
});
}
model.items.push(lineItem);
});
//Lines are in, now add Order splits if needed
if (model.splitType() === "Order") {
$.each(result.splits, function (i, split) {
//Create a new split, index starting at 0, and the model is the order/$root
var newSplit = new purchasing.OrderSplit(i, model);
addAccountIfNeeded(split.Account, split.AccountName);
addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);
newSplit.amountComputed(split.Amount);
newSplit.account(split.Account);
newSplit.subAccount(split.SubAccount);
newSplit.project(split.Project);
model.splits.push(newSplit);
});
}
//Add the basic account info if there are no splits (aka just one split)
if (model.splitType() === "None") {
var singleSplit = result.splits[0];
addAccountIfNeeded(singleSplit.Account, singleSplit.AccountName);
addSubAccountIfNeeded(singleSplit.SubAccount, model.subAccounts);
model.account(singleSplit.Account);
model.subAccount(singleSplit.SubAccount);
model.project(singleSplit.Project);
}
$(".account-number").change(); //notify that account numbers were changed to update tip UI
if (options.disableModification) {
disableLineItemAndSplitModification();
}
purchasing.OrderModel.disableSubaccountLoading = false; //Turn auto subaccount loading back on now that we are finished
});
}
//If the account is not in list of accounts, add it
function addAccountIfNeeded(account, accountName) {
if (account) {
var accountIfFound = ko.utils.arrayFirst(purchasing.OrderModel.accounts(), function (item) {
return item.id === account;
});
if (accountIfFound === null) { //not found, add to list
purchasing.OrderModel.addAccount(account, account, accountName);
}
}
}
//If the subAccount is not in the associated subAccount list, add it
function addSubAccountIfNeeded(subAccount, subAccounts) {
if (subAccount) {
var subAccountIfFound = ko.utils.arrayFirst(subAccounts(), function (item) {
return item === subAccount;
});
if (subAccountIfFound === null) { //not found, add to list
subAccounts.push(subAccount);
}
}
}
function attachModificationEvents() {
$("#item-modification-template").tmpl({}).insertBefore("#line-items-section");
purchasing.updateNav(); //Update navigation now that we inserted a new section
$("#item-modification-button").click(function (e, data) {
e.preventDefault();
var automate = data === undefined ? false : data.automate;
if (!automate && !confirm(purchasing.getMessage("ConfirmModification"))) {
return;
}
enableLineItemAndSplitModification();
});
}
function disableLineItemAndSplitModification() {
$(":input", lineItemAndSplitSections).attr("disabled", "disabled");
$("a.button, a.biggify", lineItemAndSplitSections).hide();
purchasing.OrderModel.adjustRouting("False");
}
function enableLineItemAndSplitModification() {
$(":input", lineItemAndSplitSections).removeAttr("disabled");
$("a.button, a.biggify", lineItemAndSplitSections).show();
$("#item-modification-section").hide();
//adjust the routing and for a reevaluation of the the split type so the UI updates
purchasing.OrderModel.adjustRouting("True");
purchasing.OrderModel.splitType.valueHasMutated();
}
purchasing.lowerCaseFirstLetter = function (w) {
return w.charAt(0).toLowerCase() + w.slice(1);
};
purchasing.selectListContainsValue = function ($select, val) {
var exists = false;
$select.find("option").each(function () {
if (this.value === val) {
exists = true;
}
});
return exists;
};
} (window.purchasing = window.purchasing || {}, jQuery));
| Purchasing.Web/Scripts/public/order/OrderEdit.js | ///<reference path="Order.js"/>
//Self-Executing Anonymous Function
//Adding New Functionality to Purchasing for Edit
(function (purchasing, $, undefined) {
"use strict";
//Private Property
var lineItemAndSplitSections = "#line-items-section, #order-split-section, #order-account-section";
//Public Method
purchasing.initEdit = function () {
loadLineItemsAndSplits({ disableModification: true });
attachModificationEvents();
};
//Public Method
purchasing.initCopy = function () {
loadLineItemsAndSplits({ disableModification: false });
};
function loadLineItemsAndSplits(options) {
$.getJSON(purchasing._getOption("GetLineItemsAndSplitsUrl"), null, function (result) {
//manual mapping for now. can look into mapping plugin later
var model = purchasing.OrderModel;
model.items.removeAll();
model.splitType(result.splitType);
model.shipping(purchasing.displayAmount(result.orderDetail.Shipping));
model.freight(purchasing.displayAmount(result.orderDetail.Freight));
model.tax(purchasing.displayPercent(result.orderDetail.Tax));
purchasing.OrderModel.disableSubaccountLoading = true; //Don't search subaccounts when loading existing selections
$.each(result.lineItems, function (index, lineResult) {
var lineItem = new purchasing.LineItem(index, model);
lineItem.quantity(lineResult.Quantity);
lineItem.unit(lineResult.Units);
lineItem.desc(lineResult.Description);
lineItem.price(lineResult.Price);
lineItem.catalogNumber(lineResult.CatalogNumber);
lineItem.commodity(lineResult.CommodityCode);
lineItem.url(lineResult.Url);
lineItem.note(lineResult.Notes);
if (lineItem.hasDetails()) {
lineItem.showDetails(true);
}
if (model.splitType() === "Line") {
var lineSplitCount = model.lineSplitCount(); //keep starting split count, and increment until we push the lineItem
$.each(result.splits, function (i, split) {
if (split.LineItemId === lineResult.Id) {
//Add split because it's for this line
var newSplit = new purchasing.LineSplit(lineSplitCount++, lineItem);
addAccountIfNeeded(split.Account, split.AccountName);
addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);
newSplit.amountComputed(split.Amount);
newSplit.account(split.Account);
newSplit.subAccount(split.SubAccount);
newSplit.project(split.Project);
lineItem.splits.push(newSplit);
}
});
}
model.items.push(lineItem);
});
//Lines are in, now add Order splits if needed
if (model.splitType() === "Order") {
$.each(result.splits, function (i, split) {
//Create a new split, index starting at 0, and the model is the order/$root
var newSplit = new purchasing.OrderSplit(i, model);
addAccountIfNeeded(split.Account, split.AccountName);
addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);
newSplit.amountComputed(split.Amount);
newSplit.account(split.Account);
newSplit.subAccount(split.SubAccount);
newSplit.project(split.Project);
model.splits.push(newSplit);
});
}
//Add the basic account info if there are no splits (aka just one split)
if (model.splitType() === "None") {
var singleSplit = result.splits[0];
addAccountIfNeeded(singleSplit.Account, singleSplit.AccountName);
addSubAccountIfNeeded(split.SubAccount, model.subAccounts);
model.account(singleSplit.Account);
model.subAccount(singleSplit.SubAccount);
model.project(singleSplit.Project);
}
$(".account-number").change(); //notify that account numbers were changed to update tip UI
if (options.disableModification) {
disableLineItemAndSplitModification();
}
purchasing.OrderModel.disableSubaccountLoading = false; //Turn auto subaccount loading back on now that we are finished
});
}
//If the account is not in list of accounts, add it
function addAccountIfNeeded(account, accountName) {
if (account) {
var accountIfFound = ko.utils.arrayFirst(purchasing.OrderModel.accounts(), function (item) {
return item.id === account;
});
if (accountIfFound === null) { //not found, add to list
purchasing.OrderModel.addAccount(account, account, accountName);
}
}
}
//If the subAccount is not in the associated subAccount list, add it
function addSubAccountIfNeeded(subAccount, subAccounts) {
if (subAccount) {
var subAccountIfFound = ko.utils.arrayFirst(subAccounts(), function (item) {
return item === subAccount;
});
if (subAccountIfFound === null) { //not found, add to list
subAccounts.push(subAccount);
}
}
}
function attachModificationEvents() {
$("#item-modification-template").tmpl({}).insertBefore("#line-items-section");
purchasing.updateNav(); //Update navigation now that we inserted a new section
$("#item-modification-button").click(function (e, data) {
e.preventDefault();
var automate = data === undefined ? false : data.automate;
if (!automate && !confirm(purchasing.getMessage("ConfirmModification"))) {
return;
}
enableLineItemAndSplitModification();
});
}
function disableLineItemAndSplitModification() {
$(":input", lineItemAndSplitSections).attr("disabled", "disabled");
$("a.button, a.biggify", lineItemAndSplitSections).hide();
purchasing.OrderModel.adjustRouting("False");
}
function enableLineItemAndSplitModification() {
$(":input", lineItemAndSplitSections).removeAttr("disabled");
$("a.button, a.biggify", lineItemAndSplitSections).show();
$("#item-modification-section").hide();
//adjust the routing and for a reevaluation of the the split type so the UI updates
purchasing.OrderModel.adjustRouting("True");
purchasing.OrderModel.splitType.valueHasMutated();
}
purchasing.lowerCaseFirstLetter = function (w) {
return w.charAt(0).toLowerCase() + w.slice(1);
};
purchasing.selectListContainsValue = function ($select, val) {
var exists = false;
$select.find("option").each(function () {
if (this.value === val) {
exists = true;
}
});
return exists;
};
} (window.purchasing = window.purchasing || {}, jQuery));
| fixed subaccount loading on non-splits due to typo
| Purchasing.Web/Scripts/public/order/OrderEdit.js | fixed subaccount loading on non-splits due to typo | <ide><path>urchasing.Web/Scripts/public/order/OrderEdit.js
<ide> if (model.splitType() === "None") {
<ide> var singleSplit = result.splits[0];
<ide> addAccountIfNeeded(singleSplit.Account, singleSplit.AccountName);
<del> addSubAccountIfNeeded(split.SubAccount, model.subAccounts);
<add> addSubAccountIfNeeded(singleSplit.SubAccount, model.subAccounts);
<ide>
<ide> model.account(singleSplit.Account);
<ide> model.subAccount(singleSplit.SubAccount); |
|
Java | apache-2.0 | 9d414b7b2bc88e2f8ddffb341702892de8ed4cb1 | 0 | lime-company/powerauth-webflow,lime-company/powerauth-webflow,lime-company/lime-security-powerauth-webauth,lime-company/powerauth-webflow,lime-company/lime-security-powerauth-webauth,lime-company/lime-security-powerauth-webauth | /*
* Copyright 2017 Lime - HighTech Solutions s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.app.nextstep.service;
import io.getlime.security.powerauth.app.nextstep.configuration.NextStepServerConfiguration;
import io.getlime.security.powerauth.app.nextstep.repository.AuthMethodRepository;
import io.getlime.security.powerauth.app.nextstep.repository.StepDefinitionRepository;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.AuthMethodEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.OperationEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.OperationHistoryEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.StepDefinitionEntity;
import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthStep;
import io.getlime.security.powerauth.lib.nextstep.model.entity.UserAuthMethodDetail;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthMethod;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthResult;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthStepResult;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.OperationRequestType;
import io.getlime.security.powerauth.lib.nextstep.model.exception.NextStepServiceException;
import io.getlime.security.powerauth.lib.nextstep.model.exception.OperationAlreadyFailedException;
import io.getlime.security.powerauth.lib.nextstep.model.exception.OperationAlreadyFinishedException;
import io.getlime.security.powerauth.lib.nextstep.model.request.CreateOperationRequest;
import io.getlime.security.powerauth.lib.nextstep.model.request.UpdateOperationRequest;
import io.getlime.security.powerauth.lib.nextstep.model.response.CreateOperationResponse;
import io.getlime.security.powerauth.lib.nextstep.model.response.UpdateOperationResponse;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* This service performs dynamic resolution of the next steps. Step definitions are loaded during class initialization
* and are used to generate responses for incoming requests. Step definitions are filtered by request parameters
* and matching step definitions are returned as the list of next steps (including priorities in case more step
* definitions match the request). Step definitions are also filtered by authentication methods available for the user,
* authentication methods can be enabled or disabled dynamically in user preferences.
*
* @author Roman Strobl
*/
@Service
public class StepResolutionService {
private IdGeneratorService idGeneratorService;
private OperationPersistenceService operationPersistenceService;
private NextStepServerConfiguration nextStepServerConfiguration;
private AuthMethodService authMethodService;
private AuthMethodRepository authMethodRepository;
private Map<String, List<StepDefinitionEntity>> stepDefinitionsPerOperation;
@Autowired
public StepResolutionService(StepDefinitionRepository stepDefinitionRepository, OperationPersistenceService operationPersistenceService,
IdGeneratorService idGeneratorService, NextStepServerConfiguration nextStepServerConfiguration,
AuthMethodService authMethodService, AuthMethodRepository authMethodRepository) {
this.operationPersistenceService = operationPersistenceService;
this.idGeneratorService = idGeneratorService;
this.nextStepServerConfiguration = nextStepServerConfiguration;
this.authMethodService = authMethodService;
this.authMethodRepository = authMethodRepository;
stepDefinitionsPerOperation = new HashMap<>();
List<String> operationNames = stepDefinitionRepository.findDistinctOperationNames();
for (String operationName : operationNames) {
stepDefinitionsPerOperation.put(operationName, stepDefinitionRepository.findStepDefinitionsForOperation(operationName));
}
}
/**
* Resolves the next steps for given CreateOperationRequest.
*
* @param request request to create a new operation
* @return response with ordered list of next steps
*/
public CreateOperationResponse resolveNextStepResponse(CreateOperationRequest request) {
CreateOperationResponse response = new CreateOperationResponse();
if (request.getOperationId() != null && !request.getOperationId().isEmpty()) {
// operation ID received from the client, verify that it is available
if (operationPersistenceService.getOperation(request.getOperationId()) != null) {
throw new IllegalArgumentException("Operation could not be created, operation ID is already used: " + request.getOperationId());
}
response.setOperationId(request.getOperationId());
} else {
// set auto-generated operation ID
response.setOperationId(idGeneratorService.generateOperationId());
}
response.setOperationName(request.getOperationName());
// AuthStepResult and AuthMethod are not available when creating the operation, null values are used to ignore them
List<StepDefinitionEntity> stepDefinitions = filterSteps(request.getOperationName(), OperationRequestType.CREATE, null, null, null);
response.getSteps().addAll(prepareAuthSteps(stepDefinitions));
response.setTimestampCreated(new Date());
response.setTimestampExpires(new DateTime().plusSeconds(nextStepServerConfiguration.getOperationExpirationTime()).toDate());
response.setFormData(request.getFormData());
Set<AuthResult> allResults = new HashSet<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
allResults.add(stepDef.getResponseResult());
}
if (allResults.size() == 1) {
response.setResult(allResults.iterator().next());
return response;
}
throw new IllegalStateException("Next step could not be resolved for new operation.");
}
/**
* Resolves the next steps for given UpdateOperationRequest.
*
* @param request request to update an existing operation
* @return response with ordered list of next steps
*/
public UpdateOperationResponse resolveNextStepResponse(UpdateOperationRequest request) throws NextStepServiceException {
OperationEntity operation = operationPersistenceService.getOperation(request.getOperationId());
checkLegitimityOfUpdate(operation, request);
UpdateOperationResponse response = new UpdateOperationResponse();
response.setOperationId(request.getOperationId());
response.setOperationName(operation.getOperationName());
response.setUserId(request.getUserId());
response.setTimestampCreated(new Date());
if (request.getAuthStepResult() == AuthStepResult.CANCELED) {
// User canceled the operation. Save authStepResultDescription which contains the reason for cancellation.
// The next step is still resolved according to the dynamic rules.
response.setResultDescription("canceled." + request.getAuthStepResultDescription().toLowerCase());
}
if (operation.isExpired()) {
// Operation fails in case it is expired.
// Fail authentication method.
request.setAuthStepResult(AuthStepResult.AUTH_METHOD_FAILED);
// Response expiration time matches operation expiration to avoid extending expiration time of the operation.
response.setTimestampExpires(operation.getTimestampExpires());
response.setResult(AuthResult.FAILED);
response.setResultDescription("operation.timeout");
return response;
}
response.setTimestampExpires(new DateTime().plusSeconds(nextStepServerConfiguration.getOperationExpirationTime()).toDate());
AuthStepResult authStepResult = request.getAuthStepResult();
if (isAuthMethodFailed(operation, request.getAuthMethod(), authStepResult)) {
// check whether the authentication method has already failed completely, in case it has failed, update the authStepResult
request.setAuthStepResult(AuthStepResult.AUTH_METHOD_FAILED);
}
List<StepDefinitionEntity> stepDefinitions = filterSteps(operation.getOperationName(), OperationRequestType.UPDATE, request.getAuthStepResult(), request.getAuthMethod(), request.getUserId());
sortSteps(stepDefinitions);
verifyDuplicatePrioritiesAbsent(stepDefinitions);
Set<AuthResult> allResults = new HashSet<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
allResults.add(stepDef.getResponseResult());
}
if (allResults.size() == 1) {
// Straightforward response - only one AuthResult found. Return all matching steps.
response.getSteps().addAll(prepareAuthSteps(stepDefinitions));
response.setResult(allResults.iterator().next());
return response;
} else if (allResults.size() > 1) {
// We need to make sure a specific AuthResult is returned in case multiple authentication methods lead
// to different AuthResults.
// In case there is any DONE or CONTINUE next step, prefer it over FAILED. FAILED state can be caused by a failing
// authentication method or by method canceled by the user, in this case try to switch to other
// authentication method if it is available.
Map<AuthResult, List<StepDefinitionEntity>> stepsByAuthResult = stepDefinitions
.stream()
.collect(Collectors.groupingBy(StepDefinitionEntity::getResponseResult));
if (stepsByAuthResult.containsKey(AuthResult.DONE)) {
List<StepDefinitionEntity> doneSteps = stepsByAuthResult.get(AuthResult.DONE);
response.getSteps().addAll(prepareAuthSteps(doneSteps));
response.setResult(AuthResult.DONE);
return response;
} else if (stepsByAuthResult.containsKey(AuthResult.CONTINUE)) {
List<StepDefinitionEntity> continueSteps = stepsByAuthResult.get(AuthResult.CONTINUE);
response.getSteps().addAll(prepareAuthSteps(continueSteps));
response.setResult(AuthResult.CONTINUE);
return response;
} else if (stepsByAuthResult.containsKey(AuthResult.FAILED)) {
List<StepDefinitionEntity> failedSteps = stepsByAuthResult.get(AuthResult.FAILED);
response.getSteps().addAll(prepareAuthSteps(failedSteps));
response.setResult(AuthResult.FAILED);
return response;
}
// This code should not be reached - all cases should have been handled previously.
response.getSteps().clear();
response.setResult(AuthResult.FAILED);
response.setResultDescription("error.unknown");
return response;
} else {
// No step definition matches the current criteria. Suitable step definitions might have been filtered out
// via user preferences. Fail the operation.
response.getSteps().clear();
response.setResult(AuthResult.FAILED);
response.setResultDescription("error.noAuthMethod");
return response;
}
}
/**
* Filters step definitions by given parameters and returns a list of step definitions which match the query.
*
* @param operationName name of the operation
* @param operationType type of the operation - CREATE/UPDATE
* @param authStepResult result of previous authentication step
* @param authMethod authentication method of previous authentication step
* @param userId user ID
* @return filtered list of steps
*/
private List<StepDefinitionEntity> filterSteps(String operationName, OperationRequestType operationType, AuthStepResult authStepResult, AuthMethod authMethod, String userId) {
List<StepDefinitionEntity> stepDefinitions = stepDefinitionsPerOperation.get(operationName);
List<AuthMethod> authMethodsAvailableForUser = new ArrayList<>();
if (userId != null) {
for (UserAuthMethodDetail userAuthMethodDetail : authMethodService.listAuthMethodsEnabledForUser(userId)) {
authMethodsAvailableForUser.add(userAuthMethodDetail.getAuthMethod());
}
}
List<StepDefinitionEntity> filteredStepDefinitions = new ArrayList<>();
if (stepDefinitions == null) {
throw new IllegalStateException("Step definitions are missing in Next Step server.");
}
for (StepDefinitionEntity stepDef : stepDefinitions) {
if (operationType != null && !operationType.equals(stepDef.getOperationType())) {
// filter by operation type
continue;
}
if (authStepResult != null && !authStepResult.equals(stepDef.getRequestAuthStepResult())) {
// filter by AuthStepResult
continue;
}
if (authMethod != null && !authMethod.equals(stepDef.getRequestAuthMethod())) {
// filter by request AuthMethod
continue;
}
if (userId != null && stepDef.getResponseAuthMethod() != null && !authMethodsAvailableForUser.contains(stepDef.getResponseAuthMethod())) {
// filter by response AuthMethod based on methods available for the user - the list can change
// dynamically via user preferences
continue;
}
filteredStepDefinitions.add(stepDef);
}
return filteredStepDefinitions;
}
/**
* Sorts the step definitions based on their priorities.
*
* @param stepDefinitions step definitions
*/
private void sortSteps(List<StepDefinitionEntity> stepDefinitions) {
Collections.sort(stepDefinitions, Comparator.comparing(StepDefinitionEntity::getResponsePriority));
}
/**
* Verifies that each priority is present only once in the list of step definitions.
*
* @param stepDefinitions step definitions
*/
private void verifyDuplicatePrioritiesAbsent(List<StepDefinitionEntity> stepDefinitions) {
Map<Long, List<StepDefinitionEntity>> stepsByPriority = stepDefinitions
.stream()
.collect(Collectors.groupingBy(StepDefinitionEntity::getResponsePriority));
if (stepsByPriority.size() != stepDefinitions.size()) {
throw new IllegalStateException("Multiple steps with the same priority detected while resolving next step.");
}
}
/**
* Converts List<StepDefinitionEntity> into a List<AuthStep>.
*
* @param stepDefinitions step definitions to convert
* @return converted list of authentication steps
*/
private List<AuthStep> prepareAuthSteps(List<StepDefinitionEntity> stepDefinitions) {
List<AuthStep> authSteps = new ArrayList<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
if (stepDef.getResponseAuthMethod() != null) {
AuthStep authStep = new AuthStep();
authStep.setAuthMethod(stepDef.getResponseAuthMethod());
authSteps.add(authStep);
}
}
return authSteps;
}
/**
* Check whether given authentication method has previously failed or it has exceeded the maximum number of attempts.
*
* @param operation operation whose history is being checked
* @param authMethod authentication method
* @return whether authentication method failed
*/
private boolean isAuthMethodFailed(OperationEntity operation, AuthMethod authMethod, AuthStepResult currentAuthStepResult) {
if (currentAuthStepResult == AuthStepResult.AUTH_METHOD_FAILED) {
return true;
}
// in case authentication method previously failed, it is already failed
for (OperationHistoryEntity history : operation.getOperationHistory()) {
if (history.getRequestAuthMethod() == authMethod && history.getRequestAuthStepResult() == AuthStepResult.AUTH_METHOD_FAILED) {
return true;
}
}
// check whether authMethod supports check of authorization failure count
AuthMethodEntity authMethodEntity = authMethodRepository.findByAuthMethod(authMethod);
if (authMethodEntity == null) {
throw new IllegalStateException("AuthMethod is missing in database: " + authMethod);
}
if (authMethodEntity.getCheckAuthorizationFailures()) {
// count failures
int failureCount = 0;
if (currentAuthStepResult == AuthStepResult.AUTH_FAILED) {
// add current failure
failureCount++;
}
for (OperationHistoryEntity history : operation.getOperationHistory()) {
// add all failures from history for this method
if (history.getRequestAuthMethod() == authMethod && history.getRequestAuthStepResult() == AuthStepResult.AUTH_FAILED) {
failureCount++;
}
}
if (failureCount >= authMethodEntity.getMaxAuthorizationFailures()) {
return true;
}
}
return false;
}
/**
* Check whether the update of operation is legitimate and meaningful.
*
* @param operationEntity Operation entity.
* @param request Update request.
*/
private void checkLegitimityOfUpdate(OperationEntity operationEntity, UpdateOperationRequest request) throws NextStepServiceException {
if (request == null || request.getOperationId() == null) {
throw new IllegalArgumentException("Operation update failed, because request is invalid.");
}
if (operationEntity == null) {
throw new IllegalArgumentException("Operation update failed, because operation does not exist (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthMethod() == null) {
throw new IllegalArgumentException("Operation update failed, because authentication method is missing (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthMethod() == AuthMethod.INIT) {
throw new IllegalArgumentException("Operation update failed, because INIT method cannot be updated (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthStepResult() == null) {
throw new IllegalArgumentException("Operation update failed, because result of authentication step is missing (operationId: " + request.getOperationId() + ").");
}
List<OperationHistoryEntity> operationHistory = operationEntity.getOperationHistory();
if (operationHistory.isEmpty()) {
throw new IllegalStateException("Operation update failed, because operation is missing its history (operationId: " + request.getOperationId() + ").");
}
OperationHistoryEntity initOperationItem = operationHistory.get(0);
if (initOperationItem.getRequestAuthMethod() != null || initOperationItem.getRequestAuthStepResult() != null) {
throw new IllegalStateException("Operation update failed, because INIT step for this operation is invalid (operationId: " + request.getOperationId() + ").");
}
// check whether request AuthMethod is available in response AuthSteps - this verifies operation continuity
boolean stepAuthMethodValid = false;
if (request.getAuthMethod() == AuthMethod.SHOW_OPERATION_DETAIL) {
// special handling for SHOW_OPERATION_DETAIL - either SMS_KEY or POWERAUTH_TOKEN are present in next steps
for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
if (step.getAuthMethod() == AuthMethod.SMS_KEY || step.getAuthMethod()==AuthMethod.POWERAUTH_TOKEN) {
stepAuthMethodValid = true;
}
}
} else {
// check whether request AuthMethod is available in response AuthSteps - this verifies operation continuity
for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
if (step.getAuthMethod() == request.getAuthMethod()) {
stepAuthMethodValid = true;
}
}
}
if (!stepAuthMethodValid) {
throw new IllegalStateException("Operation update failed, because AuthMethod is invalid (operationId: " + request.getOperationId() + ").");
}
for (OperationHistoryEntity historyItem : operationHistory) {
if (historyItem.getResponseResult() == AuthResult.DONE) {
throw new OperationAlreadyFinishedException("Operation update failed, because operation is already in DONE state (operationId: " + request.getOperationId() + ").");
}
if (historyItem.getResponseResult() == AuthResult.FAILED) {
// #102 - allow double cancellation requests, cancel requests may come from multiple channels, so this is a supported scenario
if (operationEntity.getCurrentOperationHistoryEntity().getRequestAuthStepResult() != AuthStepResult.CANCELED
|| request.getAuthStepResult() != AuthStepResult.CANCELED) {
throw new OperationAlreadyFailedException("Operation update failed, because operation is already in FAILED state (operationId: " + request.getOperationId() + ").");
}
}
}
}
}
| powerauth-nextstep/src/main/java/io/getlime/security/powerauth/app/nextstep/service/StepResolutionService.java | /*
* Copyright 2017 Lime - HighTech Solutions s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.app.nextstep.service;
import io.getlime.security.powerauth.app.nextstep.configuration.NextStepServerConfiguration;
import io.getlime.security.powerauth.app.nextstep.repository.AuthMethodRepository;
import io.getlime.security.powerauth.app.nextstep.repository.StepDefinitionRepository;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.AuthMethodEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.OperationEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.OperationHistoryEntity;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.StepDefinitionEntity;
import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthStep;
import io.getlime.security.powerauth.lib.nextstep.model.entity.UserAuthMethodDetail;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthMethod;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthResult;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthStepResult;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.OperationRequestType;
import io.getlime.security.powerauth.lib.nextstep.model.exception.NextStepServiceException;
import io.getlime.security.powerauth.lib.nextstep.model.exception.OperationAlreadyFailedException;
import io.getlime.security.powerauth.lib.nextstep.model.exception.OperationAlreadyFinishedException;
import io.getlime.security.powerauth.lib.nextstep.model.request.CreateOperationRequest;
import io.getlime.security.powerauth.lib.nextstep.model.request.UpdateOperationRequest;
import io.getlime.security.powerauth.lib.nextstep.model.response.CreateOperationResponse;
import io.getlime.security.powerauth.lib.nextstep.model.response.UpdateOperationResponse;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* This service performs dynamic resolution of the next steps. Step definitions are loaded during class initialization
* and are used to generate responses for incoming requests. Step definitions are filtered by request parameters
* and matching step definitions are returned as the list of next steps (including priorities in case more step
* definitions match the request). Step definitions are also filtered by authentication methods available for the user,
* authentication methods can be enabled or disabled dynamically in user preferences.
*
* @author Roman Strobl
*/
@Service
public class StepResolutionService {
private IdGeneratorService idGeneratorService;
private OperationPersistenceService operationPersistenceService;
private NextStepServerConfiguration nextStepServerConfiguration;
private AuthMethodService authMethodService;
private AuthMethodRepository authMethodRepository;
private Map<String, List<StepDefinitionEntity>> stepDefinitionsPerOperation;
@Autowired
public StepResolutionService(StepDefinitionRepository stepDefinitionRepository, OperationPersistenceService operationPersistenceService,
IdGeneratorService idGeneratorService, NextStepServerConfiguration nextStepServerConfiguration,
AuthMethodService authMethodService, AuthMethodRepository authMethodRepository) {
this.operationPersistenceService = operationPersistenceService;
this.idGeneratorService = idGeneratorService;
this.nextStepServerConfiguration = nextStepServerConfiguration;
this.authMethodService = authMethodService;
this.authMethodRepository = authMethodRepository;
stepDefinitionsPerOperation = new HashMap<>();
List<String> operationNames = stepDefinitionRepository.findDistinctOperationNames();
for (String operationName : operationNames) {
stepDefinitionsPerOperation.put(operationName, stepDefinitionRepository.findStepDefinitionsForOperation(operationName));
}
}
/**
* Resolves the next steps for given CreateOperationRequest.
*
* @param request request to create a new operation
* @return response with ordered list of next steps
*/
public CreateOperationResponse resolveNextStepResponse(CreateOperationRequest request) {
CreateOperationResponse response = new CreateOperationResponse();
if (request.getOperationId() != null && !request.getOperationId().isEmpty()) {
// operation ID received from the client, verify that it is available
if (operationPersistenceService.getOperation(request.getOperationId()) != null) {
throw new IllegalArgumentException("Operation could not be created, operation ID is already used: " + request.getOperationId());
}
response.setOperationId(request.getOperationId());
} else {
// set auto-generated operation ID
response.setOperationId(idGeneratorService.generateOperationId());
}
response.setOperationName(request.getOperationName());
// AuthStepResult and AuthMethod are not available when creating the operation, null values are used to ignore them
List<StepDefinitionEntity> stepDefinitions = filterSteps(request.getOperationName(), OperationRequestType.CREATE, null, null, null);
response.getSteps().addAll(prepareAuthSteps(stepDefinitions));
response.setTimestampCreated(new Date());
response.setTimestampExpires(new DateTime().plusSeconds(nextStepServerConfiguration.getOperationExpirationTime()).toDate());
response.setFormData(request.getFormData());
Set<AuthResult> allResults = new HashSet<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
allResults.add(stepDef.getResponseResult());
}
if (allResults.size() == 1) {
response.setResult(allResults.iterator().next());
return response;
}
throw new IllegalStateException("Next step could not be resolved for new operation.");
}
/**
* Resolves the next steps for given UpdateOperationRequest.
*
* @param request request to update an existing operation
* @return response with ordered list of next steps
*/
public UpdateOperationResponse resolveNextStepResponse(UpdateOperationRequest request) throws NextStepServiceException {
OperationEntity operation = operationPersistenceService.getOperation(request.getOperationId());
checkLegitimityOfUpdate(operation, request);
UpdateOperationResponse response = new UpdateOperationResponse();
response.setOperationId(request.getOperationId());
response.setOperationName(operation.getOperationName());
response.setUserId(request.getUserId());
response.setTimestampCreated(new Date());
if (request.getAuthStepResult() == AuthStepResult.CANCELED) {
// User canceled the operation. Save authStepResultDescription which contains the reason for cancellation.
// The next step is still resolved according to the dynamic rules.
response.setResultDescription("canceled." + request.getAuthStepResultDescription().toLowerCase());
}
if (operation.isExpired()) {
// Operation fails in case it is expired.
// Fail authentication method.
request.setAuthStepResult(AuthStepResult.AUTH_METHOD_FAILED);
// Response expiration time matches operation expiration to avoid extending expiration time of the operation.
response.setTimestampExpires(operation.getTimestampExpires());
response.setResult(AuthResult.FAILED);
response.setResultDescription("operation.timeout");
return response;
}
response.setTimestampExpires(new DateTime().plusSeconds(nextStepServerConfiguration.getOperationExpirationTime()).toDate());
AuthStepResult authStepResult = request.getAuthStepResult();
if (isAuthMethodFailed(operation, request.getAuthMethod(), authStepResult)) {
// check whether the authentication method has already failed completely, in case it has failed, update the authStepResult
request.setAuthStepResult(AuthStepResult.AUTH_METHOD_FAILED);
}
List<StepDefinitionEntity> stepDefinitions = filterSteps(operation.getOperationName(), OperationRequestType.UPDATE, request.getAuthStepResult(), request.getAuthMethod(), request.getUserId());
sortSteps(stepDefinitions);
verifyDuplicatePrioritiesAbsent(stepDefinitions);
Set<AuthResult> allResults = new HashSet<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
allResults.add(stepDef.getResponseResult());
}
if (allResults.size() == 1) {
// Straightforward response - only one AuthResult found. Return all matching steps.
response.getSteps().addAll(prepareAuthSteps(stepDefinitions));
response.setResult(allResults.iterator().next());
return response;
} else if (allResults.size() > 1) {
// We need to make sure a specific AuthResult is returned in case multiple authentication methods lead
// to different AuthResults.
// In case there is any DONE or CONTINUE next step, prefer it over FAILED. FAILED state can be caused by a failing
// authentication method or by method canceled by the user, in this case try to switch to other
// authentication method if it is available.
Map<AuthResult, List<StepDefinitionEntity>> stepsByAuthResult = stepDefinitions
.stream()
.collect(Collectors.groupingBy(StepDefinitionEntity::getResponseResult));
if (stepsByAuthResult.containsKey(AuthResult.DONE)) {
List<StepDefinitionEntity> doneSteps = stepsByAuthResult.get(AuthResult.DONE);
response.getSteps().addAll(prepareAuthSteps(doneSteps));
response.setResult(AuthResult.DONE);
return response;
} else if (stepsByAuthResult.containsKey(AuthResult.CONTINUE)) {
List<StepDefinitionEntity> continueSteps = stepsByAuthResult.get(AuthResult.CONTINUE);
response.getSteps().addAll(prepareAuthSteps(continueSteps));
response.setResult(AuthResult.CONTINUE);
return response;
} else if (stepsByAuthResult.containsKey(AuthResult.FAILED)) {
List<StepDefinitionEntity> failedSteps = stepsByAuthResult.get(AuthResult.FAILED);
response.getSteps().addAll(prepareAuthSteps(failedSteps));
response.setResult(AuthResult.FAILED);
return response;
}
// This code should not be reached - all cases should have been handled previously.
response.getSteps().clear();
response.setResult(AuthResult.FAILED);
response.setResultDescription("error.unknown");
return response;
} else {
// No step definition matches the current criteria. Suitable step definitions might have been filtered out
// via user preferences. Fail the operation.
response.getSteps().clear();
response.setResult(AuthResult.FAILED);
response.setResultDescription("error.noAuthMethod");
return response;
}
}
/**
* Filters step definitions by given parameters and returns a list of step definitions which match the query.
*
* @param operationName name of the operation
* @param operationType type of the operation - CREATE/UPDATE
* @param authStepResult result of previous authentication step
* @param authMethod authentication method of previous authentication step
* @param userId user ID
* @return filtered list of steps
*/
private List<StepDefinitionEntity> filterSteps(String operationName, OperationRequestType operationType, AuthStepResult authStepResult, AuthMethod authMethod, String userId) {
List<StepDefinitionEntity> stepDefinitions = stepDefinitionsPerOperation.get(operationName);
List<AuthMethod> authMethodsAvailableForUser = new ArrayList<>();
if (userId != null) {
for (UserAuthMethodDetail userAuthMethodDetail : authMethodService.listAuthMethodsEnabledForUser(userId)) {
authMethodsAvailableForUser.add(userAuthMethodDetail.getAuthMethod());
}
}
List<StepDefinitionEntity> filteredStepDefinitions = new ArrayList<>();
if (stepDefinitions == null) {
throw new IllegalStateException("Step definitions are missing in Next Step server.");
}
for (StepDefinitionEntity stepDef : stepDefinitions) {
if (operationType != null && !operationType.equals(stepDef.getOperationType())) {
// filter by operation type
continue;
}
if (authStepResult != null && !authStepResult.equals(stepDef.getRequestAuthStepResult())) {
// filter by AuthStepResult
continue;
}
if (authMethod != null && !authMethod.equals(stepDef.getRequestAuthMethod())) {
// filter by request AuthMethod
continue;
}
if (userId != null && stepDef.getResponseAuthMethod() != null && !authMethodsAvailableForUser.contains(stepDef.getResponseAuthMethod())) {
// filter by response AuthMethod based on methods available for the user - the list can change
// dynamically via user preferences
continue;
}
filteredStepDefinitions.add(stepDef);
}
return filteredStepDefinitions;
}
/**
* Sorts the step definitions based on their priorities.
*
* @param stepDefinitions step definitions
*/
private void sortSteps(List<StepDefinitionEntity> stepDefinitions) {
Collections.sort(stepDefinitions, Comparator.comparing(StepDefinitionEntity::getResponsePriority));
}
/**
* Verifies that each priority is present only once in the list of step definitions.
*
* @param stepDefinitions step definitions
*/
private void verifyDuplicatePrioritiesAbsent(List<StepDefinitionEntity> stepDefinitions) {
Map<Long, List<StepDefinitionEntity>> stepsByPriority = stepDefinitions
.stream()
.collect(Collectors.groupingBy(StepDefinitionEntity::getResponsePriority));
if (stepsByPriority.size() != stepDefinitions.size()) {
throw new IllegalStateException("Multiple steps with the same priority detected while resolving next step.");
}
}
/**
* Converts List<StepDefinitionEntity> into a List<AuthStep>.
*
* @param stepDefinitions step definitions to convert
* @return converted list of authentication steps
*/
private List<AuthStep> prepareAuthSteps(List<StepDefinitionEntity> stepDefinitions) {
List<AuthStep> authSteps = new ArrayList<>();
for (StepDefinitionEntity stepDef : stepDefinitions) {
if (stepDef.getResponseAuthMethod() != null) {
AuthStep authStep = new AuthStep();
authStep.setAuthMethod(stepDef.getResponseAuthMethod());
authSteps.add(authStep);
}
}
return authSteps;
}
/**
* Check whether given authentication method has previously failed or it has exceeded the maximum number of attempts.
*
* @param operation operation whose history is being checked
* @param authMethod authentication method
* @return whether authentication method failed
*/
private boolean isAuthMethodFailed(OperationEntity operation, AuthMethod authMethod, AuthStepResult currentAuthStepResult) {
if (currentAuthStepResult == AuthStepResult.AUTH_METHOD_FAILED) {
return true;
}
// in case authentication method previously failed, it is already failed
for (OperationHistoryEntity history : operation.getOperationHistory()) {
if (history.getRequestAuthMethod() == authMethod && history.getRequestAuthStepResult() == AuthStepResult.AUTH_METHOD_FAILED) {
return true;
}
}
// check whether authMethod supports check of authorization failure count
AuthMethodEntity authMethodEntity = authMethodRepository.findByAuthMethod(authMethod);
if (authMethodEntity == null) {
throw new IllegalStateException("AuthMethod is missing in database: " + authMethod);
}
if (authMethodEntity.getCheckAuthorizationFailures()) {
// count failures
int failureCount = 0;
if (currentAuthStepResult == AuthStepResult.AUTH_FAILED) {
// add current failure
failureCount++;
}
for (OperationHistoryEntity history : operation.getOperationHistory()) {
// add all failures from history for this method
if (history.getRequestAuthMethod() == authMethod && history.getRequestAuthStepResult() == AuthStepResult.AUTH_FAILED) {
failureCount++;
}
}
if (failureCount >= authMethodEntity.getMaxAuthorizationFailures()) {
return true;
}
}
return false;
}
/**
* Check whether the update of operation is legitimate and meaningful.
*
* @param operationEntity Operation entity.
* @param request Update request.
*/
private void checkLegitimityOfUpdate(OperationEntity operationEntity, UpdateOperationRequest request) throws NextStepServiceException {
if (request == null || request.getOperationId() == null) {
throw new IllegalArgumentException("Operation update failed, because request is invalid.");
}
if (operationEntity == null) {
throw new IllegalArgumentException("Operation update failed, because operation does not exist (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthMethod() == null) {
throw new IllegalArgumentException("Operation update failed, because authentication method is missing (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthMethod() == AuthMethod.INIT) {
throw new IllegalArgumentException("Operation update failed, because INIT method cannot be updated (operationId: " + request.getOperationId() + ").");
}
if (request.getAuthStepResult() == null) {
throw new IllegalArgumentException("Operation update failed, because result of authentication step is missing (operationId: " + request.getOperationId() + ").");
}
List<OperationHistoryEntity> operationHistory = operationEntity.getOperationHistory();
if (operationHistory.isEmpty()) {
throw new IllegalStateException("Operation update failed, because operation is missing its history (operationId: " + request.getOperationId() + ").");
}
OperationHistoryEntity initOperationItem = operationHistory.get(0);
if (initOperationItem.getRequestAuthMethod() != null || initOperationItem.getRequestAuthStepResult() != null) {
throw new IllegalStateException("Operation update failed, because INIT step for this operation is invalid (operationId: " + request.getOperationId() + ").");
}
// check whether request AuthMethod is available in response AuthSteps - this verifies operation continuity
boolean stepAuthMethodValid = false;
for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
if (step.getAuthMethod() == request.getAuthMethod()) {
stepAuthMethodValid = true;
}
}
if (!stepAuthMethodValid) {
throw new IllegalStateException("Operation update failed, because AuthMethod is invalid (operationId: " + request.getOperationId() + ").");
}
for (OperationHistoryEntity historyItem : operationHistory) {
if (historyItem.getResponseResult() == AuthResult.DONE) {
throw new OperationAlreadyFinishedException("Operation update failed, because operation is already in DONE state (operationId: " + request.getOperationId() + ").");
}
if (historyItem.getResponseResult() == AuthResult.FAILED) {
// #102 - allow double cancellation requests, cancel requests may come from multiple channels, so this is a supported scenario
if (operationEntity.getCurrentOperationHistoryEntity().getRequestAuthStepResult() != AuthStepResult.CANCELED
|| request.getAuthStepResult() != AuthStepResult.CANCELED) {
throw new OperationAlreadyFailedException("Operation update failed, because operation is already in FAILED state (operationId: " + request.getOperationId() + ").");
}
}
}
}
}
| Handling of SHOW_OPERATION_DETAIL step which has special status
| powerauth-nextstep/src/main/java/io/getlime/security/powerauth/app/nextstep/service/StepResolutionService.java | Handling of SHOW_OPERATION_DETAIL step which has special status | <ide><path>owerauth-nextstep/src/main/java/io/getlime/security/powerauth/app/nextstep/service/StepResolutionService.java
<ide> }
<ide> // check whether request AuthMethod is available in response AuthSteps - this verifies operation continuity
<ide> boolean stepAuthMethodValid = false;
<del> for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
<del> if (step.getAuthMethod() == request.getAuthMethod()) {
<del> stepAuthMethodValid = true;
<add> if (request.getAuthMethod() == AuthMethod.SHOW_OPERATION_DETAIL) {
<add> // special handling for SHOW_OPERATION_DETAIL - either SMS_KEY or POWERAUTH_TOKEN are present in next steps
<add> for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
<add> if (step.getAuthMethod() == AuthMethod.SMS_KEY || step.getAuthMethod()==AuthMethod.POWERAUTH_TOKEN) {
<add> stepAuthMethodValid = true;
<add> }
<add> }
<add> } else {
<add> // check whether request AuthMethod is available in response AuthSteps - this verifies operation continuity
<add> for (AuthStep step: operationPersistenceService.getResponseAuthSteps(operationEntity)) {
<add> if (step.getAuthMethod() == request.getAuthMethod()) {
<add> stepAuthMethodValid = true;
<add> }
<ide> }
<ide> }
<ide> if (!stepAuthMethodValid) { |
|
Java | apache-2.0 | f2080ffcf1ebf84105653e40bd0482bc4c5042b7 | 0 | apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.core.parsing.parser.sql.ddl.create.table;
import io.shardingsphere.core.metadata.table.TableMetaData;
import io.shardingsphere.core.parsing.parser.sql.ddl.DDLStatement;
import lombok.Getter;
import lombok.Setter;
import java.util.LinkedList;
import java.util.List;
/**
* Create table statement.
*
* @author zhangliang
*/
@Getter
@Setter
public final class CreateTableStatement extends DDLStatement {
private final List<String> columnNames = new LinkedList<>();
private final List<String> columnTypes = new LinkedList<>();
private final List<String> primaryKeyColumns = new LinkedList<>();
private TableMetaData tableMetaData;
}
| sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/table/CreateTableStatement.java | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.core.parsing.parser.sql.ddl.create.table;
import io.shardingsphere.core.metadata.table.TableMetaData;
import io.shardingsphere.core.parsing.parser.sql.ddl.DDLStatement;
import lombok.Getter;
import lombok.Setter;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
/**
* Create table statement.
*
* @author zhangliang
*/
@Getter
@Setter
public final class CreateTableStatement extends DDLStatement {
private final List<String> columnNames = new LinkedList<>();
private final List<String> columnTypes = new LinkedList<>();
private final Collection<String> primaryKeyColumns = new LinkedHashSet<>();
private TableMetaData tableMetaData;
}
| for compile
| sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/table/CreateTableStatement.java | for compile | <ide><path>harding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/table/CreateTableStatement.java
<ide> import lombok.Getter;
<ide> import lombok.Setter;
<ide>
<del>import java.util.Collection;
<del>import java.util.LinkedHashSet;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide>
<ide>
<ide> private final List<String> columnTypes = new LinkedList<>();
<ide>
<del> private final Collection<String> primaryKeyColumns = new LinkedHashSet<>();
<add> private final List<String> primaryKeyColumns = new LinkedList<>();
<ide>
<ide> private TableMetaData tableMetaData;
<ide> } |
|
Java | apache-2.0 | 21f9c6ce1128738734d3e0aba9e946cf213a770e | 0 | iservport/helianto,iservport/helianto | /* Copyright 2005 I Serv Consultoria Empresarial Ltda.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.helianto.document.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.helianto.core.SequenceMgr;
import org.helianto.core.domain.Entity;
import org.helianto.core.test.EntityTestSupport;
import org.helianto.document.domain.Document;
import org.helianto.document.domain.DocumentFolder;
import org.helianto.document.domain.PrivateDocument;
import org.helianto.document.filter.classic.DocumentFilter;
import org.helianto.document.repository.DocumentFolderRepository;
import org.helianto.document.repository.DocumentRepository;
import org.helianto.document.repository.PrivateDocumentRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Mauricio Fernandes de Castro
*/
public class DocumentMgrImplTests {
@Test
public void storeDocumentNoBuilder() {
Document document= new Document();
EasyMock.expect(documentRepository.save(document)).andReturn(document);
documentRepository.flush();
EasyMock.replay(documentRepository);
EasyMock.replay(sequenceMgr);
assertSame(document, documentMgr.storeDocument(document));
EasyMock.verify(documentRepository);
EasyMock.verify(sequenceMgr);
}
@Test
public void storeDocument() {
Entity entity = EntityTestSupport.createEntity();
Document document= new Document(entity, "");
document.setSeries(new DocumentFolder(entity, "KEY"));
EasyMock.expect(documentRepository.save(document)).andReturn(document);
EasyMock.expect(documentRepository.findLastNumber(entity, "KEY")).andReturn(new Long(1000));
documentRepository.flush();
EasyMock.replay(documentRepository);
// sequenceMgr.validateInternalNumber(document);
// EasyMock.replay(sequenceMgr);
assertSame(document, documentMgr.storeDocument(document));
EasyMock.verify(documentRepository);
assertEquals(1001, document.getInternalNumber());
// EasyMock.verify(sequenceMgr);
}
@Test
public void storePrivateDocument() {
PrivateDocument privateDocument= new PrivateDocument();
EasyMock.expect(privateDocumentRepository.saveAndFlush(privateDocument)).andReturn(privateDocument);
EasyMock.replay(privateDocumentRepository);
assertSame(privateDocument, documentMgr.storePrivateDocument(privateDocument));
EasyMock.verify(privateDocumentRepository);
}
@Test
public void findDocuments() {
List<Document> documentList = new ArrayList<Document>();
DocumentFilter documentFilter = new DocumentFilter(new Entity(), "");
EasyMock.expect(documentRepository.find(documentFilter)).andReturn(documentList);
EasyMock.replay(documentRepository);
assertSame(documentList, documentMgr.findDocuments(documentFilter));
EasyMock.verify(documentRepository);
}
@Test
public void removeDocument() {
Document document= new Document();
documentRepository.delete(document);
EasyMock.replay(documentRepository);
documentRepository.delete(document);
EasyMock.verify(documentRepository);
}
@Test
public void storeDocumentCodeBuilder() {
DocumentFolder documentFolder = new DocumentFolder();
EasyMock.expect(documentFolderRepository.saveAndFlush(documentFolder)).andReturn(documentFolder);
EasyMock.replay(documentFolderRepository);
assertSame(documentFolder, documentMgr.storeDocumentFolder(documentFolder));
EasyMock.verify(documentFolderRepository);
}
//
private DocumentMgrImpl documentMgr;
private DocumentRepository documentRepository;
private PrivateDocumentRepository privateDocumentRepository;
private DocumentFolderRepository documentFolderRepository;
private SequenceMgr sequenceMgr;
@Before
public void setUp() {
documentMgr = new DocumentMgrImpl();
documentRepository = EasyMock.createMock(DocumentRepository.class);
documentMgr.setDocumentRepository(documentRepository);
privateDocumentRepository = EasyMock.createMock(PrivateDocumentRepository.class);
documentMgr.setPrivateDocumentRepository(privateDocumentRepository);
documentFolderRepository = EasyMock.createMock(DocumentFolderRepository.class);
documentMgr.setDocumentFolderRepository(documentFolderRepository);
sequenceMgr = EasyMock.createMock(SequenceMgr.class);
documentMgr.setSequenceMgr(sequenceMgr);
}
@After
public void tearDown() {
EasyMock.reset(documentRepository);
EasyMock.reset(privateDocumentRepository);
EasyMock.reset(documentFolderRepository);
EasyMock.reset(sequenceMgr);
}
}
| helianto-document/src/test/java/org/helianto/document/service/DocumentMgrImplTests.java | /* Copyright 2005 I Serv Consultoria Empresarial Ltda.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.helianto.document.service;
import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.helianto.core.SequenceMgr;
import org.helianto.core.domain.Entity;
import org.helianto.document.domain.Document;
import org.helianto.document.domain.DocumentFolder;
import org.helianto.document.domain.PrivateDocument;
import org.helianto.document.filter.classic.DocumentFilter;
import org.helianto.document.repository.DocumentFolderRepository;
import org.helianto.document.repository.DocumentRepository;
import org.helianto.document.repository.PrivateDocumentRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Mauricio Fernandes de Castro
*/
public class DocumentMgrImplTests {
@Test
public void storeDocumentNoBuilder() {
Document document= new Document();
EasyMock.expect(documentRepository.save(document)).andReturn(document);
documentRepository.flush();
EasyMock.replay(documentRepository);
EasyMock.replay(sequenceMgr);
assertSame(document, documentMgr.storeDocument(document));
EasyMock.verify(documentRepository);
EasyMock.verify(sequenceMgr);
}
@Test
public void storeDocument() {
Document document= new Document();
document.setSeries(new DocumentFolder());
EasyMock.expect(documentRepository.save(document)).andReturn(document);
documentRepository.flush();
EasyMock.replay(documentRepository);
sequenceMgr.validateInternalNumber(document);
EasyMock.replay(sequenceMgr);
assertSame(document, documentMgr.storeDocument(document));
EasyMock.verify(documentRepository);
EasyMock.verify(sequenceMgr);
}
@Test
public void storePrivateDocument() {
PrivateDocument privateDocument= new PrivateDocument();
EasyMock.expect(privateDocumentRepository.saveAndFlush(privateDocument)).andReturn(privateDocument);
EasyMock.replay(privateDocumentRepository);
assertSame(privateDocument, documentMgr.storePrivateDocument(privateDocument));
EasyMock.verify(privateDocumentRepository);
}
@Test
public void findDocuments() {
List<Document> documentList = new ArrayList<Document>();
DocumentFilter documentFilter = new DocumentFilter(new Entity(), "");
EasyMock.expect(documentRepository.find(documentFilter)).andReturn(documentList);
EasyMock.replay(documentRepository);
assertSame(documentList, documentMgr.findDocuments(documentFilter));
EasyMock.verify(documentRepository);
}
@Test
public void removeDocument() {
Document document= new Document();
documentRepository.delete(document);
EasyMock.replay(documentRepository);
documentRepository.delete(document);
EasyMock.verify(documentRepository);
}
@Test
public void storeDocumentCodeBuilder() {
DocumentFolder documentFolder = new DocumentFolder();
EasyMock.expect(documentFolderRepository.saveAndFlush(documentFolder)).andReturn(documentFolder);
EasyMock.replay(documentFolderRepository);
assertSame(documentFolder, documentMgr.storeDocumentFolder(documentFolder));
EasyMock.verify(documentFolderRepository);
}
//
private DocumentMgrImpl documentMgr;
private DocumentRepository documentRepository;
private PrivateDocumentRepository privateDocumentRepository;
private DocumentFolderRepository documentFolderRepository;
private SequenceMgr sequenceMgr;
@Before
public void setUp() {
documentMgr = new DocumentMgrImpl();
documentRepository = EasyMock.createMock(DocumentRepository.class);
documentMgr.setDocumentRepository(documentRepository);
privateDocumentRepository = EasyMock.createMock(PrivateDocumentRepository.class);
documentMgr.setPrivateDocumentRepository(privateDocumentRepository);
documentFolderRepository = EasyMock.createMock(DocumentFolderRepository.class);
documentMgr.setDocumentFolderRepository(documentFolderRepository);
sequenceMgr = EasyMock.createMock(SequenceMgr.class);
documentMgr.setSequenceMgr(sequenceMgr);
}
@After
public void tearDown() {
EasyMock.reset(documentRepository);
EasyMock.reset(privateDocumentRepository);
EasyMock.reset(documentFolderRepository);
EasyMock.reset(sequenceMgr);
}
}
| Fixed tests. | helianto-document/src/test/java/org/helianto/document/service/DocumentMgrImplTests.java | Fixed tests. | <ide><path>elianto-document/src/test/java/org/helianto/document/service/DocumentMgrImplTests.java
<ide>
<ide> package org.helianto.document.service;
<ide>
<add>import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertSame;
<ide>
<ide> import java.util.ArrayList;
<ide> import org.easymock.EasyMock;
<ide> import org.helianto.core.SequenceMgr;
<ide> import org.helianto.core.domain.Entity;
<add>import org.helianto.core.test.EntityTestSupport;
<ide> import org.helianto.document.domain.Document;
<ide> import org.helianto.document.domain.DocumentFolder;
<ide> import org.helianto.document.domain.PrivateDocument;
<ide>
<ide> @Test
<ide> public void storeDocument() {
<del> Document document= new Document();
<del> document.setSeries(new DocumentFolder());
<add> Entity entity = EntityTestSupport.createEntity();
<add> Document document= new Document(entity, "");
<add> document.setSeries(new DocumentFolder(entity, "KEY"));
<ide>
<ide> EasyMock.expect(documentRepository.save(document)).andReturn(document);
<add> EasyMock.expect(documentRepository.findLastNumber(entity, "KEY")).andReturn(new Long(1000));
<ide> documentRepository.flush();
<ide> EasyMock.replay(documentRepository);
<del> sequenceMgr.validateInternalNumber(document);
<del> EasyMock.replay(sequenceMgr);
<add>// sequenceMgr.validateInternalNumber(document);
<add>// EasyMock.replay(sequenceMgr);
<ide>
<ide> assertSame(document, documentMgr.storeDocument(document));
<ide> EasyMock.verify(documentRepository);
<del> EasyMock.verify(sequenceMgr);
<add> assertEquals(1001, document.getInternalNumber());
<add>// EasyMock.verify(sequenceMgr);
<ide> }
<ide>
<ide> @Test |
|
Java | unlicense | 4a52cdd71030d3ccc99d6c99c0d57f7b4b3f43e9 | 0 | janlep47/nurseHelper | package com.android.janice.nursehelper;
//import java.sql.Time;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import com.android.janice.nursehelper.data.ResidentContract;
import com.android.janice.nursehelper.utility.Utility;
import com.google.firebase.database.DatabaseReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
/**
* Created by janicerichards on 2/5/17.
*/
public class AssessmentItem {
private String roomNumber;
private String bloodPressure;
private String temperature;
private int pulse;
private int respiratoryRate;
private String edema;
private String edemaLocn;
private boolean edemaPitting;
private int pain;
private String significantFindings;
private long timestamp;
//boolean mAddProblem = false;
public final static int COL_ROOM_NUMBER = 0;
public final static int COL_BLOOD_PRESSURE = 1;
public final static int COL_TEMPERATURE = 2;
public final static int COL_PULSE = 3;
public final static int COL_RR = 4;
public final static int COL_EDEMA = 5;
public final static int COL_EDEMA_LOCN = 6;
public final static int COL_EDEMA_PITTING = 7;
public final static int COL_PAIN = 8;
public final static int COL_SIGNIFICANT_FINDINGS = 9;
public final static int COL_TIMESTAMP = 10;
public String getRoomNumber() { return roomNumber; }
public String getBloodPressure() {
return bloodPressure;
}
public String getTemperature() {
return temperature;
}
public int getPulse() { return pulse; }
public int getRespiratoryRate() { return respiratoryRate; }
public String getEdema() { return edema; }
public String getEdemaLocn() { return edemaLocn; }
public boolean getPitting() { return edemaPitting; }
public int getPain() { return pain; }
public String getSignificantFindings() { return significantFindings; }
public long getTimestamp() { return timestamp; }
public void setRoomNumber(String roomNumber) { this.roomNumber = roomNumber; }
public void setBloodPressure(String bp) {
this.bloodPressure = bp;
}
public void setTemperature(String temp) { this.temperature = temp; }
public void setPulse(int pulse) { this.pulse = pulse; }
public void setRespiratoryRate(int rr) { this.respiratoryRate = rr; }
public void setEdema(String edema) { this.edema = edema; }
public void setEdemaLocn(String edemaLocn) { this.edemaLocn = edemaLocn; }
public void setPitting(boolean pitting) { this.edemaPitting = pitting; }
public void setPain(int pain) { this.pain = pain; }
public void setSignificantFindings(String findings) { this.significantFindings = findings; }
public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
public AssessmentItem(Cursor cursor) {
roomNumber = cursor.getString(COL_ROOM_NUMBER);
bloodPressure = cursor.getString(COL_BLOOD_PRESSURE);
temperature = cursor.getString(COL_TEMPERATURE);
pulse = cursor.getInt(COL_PULSE);
respiratoryRate = cursor.getInt(COL_RR);
edema = cursor.getString(COL_EDEMA);
edemaLocn = cursor.getString(COL_EDEMA_LOCN);
short pitting = cursor.getShort(COL_EDEMA_PITTING);
edemaPitting = ((pitting == 0) ? false : true);
pain = cursor.getInt(COL_PAIN);
significantFindings = cursor.getString(COL_SIGNIFICANT_FINDINGS);
timestamp = cursor.getLong(COL_TIMESTAMP);
// formate the sql Time type into util Date type: (later)
//long time = cursor.getLong(COL_DATE_TIME);
//dateTime = Date.
}
public String getReadableTimestamp(Context context) {
//Date date = new Date(timestamp);
//String dateTimeFormat = context.getString(R.string.format_admin_date_time);
//String formattedDate = new SimpleDateFormat(dateTimeFormat, Locale.US).format(date);
//return formattedDate;
return Utility.getReadableTimestamp(context, timestamp);
}
public static void putInDummyData(Context context, DatabaseReference database, String userId) {
// First see if any data in already; if so, just return
Uri uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath("200").build();
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER},
null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
cursor.close();
return;
} else {
cursor.close();
}
}
// Add some (past) assessment data for room 200
String roomNumber = "200";
uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(roomNumber).build();
long time= System.currentTimeMillis();
// Assessment #1
ContentValues aValues = new ContentValues();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, "140/90");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, "98.5 F");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, 84);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, 15);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, "stage I");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, "RLE");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, true); // true
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, 2);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, "C/O stiffness in R ankle. \n"+
"Very slight headache.");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
Uri assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
new UpdateAssessmentTask(context, database, userId).execute(aValues);
// Med #2
aValues = new ContentValues();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, "145/92");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, "98.7 F");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, 92);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, 17);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, "0");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, "");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, false); // false
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, 6);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, "Pt. says moderate pain in lower back.");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
new UpdateAssessmentTask(context, database, userId).execute(aValues);
}
/*
public static void saveFirebaseAssessment(ContentValues aValues, DatabaseReference database, String userId) {
String assessmentId = database.child("users").child(userId).child("assessments").push().getKey();
ArrayList<String> keys = new ArrayList<String>(aValues.keySet());
for (int i = 0; i < keys.size(); i++) {
Object value = aValues.get(keys.get(i));
database.child("users").child(userId).child("assessments").child(assessmentId).child(keys.get(i)).setValue(value);
}
}
*/
// Later, format the values...
public static void saveAssessment(Context context, String roomNumber, int systolicBP, int diastolicBP, float temp,
int pulse, int rr, String edema, String edemaLocn, boolean edemaPitting,
int pain, String findings,
DatabaseReference database, String userId) {
Uri uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(roomNumber).build();
ContentValues aValues = new ContentValues();
long time = System.currentTimeMillis();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, String.valueOf(systolicBP)+"/"+
String.valueOf(diastolicBP));
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, String.valueOf(temp));
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, pulse);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, rr);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, edema);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, edemaLocn);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, edemaPitting);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, pain);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, findings);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
Uri assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
UpdateAssessmentTask updateAssessmentTask = new UpdateAssessmentTask(context,database,userId);
updateAssessmentTask.execute(aValues);
}
private static class UpdateAssessmentTask extends AsyncTask<ContentValues, Void, Void> {
protected Context context;
protected DatabaseReference database;
protected String userId;
public UpdateAssessmentTask(Context context, DatabaseReference database, String userId) {
this.context = context;
this.database = database;
this.userId = userId;
}
@Override
protected Void doInBackground(ContentValues... params) {
ContentValues assessmentValues = params[0];
String assessmentId = database.child("users").child(userId).child("assessments").push().getKey();
ArrayList<String> keys = new ArrayList<String>(assessmentValues.keySet());
for (int i = 0; i < keys.size(); i++) {
Object value = assessmentValues.get(keys.get(i));
database.child("users").child(userId).child("assessments").child(assessmentId).child(keys.get(i)).setValue(value);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// If added successfully, end this activity, and go back to the calling activity:
//if (result.intValue() == 0) mActivity.finish();
//else {
// Log.e(LOG_TAG," DIDN'T add OK!! --- should we put up a dialog box here?...");
// mAddProblem = true;
//}
//mLoadingPanel.setVisibility(View.GONE);
//super.onPostExecute(result);
}
}
}
| app/src/main/java/com/android/janice/nursehelper/AssessmentItem.java | package com.android.janice.nursehelper;
//import java.sql.Time;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import com.android.janice.nursehelper.data.ResidentContract;
import com.google.firebase.database.DatabaseReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
/**
* Created by janicerichards on 2/5/17.
*/
public class AssessmentItem {
private String roomNumber;
private String bloodPressure;
private String temperature;
private int pulse;
private int respiratoryRate;
private String edema;
private String edemaLocn;
private boolean edemaPitting;
private int pain;
private String significantFindings;
private long timestamp;
//boolean mAddProblem = false;
public final static int COL_ROOM_NUMBER = 0;
public final static int COL_BLOOD_PRESSURE = 1;
public final static int COL_TEMPERATURE = 2;
public final static int COL_PULSE = 3;
public final static int COL_RR = 4;
public final static int COL_EDEMA = 5;
public final static int COL_EDEMA_LOCN = 6;
public final static int COL_EDEMA_PITTING = 7;
public final static int COL_PAIN = 8;
public final static int COL_SIGNIFICANT_FINDINGS = 9;
public final static int COL_TIMESTAMP = 10;
public String getRoomNumber() { return roomNumber; }
public String getBloodPressure() {
return bloodPressure;
}
public String getTemperature() {
return temperature;
}
public int getPulse() { return pulse; }
public int getRespiratoryRate() { return respiratoryRate; }
public String getEdema() { return edema; }
public String getEdemaLocn() { return edemaLocn; }
public boolean getPitting() { return edemaPitting; }
public int getPain() { return pain; }
public String getSignificantFindings() { return significantFindings; }
public long getTimestamp() { return timestamp; }
public void setRoomNumber(String roomNumber) { this.roomNumber = roomNumber; }
public void setBloodPressure(String bp) {
this.bloodPressure = bp;
}
public void setTemperature(String temp) { this.temperature = temp; }
public void setPulse(int pulse) { this.pulse = pulse; }
public void setRespiratoryRate(int rr) { this.respiratoryRate = rr; }
public void setEdema(String edema) { this.edema = edema; }
public void setEdemaLocn(String edemaLocn) { this.edemaLocn = edemaLocn; }
public void setPitting(boolean pitting) { this.edemaPitting = pitting; }
public void setPain(int pain) { this.pain = pain; }
public void setSignificantFindings(String findings) { this.significantFindings = findings; }
public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
public AssessmentItem(Cursor cursor) {
roomNumber = cursor.getString(COL_ROOM_NUMBER);
bloodPressure = cursor.getString(COL_BLOOD_PRESSURE);
temperature = cursor.getString(COL_TEMPERATURE);
pulse = cursor.getInt(COL_PULSE);
respiratoryRate = cursor.getInt(COL_RR);
edema = cursor.getString(COL_EDEMA);
edemaLocn = cursor.getString(COL_EDEMA_LOCN);
short pitting = cursor.getShort(COL_EDEMA_PITTING);
edemaPitting = ((pitting == 0) ? false : true);
pain = cursor.getInt(COL_PAIN);
significantFindings = cursor.getString(COL_SIGNIFICANT_FINDINGS);
timestamp = cursor.getLong(COL_TIMESTAMP);
// formate the sql Time type into util Date type: (later)
//long time = cursor.getLong(COL_DATE_TIME);
//dateTime = Date.
}
public String getReadableTimestamp(Context context) {
Date date = new Date(timestamp);
String dateTimeFormat = context.getString(R.string.format_admin_date_time);
//String formattedDate = new SimpleDateFormat("MM-dd-YY HH:mm:ss").format(date);
String formattedDate = new SimpleDateFormat(dateTimeFormat, Locale.US).format(date);
return formattedDate;
}
public static void putInDummyData(Context context, DatabaseReference database, String userId) {
// First see if any data in already; if so, just return
Uri uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath("200").build();
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER},
null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
cursor.close();
return;
} else {
cursor.close();
}
}
// Add some (past) assessment data for room 200
String roomNumber = "200";
uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(roomNumber).build();
long time= System.currentTimeMillis();
// Assessment #1
ContentValues aValues = new ContentValues();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, "140/90");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, "98.5 F");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, 84);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, 15);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, "stage I");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, "RLE");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, true); // true
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, 2);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, "C/O stiffness in R ankle. \n"+
"Very slight headache.");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
Uri assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
new UpdateAssessmentTask(context, database, userId).execute(aValues);
// Med #2
aValues = new ContentValues();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, "145/92");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, "98.7 F");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, 92);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, 17);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, "0");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, "");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, false); // false
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, 6);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, "Pt. says moderate pain in lower back.");
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
new UpdateAssessmentTask(context, database, userId).execute(aValues);
}
/*
public static void saveFirebaseAssessment(ContentValues aValues, DatabaseReference database, String userId) {
String assessmentId = database.child("users").child(userId).child("assessments").push().getKey();
ArrayList<String> keys = new ArrayList<String>(aValues.keySet());
for (int i = 0; i < keys.size(); i++) {
Object value = aValues.get(keys.get(i));
database.child("users").child(userId).child("assessments").child(assessmentId).child(keys.get(i)).setValue(value);
}
}
*/
// Later, format the values...
public static void saveAssessment(Context context, String roomNumber, int systolicBP, int diastolicBP, float temp,
int pulse, int rr, String edema, String edemaLocn, boolean edemaPitting,
int pain, String findings,
DatabaseReference database, String userId) {
Uri uri = ResidentContract.AssessmentEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(roomNumber).build();
ContentValues aValues = new ContentValues();
long time = System.currentTimeMillis();
aValues.put(ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER, roomNumber);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE, String.valueOf(systolicBP)+"/"+
String.valueOf(diastolicBP));
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE, String.valueOf(temp));
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PULSE, pulse);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_RR, rr);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA, edema);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_LOCN, edemaLocn);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_EDEMA_PITTING, edemaPitting);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_PAIN, pain);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS, findings);
aValues.put(ResidentContract.AssessmentEntry.COLUMN_TIME, time);
Uri assessmentUri = context.getContentResolver().insert(uri, aValues);
//saveFirebaseAssessment(aValues, database, userId);
UpdateAssessmentTask updateAssessmentTask = new UpdateAssessmentTask(context,database,userId);
updateAssessmentTask.execute(aValues);
}
private static class UpdateAssessmentTask extends AsyncTask<ContentValues, Void, Void> {
protected Context context;
protected DatabaseReference database;
protected String userId;
public UpdateAssessmentTask(Context context, DatabaseReference database, String userId) {
this.context = context;
this.database = database;
this.userId = userId;
}
@Override
protected Void doInBackground(ContentValues... params) {
ContentValues assessmentValues = params[0];
String assessmentId = database.child("users").child(userId).child("assessments").push().getKey();
ArrayList<String> keys = new ArrayList<String>(assessmentValues.keySet());
for (int i = 0; i < keys.size(); i++) {
Object value = assessmentValues.get(keys.get(i));
database.child("users").child(userId).child("assessments").child(assessmentId).child(keys.get(i)).setValue(value);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// If added successfully, end this activity, and go back to the calling activity:
//if (result.intValue() == 0) mActivity.finish();
//else {
// Log.e(LOG_TAG," DIDN'T add OK!! --- should we put up a dialog box here?...");
// mAddProblem = true;
//}
//mLoadingPanel.setVisibility(View.GONE);
//super.onPostExecute(result);
}
}
}
| Fix time display on Past Assessments screen - change from military to AM/PM view, to be consistent with other times
| app/src/main/java/com/android/janice/nursehelper/AssessmentItem.java | Fix time display on Past Assessments screen - change from military to AM/PM view, to be consistent with other times | <ide><path>pp/src/main/java/com/android/janice/nursehelper/AssessmentItem.java
<ide> import android.os.AsyncTask;
<ide>
<ide> import com.android.janice.nursehelper.data.ResidentContract;
<add>import com.android.janice.nursehelper.utility.Utility;
<ide> import com.google.firebase.database.DatabaseReference;
<ide>
<ide> import java.text.SimpleDateFormat;
<ide>
<ide>
<ide> public String getReadableTimestamp(Context context) {
<del> Date date = new Date(timestamp);
<del> String dateTimeFormat = context.getString(R.string.format_admin_date_time);
<del> //String formattedDate = new SimpleDateFormat("MM-dd-YY HH:mm:ss").format(date);
<del> String formattedDate = new SimpleDateFormat(dateTimeFormat, Locale.US).format(date);
<del> return formattedDate;
<add> //Date date = new Date(timestamp);
<add> //String dateTimeFormat = context.getString(R.string.format_admin_date_time);
<add> //String formattedDate = new SimpleDateFormat(dateTimeFormat, Locale.US).format(date);
<add> //return formattedDate;
<add> return Utility.getReadableTimestamp(context, timestamp);
<ide> }
<ide>
<ide> |
|
Java | mit | 5a4138da0f36624b818f2b73661008e7423e92ae | 0 | gmessner/gitlab4j-api,patrikbeno/gitlab-api | package com.messners.gitlab.api;
import java.util.List;
import com.messners.gitlab.api.models.Branch;
import com.messners.gitlab.api.models.Tag;
import com.messners.gitlab.api.models.TreeItem;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.representation.Form;
/**
* This class provides an entry point to all the GitLab API repository calls.
*
* @author Greg Messner <[email protected]>
*/
public class RepositoryApi extends AbstractApi {
public RepositoryApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* GET /projects/:id/repository/branches
*
* @param projectId
* @return the list of repository branches for mthe specified project ID
* @throws GitLabApiException
*/
public List<Branch> getBranches (Integer projectId) throws GitLabApiException {
ClientResponse response = get(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches");
return (response.getEntity(new GenericType<List<Branch>>() {}));
}
/**
* Get a single project repository branch.
*
* GET /projects/:id/repository/branches/:branch
*
* @param projectId
* @param branchName
* @return the branch info for the specified project ID/branch name pair
* @throws GitLabApiException
*/
public Branch getBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = get(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName);
return (response.getEntity(Branch.class));
}
/**
* Creates a branch for the project. Support as of version 6.8.x
*
* POST /projects/:id/repository/branches
*
* @param projectId the project to create the branch for
* @param branchName the name of the branch to create
* @param ref Source to create the branch from, can be an existing branch, tag or commit SHA
* @return the branch info for the created branch
* @throws GitLabApiException
*/
public Branch createBranch (Integer projectId, String branchName, String ref) throws GitLabApiException {
Form formData = new Form();
formData.add("branch_name ", branchName);
formData.add("ref ", ref);
ClientResponse response = post(ClientResponse.Status.OK, formData, "projects", projectId, "repository", "branches");
return (response.getEntity(Branch.class));
}
/**
* Protects a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/protect
*
* @param projectId
* @param branchName
* @return the branch info for the protected branch
* @throws GitLabApiException
*/
public Branch protectBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName, "protect");
return (response.getEntity(Branch.class));
}
/**
* Unprotects a single project repository branch. This is an idempotent function, unprotecting an
* already unprotected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/unprotect
*
* @param projectId
* @param branchName
* @return the branch info for the unprotected branch
* @throws GitLabApiException
*/
public Branch unprotectBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName, "unprotect");
return (response.getEntity(Branch.class));
}
/**
* Get a list of repository tags from a project, sorted by name in reverse alphabetical order.
*
* GET /projects/:id/repository/tags
*
* @param projectId
* @return the list of tags for the specified project ID
* @throws GitLabApiException
*/
public List<Tag> getTags (Integer projectId) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "tags");
return (response.getEntity(new GenericType<List<Tag>>() {}));
}
/**
* Get a list of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* @param projectId
* @return a tree with the diurectories and files of a project
* @throws GitLabApiException
*/
public List<TreeItem> getTree (Integer projectId) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "tree");
return (response.getEntity(new GenericType<List<TreeItem>>() {}));
}
/**
* Get the raw file contents for a file by commit sha and path.
*
* GET /projects/:id/repository/blobs/:sha
*
* @param projectId
* @param commitOrBranchName
* @return a string with the file content for the specified file
* @throws GitLabApiException
*/
public String getRawFileContent (Integer projectId, String commitOrBranchName, String filepath) throws GitLabApiException {
Form formData = new Form();
addFormParam(formData, "filepath", filepath, true);
ClientResponse response = get(ClientResponse.Status.OK, formData, "projects", projectId, "repository", "blobs", commitOrBranchName);
return (response.getEntity(String.class));
}
}
| src/main/java/com/messners/gitlab/api/RepositoryApi.java | package com.messners.gitlab.api;
import java.util.List;
import com.messners.gitlab.api.models.Branch;
import com.messners.gitlab.api.models.Tag;
import com.messners.gitlab.api.models.TreeItem;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.representation.Form;
/**
* This class provides an entry point to all the GitLab API repository calls.
*
* @author Greg Messner <[email protected]>
*/
public class RepositoryApi extends AbstractApi {
public RepositoryApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* GET /projects/:id/repository/branches
*
* @param projectId
* @return the list of repository branches for mthe specified project ID
* @throws GitLabApiException
*/
public List<Branch> getBranches (Integer projectId) throws GitLabApiException {
ClientResponse response = get(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches");
return (response.getEntity(new GenericType<List<Branch>>() {}));
}
/**
* Get a single project repository branch.
*
* GET /projects/:id/repository/branches/:branch
*
* @param projectId
* @param branchName
* @return the branch info for the specified project ID/branch name pair
* @throws GitLabApiException
*/
public Branch getBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = get(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName);
return (response.getEntity(Branch.class));
}
/**
* Protects a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/protect
*
* @param projectId
* @param branchName
* @return the branch info for the protected branch
* @throws GitLabApiException
*/
public Branch protectBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName, "protect");
return (response.getEntity(Branch.class));
}
/**
* Unprotects a single project repository branch. This is an idempotent function, unprotecting an
* already unprotected repository branch will not produce an error.
*
* PUT /projects/:id/repository/branches/:branch/unprotect
*
* @param projectId
* @param branchName
* @return the branch info for the unprotected branch
* @throws GitLabApiException
*/
public Branch unprotectBranch (Integer projectId, String branchName) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName, "unprotect");
return (response.getEntity(Branch.class));
}
/**
* Get a list of repository tags from a project, sorted by name in reverse alphabetical order.
*
* GET /projects/:id/repository/tags
*
* @param projectId
* @return the list of tags for the specified project ID
* @throws GitLabApiException
*/
public List<Tag> getTags (Integer projectId) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "tags");
return (response.getEntity(new GenericType<List<Tag>>() {}));
}
/**
* Get a list of repository files and directories in a project.
*
* GET /projects/:id/repository/tree
*
* @param projectId
* @return a tree with the diurectories and files of a project
* @throws GitLabApiException
*/
public List<TreeItem> getTree (Integer projectId) throws GitLabApiException {
ClientResponse response = put(ClientResponse.Status.OK, null, "projects", projectId, "repository", "tree");
return (response.getEntity(new GenericType<List<TreeItem>>() {}));
}
/**
* Get the raw file contents for a file by commit sha and path.
*
* GET /projects/:id/repository/blobs/:sha
*
* @param projectId
* @param commitOrBranchName
* @return a string with the file content for the specified file
* @throws GitLabApiException
*/
public String getRawFileContent (Integer projectId, String commitOrBranchName, String filepath) throws GitLabApiException {
Form formData = new Form();
addFormParam(formData, "filepath", filepath, true);
ClientResponse response = get(ClientResponse.Status.OK, formData, "projects", projectId, "repository", "blobs", commitOrBranchName);
return (response.getEntity(String.class));
}
}
| Added createBranch support for 6.8.x
| src/main/java/com/messners/gitlab/api/RepositoryApi.java | Added createBranch support for 6.8.x | <ide><path>rc/main/java/com/messners/gitlab/api/RepositoryApi.java
<ide> return (response.getEntity(new GenericType<List<Branch>>() {}));
<ide> }
<ide>
<del>
<add>
<ide> /**
<ide> * Get a single project repository branch.
<ide> *
<ide> * @return the branch info for the specified project ID/branch name pair
<ide> * @throws GitLabApiException
<ide> */
<del> public Branch getBranch (Integer projectId, String branchName) throws GitLabApiException {
<add> public Branch getBranch (Integer projectId, String branchName) throws GitLabApiException {
<ide> ClientResponse response = get(ClientResponse.Status.OK, null, "projects", projectId, "repository", "branches", branchName);
<ide> return (response.getEntity(Branch.class));
<ide> }
<add>
<add>
<add> /**
<add> * Creates a branch for the project. Support as of version 6.8.x
<add> *
<add> * POST /projects/:id/repository/branches
<add> *
<add> * @param projectId the project to create the branch for
<add> * @param branchName the name of the branch to create
<add> * @param ref Source to create the branch from, can be an existing branch, tag or commit SHA
<add> * @return the branch info for the created branch
<add> * @throws GitLabApiException
<add> */
<add> public Branch createBranch (Integer projectId, String branchName, String ref) throws GitLabApiException {
<add> Form formData = new Form();
<add> formData.add("branch_name ", branchName);
<add> formData.add("ref ", ref);
<add> ClientResponse response = post(ClientResponse.Status.OK, formData, "projects", projectId, "repository", "branches");
<add> return (response.getEntity(Branch.class));
<add> }
<ide>
<ide>
<ide> /** |
|
Java | lgpl-2.1 | b57b3aa46a3577688105023c9cf6d704935d3061 | 0 | maddingo/checkstyle,maddingo/checkstyle,lhanson/checkstyle,lhanson/checkstyle | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.LineNumberReader;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
/**
* Represents the configuration that checkstyle uses when checking. The
* configuration is Serializable, however the ClassLoader configuration is
* lost.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
**/
public class Configuration
implements Serializable
{
////////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////////
/** the set of illegal imports (comma separated package prefixes) **/
private static final String ILLEGAL_IMPORTS = "sun";
/** the set of illegal instantiations (comma separated class names) **/
private static final String ILLEGAL_INSTANTIATIONS = "";
/** pattern defaults **/
private static final Map PATTERN_DEFAULTS = new HashMap();
static {
PATTERN_DEFAULTS.put(Defn.TODO_PATTERN_PROP, "TODO:");
PATTERN_DEFAULTS.put(Defn.PARAMETER_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.STATIC_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.CONST_PATTERN_PROP, "^[A-Z](_?[A-Z0-9]+)*$");
PATTERN_DEFAULTS.put(Defn.MEMBER_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.PUBLIC_MEMBER_PATTERN_PROP,
"^f[A-Z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.TYPE_PATTERN_PROP, "^[A-Z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.LOCAL_VAR_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.LOCAL_FINAL_VAR_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.METHOD_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP, "^$");
}
////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////
/** visibility scope where Javadoc is checked **/
private Scope mJavadocScope = Scope.PRIVATE;
/** the header lines to check for **/
private transient String[] mHeaderLines = {};
/**
* class loader to resolve classes with. Needs to be transient as unable
* to persist.
**/
private transient ClassLoader mLoader =
Thread.currentThread().getContextClassLoader();
/** the root directory for relative paths **/
private File mRootDir;
/** the lines in the header to ignore */
private TreeSet mHeaderIgnoreLineNo = new TreeSet();
/** where to place right curlies **/
private RightCurlyOption mRCurly = RightCurlyOption.SAME;
/** how to pad parenthesis **/
private PadOption mParenPadOption = PadOption.NOSPACE;
/** how to wrap operators **/
private WrapOpOption mWrapOpOption = WrapOpOption.NL;
/** set of boolean properties **/
private final Set mBooleanProps = new HashSet();
/** map of Set properties **/
private final Map mStringSetProps = new HashMap();
{
setStringSetProperty(Defn.ILLEGAL_IMPORTS_PROP, ILLEGAL_IMPORTS);
setStringSetProperty(Defn.ILLEGAL_INSTANTIATIONS_PROP,
ILLEGAL_INSTANTIATIONS);
}
/** map of int properties **/
private final Map mIntProps = new HashMap();
{
mIntProps.put(Defn.MAX_LINE_LENGTH_PROP, new Integer(80));
mIntProps.put(Defn.MAX_METHOD_LENGTH_PROP, new Integer(150));
mIntProps.put(Defn.MAX_CONSTRUCTOR_LENGTH_PROP, new Integer(150));
mIntProps.put(Defn.MAX_FILE_LENGTH_PROP, new Integer(2000));
mIntProps.put(Defn.MAX_PARAMETERS_PROP, new Integer(7));
mIntProps.put(Defn.TAB_WIDTH_PROP, new Integer(8));
}
/** map of all the pattern properties **/
private final Map mPatterns = new HashMap();
/** map of all the corresponding RE objects for pattern properties **/
private transient Map mRegexps = new HashMap();
/** map of all the BlockOption properties **/
private final Map mBlockProps = new HashMap();
{
mBlockProps.put(Defn.TRY_BLOCK_PROP, BlockOption.STMT);
mBlockProps.put(Defn.CATCH_BLOCK_PROP, BlockOption.TEXT);
mBlockProps.put(Defn.FINALLY_BLOCK_PROP, BlockOption.STMT);
}
/** map of all the LeftCurlyOption properties **/
private final Map mLCurliesProps = new HashMap();
{
mLCurliesProps.put(Defn.LCURLY_METHOD_PROP, LeftCurlyOption.EOL);
mLCurliesProps.put(Defn.LCURLY_TYPE_PROP, LeftCurlyOption.EOL);
mLCurliesProps.put(Defn.LCURLY_OTHER_PROP, LeftCurlyOption.EOL);
}
/** map of all String properties - by default are null **/
private final Map mStringProps = new HashMap();
{
mStringProps.put(Defn.LOCALE_LANGUAGE_PROP,
Locale.getDefault().getLanguage());
mStringProps.put(Defn.LOCALE_COUNTRY_PROP,
Locale.getDefault().getCountry());
}
////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////
/**
* Creates a new <code>Configuration</code> instance.
*
* @param aProps where to extract configuration parameters from
* @param aLog where to log errors to
* @throws RESyntaxException if an error occurs
* @throws FileNotFoundException if an error occurs
* @throws IOException if an error occurs
*/
public Configuration(Properties aProps, PrintStream aLog)
throws RESyntaxException, FileNotFoundException, IOException
{
// Init the special properties
setHeaderIgnoreLines(aProps.getProperty(Defn.HEADER_IGNORE_LINE_PROP));
setRCurly(getRightCurlyOptionProperty(
aProps, Defn.RCURLY_PROP, RightCurlyOption.SAME, aLog));
setJavadocScope(
Scope.getInstance(aProps.getProperty(Defn.JAVADOC_CHECKSCOPE_PROP,
Scope.PRIVATE.getName())));
setParenPadOption(getPadOptionProperty(aProps,
Defn.PAREN_PAD_PROP,
PadOption.NOSPACE,
aLog));
setWrapOpOption(getWrapOpOptionProperty(aProps,
Defn.WRAP_OP_PROP,
WrapOpOption.NL,
aLog));
// Initialise the general properties
for (int i = 0; i < Defn.ALL_BOOLEAN_PROPS.length; i++) {
setBooleanProperty(aProps, Defn.ALL_BOOLEAN_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
setPatternProperty(aProps, Defn.ALL_PATTERN_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_INT_PROPS.length; i++) {
setIntProperty(aProps, aLog, Defn.ALL_INT_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_BLOCK_PROPS.length; i++) {
setBlockOptionProperty(aProps, Defn.ALL_BLOCK_PROPS[i], aLog);
}
for (int i = 0; i < Defn.ALL_STRING_PROPS.length; i++) {
setStringProperty(aProps, Defn.ALL_STRING_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_LCURLY_PROPS.length; i++) {
setLeftCurlyOptionProperty(aProps, Defn.ALL_LCURLY_PROPS[i], aLog);
}
for (int i = 0; i < Defn.ALL_STRING_SET_PROPS.length; i++) {
setStringSetProperty(aProps, Defn.ALL_STRING_SET_PROPS[i]);
}
}
/**
* Creates a new <code>Configuration</code> instance.
* @throws IllegalStateException if an error occurs
*/
public Configuration()
{
try {
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
setPatternProperty(
Defn.ALL_PATTERN_PROPS[i],
(String) PATTERN_DEFAULTS.get(Defn.ALL_PATTERN_PROPS[i]));
}
}
catch (RESyntaxException ex) {
ex.printStackTrace();
throw new IllegalStateException(ex.getMessage());
}
}
/**
* Extend default deserialization to initialize the RE member variables.
*
* @param aStream the ObjectInputStream that contains the serialized data
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
*/
private void readObject(ObjectInputStream aStream)
throws IOException, ClassNotFoundException
{
// initialize the serialized fields
aStream.defaultReadObject();
// initialize the transient fields
mLoader = Thread.currentThread().getContextClassLoader();
mRegexps = new HashMap();
// load the file to re-read the lines
loadFiles();
try {
// Loop on the patterns creating the RE's
final Iterator keys = mPatterns.keySet().iterator();
while (keys.hasNext()) {
final String k = (String) keys.next();
mRegexps.put(k, new RE((String) mPatterns.get(k)));
}
}
catch (RESyntaxException ex) {
// This should never happen, as the serialized regexp patterns
// somehow must have passed a setPattern() method.
throw new InvalidObjectException(
"invalid regular expression syntax");
}
}
/**
* Loads the files specified by properties.
* @throws IOException if an error occurs
*/
void loadFiles()
throws IOException
{
loadHeaderFile();
}
////////////////////////////////////////////////////////////////////////////
// Setters
////////////////////////////////////////////////////////////////////////////
/**
* Set the root directory for files.
* @param aRoot the root directory
*/
public void setRootDir(File aRoot)
{
if ((aRoot == null) || !aRoot.isDirectory() || !aRoot.isAbsolute()) {
throw new IllegalArgumentException("Invalid root directory");
}
mRootDir = aRoot;
}
/**
* Set the class loader for locating classes.
* @param aLoader the class loader
*/
public void setClassLoader(ClassLoader aLoader)
{
mLoader = aLoader;
}
////////////////////////////////////////////////////////////////////////////
// Getters
////////////////////////////////////////////////////////////////////////////
/** @return a Properties object representing the current configuration.
* The returned object can be used to recreate the configuration.
* Tip: used on a default object returns all the default objects. */
public Properties getProperties()
{
final Properties retVal = new Properties();
Utils.addSetString(retVal, Defn.HEADER_IGNORE_LINE_PROP,
mHeaderIgnoreLineNo);
Utils.addObjectString(retVal, Defn.RCURLY_PROP, mRCurly.toString());
Utils.addObjectString(retVal, Defn.JAVADOC_CHECKSCOPE_PROP,
mJavadocScope.getName());
Utils.addObjectString(retVal, Defn.PAREN_PAD_PROP,
mParenPadOption.toString());
Utils.addObjectString(retVal, Defn.WRAP_OP_PROP,
mWrapOpOption.toString());
for (int i = 0; i < Defn.ALL_BOOLEAN_PROPS.length; i++) {
final String key = Defn.ALL_BOOLEAN_PROPS[i];
retVal.put(key, String.valueOf(getBooleanProperty(key)));
}
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
final String key = Defn.ALL_PATTERN_PROPS[i];
Utils.addObjectString(retVal, key, getPatternProperty(key));
}
for (int i = 0; i < Defn.ALL_INT_PROPS.length; i++) {
final String key = Defn.ALL_INT_PROPS[i];
Utils.addObjectString(retVal, key,
Integer.toString(getIntProperty(key)));
}
for (int i = 0; i < Defn.ALL_BLOCK_PROPS.length; i++) {
final String key = Defn.ALL_BLOCK_PROPS[i];
Utils.addObjectString(retVal, key, getBlockOptionProperty(key));
}
for (int i = 0; i < Defn.ALL_STRING_PROPS.length; i++) {
final String key = Defn.ALL_STRING_PROPS[i];
Utils.addObjectString(retVal, key, getStringProperty(key));
}
for (int i = 0; i < Defn.ALL_LCURLY_PROPS.length; i++) {
final String key = Defn.ALL_LCURLY_PROPS[i];
Utils.addObjectString(retVal, key, getLeftCurlyOptionProperty(key));
}
for (int i = 0; i < Defn.ALL_STRING_SET_PROPS.length; i++) {
final String key = Defn.ALL_STRING_SET_PROPS[i];
Utils.addSetString(retVal, key, getStringSetProperty(key));
}
return retVal;
}
/** @return the class loader **/
ClassLoader getClassLoader()
{
return mLoader;
}
/** @return locale language to report messages **/
String getLocaleLanguage()
{
return getStringProperty(Defn.LOCALE_LANGUAGE_PROP);
}
/** @return locale country to report messages **/
String getLocaleCountry()
{
return getStringProperty(Defn.LOCALE_COUNTRY_PROP);
}
/** @return pattern to match to-do lines **/
String getTodoPat()
{
return getPatternProperty(Defn.TODO_PATTERN_PROP);
}
/** @return regexp to match to-do lines **/
RE getTodoRegexp()
{
return getRegexpProperty(Defn.TODO_PATTERN_PROP);
}
/** @return pattern to match parameters **/
String getParamPat()
{
return getPatternProperty(Defn.PARAMETER_PATTERN_PROP);
}
/** @return regexp to match parameters **/
RE getParamRegexp()
{
return getRegexpProperty(Defn.PARAMETER_PATTERN_PROP);
}
/** @return pattern to match static variables **/
String getStaticPat()
{
return getPatternProperty(Defn.STATIC_PATTERN_PROP);
}
/** @return regexp to match static variables **/
RE getStaticRegexp()
{
return getRegexpProperty(Defn.STATIC_PATTERN_PROP);
}
/** @return pattern to match static final variables **/
String getStaticFinalPat()
{
return getPatternProperty(Defn.CONST_PATTERN_PROP);
}
/** @return regexp to match static final variables **/
RE getStaticFinalRegexp()
{
return getRegexpProperty(Defn.CONST_PATTERN_PROP);
}
/** @return pattern to match member variables **/
String getMemberPat()
{
return getPatternProperty(Defn.MEMBER_PATTERN_PROP);
}
/** @return regexp to match member variables **/
RE getMemberRegexp()
{
return getRegexpProperty(Defn.MEMBER_PATTERN_PROP);
}
/** @return pattern to match public member variables **/
String getPublicMemberPat()
{
return getPatternProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
}
/** @return regexp to match public member variables **/
RE getPublicMemberRegexp()
{
return getRegexpProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
}
/** @return pattern to match type names **/
String getTypePat()
{
return getPatternProperty(Defn.TYPE_PATTERN_PROP);
}
/** @return regexp to match type names **/
RE getTypeRegexp()
{
return getRegexpProperty(Defn.TYPE_PATTERN_PROP);
}
/** @return pattern to match local variables **/
String getLocalVarPat()
{
return getPatternProperty(Defn.LOCAL_VAR_PATTERN_PROP);
}
/** @return regexp to match local variables **/
RE getLocalVarRegexp()
{
return getRegexpProperty(Defn.LOCAL_VAR_PATTERN_PROP);
}
/** @return pattern to match local final variables **/
String getLocalFinalVarPat()
{
return getPatternProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
}
/** @return regexp to match local final variables **/
RE getLocalFinalVarRegexp()
{
return getRegexpProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
}
/** @return pattern to match method names **/
String getMethodPat()
{
return getPatternProperty(Defn.METHOD_PATTERN_PROP);
}
/** @return regexp to match method names **/
RE getMethodRegexp()
{
return getRegexpProperty(Defn.METHOD_PATTERN_PROP);
}
/** @return the maximum line length **/
int getMaxLineLength()
{
return getIntProperty(Defn.MAX_LINE_LENGTH_PROP);
}
/** @return the maximum method length **/
int getMaxMethodLength()
{
return getIntProperty(Defn.MAX_METHOD_LENGTH_PROP);
}
/** @return the maximum number parameters**/
int getMaxParameters()
{
return getIntProperty(Defn.MAX_PARAMETERS_PROP);
}
/** @return the maximum constructor length **/
int getMaxConstructorLength()
{
return getIntProperty(Defn.MAX_CONSTRUCTOR_LENGTH_PROP);
}
/** @return the maximum file length **/
int getMaxFileLength()
{
return getIntProperty(Defn.MAX_FILE_LENGTH_PROP);
}
/** @return whether to allow tabs **/
boolean isAllowTabs()
{
return getBooleanProperty(Defn.ALLOW_TABS_PROP);
}
/** @return distance between tab stops */
int getTabWidth()
{
return getIntProperty(Defn.TAB_WIDTH_PROP);
}
/** @return whether to allow protected data **/
boolean isAllowProtected()
{
return getBooleanProperty(Defn.ALLOW_PROTECTED_PROP);
}
/** @return whether to allow package data **/
boolean isAllowPackage()
{
return getBooleanProperty(Defn.ALLOW_PACKAGE_PROP);
}
/** @return whether to allow having no author tag **/
boolean isAllowNoAuthor()
{
return getBooleanProperty(Defn.ALLOW_NO_AUTHOR_PROP);
}
/** @return whether to require having version tag */
boolean isRequireVersion()
{
return getBooleanProperty(Defn.REQUIRE_VERSION_PROP);
}
/** @return visibility scope where Javadoc is checked **/
Scope getJavadocScope()
{
return mJavadocScope;
}
/** @return whether javadoc package documentation is required */
boolean isRequirePackageHtml()
{
return getBooleanProperty(Defn.REQUIRE_PACKAGE_HTML_PROP);
}
/** @return whether to process imports **/
boolean isIgnoreImports()
{
return getBooleanProperty(Defn.IGNORE_IMPORTS_PROP);
}
/** @return whether to check unused @throws **/
boolean isCheckUnusedThrows()
{
return getBooleanProperty(Defn.JAVADOC_CHECK_UNUSED_THROWS_PROP);
}
/** @return Set of pkg prefixes that are illegal in import statements */
Set getIllegalImports()
{
return getStringSetProperty(Defn.ILLEGAL_IMPORTS_PROP);
}
/** @return Set of classes where calling a constructor is illegal */
Set getIllegalInstantiations()
{
return getStringSetProperty(Defn.ILLEGAL_INSTANTIATIONS_PROP);
}
/** @return pattern to exclude from line lengh checking **/
String getIgnoreLineLengthPat()
{
return getPatternProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
}
/** @return regexp to exclude from line lengh checking **/
RE getIgnoreLineLengthRegexp()
{
return getRegexpProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
}
/** @return whether to ignore checks for whitespace **/
boolean isIgnoreWhitespace()
{
return getBooleanProperty(Defn.IGNORE_WHITESPACE_PROP);
}
/** @return whether to ignore checks for whitespace after casts **/
boolean isIgnoreCastWhitespace()
{
return getBooleanProperty(Defn.IGNORE_CAST_WHITESPACE_PROP);
}
/** @return whether to ignore checks for braces **/
boolean isIgnoreBraces()
{
return getBooleanProperty(Defn.IGNORE_BRACES_PROP);
}
/** @return whether to ignore long 'L' **/
boolean isIgnoreLongEll()
{
return getBooleanProperty(Defn.IGNORE_LONG_ELL_PROP);
}
/** @return whether to ignore 'public' keyword in interface definitions **/
boolean isIgnorePublicInInterface()
{
return getBooleanProperty(Defn.IGNORE_PUBLIC_IN_INTERFACE_PROP);
}
/** @return whether to ignore max line length for import statements **/
boolean isIgnoreImportLength()
{
return getBooleanProperty(Defn.IGNORE_IMPORT_LENGTH_PROP);
}
/** @return the header lines to check for **/
String[] getHeaderLines()
{
return mHeaderLines;
}
/** @return if lines in header file are regular expressions */
boolean getHeaderLinesRegexp()
{
return getBooleanProperty(Defn.HEADER_LINES_REGEXP_PROP);
}
/**
* @param aLineNo a line number
* @return if <code>aLineNo</code> is one of the ignored header lines.
*/
boolean isHeaderIgnoreLineNo(int aLineNo)
{
return mHeaderIgnoreLineNo.contains(new Integer(aLineNo));
}
/** @return the File of the cache file **/
String getCacheFile()
{
final String fname = getStringProperty(Defn.CACHE_FILE_PROP);
return (fname == null) ? null : getAbsoluteFilename(fname);
}
/**
* Sets a String Set property. It the aFrom String is parsed for Strings
* separated by ",".
*
* @param aName name of the property to set
* @param aFrom the String to parse
*/
private void setStringSetProperty(String aName, String aFrom)
{
final Set s = new TreeSet();
final StringTokenizer tok = new StringTokenizer(aFrom, ",");
while (tok.hasMoreTokens()) {
s.add(tok.nextToken());
}
mStringSetProps.put(aName, s);
}
/**
* @param aJavadocScope visibility scope where Javadoc is checked
*/
private void setJavadocScope(Scope aJavadocScope)
{
mJavadocScope = aJavadocScope;
}
/**
* Set the boolean property.
* @param aName name of the property. Should be defined in Defn.
* @param aTo the value to set
*/
private void setBooleanProperty(String aName, boolean aTo)
{
if (aTo) {
mBooleanProps.add(aName);
}
else {
mBooleanProps.remove(aName);
}
}
/**
* Set the String property.
* @param aName name of the property. Should be defined in Defn.
* @param aTo the value to set
*/
private void setStringProperty(String aName, String aTo)
{
mStringProps.put(aName, aTo);
}
/**
* Attempts to load the contents of a header file
* @throws FileNotFoundException if an error occurs
* @throws IOException if an error occurs
*/
private void loadHeaderFile()
throws FileNotFoundException, IOException
{
final String fname = getStringProperty(Defn.HEADER_FILE_PROP);
// Handle a missing property, or an empty one
if ((fname == null) || (fname.trim().length() == 0)) {
return;
}
// load the file
final LineNumberReader lnr =
new LineNumberReader(new FileReader(getAbsoluteFilename(fname)));
final ArrayList lines = new ArrayList();
while (true) {
final String l = lnr.readLine();
if (l == null) {
break;
}
lines.add(l);
}
mHeaderLines = (String[]) lines.toArray(new String[0]);
}
/**
* @return the absolute file name for a given filename. If the passed
* filename is absolute, then that is returned. If the setRootDir() was
* called, that is used to caluclate the absolute path. Otherise, the
* absolute path of the given filename is returned (this behaviour cannot
* be determined).
*
* @param aFilename the filename to make absolute
*/
private String getAbsoluteFilename(String aFilename)
{
File f = new File(aFilename);
if (!f.isAbsolute() && (mRootDir != null)) {
f = new File(mRootDir, aFilename);
}
return f.getAbsolutePath();
}
/**
* @param aList comma separated list of line numbers to ignore in header.
*/
private void setHeaderIgnoreLines(String aList)
{
mHeaderIgnoreLineNo.clear();
if (aList == null) {
return;
}
final StringTokenizer tokens = new StringTokenizer(aList, ",");
while (tokens.hasMoreTokens()) {
final String ignoreLine = tokens.nextToken();
mHeaderIgnoreLineNo.add(new Integer(ignoreLine));
}
}
/** @return the left curly placement option for methods **/
LeftCurlyOption getLCurlyMethod()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_METHOD_PROP);
}
/** @return the left curly placement option for types **/
LeftCurlyOption getLCurlyType()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_TYPE_PROP);
}
/** @return the left curly placement option for others **/
LeftCurlyOption getLCurlyOther()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_OTHER_PROP);
}
/** @return the right curly placement option **/
RightCurlyOption getRCurly()
{
return mRCurly;
}
/** @param aTo set the right curly placement option **/
private void setRCurly(RightCurlyOption aTo)
{
mRCurly = aTo;
}
/** @return the try block option **/
BlockOption getTryBlock()
{
return getBlockOptionProperty(Defn.TRY_BLOCK_PROP);
}
/** @return the catch block option **/
BlockOption getCatchBlock()
{
return getBlockOptionProperty(Defn.CATCH_BLOCK_PROP);
}
/** @return the finally block option **/
BlockOption getFinallyBlock()
{
return getBlockOptionProperty(Defn.FINALLY_BLOCK_PROP);
}
/** @return the parenthesis padding option **/
PadOption getParenPadOption()
{
return mParenPadOption;
}
/** @param aTo set the parenthesis option **/
private void setParenPadOption(PadOption aTo)
{
mParenPadOption = aTo;
}
/** @return the wrapping on operator option **/
WrapOpOption getWrapOpOption()
{
return mWrapOpOption;
}
/** @param aTo set the wrap on operator option **/
private void setWrapOpOption(WrapOpOption aTo)
{
mWrapOpOption = aTo;
}
/** @return the base directory **/
String getBasedir()
{
return getStringProperty(Defn.BASEDIR_PROP);
}
/**
* Set an integer property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setIntProperty(String aName, int aTo)
{
mIntProps.put(aName, new Integer(aTo));
}
/**
* Set an pattern property.
* @param aName name of the property to set
* @param aPat the value to set
* @throws RESyntaxException if an error occurs
*/
private void setPatternProperty(String aName, String aPat)
throws RESyntaxException
{
// Set the regexp first, incase cannot create the RE
mRegexps.put(aName, new RE(aPat));
mPatterns.put(aName, aPat);
}
/**
* Set an BlockOption property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setBlockOptionProperty(String aName, BlockOption aTo)
{
mBlockProps.put(aName, aTo);
}
/**
* Set an LeftCurlyOption property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setLeftCurlyOptionProperty(String aName, LeftCurlyOption aTo)
{
mLCurliesProps.put(aName, aTo);
}
////////////////////////////////////////////////////////////////////////////
// Private methods
////////////////////////////////////////////////////////////////////////////
/**
* @return the BlockOption for a specified property.
* @param aName name of the property to get
*/
private LeftCurlyOption getLeftCurlyOptionProperty(String aName)
{
return (LeftCurlyOption) mLCurliesProps.get(aName);
}
/**
* @return the BlockOption for a specified property.
* @param aName name of the property to get
*/
private BlockOption getBlockOptionProperty(String aName)
{
return (BlockOption) mBlockProps.get(aName);
}
/**
* Set the value of an pattern property. If the property is not defined
* then a default value is used.
* @param aProps the properties set to use
* @param aName the name of the property to parse
* @throws RESyntaxException if an error occurs
*/
private void setPatternProperty(Properties aProps, String aName)
throws RESyntaxException
{
setPatternProperty(
aName,
aProps.getProperty(aName, (String) PATTERN_DEFAULTS.get(aName)));
}
/**
* @return the pattern for specified property
* @param aName the name of the property
*/
private String getPatternProperty(String aName)
{
return (String) mPatterns.get(aName);
}
/**
* @return the regexp for specified property
* @param aName the name of the property
*/
private RE getRegexpProperty(String aName)
{
return (RE) mRegexps.get(aName);
}
/**
* @return an integer property
* @param aName the name of the integer property to get
*/
private int getIntProperty(String aName)
{
return ((Integer) mIntProps.get(aName)).intValue();
}
/**
* @return an String property
* @param aName the name of the String property to get
*/
private String getStringProperty(String aName)
{
return (String) mStringProps.get(aName);
}
/**
* Set the value of an integer property. If the property is not defined
* or cannot be parsed, then a default value is used.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setIntProperty(Properties aProps,
PrintStream aLog,
String aName)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
try {
final int val = Integer.parseInt(strRep);
setIntProperty(aName, val);
}
catch (NumberFormatException nfe) {
aLog.println(
"Unable to parse "
+ aName
+ " property with value "
+ strRep
+ ", defaulting to "
+ getIntProperty(aName)
+ ".");
}
}
}
/**
* Set the value of a LeftCurlyOption property.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setLeftCurlyOptionProperty(Properties aProps,
String aName,
PrintStream aLog)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
final LeftCurlyOption opt = LeftCurlyOption.decode(strRep);
if (opt == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", leaving as "
+ getLeftCurlyOptionProperty(aName) + ".");
}
else {
setLeftCurlyOptionProperty(aName, opt);
}
}
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a RightCurlyOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static RightCurlyOption getRightCurlyOptionProperty(
Properties aProps,
String aName,
RightCurlyOption aDefault,
PrintStream aLog)
{
RightCurlyOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = RightCurlyOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* Set the value of a BlockOption property.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setBlockOptionProperty(Properties aProps,
String aName,
PrintStream aLog)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
final BlockOption opt = BlockOption.decode(strRep);
if (opt == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", leaving as " + getBlockOptionProperty(aName)
+ ".");
}
else {
setBlockOptionProperty(aName, opt);
}
}
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a PadOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static PadOption getPadOptionProperty(
Properties aProps,
String aName,
PadOption aDefault,
PrintStream aLog)
{
PadOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = PadOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a WrapOpOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static WrapOpOption getWrapOpOptionProperty(
Properties aProps,
String aName,
WrapOpOption aDefault,
PrintStream aLog)
{
WrapOpOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = WrapOpOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* @param aName name of the boolean property
* @return return whether a specified property is set
*/
private boolean getBooleanProperty(String aName)
{
return mBooleanProps.contains(aName);
}
/**
* Set a boolean property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setBooleanProperty(Properties aProps, String aName)
{
String strRep = aProps.getProperty(aName);
if (strRep != null) {
strRep = strRep.toLowerCase().trim();
if (strRep.equals("true") || strRep.equals("yes")
|| strRep.equals("on"))
{
setBooleanProperty(aName, true);
}
}
}
/**
* @param aName name of the Set property
* @return return whether a specified property is set
*/
private Set getStringSetProperty(String aName)
{
return (Set) mStringSetProps.get(aName);
}
/**
* Set a Set property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setStringSetProperty(Properties aProps, String aName)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
setStringSetProperty(aName, strRep);
}
}
/**
* Set a string property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setStringProperty(Properties aProps, String aName)
{
final String str = aProps.getProperty(aName);
if (str != null) {
setStringProperty(aName, aProps.getProperty(aName));
}
}
}
| src/checkstyle/com/puppycrawl/tools/checkstyle/Configuration.java | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.LineNumberReader;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
/**
* Represents the configuration that checkstyle uses when checking. The
* configuration is Serializable, however the ClassLoader configuration is
* lost.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
**/
public class Configuration
implements Serializable
{
////////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////////
/** the set of illegal imports (comma separated package prefixes) **/
private static final String ILLEGAL_IMPORTS = "sun";
/** the set of illegal instantiations (comma separated class names) **/
private static final String ILLEGAL_INSTANTIATIONS = "";
/** pattern defaults **/
private static final Map PATTERN_DEFAULTS = new HashMap();
static {
PATTERN_DEFAULTS.put(Defn.TODO_PATTERN_PROP, "TODO:");
PATTERN_DEFAULTS.put(Defn.PARAMETER_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.STATIC_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.CONST_PATTERN_PROP, "^[A-Z](_?[A-Z0-9]+)*$");
PATTERN_DEFAULTS.put(Defn.MEMBER_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.PUBLIC_MEMBER_PATTERN_PROP,
"^f[A-Z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.TYPE_PATTERN_PROP, "^[A-Z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.LOCAL_VAR_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.LOCAL_FINAL_VAR_PATTERN_PROP,
"^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.METHOD_PATTERN_PROP, "^[a-z][a-zA-Z0-9]*$");
PATTERN_DEFAULTS.put(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP, "^$");
}
////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////
/** visibility scope where Javadoc is checked **/
private Scope mJavadocScope = Scope.PRIVATE;
/** the header lines to check for **/
private transient String[] mHeaderLines = {};
/**
* class loader to resolve classes with. Needs to be transient as unable
* to persist.
**/
private transient ClassLoader mLoader =
Thread.currentThread().getContextClassLoader();
/** the root directory for relative paths **/
private File mRootDir;
/** the lines in the header to ignore */
private TreeSet mHeaderIgnoreLineNo = new TreeSet();
/** where to place right curlies **/
private RightCurlyOption mRCurly = RightCurlyOption.SAME;
/** how to pad parenthesis **/
private PadOption mParenPadOption = PadOption.NOSPACE;
/** how to wrap operators **/
private WrapOpOption mWrapOpOption = WrapOpOption.NL;
/** set of boolean properties **/
private final Set mBooleanProps = new HashSet();
/** map of Set properties **/
private final Map mStringSetProps = new HashMap();
{
setStringSetProperty(Defn.ILLEGAL_IMPORTS_PROP, ILLEGAL_IMPORTS);
setStringSetProperty(Defn.ILLEGAL_INSTANTIATIONS_PROP,
ILLEGAL_INSTANTIATIONS);
}
/** map of int properties **/
private final Map mIntProps = new HashMap();
{
mIntProps.put(Defn.MAX_LINE_LENGTH_PROP, new Integer(80));
mIntProps.put(Defn.MAX_METHOD_LENGTH_PROP, new Integer(150));
mIntProps.put(Defn.MAX_CONSTRUCTOR_LENGTH_PROP, new Integer(150));
mIntProps.put(Defn.MAX_FILE_LENGTH_PROP, new Integer(2000));
mIntProps.put(Defn.MAX_PARAMETERS_PROP, new Integer(7));
mIntProps.put(Defn.TAB_WIDTH_PROP, new Integer(8));
}
/** map of all the pattern properties **/
private final Map mPatterns = new HashMap();
/** map of all the corresponding RE objects for pattern properties **/
private transient Map mRegexps = new HashMap();
/** map of all the BlockOption properties **/
private final Map mBlockProps = new HashMap();
{
mBlockProps.put(Defn.TRY_BLOCK_PROP, BlockOption.STMT);
mBlockProps.put(Defn.CATCH_BLOCK_PROP, BlockOption.TEXT);
mBlockProps.put(Defn.FINALLY_BLOCK_PROP, BlockOption.STMT);
}
/** map of all the LeftCurlyOption properties **/
private final Map mLCurliesProps = new HashMap();
{
mLCurliesProps.put(Defn.LCURLY_METHOD_PROP, LeftCurlyOption.EOL);
mLCurliesProps.put(Defn.LCURLY_TYPE_PROP, LeftCurlyOption.EOL);
mLCurliesProps.put(Defn.LCURLY_OTHER_PROP, LeftCurlyOption.EOL);
}
/** map of all String properties - by default are null **/
private final Map mStringProps = new HashMap();
{
mStringProps.put(Defn.LOCALE_LANGUAGE_PROP,
Locale.getDefault().getLanguage());
mStringProps.put(Defn.LOCALE_COUNTRY_PROP,
Locale.getDefault().getCountry());
}
////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////
/**
* Creates a new <code>Configuration</code> instance.
*
* @param aProps where to extract configuration parameters from
* @param aLog where to log errors to
* @throws RESyntaxException if an error occurs
* @throws FileNotFoundException if an error occurs
* @throws IOException if an error occurs
*/
public Configuration(Properties aProps, PrintStream aLog)
throws RESyntaxException, FileNotFoundException, IOException
{
// Init the special properties
setHeaderIgnoreLines(aProps.getProperty(Defn.HEADER_IGNORE_LINE_PROP));
setRCurly(getRightCurlyOptionProperty(
aProps, Defn.RCURLY_PROP, RightCurlyOption.SAME, aLog));
setJavadocScope(
Scope.getInstance(aProps.getProperty(Defn.JAVADOC_CHECKSCOPE_PROP,
Scope.PRIVATE.getName())));
setParenPadOption(getPadOptionProperty(aProps,
Defn.PAREN_PAD_PROP,
PadOption.NOSPACE,
aLog));
setWrapOpOption(getWrapOpOptionProperty(aProps,
Defn.WRAP_OP_PROP,
WrapOpOption.NL,
aLog));
// Initialise the general properties
for (int i = 0; i < Defn.ALL_BOOLEAN_PROPS.length; i++) {
setBooleanProperty(aProps, Defn.ALL_BOOLEAN_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
setPatternProperty(aProps, Defn.ALL_PATTERN_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_INT_PROPS.length; i++) {
setIntProperty(aProps, aLog, Defn.ALL_INT_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_BLOCK_PROPS.length; i++) {
setBlockOptionProperty(aProps, Defn.ALL_BLOCK_PROPS[i], aLog);
}
for (int i = 0; i < Defn.ALL_STRING_PROPS.length; i++) {
setStringProperty(aProps, Defn.ALL_STRING_PROPS[i]);
}
for (int i = 0; i < Defn.ALL_LCURLY_PROPS.length; i++) {
setLeftCurlyOptionProperty(aProps, Defn.ALL_LCURLY_PROPS[i], aLog);
}
for (int i = 0; i < Defn.ALL_STRING_SET_PROPS.length; i++) {
setStringSetProperty(aProps, Defn.ALL_STRING_SET_PROPS[i]);
}
}
/**
* Creates a new <code>Configuration</code> instance.
* @throws IllegalStateException if an error occurs
*/
public Configuration()
{
try {
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
setPatternProperty(
Defn.ALL_PATTERN_PROPS[i],
(String) PATTERN_DEFAULTS.get(Defn.ALL_PATTERN_PROPS[i]));
}
}
catch (RESyntaxException ex) {
ex.printStackTrace();
throw new IllegalStateException(ex.getMessage());
}
}
/**
* Extend default deserialization to initialize the RE member variables.
*
* @param aStream the ObjectInputStream that contains the serialized data
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
*/
private void readObject(ObjectInputStream aStream)
throws IOException, ClassNotFoundException
{
// initialize the serialized fields
aStream.defaultReadObject();
// initialize the transient fields
mLoader = Thread.currentThread().getContextClassLoader();
mRegexps = new HashMap();
// load the file to re-read the lines
loadFiles();
try {
// Loop on the patterns creating the RE's
final Iterator keys = mPatterns.keySet().iterator();
while (keys.hasNext()) {
final String k = (String) keys.next();
mRegexps.put(k, new RE((String) mPatterns.get(k)));
}
}
catch (RESyntaxException ex) {
// This should never happen, as the serialized regexp patterns
// somehow must have passed a setPattern() method.
throw new InvalidObjectException(
"invalid regular expression syntax");
}
}
/**
* Loads the files specified by properties.
* @throws IOException if an error occurs
*/
void loadFiles()
throws IOException
{
loadHeaderFile();
}
////////////////////////////////////////////////////////////////////////////
// Getters
////////////////////////////////////////////////////////////////////////////
/** @return a Properties object representing the current configuration.
* The returned object can be used to recreate the configuration.
* Tip: used on a default object returns all the default objects. */
public Properties getProperties()
{
final Properties retVal = new Properties();
Utils.addSetString(retVal, Defn.HEADER_IGNORE_LINE_PROP,
mHeaderIgnoreLineNo);
Utils.addObjectString(retVal, Defn.RCURLY_PROP, mRCurly.toString());
Utils.addObjectString(retVal, Defn.JAVADOC_CHECKSCOPE_PROP,
mJavadocScope.getName());
Utils.addObjectString(retVal, Defn.PAREN_PAD_PROP,
mParenPadOption.toString());
Utils.addObjectString(retVal, Defn.WRAP_OP_PROP,
mWrapOpOption.toString());
for (int i = 0; i < Defn.ALL_BOOLEAN_PROPS.length; i++) {
final String key = Defn.ALL_BOOLEAN_PROPS[i];
retVal.put(key, String.valueOf(getBooleanProperty(key)));
}
for (int i = 0; i < Defn.ALL_PATTERN_PROPS.length; i++) {
final String key = Defn.ALL_PATTERN_PROPS[i];
Utils.addObjectString(retVal, key, getPatternProperty(key));
}
for (int i = 0; i < Defn.ALL_INT_PROPS.length; i++) {
final String key = Defn.ALL_INT_PROPS[i];
Utils.addObjectString(retVal, key,
Integer.toString(getIntProperty(key)));
}
for (int i = 0; i < Defn.ALL_BLOCK_PROPS.length; i++) {
final String key = Defn.ALL_BLOCK_PROPS[i];
Utils.addObjectString(retVal, key, getBlockOptionProperty(key));
}
for (int i = 0; i < Defn.ALL_STRING_PROPS.length; i++) {
final String key = Defn.ALL_STRING_PROPS[i];
Utils.addObjectString(retVal, key, getStringProperty(key));
}
for (int i = 0; i < Defn.ALL_LCURLY_PROPS.length; i++) {
final String key = Defn.ALL_LCURLY_PROPS[i];
Utils.addObjectString(retVal, key, getLeftCurlyOptionProperty(key));
}
for (int i = 0; i < Defn.ALL_STRING_SET_PROPS.length; i++) {
final String key = Defn.ALL_STRING_SET_PROPS[i];
Utils.addSetString(retVal, key, getStringSetProperty(key));
}
return retVal;
}
/** @return the class loader **/
public ClassLoader getClassLoader()
{
return mLoader;
}
/** @return locale language to report messages **/
public String getLocaleLanguage()
{
return getStringProperty(Defn.LOCALE_LANGUAGE_PROP);
}
/** @return locale country to report messages **/
public String getLocaleCountry()
{
return getStringProperty(Defn.LOCALE_COUNTRY_PROP);
}
/** @return pattern to match to-do lines **/
public String getTodoPat()
{
return getPatternProperty(Defn.TODO_PATTERN_PROP);
}
/** @return regexp to match to-do lines **/
public RE getTodoRegexp()
{
return getRegexpProperty(Defn.TODO_PATTERN_PROP);
}
/** @return pattern to match parameters **/
public String getParamPat()
{
return getPatternProperty(Defn.PARAMETER_PATTERN_PROP);
}
/** @return regexp to match parameters **/
public RE getParamRegexp()
{
return getRegexpProperty(Defn.PARAMETER_PATTERN_PROP);
}
/** @return pattern to match static variables **/
public String getStaticPat()
{
return getPatternProperty(Defn.STATIC_PATTERN_PROP);
}
/** @return regexp to match static variables **/
public RE getStaticRegexp()
{
return getRegexpProperty(Defn.STATIC_PATTERN_PROP);
}
/** @return pattern to match static final variables **/
public String getStaticFinalPat()
{
return getPatternProperty(Defn.CONST_PATTERN_PROP);
}
/** @return regexp to match static final variables **/
public RE getStaticFinalRegexp()
{
return getRegexpProperty(Defn.CONST_PATTERN_PROP);
}
/** @return pattern to match member variables **/
public String getMemberPat()
{
return getPatternProperty(Defn.MEMBER_PATTERN_PROP);
}
/** @return regexp to match member variables **/
public RE getMemberRegexp()
{
return getRegexpProperty(Defn.MEMBER_PATTERN_PROP);
}
/** @return pattern to match public member variables **/
public String getPublicMemberPat()
{
return getPatternProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
}
/** @return regexp to match public member variables **/
public RE getPublicMemberRegexp()
{
return getRegexpProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
}
/** @return pattern to match type names **/
public String getTypePat()
{
return getPatternProperty(Defn.TYPE_PATTERN_PROP);
}
/** @return regexp to match type names **/
public RE getTypeRegexp()
{
return getRegexpProperty(Defn.TYPE_PATTERN_PROP);
}
/** @return pattern to match local variables **/
public String getLocalVarPat()
{
return getPatternProperty(Defn.LOCAL_VAR_PATTERN_PROP);
}
/** @return regexp to match local variables **/
public RE getLocalVarRegexp()
{
return getRegexpProperty(Defn.LOCAL_VAR_PATTERN_PROP);
}
/** @return pattern to match local final variables **/
public String getLocalFinalVarPat()
{
return getPatternProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
}
/** @return regexp to match local final variables **/
public RE getLocalFinalVarRegexp()
{
return getRegexpProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
}
/** @return pattern to match method names **/
public String getMethodPat()
{
return getPatternProperty(Defn.METHOD_PATTERN_PROP);
}
/** @return regexp to match method names **/
public RE getMethodRegexp()
{
return getRegexpProperty(Defn.METHOD_PATTERN_PROP);
}
/** @return the maximum line length **/
public int getMaxLineLength()
{
return getIntProperty(Defn.MAX_LINE_LENGTH_PROP);
}
/** @return the maximum method length **/
public int getMaxMethodLength()
{
return getIntProperty(Defn.MAX_METHOD_LENGTH_PROP);
}
/** @return the maximum number parameters**/
public int getMaxParameters()
{
return getIntProperty(Defn.MAX_PARAMETERS_PROP);
}
/** @return the maximum constructor length **/
public int getMaxConstructorLength()
{
return getIntProperty(Defn.MAX_CONSTRUCTOR_LENGTH_PROP);
}
/** @return the maximum file length **/
public int getMaxFileLength()
{
return getIntProperty(Defn.MAX_FILE_LENGTH_PROP);
}
/** @return whether to allow tabs **/
public boolean isAllowTabs()
{
return getBooleanProperty(Defn.ALLOW_TABS_PROP);
}
/** @return distance between tab stops */
public int getTabWidth()
{
return getIntProperty(Defn.TAB_WIDTH_PROP);
}
/** @return whether to allow protected data **/
public boolean isAllowProtected()
{
return getBooleanProperty(Defn.ALLOW_PROTECTED_PROP);
}
/** @return whether to allow package data **/
public boolean isAllowPackage()
{
return getBooleanProperty(Defn.ALLOW_PACKAGE_PROP);
}
/** @return whether to allow having no author tag **/
public boolean isAllowNoAuthor()
{
return getBooleanProperty(Defn.ALLOW_NO_AUTHOR_PROP);
}
/** @return whether to require having version tag */
public boolean isRequireVersion()
{
return getBooleanProperty(Defn.REQUIRE_VERSION_PROP);
}
/** @return visibility scope where Javadoc is checked **/
public Scope getJavadocScope()
{
return mJavadocScope;
}
/** @return whether javadoc package documentation is required */
public boolean isRequirePackageHtml()
{
return getBooleanProperty(Defn.REQUIRE_PACKAGE_HTML_PROP);
}
/** @return whether to process imports **/
public boolean isIgnoreImports()
{
return getBooleanProperty(Defn.IGNORE_IMPORTS_PROP);
}
/** @return whether to check unused @throws **/
public boolean isCheckUnusedThrows()
{
return getBooleanProperty(Defn.JAVADOC_CHECK_UNUSED_THROWS_PROP);
}
/** @return Set of pkg prefixes that are illegal in import statements */
public Set getIllegalImports()
{
return getStringSetProperty(Defn.ILLEGAL_IMPORTS_PROP);
}
/** @return Set of classes where calling a constructor is illegal */
public Set getIllegalInstantiations()
{
return getStringSetProperty(Defn.ILLEGAL_INSTANTIATIONS_PROP);
}
/** @return pattern to exclude from line lengh checking **/
public String getIgnoreLineLengthPat()
{
return getPatternProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
}
/** @return regexp to exclude from line lengh checking **/
public RE getIgnoreLineLengthRegexp()
{
return getRegexpProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
}
/** @return whether to ignore checks for whitespace **/
public boolean isIgnoreWhitespace()
{
return getBooleanProperty(Defn.IGNORE_WHITESPACE_PROP);
}
/** @return whether to ignore checks for whitespace after casts **/
public boolean isIgnoreCastWhitespace()
{
return getBooleanProperty(Defn.IGNORE_CAST_WHITESPACE_PROP);
}
/** @return whether to ignore checks for braces **/
public boolean isIgnoreBraces()
{
return getBooleanProperty(Defn.IGNORE_BRACES_PROP);
}
/** @return whether to ignore long 'L' **/
public boolean isIgnoreLongEll()
{
return getBooleanProperty(Defn.IGNORE_LONG_ELL_PROP);
}
/** @return whether to ignore 'public' keyword in interface definitions **/
public boolean isIgnorePublicInInterface()
{
return getBooleanProperty(Defn.IGNORE_PUBLIC_IN_INTERFACE_PROP);
}
/** @return whether to ignore max line length for import statements **/
public boolean isIgnoreImportLength()
{
return getBooleanProperty(Defn.IGNORE_IMPORT_LENGTH_PROP);
}
/** @return the header lines to check for **/
public String[] getHeaderLines()
{
return mHeaderLines;
}
/** @return if lines in header file are regular expressions */
public boolean getHeaderLinesRegexp()
{
return getBooleanProperty(Defn.HEADER_LINES_REGEXP_PROP);
}
/**
* @param aLineNo a line number
* @return if <code>aLineNo</code> is one of the ignored header lines.
*/
public boolean isHeaderIgnoreLineNo(int aLineNo)
{
return mHeaderIgnoreLineNo.contains(new Integer(aLineNo));
}
/** @return the File of the cache file **/
public String getCacheFile()
{
final String fname = getStringProperty(Defn.CACHE_FILE_PROP);
return (fname == null) ? null : getAbsoluteFilename(fname);
}
////////////////////////////////////////////////////////////////////////////
// Setters
////////////////////////////////////////////////////////////////////////////
/**
* Set the root directory for files.
* @param aRoot the root directory
*/
public void setRootDir(File aRoot)
{
if ((aRoot == null) || !aRoot.isDirectory() || !aRoot.isAbsolute()) {
throw new IllegalArgumentException("Invalid root directory");
}
mRootDir = aRoot;
}
/**
* Set the class loader for locating classes.
* @param aLoader the class loader
*/
public void setClassLoader(ClassLoader aLoader)
{
mLoader = aLoader;
}
/**
* Sets a String Set property. It the aFrom String is parsed for Strings
* separated by ",".
*
* @param aName name of the property to set
* @param aFrom the String to parse
*/
private void setStringSetProperty(String aName, String aFrom)
{
final Set s = new TreeSet();
final StringTokenizer tok = new StringTokenizer(aFrom, ",");
while (tok.hasMoreTokens()) {
s.add(tok.nextToken());
}
mStringSetProps.put(aName, s);
}
/**
* @param aJavadocScope visibility scope where Javadoc is checked
*/
private void setJavadocScope(Scope aJavadocScope)
{
mJavadocScope = aJavadocScope;
}
/**
* Set the boolean property.
* @param aName name of the property. Should be defined in Defn.
* @param aTo the value to set
*/
private void setBooleanProperty(String aName, boolean aTo)
{
if (aTo) {
mBooleanProps.add(aName);
}
else {
mBooleanProps.remove(aName);
}
}
/**
* Set the String property.
* @param aName name of the property. Should be defined in Defn.
* @param aTo the value to set
*/
private void setStringProperty(String aName, String aTo)
{
mStringProps.put(aName, aTo);
}
/**
* Attempts to load the contents of a header file
* @throws FileNotFoundException if an error occurs
* @throws IOException if an error occurs
*/
private void loadHeaderFile()
throws FileNotFoundException, IOException
{
final String fname = getStringProperty(Defn.HEADER_FILE_PROP);
// Handle a missing property, or an empty one
if ((fname == null) || (fname.trim().length() == 0)) {
return;
}
// load the file
final LineNumberReader lnr =
new LineNumberReader(new FileReader(getAbsoluteFilename(fname)));
final ArrayList lines = new ArrayList();
while (true) {
final String l = lnr.readLine();
if (l == null) {
break;
}
lines.add(l);
}
mHeaderLines = (String[]) lines.toArray(new String[0]);
}
/**
* @return the absolute file name for a given filename. If the passed
* filename is absolute, then that is returned. If the setRootDir() was
* called, that is used to caluclate the absolute path. Otherise, the
* absolute path of the given filename is returned (this behaviour cannot
* be determined).
*
* @param aFilename the filename to make absolute
*/
private String getAbsoluteFilename(String aFilename)
{
File f = new File(aFilename);
if (!f.isAbsolute() && (mRootDir != null)) {
f = new File(mRootDir, aFilename);
}
return f.getAbsolutePath();
}
/**
* @param aList comma separated list of line numbers to ignore in header.
*/
private void setHeaderIgnoreLines(String aList)
{
mHeaderIgnoreLineNo.clear();
if (aList == null) {
return;
}
final StringTokenizer tokens = new StringTokenizer(aList, ",");
while (tokens.hasMoreTokens()) {
final String ignoreLine = tokens.nextToken();
mHeaderIgnoreLineNo.add(new Integer(ignoreLine));
}
}
/** @return the left curly placement option for methods **/
public LeftCurlyOption getLCurlyMethod()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_METHOD_PROP);
}
/** @return the left curly placement option for types **/
public LeftCurlyOption getLCurlyType()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_TYPE_PROP);
}
/** @return the left curly placement option for others **/
public LeftCurlyOption getLCurlyOther()
{
return getLeftCurlyOptionProperty(Defn.LCURLY_OTHER_PROP);
}
/** @return the right curly placement option **/
public RightCurlyOption getRCurly()
{
return mRCurly;
}
/** @param aTo set the right curly placement option **/
private void setRCurly(RightCurlyOption aTo)
{
mRCurly = aTo;
}
/** @return the try block option **/
public BlockOption getTryBlock()
{
return getBlockOptionProperty(Defn.TRY_BLOCK_PROP);
}
/** @return the catch block option **/
public BlockOption getCatchBlock()
{
return getBlockOptionProperty(Defn.CATCH_BLOCK_PROP);
}
/** @return the finally block option **/
public BlockOption getFinallyBlock()
{
return getBlockOptionProperty(Defn.FINALLY_BLOCK_PROP);
}
/** @return the parenthesis padding option **/
public PadOption getParenPadOption()
{
return mParenPadOption;
}
/** @param aTo set the parenthesis option **/
private void setParenPadOption(PadOption aTo)
{
mParenPadOption = aTo;
}
/** @return the wrapping on operator option **/
public WrapOpOption getWrapOpOption()
{
return mWrapOpOption;
}
/** @param aTo set the wrap on operator option **/
private void setWrapOpOption(WrapOpOption aTo)
{
mWrapOpOption = aTo;
}
/** @return the base directory **/
public String getBasedir()
{
return getStringProperty(Defn.BASEDIR_PROP);
}
/**
* Set an integer property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setIntProperty(String aName, int aTo)
{
mIntProps.put(aName, new Integer(aTo));
}
/**
* Set an pattern property.
* @param aName name of the property to set
* @param aPat the value to set
* @throws RESyntaxException if an error occurs
*/
private void setPatternProperty(String aName, String aPat)
throws RESyntaxException
{
// Set the regexp first, incase cannot create the RE
mRegexps.put(aName, new RE(aPat));
mPatterns.put(aName, aPat);
}
/**
* Set an BlockOption property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setBlockOptionProperty(String aName, BlockOption aTo)
{
mBlockProps.put(aName, aTo);
}
/**
* Set an LeftCurlyOption property.
* @param aName name of the property to set
* @param aTo the value to set
*/
private void setLeftCurlyOptionProperty(String aName, LeftCurlyOption aTo)
{
mLCurliesProps.put(aName, aTo);
}
////////////////////////////////////////////////////////////////////////////
// Private methods
////////////////////////////////////////////////////////////////////////////
/**
* @return the BlockOption for a specified property.
* @param aName name of the property to get
*/
private LeftCurlyOption getLeftCurlyOptionProperty(String aName)
{
return (LeftCurlyOption) mLCurliesProps.get(aName);
}
/**
* @return the BlockOption for a specified property.
* @param aName name of the property to get
*/
private BlockOption getBlockOptionProperty(String aName)
{
return (BlockOption) mBlockProps.get(aName);
}
/**
* Set the value of an pattern property. If the property is not defined
* then a default value is used.
* @param aProps the properties set to use
* @param aName the name of the property to parse
* @throws RESyntaxException if an error occurs
*/
private void setPatternProperty(Properties aProps, String aName)
throws RESyntaxException
{
setPatternProperty(
aName,
aProps.getProperty(aName, (String) PATTERN_DEFAULTS.get(aName)));
}
/**
* @return the pattern for specified property
* @param aName the name of the property
*/
private String getPatternProperty(String aName)
{
return (String) mPatterns.get(aName);
}
/**
* @return the regexp for specified property
* @param aName the name of the property
*/
private RE getRegexpProperty(String aName)
{
return (RE) mRegexps.get(aName);
}
/**
* @return an integer property
* @param aName the name of the integer property to get
*/
private int getIntProperty(String aName)
{
return ((Integer) mIntProps.get(aName)).intValue();
}
/**
* @return an String property
* @param aName the name of the String property to get
*/
private String getStringProperty(String aName)
{
return (String) mStringProps.get(aName);
}
/**
* Set the value of an integer property. If the property is not defined
* or cannot be parsed, then a default value is used.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setIntProperty(Properties aProps,
PrintStream aLog,
String aName)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
try {
final int val = Integer.parseInt(strRep);
setIntProperty(aName, val);
}
catch (NumberFormatException nfe) {
aLog.println(
"Unable to parse "
+ aName
+ " property with value "
+ strRep
+ ", defaulting to "
+ getIntProperty(aName)
+ ".");
}
}
}
/**
* Set the value of a LeftCurlyOption property.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setLeftCurlyOptionProperty(Properties aProps,
String aName,
PrintStream aLog)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
final LeftCurlyOption opt = LeftCurlyOption.decode(strRep);
if (opt == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", leaving as "
+ getLeftCurlyOptionProperty(aName) + ".");
}
else {
setLeftCurlyOptionProperty(aName, opt);
}
}
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a RightCurlyOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static RightCurlyOption getRightCurlyOptionProperty(
Properties aProps,
String aName,
RightCurlyOption aDefault,
PrintStream aLog)
{
RightCurlyOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = RightCurlyOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* Set the value of a BlockOption property.
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
*/
private void setBlockOptionProperty(Properties aProps,
String aName,
PrintStream aLog)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
final BlockOption opt = BlockOption.decode(strRep);
if (opt == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", leaving as " + getBlockOptionProperty(aName)
+ ".");
}
else {
setBlockOptionProperty(aName, opt);
}
}
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a PadOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static PadOption getPadOptionProperty(
Properties aProps,
String aName,
PadOption aDefault,
PrintStream aLog)
{
PadOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = PadOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* @param aProps the properties set to use
* @param aLog where to log errors to
* @param aName the name of the property to parse
* @param aDefault the default value to use.
*
* @return the value of a WrapOpOption property. If the property is not
* defined or cannot be decoded, then a default value is returned.
*/
private static WrapOpOption getWrapOpOptionProperty(
Properties aProps,
String aName,
WrapOpOption aDefault,
PrintStream aLog)
{
WrapOpOption retVal = aDefault;
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
retVal = WrapOpOption.decode(strRep);
if (retVal == null) {
aLog.println("Unable to parse " + aName
+ " property with value " + strRep
+ ", defaulting to " + aDefault + ".");
}
}
return retVal;
}
/**
* @param aName name of the boolean property
* @return return whether a specified property is set
*/
private boolean getBooleanProperty(String aName)
{
return mBooleanProps.contains(aName);
}
/**
* Set a boolean property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setBooleanProperty(Properties aProps, String aName)
{
String strRep = aProps.getProperty(aName);
if (strRep != null) {
strRep = strRep.toLowerCase().trim();
if (strRep.equals("true") || strRep.equals("yes")
|| strRep.equals("on"))
{
setBooleanProperty(aName, true);
}
}
}
/**
* @param aName name of the Set property
* @return return whether a specified property is set
*/
private Set getStringSetProperty(String aName)
{
return (Set) mStringSetProps.get(aName);
}
/**
* Set a Set property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setStringSetProperty(Properties aProps, String aName)
{
final String strRep = aProps.getProperty(aName);
if (strRep != null) {
setStringSetProperty(aName, strRep);
}
}
/**
* Set a string property from a property set.
* @param aProps the properties set to extract property from
* @param aName name of the property to extract
*/
private void setStringProperty(Properties aProps, String aName)
{
final String str = aProps.getProperty(aName);
if (str != null) {
setStringProperty(aName, aProps.getProperty(aName));
}
}
}
| Cleaned up visibility
| src/checkstyle/com/puppycrawl/tools/checkstyle/Configuration.java | Cleaned up visibility | <ide><path>rc/checkstyle/com/puppycrawl/tools/checkstyle/Configuration.java
<ide> loadHeaderFile();
<ide> }
<ide>
<add>
<add> ////////////////////////////////////////////////////////////////////////////
<add> // Setters
<add> ////////////////////////////////////////////////////////////////////////////
<add>
<add> /**
<add> * Set the root directory for files.
<add> * @param aRoot the root directory
<add> */
<add> public void setRootDir(File aRoot)
<add> {
<add> if ((aRoot == null) || !aRoot.isDirectory() || !aRoot.isAbsolute()) {
<add> throw new IllegalArgumentException("Invalid root directory");
<add> }
<add> mRootDir = aRoot;
<add> }
<add>
<add> /**
<add> * Set the class loader for locating classes.
<add> * @param aLoader the class loader
<add> */
<add> public void setClassLoader(ClassLoader aLoader)
<add> {
<add> mLoader = aLoader;
<add> }
<add>
<ide> ////////////////////////////////////////////////////////////////////////////
<ide> // Getters
<ide> ////////////////////////////////////////////////////////////////////////////
<ide> }
<ide>
<ide> /** @return the class loader **/
<del> public ClassLoader getClassLoader()
<add> ClassLoader getClassLoader()
<ide> {
<ide> return mLoader;
<ide> }
<ide>
<ide> /** @return locale language to report messages **/
<del> public String getLocaleLanguage()
<add> String getLocaleLanguage()
<ide> {
<ide> return getStringProperty(Defn.LOCALE_LANGUAGE_PROP);
<ide> }
<ide>
<ide> /** @return locale country to report messages **/
<del> public String getLocaleCountry()
<add> String getLocaleCountry()
<ide> {
<ide> return getStringProperty(Defn.LOCALE_COUNTRY_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match to-do lines **/
<del> public String getTodoPat()
<add> String getTodoPat()
<ide> {
<ide> return getPatternProperty(Defn.TODO_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match to-do lines **/
<del> public RE getTodoRegexp()
<add> RE getTodoRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.TODO_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match parameters **/
<del> public String getParamPat()
<add> String getParamPat()
<ide> {
<ide> return getPatternProperty(Defn.PARAMETER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match parameters **/
<del> public RE getParamRegexp()
<add> RE getParamRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.PARAMETER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match static variables **/
<del> public String getStaticPat()
<add> String getStaticPat()
<ide> {
<ide> return getPatternProperty(Defn.STATIC_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match static variables **/
<del> public RE getStaticRegexp()
<add> RE getStaticRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.STATIC_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match static final variables **/
<del> public String getStaticFinalPat()
<add> String getStaticFinalPat()
<ide> {
<ide> return getPatternProperty(Defn.CONST_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match static final variables **/
<del> public RE getStaticFinalRegexp()
<add> RE getStaticFinalRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.CONST_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match member variables **/
<del> public String getMemberPat()
<add> String getMemberPat()
<ide> {
<ide> return getPatternProperty(Defn.MEMBER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match member variables **/
<del> public RE getMemberRegexp()
<add> RE getMemberRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.MEMBER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match public member variables **/
<del> public String getPublicMemberPat()
<add> String getPublicMemberPat()
<ide> {
<ide> return getPatternProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match public member variables **/
<del> public RE getPublicMemberRegexp()
<add> RE getPublicMemberRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.PUBLIC_MEMBER_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match type names **/
<del> public String getTypePat()
<add> String getTypePat()
<ide> {
<ide> return getPatternProperty(Defn.TYPE_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match type names **/
<del> public RE getTypeRegexp()
<add> RE getTypeRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.TYPE_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match local variables **/
<del> public String getLocalVarPat()
<add> String getLocalVarPat()
<ide> {
<ide> return getPatternProperty(Defn.LOCAL_VAR_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match local variables **/
<del> public RE getLocalVarRegexp()
<add> RE getLocalVarRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.LOCAL_VAR_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match local final variables **/
<del> public String getLocalFinalVarPat()
<add> String getLocalFinalVarPat()
<ide> {
<ide> return getPatternProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match local final variables **/
<del> public RE getLocalFinalVarRegexp()
<add> RE getLocalFinalVarRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.LOCAL_FINAL_VAR_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return pattern to match method names **/
<del> public String getMethodPat()
<add> String getMethodPat()
<ide> {
<ide> return getPatternProperty(Defn.METHOD_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to match method names **/
<del> public RE getMethodRegexp()
<add> RE getMethodRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.METHOD_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return the maximum line length **/
<del> public int getMaxLineLength()
<add> int getMaxLineLength()
<ide> {
<ide> return getIntProperty(Defn.MAX_LINE_LENGTH_PROP);
<ide> }
<ide>
<ide> /** @return the maximum method length **/
<del> public int getMaxMethodLength()
<add> int getMaxMethodLength()
<ide> {
<ide> return getIntProperty(Defn.MAX_METHOD_LENGTH_PROP);
<ide> }
<ide>
<ide> /** @return the maximum number parameters**/
<del> public int getMaxParameters()
<add> int getMaxParameters()
<ide> {
<ide> return getIntProperty(Defn.MAX_PARAMETERS_PROP);
<ide> }
<ide>
<ide> /** @return the maximum constructor length **/
<del> public int getMaxConstructorLength()
<add> int getMaxConstructorLength()
<ide> {
<ide> return getIntProperty(Defn.MAX_CONSTRUCTOR_LENGTH_PROP);
<ide> }
<ide>
<ide> /** @return the maximum file length **/
<del> public int getMaxFileLength()
<add> int getMaxFileLength()
<ide> {
<ide> return getIntProperty(Defn.MAX_FILE_LENGTH_PROP);
<ide> }
<ide>
<ide> /** @return whether to allow tabs **/
<del> public boolean isAllowTabs()
<add> boolean isAllowTabs()
<ide> {
<ide> return getBooleanProperty(Defn.ALLOW_TABS_PROP);
<ide> }
<ide>
<ide> /** @return distance between tab stops */
<del> public int getTabWidth()
<add> int getTabWidth()
<ide> {
<ide> return getIntProperty(Defn.TAB_WIDTH_PROP);
<ide> }
<ide>
<ide> /** @return whether to allow protected data **/
<del> public boolean isAllowProtected()
<add> boolean isAllowProtected()
<ide> {
<ide> return getBooleanProperty(Defn.ALLOW_PROTECTED_PROP);
<ide> }
<ide>
<ide> /** @return whether to allow package data **/
<del> public boolean isAllowPackage()
<add> boolean isAllowPackage()
<ide> {
<ide> return getBooleanProperty(Defn.ALLOW_PACKAGE_PROP);
<ide> }
<ide>
<ide> /** @return whether to allow having no author tag **/
<del> public boolean isAllowNoAuthor()
<add> boolean isAllowNoAuthor()
<ide> {
<ide> return getBooleanProperty(Defn.ALLOW_NO_AUTHOR_PROP);
<ide> }
<ide>
<ide> /** @return whether to require having version tag */
<del> public boolean isRequireVersion()
<add> boolean isRequireVersion()
<ide> {
<ide> return getBooleanProperty(Defn.REQUIRE_VERSION_PROP);
<ide> }
<ide>
<ide> /** @return visibility scope where Javadoc is checked **/
<del> public Scope getJavadocScope()
<add> Scope getJavadocScope()
<ide> {
<ide> return mJavadocScope;
<ide> }
<ide>
<ide> /** @return whether javadoc package documentation is required */
<del> public boolean isRequirePackageHtml()
<add> boolean isRequirePackageHtml()
<ide> {
<ide> return getBooleanProperty(Defn.REQUIRE_PACKAGE_HTML_PROP);
<ide> }
<ide>
<ide> /** @return whether to process imports **/
<del> public boolean isIgnoreImports()
<add> boolean isIgnoreImports()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_IMPORTS_PROP);
<ide> }
<ide>
<ide> /** @return whether to check unused @throws **/
<del> public boolean isCheckUnusedThrows()
<add> boolean isCheckUnusedThrows()
<ide> {
<ide> return getBooleanProperty(Defn.JAVADOC_CHECK_UNUSED_THROWS_PROP);
<ide> }
<ide>
<ide> /** @return Set of pkg prefixes that are illegal in import statements */
<del> public Set getIllegalImports()
<add> Set getIllegalImports()
<ide> {
<ide> return getStringSetProperty(Defn.ILLEGAL_IMPORTS_PROP);
<ide> }
<ide>
<ide> /** @return Set of classes where calling a constructor is illegal */
<del> public Set getIllegalInstantiations()
<add> Set getIllegalInstantiations()
<ide> {
<ide> return getStringSetProperty(Defn.ILLEGAL_INSTANTIATIONS_PROP);
<ide> }
<ide>
<ide> /** @return pattern to exclude from line lengh checking **/
<del> public String getIgnoreLineLengthPat()
<add> String getIgnoreLineLengthPat()
<ide> {
<ide> return getPatternProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return regexp to exclude from line lengh checking **/
<del> public RE getIgnoreLineLengthRegexp()
<add> RE getIgnoreLineLengthRegexp()
<ide> {
<ide> return getRegexpProperty(Defn.IGNORE_LINE_LENGTH_PATTERN_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore checks for whitespace **/
<del> public boolean isIgnoreWhitespace()
<add> boolean isIgnoreWhitespace()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_WHITESPACE_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore checks for whitespace after casts **/
<del> public boolean isIgnoreCastWhitespace()
<add> boolean isIgnoreCastWhitespace()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_CAST_WHITESPACE_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore checks for braces **/
<del> public boolean isIgnoreBraces()
<add> boolean isIgnoreBraces()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_BRACES_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore long 'L' **/
<del> public boolean isIgnoreLongEll()
<add> boolean isIgnoreLongEll()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_LONG_ELL_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore 'public' keyword in interface definitions **/
<del> public boolean isIgnorePublicInInterface()
<add> boolean isIgnorePublicInInterface()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_PUBLIC_IN_INTERFACE_PROP);
<ide> }
<ide>
<ide> /** @return whether to ignore max line length for import statements **/
<del> public boolean isIgnoreImportLength()
<add> boolean isIgnoreImportLength()
<ide> {
<ide> return getBooleanProperty(Defn.IGNORE_IMPORT_LENGTH_PROP);
<ide> }
<ide>
<ide> /** @return the header lines to check for **/
<del> public String[] getHeaderLines()
<add> String[] getHeaderLines()
<ide> {
<ide> return mHeaderLines;
<ide> }
<ide>
<ide>
<ide> /** @return if lines in header file are regular expressions */
<del> public boolean getHeaderLinesRegexp()
<add> boolean getHeaderLinesRegexp()
<ide> {
<ide> return getBooleanProperty(Defn.HEADER_LINES_REGEXP_PROP);
<ide> }
<ide> * @param aLineNo a line number
<ide> * @return if <code>aLineNo</code> is one of the ignored header lines.
<ide> */
<del> public boolean isHeaderIgnoreLineNo(int aLineNo)
<add> boolean isHeaderIgnoreLineNo(int aLineNo)
<ide> {
<ide> return mHeaderIgnoreLineNo.contains(new Integer(aLineNo));
<ide> }
<ide>
<ide> /** @return the File of the cache file **/
<del> public String getCacheFile()
<add> String getCacheFile()
<ide> {
<ide> final String fname = getStringProperty(Defn.CACHE_FILE_PROP);
<ide> return (fname == null) ? null : getAbsoluteFilename(fname);
<del> }
<del>
<del> ////////////////////////////////////////////////////////////////////////////
<del> // Setters
<del> ////////////////////////////////////////////////////////////////////////////
<del>
<del> /**
<del> * Set the root directory for files.
<del> * @param aRoot the root directory
<del> */
<del> public void setRootDir(File aRoot)
<del> {
<del> if ((aRoot == null) || !aRoot.isDirectory() || !aRoot.isAbsolute()) {
<del> throw new IllegalArgumentException("Invalid root directory");
<del> }
<del> mRootDir = aRoot;
<del> }
<del>
<del> /**
<del> * Set the class loader for locating classes.
<del> * @param aLoader the class loader
<del> */
<del> public void setClassLoader(ClassLoader aLoader)
<del> {
<del> mLoader = aLoader;
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /** @return the left curly placement option for methods **/
<del> public LeftCurlyOption getLCurlyMethod()
<add> LeftCurlyOption getLCurlyMethod()
<ide> {
<ide> return getLeftCurlyOptionProperty(Defn.LCURLY_METHOD_PROP);
<ide> }
<ide>
<ide> /** @return the left curly placement option for types **/
<del> public LeftCurlyOption getLCurlyType()
<add> LeftCurlyOption getLCurlyType()
<ide> {
<ide> return getLeftCurlyOptionProperty(Defn.LCURLY_TYPE_PROP);
<ide> }
<ide>
<ide> /** @return the left curly placement option for others **/
<del> public LeftCurlyOption getLCurlyOther()
<add> LeftCurlyOption getLCurlyOther()
<ide> {
<ide> return getLeftCurlyOptionProperty(Defn.LCURLY_OTHER_PROP);
<ide> }
<ide>
<ide> /** @return the right curly placement option **/
<del> public RightCurlyOption getRCurly()
<add> RightCurlyOption getRCurly()
<ide> {
<ide> return mRCurly;
<ide> }
<ide> }
<ide>
<ide> /** @return the try block option **/
<del> public BlockOption getTryBlock()
<add> BlockOption getTryBlock()
<ide> {
<ide> return getBlockOptionProperty(Defn.TRY_BLOCK_PROP);
<ide> }
<ide>
<ide> /** @return the catch block option **/
<del> public BlockOption getCatchBlock()
<add> BlockOption getCatchBlock()
<ide> {
<ide> return getBlockOptionProperty(Defn.CATCH_BLOCK_PROP);
<ide> }
<ide>
<ide> /** @return the finally block option **/
<del> public BlockOption getFinallyBlock()
<add> BlockOption getFinallyBlock()
<ide> {
<ide> return getBlockOptionProperty(Defn.FINALLY_BLOCK_PROP);
<ide> }
<ide>
<ide> /** @return the parenthesis padding option **/
<del> public PadOption getParenPadOption()
<add> PadOption getParenPadOption()
<ide> {
<ide> return mParenPadOption;
<ide> }
<ide> }
<ide>
<ide> /** @return the wrapping on operator option **/
<del> public WrapOpOption getWrapOpOption()
<add> WrapOpOption getWrapOpOption()
<ide> {
<ide> return mWrapOpOption;
<ide> }
<ide> }
<ide>
<ide> /** @return the base directory **/
<del> public String getBasedir()
<add> String getBasedir()
<ide> {
<ide> return getStringProperty(Defn.BASEDIR_PROP);
<ide> } |
|
Java | apache-2.0 | 603b35a20808b28a401181e108b18ae3424ce6dc | 0 | protegeproject/styledstring | package edu.stanford.bmir.styledstring.swing;
import com.google.common.collect.ImmutableList;
import edu.stanford.bmir.styledstring.StyledString;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
/**
* Matthew Horridge
* Stanford University
* Bio-Medical Informatics Research Group
* Date: 5th December 2014
*/
public class StyledStringLayout {
private final ImmutableList<TextLayoutCache> textLayoutLines;
public StyledStringLayout(StyledString styledString) {
textLayoutLines = createLines(styledString);
}
private static ImmutableList<TextLayoutCache> createLines(StyledString styledString) {
if (styledString.isEmpty()) {
return ImmutableList.of();
}
String[] lines = styledString.getString().split("\\n");
int lineStart = 0;
final AttributedStringRenderer attributedStringRenderer = new AttributedStringRenderer();
final AttributedCharacterIterator iterator = attributedStringRenderer.toAttributedString(styledString).getIterator();
ImmutableList.Builder<TextLayoutCache> builder = ImmutableList.builder();
for (String line : lines) {
int lineEnd = lineStart + line.length();
AttributedString attributedLine = new AttributedString(iterator, lineStart, lineEnd);
builder.add(new TextLayoutCache(attributedLine));
lineStart = lineEnd + 1;
}
return builder.build();
}
public float getWidth(FontRenderContext fontRenderContext) {
float maxWidth = 0;
for (TextLayoutCache cache : textLayoutLines) {
float visibleAdvance = cache.getVisibleAdvance(fontRenderContext);
if (visibleAdvance > maxWidth) {
maxWidth = visibleAdvance;
}
}
return maxWidth;
}
public float getHeight(FontRenderContext fontRenderContext) {
float height = 0;
for (TextLayoutCache textLayoutCache : textLayoutLines) {
height += textLayoutCache.getHeight(fontRenderContext);
}
return height;
}
public void draw(Graphics2D g2, float x, float y) {
float yOffset = y;
float leading;
float ascent;
float descent = 0;
for (TextLayoutCache cache : textLayoutLines) {
FontRenderContext frc = g2.getFontRenderContext();
TextLayout textLayout = cache.getTextLayout(frc);
leading = textLayout.getLeading();
ascent = textLayout.getAscent();
yOffset += leading + ascent + descent;
textLayout.draw(g2, x, yOffset);
descent = textLayout.getDescent();
}
}
}
| src/main/java/edu/stanford/bmir/styledstring/swing/StyledStringLayout.java | package edu.stanford.bmir.styledstring.swing;
import edu.stanford.bmir.styledstring.StyledString;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
/**
* Matthew Horridge
* Stanford University
* Bio-Medical Informatics Research Group
* Date: 5th December 2014
*/
public class StyledStringLayout {
private final List<TextLayoutCache> textLayoutLines = new ArrayList<TextLayoutCache>();
public StyledStringLayout(StyledString styledString) {
createLines(styledString);
}
private void createLines(StyledString styledString) {
if (styledString.isEmpty()) {
return;
}
String[] lines = styledString.getString().split("\\n");
int lineStart = 0;
int lineEnd = 0;
final AttributedStringRenderer attributedStringRenderer = new AttributedStringRenderer();
final AttributedCharacterIterator iterator = attributedStringRenderer.toAttributedString(styledString).getIterator();
for (String line : lines) {
lineEnd = lineStart + line.length();
AttributedString attributedLine = new AttributedString(iterator, lineStart, lineEnd);
textLayoutLines.add(new TextLayoutCache(attributedLine));
lineStart = lineEnd + 1;
}
}
public float getWidth(FontRenderContext fontRenderContext) {
float maxWidth = 0;
for (TextLayoutCache cache : textLayoutLines) {
float visibleAdvance = cache.getVisibleAdvance(fontRenderContext);
if (visibleAdvance > maxWidth) {
maxWidth = visibleAdvance;
}
}
return maxWidth;
}
public float getHeight(FontRenderContext fontRenderContext) {
float height = 0;
for (TextLayoutCache textLayoutCache : textLayoutLines) {
height += textLayoutCache.getHeight(fontRenderContext);
}
return height;
}
public void draw(Graphics2D g2, float x, float y) {
float yOffset = y;
float leading = 0;
float ascent = 0;
float descent = 0;
for (TextLayoutCache cache : textLayoutLines) {
FontRenderContext frc = g2.getFontRenderContext();
TextLayout textLayout = cache.getTextLayout(frc);
leading = textLayout.getLeading();
ascent = textLayout.getAscent();
yOffset += leading + ascent + descent;
textLayout.draw(g2, x, yOffset);
descent = textLayout.getDescent();
}
}
}
| Tidy of StyledStringLayout
| src/main/java/edu/stanford/bmir/styledstring/swing/StyledStringLayout.java | Tidy of StyledStringLayout | <ide><path>rc/main/java/edu/stanford/bmir/styledstring/swing/StyledStringLayout.java
<ide> package edu.stanford.bmir.styledstring.swing;
<ide>
<add>import com.google.common.collect.ImmutableList;
<ide> import edu.stanford.bmir.styledstring.StyledString;
<ide>
<ide> import java.awt.*;
<ide> public class StyledStringLayout {
<ide>
<ide>
<del> private final List<TextLayoutCache> textLayoutLines = new ArrayList<TextLayoutCache>();
<add> private final ImmutableList<TextLayoutCache> textLayoutLines;
<ide>
<ide> public StyledStringLayout(StyledString styledString) {
<del> createLines(styledString);
<add> textLayoutLines = createLines(styledString);
<ide> }
<ide>
<ide>
<del> private void createLines(StyledString styledString) {
<add> private static ImmutableList<TextLayoutCache> createLines(StyledString styledString) {
<ide> if (styledString.isEmpty()) {
<del> return;
<add> return ImmutableList.of();
<ide> }
<ide> String[] lines = styledString.getString().split("\\n");
<ide> int lineStart = 0;
<del> int lineEnd = 0;
<ide> final AttributedStringRenderer attributedStringRenderer = new AttributedStringRenderer();
<ide> final AttributedCharacterIterator iterator = attributedStringRenderer.toAttributedString(styledString).getIterator();
<add> ImmutableList.Builder<TextLayoutCache> builder = ImmutableList.builder();
<ide> for (String line : lines) {
<del> lineEnd = lineStart + line.length();
<add> int lineEnd = lineStart + line.length();
<ide> AttributedString attributedLine = new AttributedString(iterator, lineStart, lineEnd);
<del> textLayoutLines.add(new TextLayoutCache(attributedLine));
<add> builder.add(new TextLayoutCache(attributedLine));
<ide> lineStart = lineEnd + 1;
<ide> }
<add> return builder.build();
<ide> }
<ide>
<ide>
<ide>
<ide> public void draw(Graphics2D g2, float x, float y) {
<ide> float yOffset = y;
<del> float leading = 0;
<del> float ascent = 0;
<add> float leading;
<add> float ascent;
<ide> float descent = 0;
<ide> for (TextLayoutCache cache : textLayoutLines) {
<ide> FontRenderContext frc = g2.getFontRenderContext(); |
|
Java | agpl-3.0 | f0a995aadca101615a19276d0086ae64402dc5c9 | 0 | Marine-22/libre,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,dgray16/libreplan,LibrePlan/libreplan,skylow95/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,poum/libreplan,Marine-22/libre,dgray16/libreplan,skylow95/libreplan,poum/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,poum/libreplan,LibrePlan/libreplan,dgray16/libreplan,poum/libreplan,dgray16/libreplan,dgray16/libreplan,poum/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,Marine-22/libre,PaulLuchyn/libreplan,skylow95/libreplan,Marine-22/libre,Marine-22/libre | /*
* This file is part of ###PROJECT_NAME###
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zkoss.ganttz.data.criticalpath;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.zkoss.ganttz.data.DependencyType;
import org.zkoss.ganttz.data.IDependency;
import org.zkoss.ganttz.data.ITaskFundamentalProperties;
import org.zkoss.ganttz.data.constraint.Constraint;
import org.zkoss.ganttz.data.constraint.DateConstraint;
/**
* Class that calculates the critical path of a Gantt diagram graph.
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
public class CriticalPathCalculator<T extends ITaskFundamentalProperties> {
private ICriticalPathCalculable<T> graph;
private LocalDate initDate;
private Map<T, Node<T>> nodes;
private InitialNode<T> bop;
private LastNode<T> eop;
public List<T> calculateCriticalPath(ICriticalPathCalculable<T> graph) {
this.graph = graph;
initDate = calculateInitDate();
bop = createBeginningOfProjectNode();
eop = createEndOfProjectNode();
nodes = createGraphNodes();
forward(bop);
eop.updateLatestValues();
backward(eop);
return getTasksOnCriticalPath();
}
private LocalDate calculateInitDate() {
List<T> initialTasks = graph.getInitialTasks();
if (initialTasks.isEmpty()) {
return null;
}
Date result = initialTasks.get(0).getBeginDate();
for (T task : initialTasks) {
Date date = task.getBeginDate();
if (date.compareTo(result) < 0) {
result = date;
}
}
return new LocalDate(result);
}
private InitialNode<T> createBeginningOfProjectNode() {
return new InitialNode<T>(new HashSet<T>(graph.getInitialTasks()));
}
private LastNode<T> createEndOfProjectNode() {
return new LastNode<T>(new HashSet<T>(graph.getLatestTasks()));
}
private Map<T, Node<T>> createGraphNodes() {
Map<T, Node<T>> result = new HashMap<T, Node<T>>();
for (T task : graph.getTasks()) {
Node<T> node = new Node<T>(task, graph.getIncomingTasksFor(task),
graph.getOutgoingTasksFor(task));
result.put(task, node);
}
return result;
}
private DependencyType getDependencyTypeEndStartByDefault(T from, T to) {
if ((from != null) && (to != null)) {
IDependency<T> dependency = graph.getDependencyFrom(from, to);
if (dependency != null) {
return dependency.getType();
}
}
return DependencyType.END_START;
}
private void forward(Node<T> currentNode) {
T currentTask = currentNode.getTask();
int earliestStart = currentNode.getEarliestStart();
int earliestFinish = currentNode.getEarliestFinish();
Set<T> nextTasks = currentNode.getNextTasks();
if (nextTasks.isEmpty()) {
eop.setEarliestStart(earliestFinish);
} else {
int countStartStart = 0;
for (T task : nextTasks) {
Node<T> node = nodes.get(task);
DependencyType dependencyType = getDependencyTypeEndStartByDefault(
currentTask, task);
DateConstraint constraint = getDateConstraint(task);
switch (dependencyType) {
case START_START:
setEarliestStart(node, earliestStart, constraint);
countStartStart++;
break;
case END_END:
setEarliestStart(node, earliestFinish - node.getDuration(),
constraint);
break;
case END_START:
default:
setEarliestStart(node, earliestFinish, constraint);
break;
}
forward(node);
}
if (nextTasks.size() == countStartStart) {
eop.setEarliestStart(earliestFinish);
}
}
}
private void setEarliestStart(Node<T> node, int earliestStart,
DateConstraint constraint) {
if (constraint != null) {
Date date = initDate.plusDays(earliestStart)
.toDateTimeAtStartOfDay().toDate();
date = constraint.applyTo(date);
earliestStart = Days.daysBetween(initDate, new LocalDate(date))
.getDays();
}
node.setEarliestStart(earliestStart);
}
private DateConstraint getDateConstraint(T task) {
if (task == null) {
return null;
}
List<Constraint<Date>> constraints = task.getStartConstraints();
if (constraints == null) {
return null;
}
for (Constraint<Date> constraint : constraints) {
if (constraint instanceof DateConstraint) {
return (DateConstraint) constraint;
}
}
return null;
}
private void backward(Node<T> currentNode) {
T currentTask = currentNode.getTask();
int latestStart = currentNode.getLatestStart();
int latestFinish = currentNode.getLatestFinish();
Set<T> previousTasks = currentNode.getPreviousTasks();
if (previousTasks.isEmpty()) {
bop.setLatestFinish(latestStart);
} else {
int countEndEnd = 0;
for (T task : previousTasks) {
Node<T> node = nodes.get(task);
DependencyType dependencyType = getDependencyTypeEndStartByDefault(
task, currentTask);
DateConstraint constraint = getDateConstraint(task);
switch (dependencyType) {
case START_START:
setLatestFinish(node, latestStart + node.getDuration(),
constraint);
break;
case END_END:
setLatestFinish(node, latestFinish, constraint);
countEndEnd++;
break;
case END_START:
default:
setLatestFinish(node, latestStart, constraint);
break;
}
backward(node);
}
if (previousTasks.size() == countEndEnd) {
bop.setLatestFinish(latestStart);
}
}
}
private void setLatestFinish(Node<T> node, int latestFinish,
DateConstraint constraint) {
if (constraint != null) {
int duration = node.getDuration();
Date date = initDate.plusDays(latestFinish - duration)
.toDateTimeAtStartOfDay().toDate();
date = constraint.applyTo(date);
latestFinish = Days.daysBetween(initDate, new LocalDate(date))
.getDays()
+ duration;
}
node.setLatestFinish(latestFinish);
}
private List<T> getTasksOnCriticalPath() {
List<T> result = new ArrayList<T>();
for (Node<T> node : nodes.values()) {
if (node.getLatestStart() == node.getEarliestStart()) {
result.add(node.getTask());
}
}
return result;
}
}
| ganttzk/src/main/java/org/zkoss/ganttz/data/criticalpath/CriticalPathCalculator.java | /*
* This file is part of ###PROJECT_NAME###
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zkoss.ganttz.data.criticalpath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.zkoss.ganttz.data.DependencyType;
import org.zkoss.ganttz.data.IDependency;
import org.zkoss.ganttz.data.ITaskFundamentalProperties;
/**
* Class that calculates the critical path of a Gantt diagram graph.
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
public class CriticalPathCalculator<T extends ITaskFundamentalProperties> {
private ICriticalPathCalculable<T> graph;
private Map<T, Node<T>> nodes;
private InitialNode<T> bop;
private LastNode<T> eop;
public List<T> calculateCriticalPath(ICriticalPathCalculable<T> graph) {
this.graph = graph;
bop = createBeginningOfProjectNode();
eop = createEndOfProjectNode();
nodes = createGraphNodes();
forward(bop);
eop.updateLatestValues();
backward(eop);
return getTasksOnCriticalPath();
}
private InitialNode<T> createBeginningOfProjectNode() {
return new InitialNode<T>(new HashSet<T>(graph.getInitialTasks()));
}
private LastNode<T> createEndOfProjectNode() {
return new LastNode<T>(new HashSet<T>(graph.getLatestTasks()));
}
private Map<T, Node<T>> createGraphNodes() {
Map<T, Node<T>> result = new HashMap<T, Node<T>>();
for (T task : graph.getTasks()) {
Node<T> node = new Node<T>(task, graph.getIncomingTasksFor(task),
graph.getOutgoingTasksFor(task));
result.put(task, node);
}
return result;
}
private void forward(Node<T> currentNode) {
T currentTask = currentNode.getTask();
int earliestStart = currentNode.getEarliestStart();
int earliestFinish = currentNode.getEarliestFinish();
Set<T> nextTasks = currentNode.getNextTasks();
if (nextTasks.isEmpty()) {
eop.setEarliestStart(earliestFinish);
} else {
int countStartStart = 0;
for (T task : nextTasks) {
Node<T> node = nodes.get(task);
DependencyType dependencyType = DependencyType.END_START;
if (currentTask != null) {
IDependency<T> dependency = graph.getDependencyFrom(
currentTask, task);
if (dependency != null) {
dependencyType = dependency.getType();
}
}
switch (dependencyType) {
case START_START:
node.setEarliestStart(earliestStart);
countStartStart++;
break;
case END_END:
node.setEarliestStart(earliestFinish - node.getDuration());
break;
case END_START:
default:
node.setEarliestStart(earliestFinish);
break;
}
forward(node);
}
if (nextTasks.size() == countStartStart) {
eop.setEarliestStart(earliestFinish);
}
}
}
private void backward(Node<T> currentNode) {
T currentTask = currentNode.getTask();
int latestStart = currentNode.getLatestStart();
int latestFinish = currentNode.getLatestFinish();
Set<T> previousTasks = currentNode.getPreviousTasks();
if (previousTasks.isEmpty()) {
bop.setLatestFinish(latestStart);
} else {
int countEndEnd = 0;
for (T task : previousTasks) {
Node<T> node = nodes.get(task);
DependencyType dependencyType = DependencyType.END_START;
if (currentTask != null) {
IDependency<T> dependency = graph.getDependencyFrom(task,
currentTask);
if (dependency != null) {
dependencyType = dependency.getType();
}
}
switch (dependencyType) {
case START_START:
node.setLatestFinish(latestStart + node.getDuration());
break;
case END_END:
node.setLatestFinish(latestFinish);
countEndEnd++;
break;
case END_START:
default:
node.setLatestFinish(latestStart);
break;
}
backward(node);
}
if (previousTasks.size() == countEndEnd) {
bop.setLatestFinish(latestStart);
}
}
}
private List<T> getTasksOnCriticalPath() {
List<T> result = new ArrayList<T>();
for (Node<T> node : nodes.values()) {
if (node.getLatestStart() == node.getEarliestStart()) {
result.add(node.getTask());
}
}
return result;
}
}
| ItEr37S18CUCalculoCaminhoCriticoItEr36S20: Added support for constraints (START_NOT_EARLIER_THAN and START_IN_FIXED_DATE) to critical path method calculator.
| ganttzk/src/main/java/org/zkoss/ganttz/data/criticalpath/CriticalPathCalculator.java | ItEr37S18CUCalculoCaminhoCriticoItEr36S20: Added support for constraints (START_NOT_EARLIER_THAN and START_IN_FIXED_DATE) to critical path method calculator. | <ide><path>anttzk/src/main/java/org/zkoss/ganttz/data/criticalpath/CriticalPathCalculator.java
<ide> package org.zkoss.ganttz.data.criticalpath;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Date;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import org.joda.time.Days;
<add>import org.joda.time.LocalDate;
<ide> import org.zkoss.ganttz.data.DependencyType;
<ide> import org.zkoss.ganttz.data.IDependency;
<ide> import org.zkoss.ganttz.data.ITaskFundamentalProperties;
<add>import org.zkoss.ganttz.data.constraint.Constraint;
<add>import org.zkoss.ganttz.data.constraint.DateConstraint;
<ide>
<ide> /**
<ide> * Class that calculates the critical path of a Gantt diagram graph.
<ide>
<ide> private ICriticalPathCalculable<T> graph;
<ide>
<add> private LocalDate initDate;
<add>
<ide> private Map<T, Node<T>> nodes;
<ide>
<ide> private InitialNode<T> bop;
<ide>
<ide> public List<T> calculateCriticalPath(ICriticalPathCalculable<T> graph) {
<ide> this.graph = graph;
<add>
<add> initDate = calculateInitDate();
<add>
<ide> bop = createBeginningOfProjectNode();
<ide> eop = createEndOfProjectNode();
<ide>
<ide> backward(eop);
<ide>
<ide> return getTasksOnCriticalPath();
<add> }
<add>
<add> private LocalDate calculateInitDate() {
<add> List<T> initialTasks = graph.getInitialTasks();
<add> if (initialTasks.isEmpty()) {
<add> return null;
<add> }
<add>
<add> Date result = initialTasks.get(0).getBeginDate();
<add> for (T task : initialTasks) {
<add> Date date = task.getBeginDate();
<add> if (date.compareTo(result) < 0) {
<add> result = date;
<add> }
<add> }
<add> return new LocalDate(result);
<ide> }
<ide>
<ide> private InitialNode<T> createBeginningOfProjectNode() {
<ide> }
<ide>
<ide> return result;
<add> }
<add>
<add> private DependencyType getDependencyTypeEndStartByDefault(T from, T to) {
<add> if ((from != null) && (to != null)) {
<add> IDependency<T> dependency = graph.getDependencyFrom(from, to);
<add> if (dependency != null) {
<add> return dependency.getType();
<add> }
<add> }
<add> return DependencyType.END_START;
<ide> }
<ide>
<ide> private void forward(Node<T> currentNode) {
<ide>
<ide> for (T task : nextTasks) {
<ide> Node<T> node = nodes.get(task);
<del>
<del> DependencyType dependencyType = DependencyType.END_START;
<del> if (currentTask != null) {
<del> IDependency<T> dependency = graph.getDependencyFrom(
<del> currentTask, task);
<del> if (dependency != null) {
<del> dependencyType = dependency.getType();
<del> }
<del> }
<add> DependencyType dependencyType = getDependencyTypeEndStartByDefault(
<add> currentTask, task);
<add> DateConstraint constraint = getDateConstraint(task);
<ide>
<ide> switch (dependencyType) {
<ide> case START_START:
<del> node.setEarliestStart(earliestStart);
<add> setEarliestStart(node, earliestStart, constraint);
<ide> countStartStart++;
<ide> break;
<ide> case END_END:
<del> node.setEarliestStart(earliestFinish - node.getDuration());
<add> setEarliestStart(node, earliestFinish - node.getDuration(),
<add> constraint);
<ide> break;
<ide> case END_START:
<ide> default:
<del> node.setEarliestStart(earliestFinish);
<add> setEarliestStart(node, earliestFinish, constraint);
<ide> break;
<ide> }
<ide>
<ide> eop.setEarliestStart(earliestFinish);
<ide> }
<ide> }
<add> }
<add>
<add> private void setEarliestStart(Node<T> node, int earliestStart,
<add> DateConstraint constraint) {
<add> if (constraint != null) {
<add> Date date = initDate.plusDays(earliestStart)
<add> .toDateTimeAtStartOfDay().toDate();
<add> date = constraint.applyTo(date);
<add> earliestStart = Days.daysBetween(initDate, new LocalDate(date))
<add> .getDays();
<add> }
<add> node.setEarliestStart(earliestStart);
<add> }
<add>
<add> private DateConstraint getDateConstraint(T task) {
<add> if (task == null) {
<add> return null;
<add> }
<add>
<add> List<Constraint<Date>> constraints = task.getStartConstraints();
<add> if (constraints == null) {
<add> return null;
<add> }
<add>
<add> for (Constraint<Date> constraint : constraints) {
<add> if (constraint instanceof DateConstraint) {
<add> return (DateConstraint) constraint;
<add> }
<add> }
<add> return null;
<ide> }
<ide>
<ide> private void backward(Node<T> currentNode) {
<ide>
<ide> for (T task : previousTasks) {
<ide> Node<T> node = nodes.get(task);
<del>
<del> DependencyType dependencyType = DependencyType.END_START;
<del> if (currentTask != null) {
<del> IDependency<T> dependency = graph.getDependencyFrom(task,
<del> currentTask);
<del> if (dependency != null) {
<del> dependencyType = dependency.getType();
<del> }
<del> }
<add> DependencyType dependencyType = getDependencyTypeEndStartByDefault(
<add> task, currentTask);
<add> DateConstraint constraint = getDateConstraint(task);
<ide>
<ide> switch (dependencyType) {
<ide> case START_START:
<del> node.setLatestFinish(latestStart + node.getDuration());
<add> setLatestFinish(node, latestStart + node.getDuration(),
<add> constraint);
<ide> break;
<ide> case END_END:
<del> node.setLatestFinish(latestFinish);
<add> setLatestFinish(node, latestFinish, constraint);
<ide> countEndEnd++;
<ide> break;
<ide> case END_START:
<ide> default:
<del> node.setLatestFinish(latestStart);
<add> setLatestFinish(node, latestStart, constraint);
<ide> break;
<ide> }
<ide>
<ide> bop.setLatestFinish(latestStart);
<ide> }
<ide> }
<add> }
<add>
<add> private void setLatestFinish(Node<T> node, int latestFinish,
<add> DateConstraint constraint) {
<add> if (constraint != null) {
<add> int duration = node.getDuration();
<add> Date date = initDate.plusDays(latestFinish - duration)
<add> .toDateTimeAtStartOfDay().toDate();
<add> date = constraint.applyTo(date);
<add> latestFinish = Days.daysBetween(initDate, new LocalDate(date))
<add> .getDays()
<add> + duration;
<add> }
<add> node.setLatestFinish(latestFinish);
<ide> }
<ide>
<ide> private List<T> getTasksOnCriticalPath() { |
|
Java | bsd-3-clause | 4343ae4960684ab36da8a3c300c314376ea3640e | 0 | team-worthwhile/worthwhile,team-worthwhile/worthwhile | package edu.kit.iti.formal.pse.worthwhile.prover;
import java.util.LinkedHashSet;
import java.util.Set;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayFunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayFunctionAccess;
import edu.kit.iti.formal.pse.worthwhile.model.ast.BinaryExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Literal;
import edu.kit.iti.formal.pse.worthwhile.model.ast.QuantifiedExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.UnaryExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference;
import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor;
/**
* A visitor to find variables that are unbound and have to be declared.
*
* @author Leon Handreke
*
*/
public class UnboundVariableFinderVisitor extends HierarchialASTNodeVisitor {
/**
* The set of variables that is bound in the current visitor state.
*/
private Set<VariableDeclaration> boundVariables = new LinkedHashSet<VariableDeclaration>();
/**
* The set of unbound variables that have to be declared.
*/
private Set<VariableDeclaration> unboundVariables = new LinkedHashSet<VariableDeclaration>();
/**
* @return the set of unbound variables in the visited {@link Expression}s
*/
public final Set<VariableDeclaration> getUnboundVariables() {
return this.unboundVariables;
}
@Override
public final void visit(final ArrayFunction arrayFunction) {
final Expression index = arrayFunction.getIndex();
if (index != null) {
index.accept(this);
}
arrayFunction.getValue().accept(this);
final ArrayFunction chainedFunction = arrayFunction.getChainedFunction();
if (chainedFunction != null) {
chainedFunction.accept(this);
}
}
@Override
public final void visit(final ArrayFunctionAccess arrayFunctionAccess) {
arrayFunctionAccess.getFunction().accept(this);
arrayFunctionAccess.getIndex().accept(this);
}
@Override
public final void visit(final BinaryExpression binaryExpression) {
binaryExpression.getLeft().accept(this);
binaryExpression.getRight().accept(this);
}
@Override
public final void visit(final UnaryExpression unaryExpression) {
unaryExpression.getOperand().accept(this);
}
@Override
public final void visit(final Literal literal) {
// literals can't really have any unbound variables...
}
@Override
public final void visit(final QuantifiedExpression quantifiedExpression) {
// a quantifiedExpression binds a variable
this.boundVariables.add(quantifiedExpression.getParameter());
if (quantifiedExpression.getCondition() != null) {
quantifiedExpression.getCondition().accept(this);
}
quantifiedExpression.getExpression().accept(this);
this.boundVariables.remove(quantifiedExpression.getParameter());
}
@Override
public final void visit(final VariableReference variableReference) {
variableReference.getVariable().accept(this);
}
@Override
public final void visit(final VariableDeclaration variableDeclaration) {
if (!this.boundVariables.contains(variableDeclaration)) {
this.unboundVariables.add(variableDeclaration);
}
}
}
| implementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/UnboundVariableFinderVisitor.java | package edu.kit.iti.formal.pse.worthwhile.prover;
import java.util.HashSet;
import java.util.Set;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayFunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayFunctionAccess;
import edu.kit.iti.formal.pse.worthwhile.model.ast.BinaryExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Literal;
import edu.kit.iti.formal.pse.worthwhile.model.ast.QuantifiedExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.UnaryExpression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration;
import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference;
import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor;
/**
* A visitor to find variables that are unbound and have to be declared.
*
* @author Leon Handreke
*
*/
public class UnboundVariableFinderVisitor extends HierarchialASTNodeVisitor {
/**
* The set of variables that is bound in the current visitor state.
*/
private Set<VariableDeclaration> boundVariables = new HashSet<VariableDeclaration>();
/**
* The set of unbound variables that have to be declared.
*/
private Set<VariableDeclaration> unboundVariables = new HashSet<VariableDeclaration>();
/**
* @return the set of unbound variables in the visited {@link Expression}s
*/
public final Set<VariableDeclaration> getUnboundVariables() {
return this.unboundVariables;
}
@Override
public final void visit(final ArrayFunction arrayFunction) {
final Expression index = arrayFunction.getIndex();
if (index != null) {
index.accept(this);
}
arrayFunction.getValue().accept(this);
final ArrayFunction chainedFunction = arrayFunction.getChainedFunction();
if (chainedFunction != null) {
chainedFunction.accept(this);
}
}
@Override
public final void visit(final ArrayFunctionAccess arrayFunctionAccess) {
arrayFunctionAccess.getFunction().accept(this);
arrayFunctionAccess.getIndex().accept(this);
}
@Override
public final void visit(final BinaryExpression binaryExpression) {
binaryExpression.getLeft().accept(this);
binaryExpression.getRight().accept(this);
}
@Override
public final void visit(final UnaryExpression unaryExpression) {
unaryExpression.getOperand().accept(this);
}
@Override
public final void visit(final Literal literal) {
// literals can't really have any unbound variables...
}
@Override
public final void visit(final QuantifiedExpression quantifiedExpression) {
// a quantifiedExpression binds a variable
this.boundVariables.add(quantifiedExpression.getParameter());
if (quantifiedExpression.getCondition() != null) {
quantifiedExpression.getCondition().accept(this);
}
quantifiedExpression.getExpression().accept(this);
this.boundVariables.remove(quantifiedExpression.getParameter());
}
@Override
public final void visit(final VariableReference variableReference) {
variableReference.getVariable().accept(this);
}
@Override
public final void visit(final VariableDeclaration variableDeclaration) {
if (!this.boundVariables.contains(variableDeclaration)) {
this.unboundVariables.add(variableDeclaration);
}
}
}
| [prover] Make set returned by UnboundVariableFinderVisitor stable
| implementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/UnboundVariableFinderVisitor.java | [prover] Make set returned by UnboundVariableFinderVisitor stable | <ide><path>mplementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/UnboundVariableFinderVisitor.java
<ide> package edu.kit.iti.formal.pse.worthwhile.prover;
<ide>
<del>import java.util.HashSet;
<add>import java.util.LinkedHashSet;
<ide> import java.util.Set;
<ide>
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayFunction;
<ide> /**
<ide> * The set of variables that is bound in the current visitor state.
<ide> */
<del> private Set<VariableDeclaration> boundVariables = new HashSet<VariableDeclaration>();
<add> private Set<VariableDeclaration> boundVariables = new LinkedHashSet<VariableDeclaration>();
<ide>
<ide> /**
<ide> * The set of unbound variables that have to be declared.
<ide> */
<del> private Set<VariableDeclaration> unboundVariables = new HashSet<VariableDeclaration>();
<add> private Set<VariableDeclaration> unboundVariables = new LinkedHashSet<VariableDeclaration>();
<ide>
<ide> /**
<ide> * @return the set of unbound variables in the visited {@link Expression}s |
|
Java | mit | 43f8729eefae6aef701e6d696956e0d1dc7993a2 | 0 | dhanji/loop,dhanji/loop | package loop.runtime;
import loop.StackTraceSanitizer;
import loop.lang.ImmutableLoopObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Concurrent Channels support class for loop's event-driven channel API.
*
* @author [email protected] (Dhanji R. Prasanna)
*/
public class Channel {
private static final ExecutorService GLOBAL_EXECUTOR = Executors.newCachedThreadPool();
private static final int YIELD_FAIRNESS_CYCLES = 15;
private static final String SHUTDOWN = "shutdown";
private static final String DIE = "die";
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override public void run() {
GLOBAL_EXECUTOR.shutdown();
}
});
}
private final String name;
private final Closure actor;
private final ConcurrentLinkedQueue<Object> queue;
private final AtomicBoolean running = new AtomicBoolean();
private final Runnable runnable;
private final ExecutorService executor;
private final boolean isDedicatedPool;
private final Map<String, Object> channelMemory = new HashMap<String, Object>();
public Channel(String name, Closure actor, boolean parallel, int workers) {
this.name = name;
this.actor = actor;
this.queue = new ConcurrentLinkedQueue<Object>();
if (isDedicatedPool = workers > 0) {
this.executor = Executors.newFixedThreadPool(workers);
} else
this.executor = GLOBAL_EXECUTOR;
this.runnable = parallel ? concurrentRunnable : isolatedRunnable;
}
/**
* Isolated runnables allow only one message to be processed at a time, regardless
* of the available worker threads. They are useful for sharding semantics.
*/
private final Runnable isolatedRunnable = new Runnable() {
@Override public void run() {
if (!running.compareAndSet(false, true))
return;
try {
currentChannelMemory.set(channelMemory);
int processed = 0;
while (!queue.isEmpty() && processed < YIELD_FAIRNESS_CYCLES) {
try {
Object result = Caller.callClosure(actor, actor.target, new Object[]{queue.poll()});
// Check if we should shutdown this channel.
// Allows graceful drain of queued messages.
if (SHUTDOWN.equals(result))
shutdown();
else if (DIE.equals(result)) {
// Process no more messages.
die();
break;
}
} catch (Throwable throwable) {
try {
StackTraceSanitizer.clean(throwable);
// Swallow exception if possible.
throwable.printStackTrace(System.err);
} finally {
// Quit VM forcibly on out of memory error.
if (throwable instanceof OutOfMemoryError)
System.exit(1);
}
} finally {
processed++;
}
}
} finally {
currentChannelMemory.remove();
running.compareAndSet(true, false);
// Tail-call ourselves if we're not done with this queue.
if (!queue.isEmpty())
executor.submit(isolatedRunnable);
}
}
};
/**
* Concurrent runnables burst-process tasks as fast as possible. This is
* the default.
*/
private final Runnable concurrentRunnable = new Runnable() {
@Override public void run() {
int processed = 0;
while (!queue.isEmpty() && processed < YIELD_FAIRNESS_CYCLES) {
try {
Object result = Caller.callClosure(actor, actor.target, new Object[]{queue.poll()});
if (SHUTDOWN.equals(result))
shutdown();
else if (DIE.equals(result)) {
// Process no more messages.
die();
break;
}
} catch (Throwable throwable) {
try {
StackTraceSanitizer.clean(throwable);
// Swallow exception if possible.
throwable.printStackTrace(System.err);
} finally {
// Quit VM forcibly on out of memory error.
if (throwable instanceof OutOfMemoryError)
System.exit(1);
}
} finally {
processed++;
}
}
}
};
private static final ThreadLocal<Map<String, Object>> currentChannelMemory = new ThreadLocal<Map<String, Object>>();
public static Object currentMemory() {
Map<String, Object> map = currentChannelMemory.get();
if (map == null)
throw new RuntimeException("Illegal shared memory request. (Hint: use transactional cells instead)");
return map;
}
public void shutdown() {
channels.remove(name);
if (isDedicatedPool)
executor.shutdown();
}
public void die() {
channels.remove(name);
queue.clear();
if (isDedicatedPool)
executor.shutdownNow();
}
public void receive(Object message) {
queue.add(message);
if (!running.get())
executor.submit(runnable);
}
private static final ConcurrentMap<String, Channel> channels =
new ConcurrentHashMap<String, Channel>();
public static Channel named(Object name) {
assert name instanceof String;
Channel channel = channels.get(name);
if (channel == null)
throw new RuntimeException("No such channel established: " + name);
return channel;
}
public static void establish(Object nameObj, Object actor, Object optionsObj) {
assert nameObj instanceof String;
assert actor instanceof Closure;
assert optionsObj instanceof Map;
String name = (String) nameObj;
@SuppressWarnings("unchecked")
Map<String, Object> options = (Map<String, Object>) optionsObj;
Object serialize = options.get("serialize");
Object threads = options.get("workers");
int workers = 0;
if (null != threads)
workers = (Integer)threads;
boolean parallel = serialize == null || !(Boolean) serialize;
channels.put(name, new Channel(name, (Closure)actor, parallel, workers));
}
}
| src/loop/runtime/Channel.java | package loop.runtime;
import loop.StackTraceSanitizer;
import loop.lang.ImmutableLoopObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Concurrent Channels support class for loop's event-driven channel API.
*
* @author [email protected] (Dhanji R. Prasanna)
*/
public class Channel {
private static final ExecutorService GLOBAL_EXECUTOR = Executors.newCachedThreadPool();
private static final int YIELD_FAIRNESS_CYCLES = 15;
private static final String SHUTDOWN = "shutdown";
private static final String DIE = "die";
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override public void run() {
GLOBAL_EXECUTOR.shutdown();
}
});
}
private final String name;
private final Closure actor;
private final ConcurrentLinkedQueue<Object> queue;
private final AtomicBoolean running = new AtomicBoolean();
private final Runnable runnable;
private final ExecutorService executor;
private final boolean isDedicatedPool;
private final Map<String, Object> channelMemory = new HashMap<String, Object>();
public Channel(String name, Closure actor, boolean parallel, int workers) {
this.name = name;
this.actor = actor;
this.queue = new ConcurrentLinkedQueue<Object>();
if (isDedicatedPool = workers > 0) {
this.executor = Executors.newFixedThreadPool(workers);
} else
this.executor = GLOBAL_EXECUTOR;
this.runnable = parallel ? concurrentRunnable : isolatedRunnable;
}
/**
* Isolated runnables allow only one message to be processed at a time, regardless
* of the available worker threads. They are useful for sharding semantics.
*/
private final Runnable isolatedRunnable = new Runnable() {
@Override public void run() {
if (!running.compareAndSet(false, true))
return;
try {
currentChannelMemory.set(channelMemory);
int processed = 0;
while (!queue.isEmpty() && processed < YIELD_FAIRNESS_CYCLES) {
try {
Object result = Caller.callClosure(actor, actor.target, new Object[]{queue.poll()});
// Check if we should shutdown this channel.
// Allows graceful drain of queued messages.
if (SHUTDOWN == result)
shutdown();
else if (DIE == result) {
// Process no more messages.
die();
break;
}
} catch (Throwable throwable) {
try {
StackTraceSanitizer.clean(throwable);
// Swallow exception if possible.
throwable.printStackTrace(System.err);
} finally {
// Quit VM forcibly on out of memory error.
if (throwable instanceof OutOfMemoryError)
System.exit(1);
}
} finally {
processed++;
}
}
} finally {
currentChannelMemory.remove();
running.compareAndSet(true, false);
// Tail-call ourselves if we're not done with this queue.
if (!queue.isEmpty())
executor.submit(isolatedRunnable);
}
}
};
/**
* Concurrent runnables burst-process tasks as fast as possible. This is
* the default.
*/
private final Runnable concurrentRunnable = new Runnable() {
@Override public void run() {
int processed = 0;
while (!queue.isEmpty() && processed < YIELD_FAIRNESS_CYCLES) {
try {
Object result = Caller.callClosure(actor, actor.target, new Object[]{queue.poll()});
if (SHUTDOWN == result)
shutdown();
else if (DIE == result) {
// Process no more messages.
die();
break;
}
} catch (Throwable throwable) {
try {
StackTraceSanitizer.clean(throwable);
// Swallow exception if possible.
throwable.printStackTrace(System.err);
} finally {
// Quit VM forcibly on out of memory error.
if (throwable instanceof OutOfMemoryError)
System.exit(1);
}
} finally {
processed++;
}
}
}
};
private static final ThreadLocal<Map<String, Object>> currentChannelMemory = new ThreadLocal<Map<String, Object>>();
public static Object currentMemory() {
Map<String, Object> map = currentChannelMemory.get();
if (map == null)
throw new RuntimeException("Illegal shared memory request. (Hint: use transactional cells instead)");
return map;
}
public void shutdown() {
channels.remove(name);
if (isDedicatedPool)
executor.shutdown();
}
public void die() {
channels.remove(name);
queue.clear();
if (isDedicatedPool)
executor.shutdownNow();
}
public void receive(Object message) {
queue.add(message);
if (!running.get())
executor.submit(runnable);
}
private static final ConcurrentMap<String, Channel> channels =
new ConcurrentHashMap<String, Channel>();
public static Channel named(Object name) {
assert name instanceof String;
Channel channel = channels.get(name);
if (channel == null)
throw new RuntimeException("No such channel established: " + name);
return channel;
}
public static void establish(Object nameObj, Object actor, Object optionsObj) {
assert nameObj instanceof String;
assert actor instanceof Closure;
assert optionsObj instanceof Map;
String name = (String) nameObj;
@SuppressWarnings("unchecked")
Map<String, Object> options = (Map<String, Object>) optionsObj;
Object serialize = options.get("serialize");
Object threads = options.get("workers");
int workers = 0;
if (null != threads)
workers = (Integer)threads;
boolean parallel = serialize == null || !(Boolean) serialize;
channels.put(name, new Channel(name, (Closure)actor, parallel, workers));
}
}
| fix bug where we were expecting an interned string where one was not interned
| src/loop/runtime/Channel.java | fix bug where we were expecting an interned string where one was not interned | <ide><path>rc/loop/runtime/Channel.java
<ide>
<ide> // Check if we should shutdown this channel.
<ide> // Allows graceful drain of queued messages.
<del> if (SHUTDOWN == result)
<add> if (SHUTDOWN.equals(result))
<ide> shutdown();
<del> else if (DIE == result) {
<add> else if (DIE.equals(result)) {
<ide> // Process no more messages.
<ide> die();
<ide> break;
<ide> try {
<ide> Object result = Caller.callClosure(actor, actor.target, new Object[]{queue.poll()});
<ide>
<del> if (SHUTDOWN == result)
<add> if (SHUTDOWN.equals(result))
<ide> shutdown();
<del> else if (DIE == result) {
<add> else if (DIE.equals(result)) {
<ide> // Process no more messages.
<ide> die();
<ide> break; |
|
Java | agpl-3.0 | e575beedebd13dc8e0619cb2de9ed2215565c093 | 0 | rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat | package roart.component;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roart.config.ConfigConstants;
import roart.config.IclijConfig;
import roart.config.IclijXMLConfig;
import roart.config.MyMyConfig;
import roart.model.IncDecItem;
import roart.model.MemoryItem;
import roart.pipeline.PipelineConstants;
import roart.queue.MyExecutors;
import roart.service.ControlService;
import roart.util.Constants;
import roart.util.ServiceUtil;
import roart.util.TimeUtil;
public class ComponentRecommender extends Component {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void enable(MyMyConfig conf) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORS, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEX, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACD, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSI, Boolean.TRUE);
}
@Override
public void disable(MyMyConfig conf) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORS, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEX, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACD, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSI, Boolean.FALSE);
}
@Override
public void handle(ControlService srv, MyMyConfig conf, Map<String, Map<String, Object>> resultMaps, List<Integer> positions,
Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap,
Map<Object[], List<MemoryItem>> okListMap, Map<String, String> nameMap, IclijConfig config, Map<String, Object> updateMap) {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
if (instance.wantEvolveRecommender()) {
srv.getEvolveRecommender(true, new ArrayList<>());
}
resultMaps = srv.getContent();
String market = okListMap.values().iterator().next().get(0).getMarket();
findBuySellRecommendations(resultMaps, nameMap, market, buys, sells, okConfMap, okListMap, srv, config);
}
private void findBuySellRecommendations(Map<String, Map<String, Object>> resultMaps, Map<String, String> nameMap, String market, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap, Map<Object[], List<MemoryItem>> okListMap, ControlService srv, IclijConfig config) {
Object[] keys = new Object[2];
keys[0] = PipelineConstants.AGGREGATORRECOMMENDERINDICATOR;
keys[1] = 0;
keys = ComponentMLMACD.getRealKeys(keys, okConfMap.keySet());
//System.out.println(okListMap.get(keys));
Double confidenceFactor = okConfMap.get(keys);
//System.out.println(okConfMap.keySet());
//System.out.println(okListMap.keySet());
Map maps = (Map) resultMaps.get(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
Integer category = (Integer) maps.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) maps.get(PipelineConstants.CATEGORYTITLE);
Map<String, Map> resultMap0 = (Map<String, Map>) maps.get(PipelineConstants.RESULT);
Map<String, List<Double>> resultMap = (Map<String, List<Double>>) resultMap0.get("complex");
if (resultMap == null) {
return;
}
List<MyElement> list0 = new ArrayList<>();
List<MyElement> list1 = new ArrayList<>();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) resultMaps.get("" + category).get(PipelineConstants.LIST);
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String key = entry.getKey();
List<List<Double>> resultList = entry.getValue();
List<Double> mainList = resultList.get(0);
if (mainList == null) {
continue;
}
List<Double> list = resultMap.get(key);
if (list == null) {
continue;
}
list0.add(new MyElement(key, list.get(0)));
list1.add(new MyElement(key, list.get(1)));
}
Collections.sort(list0, (o1, o2) -> (o2.getValue().compareTo(o1.getValue())));
Collections.sort(list1, (o1, o2) -> (o2.getValue().compareTo(o1.getValue())));
handleBuySell(nameMap, buys, sells, okListMap, srv, config, keys, confidenceFactor, list0);
//handleBuySell(nameMap, buys, sells, okListMap, srv, config, keys, confidenceFactor, list1);
}
private void handleBuySell(Map<String, String> nameMap, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells,
Map<Object[], List<MemoryItem>> okListMap, ControlService srv, IclijConfig config, Object[] keys,
Double confidenceFactor, List<MyElement> list) {
int listSize = list.size();
int recommend = config.recommendTopBottom();
if (listSize < recommend * 3) {
return;
}
List<MyElement> topList = list.subList(0, recommend);
List<MyElement> bottomList = list.subList(listSize - recommend, listSize);
Double max = list.get(0).getValue();
Double min = list.get(listSize - 1).getValue();
Double diff = max - min;
for (MyElement element : topList) {
if (confidenceFactor == null || element.getValue() == null) {
int jj = 0;
continue;
}
double confidence = confidenceFactor * (element.getValue() - min) / diff;
String recommendation = "recommend buy";
//IncDecItem incdec = getIncDec(element, confidence, recommendation, nameMap, market);
//incdec.setIncrease(true);
//buys.put(element.getKey(), incdec);
IncDecItem incdec = ComponentMLMACD.mapAdder(buys, element.getKey(), confidence, okListMap.get(keys), nameMap, TimeUtil.convertDate(srv.conf.getdate()));
incdec.setIncrease(true);
}
for (MyElement element : bottomList) {
double confidence = confidenceFactor * (element.getValue() - min) / diff;
String recommendation = "recommend sell";
//IncDecItem incdec = getIncDec(element, confidence, recommendation, nameMap, market);
//incdec.setIncrease(false);
IncDecItem incdec = ComponentMLMACD.mapAdder(sells, element.getKey(), confidence, okListMap.get(keys), nameMap, TimeUtil.convertDate(srv.conf.getdate()));
incdec.setIncrease(false);
}
}
private IncDecItem getIncDec(MyElement element, double confidence, String recommendation, Map<String, String> nameMap, String market) {
IncDecItem incdec = new IncDecItem();
incdec.setRecord(LocalDate.now());
incdec.setId(element.getKey());
incdec.setMarket(market);
incdec.setDescription(recommendation);
incdec.setName(nameMap.get(element.getKey()));
incdec.setScore(confidence);
return incdec;
}
public List<String> getBuy() {
List<String> buyList = new ArrayList<>();
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTHISTOGRAMNODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTHISTOGRAMDELTANODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTMOMENTUMNODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTMOMENTUMDELTANODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSIBUYWEIGHTRSINODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSIBUYWEIGHTRSIDELTANODE);
return buyList;
}
public List<String> getSell() {
List<String> sellList = new ArrayList<>();
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTHISTOGRAMNODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTHISTOGRAMDELTANODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTMOMENTUMNODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTMOMENTUMDELTANODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSISELLWEIGHTRSINODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSISELLWEIGHTRSIDELTANODE);
return sellList;
}
@Override
public Map<String, String> improve(MyMyConfig conf, Map<String, Map<String, Object>> maps, List<Integer> positions,
Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> badConfMap,
Map<Object[], List<MemoryItem>> badListMap, Map<String, String> nameMap) {
Map<String, String> retMap = new HashMap<>();
List<String> list = getBuy();
retMap.putAll(handleBuySell(conf, badListMap, list));
list = getSell();
retMap.putAll(handleBuySell(conf, badListMap, list));
return retMap;
}
private List<List<String>> disableAllButOne(List<String> list) {
List<List<String>> listPerm = new ArrayList<>();
int size = list.size();
int bitsize = (1 << size) - 1;
for (int i = 0; i < size; i++) {
int pattern = bitsize - (1 << i);
log.info("using {}", Integer.toBinaryString(pattern));
List<String> aList = new ArrayList<>();
for (int j = 0; j < size; j++) {
if ((pattern & (1 << j)) != 0) {
aList.add(list.get(j));
}
}
listPerm.add(aList);
}
return listPerm;
}
private Map<String, String> handleBuySell(MyMyConfig conf, Map<Object[], List<MemoryItem>> badListMap, List<String> list) {
Map<String, String> retMap = new HashMap<>();
//List<List<String>> listPerm = getAllPerms(list);
List<List<String>> listPerm = disableAllButOne(list);
String market = badListMap.values().iterator().next().get(0).getMarket();
ControlService srv = new ControlService();
srv.getConfig();
// plus testrecommendfactor
int factor = 100;
log.info("market {}", market);
//log.info("factor {}", factor);
//srv.conf.getConfigValueMap().put(ConfigConstants.TESTRECOMMENDFACTOR, factor);
int index = 0;
Map<Future<List<MemoryItem>>, List<String>> futureMap = new HashMap<>();
List<Future<List<MemoryItem>>> futureList = new ArrayList<>();
for (List<String> aList : listPerm) {
log.info("For disable {}", Integer.toHexString(index++));
try {
//List<MemoryItem> memories = ServiceUtil.doRecommender(srv, market, 0, null, false, aList, false);
Callable callable = new RecommenderCallable(srv, market, 0, null, false, aList, false);
Future<List<MemoryItem>> future = MyExecutors.run(callable);
futureList.add(future);
futureMap.put(future, aList);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
for (Future<List<MemoryItem>> future : futureList) {
try {
List<String> aList = futureMap.get(future);
List<MemoryItem> memories = future.get();
if (memories == null) {
log.info("No memories in {}", market);
continue;
}
List<Double> newConfidenceList = new ArrayList<>();
for(MemoryItem memory : memories) {
newConfidenceList.add(memory.getConfidence());
}
log.info("New confidences {}", newConfidenceList);
retMap.put(aList.toString(), newConfidenceList.toString());
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
return retMap;
}
private List<List<String>> getAllPerms(List<String> list) {
List<List<String>> listPerm = new ArrayList<>();
int size = list.size();
int bitsize = (1 << size) - 1;
for (int i = 0; i < bitsize; i++) {
List<String> aList = new ArrayList<>();
for (int j = 0; j < size; j++) {
if ((i & (1 << j)) != 0) {
aList.add(list.get(j));
}
}
listPerm.add(aList);
}
return listPerm;
}
public List<MemoryItem> calculateRecommender(String market, int futuredays, LocalDate baseDate, LocalDate futureDate,
String categoryTitle, Map<String, List<Double>> recommendBuySell, double buyMedian, double sellMedian,
Map<String, Map<String, Object>> result, Map<String, List<List<Double>>> categoryValueMap, Integer usedsec, boolean doSave, boolean doPrint) throws Exception {
List<MemoryItem> memoryList = new ArrayList<>();
Set<Double> changeSet = getChangeSet(futuredays, categoryValueMap);
Double medianChange = ServiceUtil.median(changeSet);
/*
getMemoriesOld(market, futuredays, baseDate, futureDate, categoryTitle, recommendBuySell, buyMedian, sellMedian,
categoryValueMap, usedsec, doSave, memoryList, medianChange);
*/
getMemories(market, futuredays, baseDate, futureDate, categoryTitle, recommendBuySell, buyMedian, sellMedian,
categoryValueMap, usedsec, doSave, memoryList, medianChange, changeSet, doPrint);
return memoryList;
}
private Set<Double> getChangeSet(int futuredays, Map<String, List<List<Double>>> categoryValueMap) {
Set<Double> changeSet = new HashSet<>();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
List<List<Double>> resultList = entry.getValue();
List<Double> mainList = resultList.get(0);
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
Double change = valFuture / valNow;
changeSet.add(change);
}
}
}
return changeSet;
}
public void getMemories(String market, int futuredays, LocalDate baseDate, LocalDate futureDate,
String categoryTitle, Map<String, List<Double>> recommendBuySell, double buyMedian, double sellMedian,
Map<String, List<List<Double>>> categoryValueMap, Integer usedsec, boolean doSave,
List<MemoryItem> memoryList, Double medianChange, Set<Double> changeSet, boolean doPrint) throws Exception {
double goodBuy = 0;
double goodSell = 0;
long totalBuy = 0;
long totalSell = 0;
Optional<Double> minOpt = changeSet.parallelStream().reduce(Double::min);
Double minChange = 0.0;
if (minOpt.isPresent()) {
minChange = minOpt.get();
}
Optional<Double> maxOpt = changeSet.parallelStream().reduce(Double::max);
Double maxChange = 0.0;
if (maxOpt.isPresent()) {
maxChange = maxOpt.get();
}
Double diffChange = maxChange - minChange;
List<Double> buyList = new ArrayList<>();
List<Double> sellList = new ArrayList<>();
for (List<Double> list : recommendBuySell.values()) {
buyList.add(list.get(0));
sellList.add(list.get(1));
}
Optional<Double> buyMaxOpt = buyList.parallelStream().reduce(Double::max);
if (!buyMaxOpt.isPresent()) {
}
Double buyMax = buyMaxOpt.get();
Optional<Double> buyMinOpt = buyList.parallelStream().reduce(Double::min);
if (!buyMinOpt.isPresent()) {
}
Double buyMin = buyMinOpt.get();
Double diffBuy = buyMax - buyMin;
Optional<Double> sellMaxOpt = sellList.parallelStream().reduce(Double::max);
if (!sellMaxOpt.isPresent()) {
}
Double sellMax = sellMaxOpt.get();
Optional<Double> sellMinOpt = sellList.parallelStream().reduce(Double::min);
if (!sellMinOpt.isPresent()) {
}
Double sellMin = sellMinOpt.get();
Double diffSell = sellMax - sellMin;
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
Double change = null;
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
change = valFuture / valNow;
}
}
if (change == null) {
continue;
}
List<Double> vals = recommendBuySell.get(key);
if (vals == null) {
continue;
}
Double buy = vals.get(0);
Double sell = vals.get(1);
if (buy != null) {
totalBuy++;
//double delta = change / buy * (buyMax / maxChange);
double expectedChange = minChange + diffChange * (buy - buyMin) / diffBuy;
//double delta = expectedChange / change;
double confidence = 1 - Math.abs(expectedChange - change) / diffChange;
/*
if (delta > 1) {
delta = 1 / delta;
}
*/
goodBuy += confidence;
}
if (sell != null) {
totalSell++;
//double delta = change / sell * (sellMax / minChange);
double expectedChange = minChange + diffChange * (sell - sellMin) / diffSell;
//double delta = expectedChange / change;
/*
if (delta > 1) {
delta = 1 / delta;
}
*/
double confidence = 1 - Math.abs(expectedChange - change) / diffChange;
goodSell += confidence;
}
}
MemoryItem buyMemory = new MemoryItem();
buyMemory.setMarket(market);
buyMemory.setRecord(LocalDate.now());
buyMemory.setDate(baseDate);
buyMemory.setUsedsec(usedsec);
buyMemory.setFuturedays(futuredays);
buyMemory.setFuturedate(futureDate);
buyMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
buyMemory.setSubcomponent("buy");
buyMemory.setCategory(categoryTitle);
buyMemory.setPositives((long) goodBuy);
buyMemory.setSize(totalBuy);
buyMemory.setConfidence((double) goodBuy / totalBuy);
buyMemory.setPosition(0);
if (doSave) {
buyMemory.save();
}
MemoryItem sellMemory = new MemoryItem();
sellMemory.setMarket(market);
sellMemory.setRecord(LocalDate.now());
sellMemory.setDate(baseDate);
sellMemory.setUsedsec(usedsec);
sellMemory.setFuturedays(futuredays);
sellMemory.setFuturedate(futureDate);
sellMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
sellMemory.setSubcomponent("sell");
sellMemory.setCategory(categoryTitle);
sellMemory.setPositives((long) goodSell);
sellMemory.setSize(totalSell);
sellMemory.setConfidence((double) goodSell / totalSell);
sellMemory.setPosition(1);
if (doSave) {
sellMemory.save();
}
//System.out.println("testing buy " + goodBuy + " " + totalBuy + " sell " + goodSell + " " + totalSell);
//System.out.println("k3 " + categoryValueMap.get("VIX"));
//System.out.println(result.get("Index").keySet());
if (doPrint) {
System.out.println(buyMemory);
System.out.println(sellMemory);
}
memoryList.add(buyMemory);
memoryList.add(sellMemory);
}
private class MyElement {
public String key;
public Double value;
public MyElement(String key, Double value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public Double getValue() {
return value;
}
}
class RecommenderCallable implements Callable {
private ControlService srv;
private String market;
private Integer offset;
private String aDate;
private boolean doSave;
private List<String> disableList;
private boolean doPrint;
public RecommenderCallable(ControlService srv, String market, Integer offset, String aDate, boolean doSave,
List<String> disableList, boolean doPrint) {
super();
this.srv = srv;
this.market = market;
this.offset = offset;
this.aDate = aDate;
this.doSave = doSave;
this.disableList = disableList;
this.doPrint = doPrint;
}
public ControlService getSrv() {
return srv;
}
public void setSrv(ControlService srv) {
this.srv = srv;
}
public String getMarket() {
return market;
}
public void setMarket(String market) {
this.market = market;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public String getaDate() {
return aDate;
}
public void setaDate(String aDate) {
this.aDate = aDate;
}
public boolean isDoSave() {
return doSave;
}
public void setDoSave(boolean doSave) {
this.doSave = doSave;
}
public List<String> getDisableList() {
return disableList;
}
public void setDisableList(List<String> disableList) {
this.disableList = disableList;
}
public boolean isDoPrint() {
return doPrint;
}
public void setDoPrint(boolean doPrint) {
this.doPrint = doPrint;
}
@Override
public List<MemoryItem> call() throws Exception {
return ServiceUtil.doRecommender(srv, market, 0, null, doSave, disableList, false);
}
}
}
| iclij/iclij-core/src/main/java/roart/component/ComponentRecommender.java | package roart.component;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roart.config.ConfigConstants;
import roart.config.IclijConfig;
import roart.config.IclijXMLConfig;
import roart.config.MyMyConfig;
import roart.model.IncDecItem;
import roart.model.MemoryItem;
import roart.pipeline.PipelineConstants;
import roart.queue.MyExecutors;
import roart.service.ControlService;
import roart.util.Constants;
import roart.util.ServiceUtil;
import roart.util.TimeUtil;
public class ComponentRecommender extends Component {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void enable(MyMyConfig conf) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORS, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEX, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACD, Boolean.TRUE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSI, Boolean.TRUE);
}
@Override
public void disable(MyMyConfig conf) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORS, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEX, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACD, Boolean.FALSE);
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSI, Boolean.FALSE);
}
@Override
public void handle(ControlService srv, MyMyConfig conf, Map<String, Map<String, Object>> resultMaps, List<Integer> positions,
Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap,
Map<Object[], List<MemoryItem>> okListMap, Map<String, String> nameMap, IclijConfig config, Map<String, Object> updateMap) {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
if (instance.wantEvolveRecommender()) {
srv.getEvolveRecommender(true, new ArrayList<>());
}
resultMaps = srv.getContent();
String market = okListMap.values().iterator().next().get(0).getMarket();
findBuySellRecommendations(resultMaps, nameMap, market, buys, sells, okConfMap, okListMap, srv, config);
}
private void findBuySellRecommendations(Map<String, Map<String, Object>> resultMaps, Map<String, String> nameMap, String market, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> okConfMap, Map<Object[], List<MemoryItem>> okListMap, ControlService srv, IclijConfig config) {
Object[] keys = new Object[2];
keys[0] = PipelineConstants.AGGREGATORRECOMMENDERINDICATOR;
keys[1] = 0;
keys = ComponentMLMACD.getRealKeys(keys, okConfMap.keySet());
//System.out.println(okListMap.get(keys));
Double confidenceFactor = okConfMap.get(keys);
//System.out.println(okConfMap.keySet());
//System.out.println(okListMap.keySet());
Map maps = (Map) resultMaps.get(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
Integer category = (Integer) maps.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) maps.get(PipelineConstants.CATEGORYTITLE);
Map<String, Map> resultMap0 = (Map<String, Map>) maps.get(PipelineConstants.RESULT);
Map<String, List<Double>> resultMap = (Map<String, List<Double>>) resultMap0.get("complex");
if (resultMap == null) {
return;
}
List<MyElement> list0 = new ArrayList<>();
List<MyElement> list1 = new ArrayList<>();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) resultMaps.get("" + category).get(PipelineConstants.LIST);
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
String key = entry.getKey();
List<List<Double>> resultList = entry.getValue();
List<Double> mainList = resultList.get(0);
if (mainList == null) {
continue;
}
List<Double> list = resultMap.get(key);
if (list == null) {
continue;
}
list0.add(new MyElement(key, list.get(0)));
list1.add(new MyElement(key, list.get(1)));
}
Collections.sort(list0, (o1, o2) -> (o2.getValue().compareTo(o1.getValue())));
Collections.sort(list1, (o1, o2) -> (o2.getValue().compareTo(o1.getValue())));
handleBuySell(nameMap, buys, sells, okListMap, srv, config, keys, confidenceFactor, list0);
//handleBuySell(nameMap, buys, sells, okListMap, srv, config, keys, confidenceFactor, list1);
}
private void handleBuySell(Map<String, String> nameMap, Map<String, IncDecItem> buys, Map<String, IncDecItem> sells,
Map<Object[], List<MemoryItem>> okListMap, ControlService srv, IclijConfig config, Object[] keys,
Double confidenceFactor, List<MyElement> list) {
int listSize = list.size();
int recommend = config.recommendTopBottom();
if (listSize < recommend * 3) {
return;
}
List<MyElement> topList = list.subList(0, recommend);
List<MyElement> bottomList = list.subList(listSize - recommend, listSize);
Double max = list.get(0).getValue();
Double min = list.get(listSize - 1).getValue();
Double diff = max - min;
for (MyElement element : topList) {
double confidence = confidenceFactor * (element.getValue() - min) / diff;
String recommendation = "recommend buy";
//IncDecItem incdec = getIncDec(element, confidence, recommendation, nameMap, market);
//incdec.setIncrease(true);
//buys.put(element.getKey(), incdec);
IncDecItem incdec = ComponentMLMACD.mapAdder(buys, element.getKey(), confidence, okListMap.get(keys), nameMap, TimeUtil.convertDate(srv.conf.getdate()));
incdec.setIncrease(true);
}
for (MyElement element : bottomList) {
double confidence = confidenceFactor * (element.getValue() - min) / diff;
String recommendation = "recommend sell";
//IncDecItem incdec = getIncDec(element, confidence, recommendation, nameMap, market);
//incdec.setIncrease(false);
IncDecItem incdec = ComponentMLMACD.mapAdder(sells, element.getKey(), confidence, okListMap.get(keys), nameMap, TimeUtil.convertDate(srv.conf.getdate()));
incdec.setIncrease(false);
}
}
private IncDecItem getIncDec(MyElement element, double confidence, String recommendation, Map<String, String> nameMap, String market) {
IncDecItem incdec = new IncDecItem();
incdec.setRecord(LocalDate.now());
incdec.setId(element.getKey());
incdec.setMarket(market);
incdec.setDescription(recommendation);
incdec.setName(nameMap.get(element.getKey()));
incdec.setScore(confidence);
return incdec;
}
public List<String> getBuy() {
List<String> buyList = new ArrayList<>();
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTHISTOGRAMNODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTHISTOGRAMDELTANODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTMOMENTUMNODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDBUYWEIGHTMOMENTUMDELTANODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSIBUYWEIGHTRSINODE);
buyList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSIBUYWEIGHTRSIDELTANODE);
return buyList;
}
public List<String> getSell() {
List<String> sellList = new ArrayList<>();
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTHISTOGRAMNODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTHISTOGRAMDELTANODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTMOMENTUMNODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXMACDSELLWEIGHTMOMENTUMDELTANODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSISELLWEIGHTRSINODE);
sellList.add(ConfigConstants.AGGREGATORSINDICATORRECOMMENDERCOMPLEXRSISELLWEIGHTRSIDELTANODE);
return sellList;
}
@Override
public Map<String, String> improve(MyMyConfig conf, Map<String, Map<String, Object>> maps, List<Integer> positions,
Map<String, IncDecItem> buys, Map<String, IncDecItem> sells, Map<Object[], Double> badConfMap,
Map<Object[], List<MemoryItem>> badListMap, Map<String, String> nameMap) {
Map<String, String> retMap = new HashMap<>();
List<String> list = getBuy();
retMap.putAll(handleBuySell(conf, badListMap, list));
list = getSell();
retMap.putAll(handleBuySell(conf, badListMap, list));
return retMap;
}
private List<List<String>> disableAllButOne(List<String> list) {
List<List<String>> listPerm = new ArrayList<>();
int size = list.size();
int bitsize = (1 << size) - 1;
for (int i = 0; i < size; i++) {
int pattern = bitsize - (1 << i);
log.info("using {}", Integer.toBinaryString(pattern));
List<String> aList = new ArrayList<>();
for (int j = 0; j < size; j++) {
if ((pattern & (1 << j)) != 0) {
aList.add(list.get(j));
}
}
listPerm.add(aList);
}
return listPerm;
}
private Map<String, String> handleBuySell(MyMyConfig conf, Map<Object[], List<MemoryItem>> badListMap, List<String> list) {
Map<String, String> retMap = new HashMap<>();
//List<List<String>> listPerm = getAllPerms(list);
List<List<String>> listPerm = disableAllButOne(list);
String market = badListMap.values().iterator().next().get(0).getMarket();
ControlService srv = new ControlService();
srv.getConfig();
// plus testrecommendfactor
int factor = 100;
log.info("market {}", market);
//log.info("factor {}", factor);
//srv.conf.getConfigValueMap().put(ConfigConstants.TESTRECOMMENDFACTOR, factor);
int index = 0;
Map<Future<List<MemoryItem>>, List<String>> futureMap = new HashMap<>();
List<Future<List<MemoryItem>>> futureList = new ArrayList<>();
for (List<String> aList : listPerm) {
log.info("For disable {}", Integer.toHexString(index++));
try {
//List<MemoryItem> memories = ServiceUtil.doRecommender(srv, market, 0, null, false, aList, false);
Callable callable = new RecommenderCallable(srv, market, 0, null, false, aList, false);
Future<List<MemoryItem>> future = MyExecutors.run(callable);
futureList.add(future);
futureMap.put(future, aList);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
for (Future<List<MemoryItem>> future : futureList) {
try {
List<String> aList = futureMap.get(future);
List<MemoryItem> memories = future.get();
if (memories == null) {
log.info("No memories in {}", market);
continue;
}
List<Double> newConfidenceList = new ArrayList<>();
for(MemoryItem memory : memories) {
newConfidenceList.add(memory.getConfidence());
}
log.info("New confidences {}", newConfidenceList);
retMap.put(aList.toString(), newConfidenceList.toString());
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
}
return retMap;
}
private List<List<String>> getAllPerms(List<String> list) {
List<List<String>> listPerm = new ArrayList<>();
int size = list.size();
int bitsize = (1 << size) - 1;
for (int i = 0; i < bitsize; i++) {
List<String> aList = new ArrayList<>();
for (int j = 0; j < size; j++) {
if ((i & (1 << j)) != 0) {
aList.add(list.get(j));
}
}
listPerm.add(aList);
}
return listPerm;
}
public List<MemoryItem> calculateRecommender(String market, int futuredays, LocalDate baseDate, LocalDate futureDate,
String categoryTitle, Map<String, List<Double>> recommendBuySell, double buyMedian, double sellMedian,
Map<String, Map<String, Object>> result, Map<String, List<List<Double>>> categoryValueMap, Integer usedsec, boolean doSave, boolean doPrint) throws Exception {
List<MemoryItem> memoryList = new ArrayList<>();
Set<Double> changeSet = getChangeSet(futuredays, categoryValueMap);
Double medianChange = ServiceUtil.median(changeSet);
/*
getMemoriesOld(market, futuredays, baseDate, futureDate, categoryTitle, recommendBuySell, buyMedian, sellMedian,
categoryValueMap, usedsec, doSave, memoryList, medianChange);
*/
getMemories(market, futuredays, baseDate, futureDate, categoryTitle, recommendBuySell, buyMedian, sellMedian,
categoryValueMap, usedsec, doSave, memoryList, medianChange, changeSet, doPrint);
return memoryList;
}
private Set<Double> getChangeSet(int futuredays, Map<String, List<List<Double>>> categoryValueMap) {
Set<Double> changeSet = new HashSet<>();
for (Entry<String, List<List<Double>>> entry : categoryValueMap.entrySet()) {
List<List<Double>> resultList = entry.getValue();
List<Double> mainList = resultList.get(0);
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
Double change = valFuture / valNow;
changeSet.add(change);
}
}
}
return changeSet;
}
public void getMemories(String market, int futuredays, LocalDate baseDate, LocalDate futureDate,
String categoryTitle, Map<String, List<Double>> recommendBuySell, double buyMedian, double sellMedian,
Map<String, List<List<Double>>> categoryValueMap, Integer usedsec, boolean doSave,
List<MemoryItem> memoryList, Double medianChange, Set<Double> changeSet, boolean doPrint) throws Exception {
double goodBuy = 0;
double goodSell = 0;
long totalBuy = 0;
long totalSell = 0;
Optional<Double> minOpt = changeSet.parallelStream().reduce(Double::min);
Double minChange = 0.0;
if (minOpt.isPresent()) {
minChange = minOpt.get();
}
Optional<Double> maxOpt = changeSet.parallelStream().reduce(Double::max);
Double maxChange = 0.0;
if (maxOpt.isPresent()) {
maxChange = maxOpt.get();
}
Double diffChange = maxChange - minChange;
List<Double> buyList = new ArrayList<>();
List<Double> sellList = new ArrayList<>();
for (List<Double> list : recommendBuySell.values()) {
buyList.add(list.get(0));
sellList.add(list.get(1));
}
Optional<Double> buyMaxOpt = buyList.parallelStream().reduce(Double::max);
if (!buyMaxOpt.isPresent()) {
}
Double buyMax = buyMaxOpt.get();
Optional<Double> buyMinOpt = buyList.parallelStream().reduce(Double::min);
if (!buyMinOpt.isPresent()) {
}
Double buyMin = buyMinOpt.get();
Double diffBuy = buyMax - buyMin;
Optional<Double> sellMaxOpt = sellList.parallelStream().reduce(Double::max);
if (!sellMaxOpt.isPresent()) {
}
Double sellMax = sellMaxOpt.get();
Optional<Double> sellMinOpt = sellList.parallelStream().reduce(Double::min);
if (!sellMinOpt.isPresent()) {
}
Double sellMin = sellMinOpt.get();
Double diffSell = sellMax - sellMin;
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
Double change = null;
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
change = valFuture / valNow;
}
}
if (change == null) {
continue;
}
List<Double> vals = recommendBuySell.get(key);
if (vals == null) {
continue;
}
Double buy = vals.get(0);
Double sell = vals.get(1);
if (buy != null) {
totalBuy++;
//double delta = change / buy * (buyMax / maxChange);
double expectedChange = minChange + diffChange * (buy - buyMin) / diffBuy;
//double delta = expectedChange / change;
double confidence = 1 - Math.abs(expectedChange - change) / diffChange;
/*
if (delta > 1) {
delta = 1 / delta;
}
*/
goodBuy += confidence;
}
if (sell != null) {
totalSell++;
//double delta = change / sell * (sellMax / minChange);
double expectedChange = minChange + diffChange * (sell - sellMin) / diffSell;
//double delta = expectedChange / change;
/*
if (delta > 1) {
delta = 1 / delta;
}
*/
double confidence = 1 - Math.abs(expectedChange - change) / diffChange;
goodSell += confidence;
}
}
MemoryItem buyMemory = new MemoryItem();
buyMemory.setMarket(market);
buyMemory.setRecord(LocalDate.now());
buyMemory.setDate(baseDate);
buyMemory.setUsedsec(usedsec);
buyMemory.setFuturedays(futuredays);
buyMemory.setFuturedate(futureDate);
buyMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
buyMemory.setSubcomponent("buy");
buyMemory.setCategory(categoryTitle);
buyMemory.setPositives((long) goodBuy);
buyMemory.setSize(totalBuy);
buyMemory.setConfidence((double) goodBuy / totalBuy);
buyMemory.setPosition(0);
if (doSave) {
buyMemory.save();
}
MemoryItem sellMemory = new MemoryItem();
sellMemory.setMarket(market);
sellMemory.setRecord(LocalDate.now());
sellMemory.setDate(baseDate);
sellMemory.setUsedsec(usedsec);
sellMemory.setFuturedays(futuredays);
sellMemory.setFuturedate(futureDate);
sellMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
sellMemory.setSubcomponent("sell");
sellMemory.setCategory(categoryTitle);
sellMemory.setPositives((long) goodSell);
sellMemory.setSize(totalSell);
sellMemory.setConfidence((double) goodSell / totalSell);
sellMemory.setPosition(1);
if (doSave) {
sellMemory.save();
}
//System.out.println("testing buy " + goodBuy + " " + totalBuy + " sell " + goodSell + " " + totalSell);
//System.out.println("k3 " + categoryValueMap.get("VIX"));
//System.out.println(result.get("Index").keySet());
if (doPrint) {
System.out.println(buyMemory);
System.out.println(sellMemory);
}
memoryList.add(buyMemory);
memoryList.add(sellMemory);
}
private class MyElement {
public String key;
public Double value;
public MyElement(String key, Double value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public Double getValue() {
return value;
}
}
class RecommenderCallable implements Callable {
private ControlService srv;
private String market;
private Integer offset;
private String aDate;
private boolean doSave;
private List<String> disableList;
private boolean doPrint;
public RecommenderCallable(ControlService srv, String market, Integer offset, String aDate, boolean doSave,
List<String> disableList, boolean doPrint) {
super();
this.srv = srv;
this.market = market;
this.offset = offset;
this.aDate = aDate;
this.doSave = doSave;
this.disableList = disableList;
this.doPrint = doPrint;
}
public ControlService getSrv() {
return srv;
}
public void setSrv(ControlService srv) {
this.srv = srv;
}
public String getMarket() {
return market;
}
public void setMarket(String market) {
this.market = market;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public String getaDate() {
return aDate;
}
public void setaDate(String aDate) {
this.aDate = aDate;
}
public boolean isDoSave() {
return doSave;
}
public void setDoSave(boolean doSave) {
this.doSave = doSave;
}
public List<String> getDisableList() {
return disableList;
}
public void setDisableList(List<String> disableList) {
this.disableList = disableList;
}
public boolean isDoPrint() {
return doPrint;
}
public void setDoPrint(boolean doPrint) {
this.doPrint = doPrint;
}
@Override
public List<MemoryItem> call() throws Exception {
return ServiceUtil.doRecommender(srv, market, 0, null, doSave, disableList, false);
}
}
}
| Continue if null (but should not happen).
| iclij/iclij-core/src/main/java/roart/component/ComponentRecommender.java | Continue if null (but should not happen). | <ide><path>clij/iclij-core/src/main/java/roart/component/ComponentRecommender.java
<ide> Double min = list.get(listSize - 1).getValue();
<ide> Double diff = max - min;
<ide> for (MyElement element : topList) {
<add> if (confidenceFactor == null || element.getValue() == null) {
<add> int jj = 0;
<add> continue;
<add> }
<ide> double confidence = confidenceFactor * (element.getValue() - min) / diff;
<ide> String recommendation = "recommend buy";
<ide> //IncDecItem incdec = getIncDec(element, confidence, recommendation, nameMap, market); |
|
Java | apache-2.0 | 457a741bf5137c17ef466843e6e71b57ad9fec00 | 0 | kieker-monitoring/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,HaStr/kieker,HaStr/kieker | package kieker.loganalysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.TreeSet;
import kieker.common.logReader.IMonitoringRecordConsumer;
import kieker.common.logReader.filesystemReader.FilesystemReader;
import kieker.loganalysis.datamodel.ExecutionSequence;
import kieker.loganalysis.datamodel.InvalidTraceException;
import kieker.loganalysis.datamodel.MessageSequence;
import kieker.loganalysis.plugins.DependencyGraphPlugin;
import kieker.loganalysis.plugins.SequenceDiagramPlugin;
import kieker.loganalysis.recordConsumer.ExecutionSequenceRepositoryFiller;
import kieker.tpmon.core.TpmonController;
import kieker.tpmon.monitoringRecord.AbstractKiekerMonitoringRecord;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* kieker.loganalysis.LogAnalysisTool
*
* ==================LICENCE=========================
* Copyright 2006-2009 Kieker Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 Andre van Hoorn
*/
public class LogAnalysisTool {
private static final Log log = LogFactory.getLog(LogAnalysisTool.class);
private static final String SEQUENCE_DIAGRAM_FN_PREFIX = "sequenceDiagram";
private static final String DEPENDENCY_GRAPH_FN_PREFIX = "dependencyGraph";
private static final String MESSAGE_TRACES_FN_PREFIX = "messageTraces";
private static final String EXECUTION_TRACES_FN_PREFIX = "executionTraces";
private static CommandLine cmdl = null;
private static final CommandLineParser cmdlParser = new BasicParser();
private static final HelpFormatter cmdHelpFormatter = new HelpFormatter();
private static final Options cmdlOpts = new Options();
private static String inputDir = null;
private static String outputDir = null;
private static String task = null;
private static String outputFnPrefix = null;
private static TreeSet<Long> selectedTraces = null;
static {
cmdlOpts.addOption(OptionBuilder.withLongOpt("inputdir").withArgName("dir").hasArg(true).isRequired(true).withDescription("Log directory to read data from").withValueSeparator('=').create("i"));
cmdlOpts.addOption(OptionBuilder.withLongOpt("outputdir").withArgName("dir").hasArg(true).isRequired(true).withDescription("Directory for the generated file(s)").withValueSeparator('=').create("o"));
cmdlOpts.addOption(OptionBuilder.withLongOpt("output-filename-prefix").withArgName("dir").hasArg(true).isRequired(false).withDescription("Prefix for output filenames\n").withValueSeparator('=').create("p"));
//OptionGroup cmdlOptGroupTask = new OptionGroup();
//cmdlOptGroupTask.isRequired();
cmdlOpts.addOption(OptionBuilder.withLongOpt("plot-Sequence-Diagram").hasArg(false).withDescription("Generate sequence diagrams (.pic format) from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("plot-Dependency-Graph").hasArg(false).withDescription("Generate a dependency graph (.dot format) from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("print-Message-Trace").hasArg(false).withDescription("Generate a message trace representation from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("print-Execution-Trace").hasArg(false).withDescription("Generate an execution trace representation from log data").create());
//cmdlOpts.addOptionGroup(cmdlOptGroupTask);
cmdlOpts.addOption(OptionBuilder.withLongOpt("select-traces").withArgName("id0,...,idn").hasArgs().isRequired(false).withDescription("Consider only the traces identified by the comma-separated list of trace IDs. Defaults to all traces.").create("t"));
}
private static boolean parseArgs(String[] args) {
try {
cmdl = cmdlParser.parse(cmdlOpts, args);
} catch (ParseException e) {
System.err.println("Error parsing arguments: " + e.getMessage());
printUsage();
return false;
}
return true;
}
private static void printUsage() {
cmdHelpFormatter.printHelp(LogAnalysisTool.class.getName(), cmdlOpts);
}
private static boolean initFromArgs() {
inputDir = cmdl.getOptionValue("inputdir") + File.separator;
outputDir = cmdl.getOptionValue("outputdir") + File.separator;
outputFnPrefix = cmdl.getOptionValue("output-filename-prefix", "");
if (cmdl.hasOption("select-traces")) { /* Parse liste of trace Ids */
String[] traceIdList = cmdl.getOptionValues("select-traces");
selectedTraces = new TreeSet<Long>();
int numSelectedTraces = traceIdList.length;
try {
for (String idStr : traceIdList) {
selectedTraces.add(Long.valueOf(idStr));
}
log.info(numSelectedTraces + " trace" + (numSelectedTraces > 1 ? "s" : "") + " selected");
} catch (Exception e) {
System.err.println("Failed to parse list of trace IDs: " + traceIdList + "(" + e.getMessage() + ")");
return false;
}
}
return true;
}
private static boolean dispatchTasks() {
boolean retVal = true;
int numRequestedTasks = 0;
try {
if (retVal && cmdl.hasOption("print-Message-Trace")) {
numRequestedTasks++;
retVal = task_genMessageTracesForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("print-Execution-Trace")) {
numRequestedTasks++;
retVal = task_genExecutionTracesForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("plot-Sequence-Diagram")) {
numRequestedTasks++;
retVal = task_genSequenceDiagramsForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("plot-Dependency-Graph")) {
numRequestedTasks++;
retVal = task_genDependencyGraphsForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if(!retVal) {
System.err.println("A task failed");
}
} catch (Exception ex) {
System.err.println("An error occured: " + ex);
log.error("Exception", ex);
retVal = false;
}
if (numRequestedTasks == 0) {
System.err.println("No task requested");
printUsage();
retVal = false;
}
return retVal;
}
public static void main(String args[]) {
if (true && ((!parseArgs(args) || !initFromArgs() || !dispatchTasks()))) {
System.exit(1);
}
/* As long as we have a dependency from logAnalysis to tpmon,
* we need to explicitly terminate tpmon. */
TpmonController.getInstance().terminateMonitoring();
}
/**
* Reads the traces from the directory inputDirName and write the
* sequence diagrams for traces with IDs given in traceSet to
* the directory outputFnPrefix.
* If traceSet is null, a sequence diagram for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genSequenceDiagramsForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output sequence diagrams */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numPlots = 0;
long lastTraceId = -1;
String outputFnBase = new File(outputFnPrefix + SEQUENCE_DIAGRAM_FN_PREFIX).getCanonicalPath();
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
//String fileName = "/tmp/seqDia" + msgTrace.traceId + ".pic";
MessageSequence mSeq = t.toMessageSequence();
if (mSeq == null) {
log.error("Transformation to message trace failed for trace " + id);
retVal = false;
}
SequenceDiagramPlugin.writeDotForMessageTrace(mSeq, outputFnBase + "-" + id + ".pic");
numPlots++;
lastTraceId = t.getTraceId();
}
}
if (numPlots > 0) {
System.out.println("Wrote " + numPlots + " sequence diagram" + (numPlots > 1 ? "s" : "") + " to file" + (numPlots > 1 ? "s" : "") + " with name pattern '" + outputFnBase + "-<traceId>.pic'");
System.out.println("Pic files can be converted using the pic2plot tool (package plotutils)");
System.out.println("Example: pic2plot -T svg " + outputFnBase + "-" + ((numPlots > 0) ? lastTraceId : "<traceId>") + ".pic > " + outputFnBase + "-" + ((numPlots > 0) ? lastTraceId : "<traceId>") + ".svg");
} else {
System.out.println("Wrote 0 sequence diagrams");
}
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* dependency graph for traces with IDs given in traceSet to
* the directory outputFnPrefix.
* If traceSet is null, a dependency graph containing the information
* of all traces is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genDependencyGraphsForTraceSet(String inputDirName, String outputFnPrefix, TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output dependency graphs */
Collection<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.values();
String outputFnBase = new File(outputFnPrefix + DEPENDENCY_GRAPH_FN_PREFIX).getCanonicalPath();
DependencyGraphPlugin.writeDotFromExecutionTraces(seqEnum, outputFnBase + ".pic", traceIds);
System.out.println("Wrote dependency graph to file '" + outputFnBase + ".pic" + "'");
System.out.println("Dot file can be converted using the dot tool");
System.out.println("Example: dot -T svg " + outputFnBase + ".pic" + " > " + outputFnBase + ".svg");
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* message trace representation for traces with IDs given in traceSet
* to the directory outputFnPrefix.
* If traceSet is null, a message trace for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genMessageTracesForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output message traces */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numTraces = 0;
String outputFn = new File(outputFnPrefix + MESSAGE_TRACES_FN_PREFIX + ".txt").getCanonicalPath();
PrintStream ps = System.out;
try {
ps = new PrintStream(new FileOutputStream(outputFn));
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
numTraces++;
ps.println(t.toMessageSequence());
}
}
System.out.println("Wrote " + numTraces + " messageTraces" + (numTraces > 1 ? "s" : "") + " to file '" + outputFn + "'");
} catch (FileNotFoundException e) {
log.error("File not found", e);
retVal = false;
} finally {
ps.close();
}
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* execution trace representation for traces with IDs given in traceSet
* to the directory outputFnPrefix.
* If traceSet is null, an execution trace for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genExecutionTracesForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output message traces */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numTraces = 0;
String outputFn = new File(outputFnPrefix + EXECUTION_TRACES_FN_PREFIX + ".txt").getCanonicalPath();
PrintStream ps = System.out;
try {
ps = new PrintStream(new FileOutputStream(outputFn));
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
numTraces++;
ps.println(t);
}
}
System.out.println("Wrote " + numTraces + " executionTraces" + (numTraces > 1 ? "s" : "") + " to file '" + outputFn + "'");
} catch (FileNotFoundException e) {
log.error("File not found", e);
retVal = false;
} finally {
ps.close();
}
return retVal;
}
}
| src/kieker/loganalysis/LogAnalysisTool.java | package kieker.loganalysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.TreeSet;
import kieker.common.logReader.filesystemReader.FilesystemReader;
import kieker.loganalysis.datamodel.ExecutionSequence;
import kieker.loganalysis.datamodel.InvalidTraceException;
import kieker.loganalysis.datamodel.MessageSequence;
import kieker.loganalysis.plugins.DependencyGraphPlugin;
import kieker.loganalysis.plugins.SequenceDiagramPlugin;
import kieker.loganalysis.recordConsumer.ExecutionSequenceRepositoryFiller;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* kieker.loganalysis.LogAnalysisTool
*
* ==================LICENCE=========================
* Copyright 2006-2009 Kieker Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 Andre van Hoorn
*/
public class LogAnalysisTool {
private static final Log log = LogFactory.getLog(LogAnalysisTool.class);
private static final String SEQUENCE_DIAGRAM_FN_PREFIX = "sequenceDiagram";
private static final String DEPENDENCY_GRAPH_FN_PREFIX = "dependencyGraph";
private static final String MESSAGE_TRACES_FN_PREFIX = "messageTraces";
private static final String EXECUTION_TRACES_FN_PREFIX = "executionTraces";
private static CommandLine cmdl = null;
private static final CommandLineParser cmdlParser = new BasicParser();
private static final HelpFormatter cmdHelpFormatter = new HelpFormatter();
private static final Options cmdlOpts = new Options();
private static String inputDir = null;
private static String outputDir = null;
private static String task = null;
private static String outputFnPrefix = null;
private static TreeSet<Long> selectedTraces = null;
static {
cmdlOpts.addOption(OptionBuilder.withLongOpt("inputdir").withArgName("dir").hasArg(true).isRequired(true).withDescription("Log directory to read data from").withValueSeparator('=').create("i"));
cmdlOpts.addOption(OptionBuilder.withLongOpt("outputdir").withArgName("dir").hasArg(true).isRequired(true).withDescription("Directory for the generated file(s)").withValueSeparator('=').create("o"));
cmdlOpts.addOption(OptionBuilder.withLongOpt("output-filename-prefix").withArgName("dir").hasArg(true).isRequired(false).withDescription("Prefix for output filenames\n").withValueSeparator('=').create("p"));
//OptionGroup cmdlOptGroupTask = new OptionGroup();
//cmdlOptGroupTask.isRequired();
cmdlOpts.addOption(OptionBuilder.withLongOpt("plot-Sequence-Diagram").hasArg(false).withDescription("Generate sequence diagrams (.pic format) from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("plot-Dependency-Graph").hasArg(false).withDescription("Generate a dependency graph (.dot format) from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("print-Message-Trace").hasArg(false).withDescription("Generate a message trace representation from log data").create());
cmdlOpts.addOption(OptionBuilder.withLongOpt("print-Execution-Trace").hasArg(false).withDescription("Generate an execution trace representation from log data").create());
//cmdlOpts.addOptionGroup(cmdlOptGroupTask);
cmdlOpts.addOption(OptionBuilder.withLongOpt("select-traces").withArgName("id0,...,idn").hasArgs().isRequired(false).withDescription("Consider only the traces identified by the comma-separated list of trace IDs. Defaults to all traces.").create("t"));
}
private static boolean parseArgs(String[] args) {
try {
cmdl = cmdlParser.parse(cmdlOpts, args);
} catch (ParseException e) {
System.err.println("Error parsing arguments: " + e.getMessage());
printUsage();
return false;
}
return true;
}
private static void printUsage() {
cmdHelpFormatter.printHelp(LogAnalysisTool.class.getName(), cmdlOpts);
}
private static boolean initFromArgs() {
inputDir = cmdl.getOptionValue("inputdir") + File.separator;
outputDir = cmdl.getOptionValue("outputdir") + File.separator;
outputFnPrefix = cmdl.getOptionValue("output-filename-prefix", "");
if (cmdl.hasOption("select-traces")) { /* Parse liste of trace Ids */
String[] traceIdList = cmdl.getOptionValues("select-traces");
selectedTraces = new TreeSet<Long>();
int numSelectedTraces = traceIdList.length;
try {
for (String idStr : traceIdList) {
selectedTraces.add(Long.valueOf(idStr));
}
log.info(numSelectedTraces + " trace" + (numSelectedTraces > 1 ? "s" : "") + " selected");
} catch (Exception e) {
System.err.println("Failed to parse list of trace IDs: " + traceIdList + "(" + e.getMessage() + ")");
return false;
}
}
return true;
}
private static boolean dispatchTasks() {
boolean retVal = true;
int numRequestedTasks = 0;
try {
if (retVal && cmdl.hasOption("print-Message-Trace")) {
numRequestedTasks++;
retVal = task_genMessageTracesForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("print-Execution-Trace")) {
numRequestedTasks++;
retVal = task_genExecutionTracesForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("plot-Sequence-Diagram")) {
numRequestedTasks++;
retVal = task_genSequenceDiagramsForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if (retVal && cmdl.hasOption("plot-Dependency-Graph")) {
numRequestedTasks++;
retVal = task_genDependencyGraphsForTraceSet(inputDir, outputDir + File.separator + outputFnPrefix, selectedTraces);
}
if(!retVal) {
System.err.println("A task failed");
}
} catch (Exception ex) {
System.err.println("An error occured: " + ex);
log.error("Exception", ex);
retVal = false;
}
if (numRequestedTasks == 0) {
System.err.println("No task requested");
printUsage();
retVal = false;
}
return retVal;
}
public static void main(String args[]) {
if (!parseArgs(args) || !initFromArgs() || !dispatchTasks()) {
System.exit(1);
}
}
/**
* Reads the traces from the directory inputDirName and write the
* sequence diagrams for traces with IDs given in traceSet to
* the directory outputFnPrefix.
* If traceSet is null, a sequence diagram for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genSequenceDiagramsForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output sequence diagrams */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numPlots = 0;
long lastTraceId = -1;
String outputFnBase = new File(outputFnPrefix + SEQUENCE_DIAGRAM_FN_PREFIX).getCanonicalPath();
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
//String fileName = "/tmp/seqDia" + msgTrace.traceId + ".pic";
MessageSequence mSeq = t.toMessageSequence();
if (mSeq == null) {
log.error("Transformation to message trace failed for trace " + id);
retVal = false;
}
SequenceDiagramPlugin.writeDotForMessageTrace(mSeq, outputFnBase + "-" + id + ".pic");
numPlots++;
lastTraceId = t.getTraceId();
}
}
if (numPlots > 0) {
System.out.println("Wrote " + numPlots + " sequence diagram" + (numPlots > 1 ? "s" : "") + " to file" + (numPlots > 1 ? "s" : "") + " with name pattern '" + outputFnBase + "-<traceId>.pic'");
System.out.println("Pic files can be converted using the pic2plot tool (package plotutils)");
System.out.println("Example: pic2plot -T svg " + outputFnBase + "-" + ((numPlots > 0) ? lastTraceId : "<traceId>") + ".pic > " + outputFnBase + "-" + ((numPlots > 0) ? lastTraceId : "<traceId>") + ".svg");
} else {
System.out.println("Wrote 0 sequence diagrams");
}
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* dependency graph for traces with IDs given in traceSet to
* the directory outputFnPrefix.
* If traceSet is null, a dependency graph containing the information
* of all traces is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genDependencyGraphsForTraceSet(String inputDirName, String outputFnPrefix, TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output dependency graphs */
Collection<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.values();
String outputFnBase = new File(outputFnPrefix + DEPENDENCY_GRAPH_FN_PREFIX).getCanonicalPath();
DependencyGraphPlugin.writeDotFromExecutionTraces(seqEnum, outputFnBase + ".pic", traceIds);
System.out.println("Wrote dependency graph to file '" + outputFnBase + ".pic" + "'");
System.out.println("Dot file can be converted using the dot tool");
System.out.println("Example: dot -T svg " + outputFnBase + ".pic" + " > " + outputFnBase + ".svg");
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* message trace representation for traces with IDs given in traceSet
* to the directory outputFnPrefix.
* If traceSet is null, a message trace for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genMessageTracesForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException, InvalidTraceException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output message traces */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numTraces = 0;
String outputFn = new File(outputFnPrefix + MESSAGE_TRACES_FN_PREFIX + ".txt").getCanonicalPath();
PrintStream ps = System.out;
try {
ps = new PrintStream(new FileOutputStream(outputFn));
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
numTraces++;
ps.println(t.toMessageSequence());
}
}
System.out.println("Wrote " + numTraces + " messageTraces" + (numTraces > 1 ? "s" : "") + " to file '" + outputFn + "'");
} catch (FileNotFoundException e) {
log.error("File not found", e);
retVal = false;
} finally {
ps.close();
}
return retVal;
}
/**
* Reads the traces from the directory inputDirName and write the
* execution trace representation for traces with IDs given in traceSet
* to the directory outputFnPrefix.
* If traceSet is null, an execution trace for each trace is generated.
*
* @param inputDirName
* @param outputFnPrefix
* @param traceSet
*/
private static boolean task_genExecutionTracesForTraceSet(String inputDirName, String outputFnPrefix, final TreeSet<Long> traceIds) throws IOException {
boolean retVal = true;
log.info("Reading traces from directory '" + inputDirName + "'");
/* Read log data and collect execution traces */
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
//analysisInstance.addLogReader(new FSReader(inputDirName));
analysisInstance.addLogReader(new FilesystemReader(inputDirName));
ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
analysisInstance.addConsumer(seqRepConsumer);
analysisInstance.run();
/* Generate and output message traces */
Enumeration<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.elements();
int numTraces = 0;
String outputFn = new File(outputFnPrefix + EXECUTION_TRACES_FN_PREFIX + ".txt").getCanonicalPath();
PrintStream ps = System.out;
try {
ps = new PrintStream(new FileOutputStream(outputFn));
while (seqEnum.hasMoreElements()) {
ExecutionSequence t = seqEnum.nextElement();
Long id = t.getTraceId();
if (traceIds == null || traceIds.contains(id)) {
numTraces++;
ps.println(t);
}
}
System.out.println("Wrote " + numTraces + " executionTraces" + (numTraces > 1 ? "s" : "") + " to file '" + outputFn + "'");
} catch (FileNotFoundException e) {
log.error("File not found", e);
retVal = false;
} finally {
ps.close();
}
return retVal;
}
}
| workaround
| src/kieker/loganalysis/LogAnalysisTool.java | workaround | <ide><path>rc/kieker/loganalysis/LogAnalysisTool.java
<ide> import java.util.Enumeration;
<ide>
<ide> import java.util.TreeSet;
<add>import kieker.common.logReader.IMonitoringRecordConsumer;
<ide> import kieker.common.logReader.filesystemReader.FilesystemReader;
<ide> import kieker.loganalysis.datamodel.ExecutionSequence;
<ide> import kieker.loganalysis.datamodel.InvalidTraceException;
<ide> import kieker.loganalysis.plugins.SequenceDiagramPlugin;
<ide> import kieker.loganalysis.recordConsumer.ExecutionSequenceRepositoryFiller;
<ide>
<add>import kieker.tpmon.core.TpmonController;
<add>import kieker.tpmon.monitoringRecord.AbstractKiekerMonitoringRecord;
<ide> import org.apache.commons.cli.BasicParser;
<ide> import org.apache.commons.cli.CommandLine;
<ide> import org.apache.commons.cli.CommandLineParser;
<ide> }
<ide>
<ide> public static void main(String args[]) {
<del> if (!parseArgs(args) || !initFromArgs() || !dispatchTasks()) {
<add> if (true && ((!parseArgs(args) || !initFromArgs() || !dispatchTasks()))) {
<ide> System.exit(1);
<ide> }
<add>
<add> /* As long as we have a dependency from logAnalysis to tpmon,
<add> * we need to explicitly terminate tpmon. */
<add> TpmonController.getInstance().terminateMonitoring();
<ide> }
<ide>
<ide> /**
<ide> log.info("Reading traces from directory '" + inputDirName + "'");
<ide> /* Read log data and collect execution traces */
<ide> LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
<del> //analysisInstance.addLogReader(new FSReader(inputDirName));
<ide> analysisInstance.addLogReader(new FilesystemReader(inputDirName));
<ide> ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
<ide> analysisInstance.addConsumer(seqRepConsumer); |
|
Java | apache-2.0 | a5b896ddcc8237646eb76d0b094e82d71fce35de | 0 | BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.naoth.rc;
import de.naoth.rc.components.ExceptionDialog;
import de.naoth.rc.core.server.MessageServer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
/**
*
* @author thomas
*/
public class Helper
{
public static void handleException(final String message, final Exception ex)
{
// log
Logger.getLogger("RobotControl").log(Level.SEVERE, message, ex);
// show
if (SwingUtilities.isEventDispatchThread())
{
ExceptionDialog dlg = new ExceptionDialog(null, message, ex);
dlg.setVisible(true);
} else
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
ExceptionDialog dlg = new ExceptionDialog(null, message, ex);
dlg.setVisible(true);
}
});
}
}
public static void handleException(Exception ex)
{
handleException(null, ex);
}
/**
* Checks if a we are connected to a server and if not displays an error
* message to the user.
*/
public static boolean checkConnected(MessageServer server)
{
if (server.isConnected())
{
return true;
} else
{
JOptionPane.showMessageDialog(null,
"Not connected. Please connect first to a robot.", "WARNING",
JOptionPane.WARNING_MESSAGE);
return false;
}
}//end checkConnected
/**
* Reads a resource file as string.
*/
public static String getResourceAsString(String name)
{
InputStream stream = (new Object()).getClass().getResourceAsStream(name);
StringBuilder builder = new StringBuilder();
if (stream != null)
{
try
{
while (stream.available() > 0)
{
builder.append((char) stream.read());
}
} catch (IOException e)
{
Helper.handleException(e);
}
return builder.toString();
}//end if
return null;
}//end getResourceAsString
public static List<Path> getFiles(String location) {
return getFiles(location, null);
}
public static List<Path> getFiles(String location, Predicate<Path> filter) {
try {
URI res = Helper.class.getResource(location).toURI();
// handle current execution location (jar, file)
Path resPath;
if (res.getScheme().equals("jar")) {
FileSystem fs = FileSystems.newFileSystem(res, Collections.<String, Object>emptyMap());
resPath = fs.getPath(location);
} else {
resPath = Paths.get(res);
}
Stream<Path> s = Files.walk(resPath, 1);
if (filter != null) { s = s.filter(filter); }
return s.sorted().collect(Collectors.toList());
} catch (IOException | URISyntaxException e) {
Logger.getLogger(HelpDialog.class.getName()).log(Level.SEVERE, null, e);
}
return Collections.emptyList();
}
/**
* Validates the name of a given file, i.e., if the file name doesn't have the
* proper ending, it will be appended.
*
* @param file the file which name has to be validated
* @param filter a file filter containing the definition of the file ending.
* @return a file with validated file name
*/
public static File validateFileName(final File file, final javax.swing.filechooser.FileFilter filter)
{
if (file == null || filter == null || filter.accept(file))
{
return file;
}
// remove wrong file extension if any
String fileName = file.getName();
int index = fileName.lastIndexOf(".");
if (index > 0)
{
fileName = fileName.substring(0, index);
}
final String extension = filter.toString();
if (extension.matches("(\\w)*"))
{
String newFileName = fileName + "." + extension;
File newFile = new File(file.getParent(), newFileName);
return newFile;
}//end if
return file;
}//end validateFileName
/**
* Hashes a string using SHA-256.
*/
public static String calculateSHAHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(s.getBytes("UTF-8"));
byte[] digest = md.digest();
String hashVal = "";
for (byte b : digest)
{
hashVal += String.format("%02x", b);
}
return hashVal;
}
}//end class Helper
| RobotControl/src/de/naoth/rc/Helper.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.naoth.rc;
import de.naoth.rc.components.ExceptionDialog;
import de.naoth.rc.core.server.MessageServer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
/**
*
* @author thomas
*/
public class Helper
{
public static void handleException(final String message, final Exception ex)
{
// log
Logger.getLogger("RobotControl").log(Level.SEVERE, message, ex);
// show
if (SwingUtilities.isEventDispatchThread())
{
ExceptionDialog dlg = new ExceptionDialog(null, message, ex);
dlg.setVisible(true);
} else
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
ExceptionDialog dlg = new ExceptionDialog(null, message, ex);
dlg.setVisible(true);
}
});
}
}
public static void handleException(Exception ex)
{
handleException(null, ex);
}
/**
* Checks if a we are connected to a server and if not displays an error
* message to the user.
*/
public static boolean checkConnected(MessageServer server)
{
if (server.isConnected())
{
return true;
} else
{
JOptionPane.showMessageDialog(null,
"Not connected. Please connect first to a robot.", "WARNING",
JOptionPane.WARNING_MESSAGE);
return false;
}
}//end checkConnected
/**
* Reads a resource file as string.
*/
public static String getResourceAsString(String name)
{
InputStream stream = (new Object()).getClass().getResourceAsStream(name);
StringBuilder builder = new StringBuilder();
if (stream != null)
{
try
{
while (stream.available() > 0)
{
builder.append((char) stream.read());
}
} catch (IOException e)
{
Helper.handleException(e);
}
return builder.toString();
}//end if
return null;
}//end getResourceAsString
public static List<Path> getFiles(String location) {
return getFiles(location, null);
}
public static List<Path> getFiles(String location, Predicate<Path> filter) {
try {
URI res = (new Object()).getClass().getResource(location).toURI();
// handle current execution location (jar, file)
Path resPath;
if (res.getScheme().equals("jar")) {
FileSystem fs = FileSystems.newFileSystem(res, Collections.<String, Object>emptyMap());
resPath = fs.getPath(location);
} else {
resPath = Paths.get(res);
}
Stream<Path> s = Files.walk(resPath, 1);
if (filter != null) { s = s.filter(filter); }
return s.sorted().collect(Collectors.toList());
} catch (IOException | URISyntaxException e) {
Logger.getLogger(HelpDialog.class.getName()).log(Level.SEVERE, null, e);
}
return Collections.emptyList();
}
/**
* Validates the name of a given file, i.e., if the file name doesn't have the
* proper ending, it will be appended.
*
* @param file the file which name has to be validated
* @param filter a file filter containing the definition of the file ending.
* @return a file with validated file name
*/
public static File validateFileName(final File file, final javax.swing.filechooser.FileFilter filter)
{
if (file == null || filter == null || filter.accept(file))
{
return file;
}
// remove wrong file extension if any
String fileName = file.getName();
int index = fileName.lastIndexOf(".");
if (index > 0)
{
fileName = fileName.substring(0, index);
}
final String extension = filter.toString();
if (extension.matches("(\\w)*"))
{
String newFileName = fileName + "." + extension;
File newFile = new File(file.getParent(), newFileName);
return newFile;
}//end if
return file;
}//end validateFileName
/**
* Hashes a string using SHA-256.
*/
public static String calculateSHAHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(s.getBytes("UTF-8"));
byte[] digest = md.digest();
String hashVal = "";
for (byte b : digest)
{
hashVal += String.format("%02x", b);
}
return hashVal;
}
}//end class Helper
| fix for java 11+
| RobotControl/src/de/naoth/rc/Helper.java | fix for java 11+ | <ide><path>obotControl/src/de/naoth/rc/Helper.java
<ide>
<ide> public static List<Path> getFiles(String location, Predicate<Path> filter) {
<ide> try {
<del> URI res = (new Object()).getClass().getResource(location).toURI();
<add> URI res = Helper.class.getResource(location).toURI();
<ide>
<ide> // handle current execution location (jar, file)
<ide> Path resPath; |
|
Java | apache-2.0 | d64e31e8d6043e1b4a1ec5c226a030ba755f9bec | 0 | fitermay/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,fitermay/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,hurricup/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,da1z/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,allotria/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,caot/intellij-community,signed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,semonte/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,fnouama/intellij-community,robovm/robovm-studio,apixandru/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,caot/intellij-community,ibinti/intellij-community,amith01994/intellij-community,semonte/intellij-community,blademainer/intellij-community,caot/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,FHannes/intellij-community,hurricup/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,samthor/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,xfournet/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,fitermay/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,jagguli/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,dslomov/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,dslomov/intellij-community,jagguli/intellij-community,allotria/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fnouama/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,semonte/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,signed/intellij-community,nicolargo/intellij-community,izonder/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,nicolargo/intellij-community,holmes/intellij-community,izonder/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,diorcety/intellij-community,blademainer/intellij-community,supersven/intellij-community,retomerz/intellij-community,holmes/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,slisson/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,kool79/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,da1z/intellij-community,signed/intellij-community,hurricup/intellij-community,apixandru/intellij-community,semonte/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,retomerz/intellij-community,izonder/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,da1z/intellij-community,gnuhub/intellij-community,samthor/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,caot/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,slisson/intellij-community,clumsy/intellij-community,allotria/intellij-community,kool79/intellij-community,adedayo/intellij-community,supersven/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,semonte/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,caot/intellij-community,robovm/robovm-studio,allotria/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,signed/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,semonte/intellij-community,allotria/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,adedayo/intellij-community,apixandru/intellij-community,allotria/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,izonder/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,ibinti/intellij-community,samthor/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,holmes/intellij-community,clumsy/intellij-community,petteyg/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ibinti/intellij-community,slisson/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,adedayo/intellij-community,retomerz/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,holmes/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,da1z/intellij-community,wreckJ/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,izonder/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,slisson/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,slisson/intellij-community,hurricup/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,signed/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,robovm/robovm-studio,supersven/intellij-community,petteyg/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ryano144/intellij-community,FHannes/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,jagguli/intellij-community,izonder/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,retomerz/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,semonte/intellij-community,supersven/intellij-community,slisson/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,izonder/intellij-community,fnouama/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,supersven/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,izonder/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,retomerz/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,signed/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ibinti/intellij-community,diorcety/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,amith01994/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,petteyg/intellij-community,samthor/intellij-community,kool79/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,samthor/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,da1z/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,kool79/intellij-community,blademainer/intellij-community,izonder/intellij-community,ahb0327/intellij-community,slisson/intellij-community,signed/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,amith01994/intellij-community,petteyg/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,adedayo/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,da1z/intellij-community,slisson/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,da1z/intellij-community,xfournet/intellij-community,retomerz/intellij-community,ibinti/intellij-community,jagguli/intellij-community,retomerz/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,caot/intellij-community,semonte/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ryano144/intellij-community,signed/intellij-community,diorcety/intellij-community,blademainer/intellij-community,caot/intellij-community,vladmm/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,caot/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,caot/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,fnouama/intellij-community,amith01994/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,holmes/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,slisson/intellij-community,xfournet/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,apixandru/intellij-community,supersven/intellij-community,kool79/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community | package com.jetbrains.python;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.Lookup;
import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
import com.jetbrains.python.fixtures.PyTestCase;
/**
* @author yole
*/
public class PyClassNameCompletionTest extends PyTestCase {
public void testSimple() {
doTest();
}
public void testReuseExisting() {
doTest();
}
public void testQualified() {
doTestWithoutFromImport();
}
public void testFunction() {
doTest();
}
public void testModule() {
doTest();
}
public void testVariable() {
doTest();
}
public void testSubmodule() { // PY-7887
doTest();
}
public void testSubmoduleRegularImport() { // PY-7887
doTestWithoutFromImport();
}
private void doTestWithoutFromImport() {
final PyCodeInsightSettings settings = PyCodeInsightSettings.getInstance();
boolean oldValue = settings.PREFER_FROM_IMPORT;
settings.PREFER_FROM_IMPORT = false;
try {
doTest();
}
finally {
settings.PREFER_FROM_IMPORT = oldValue;
}
}
private void doTest() {
final String path = "/completion/className/" + getTestName(true);
myFixture.copyDirectoryToProject(path, "");
myFixture.configureFromTempProjectFile(getTestName(true) + ".py");
myFixture.complete(CompletionType.BASIC, 2);
if (myFixture.getLookupElements() != null) {
myFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
}
myFixture.checkResultByFile(path + "/" + getTestName(true) + ".after.py", true);
}
}
| python/testSrc/com/jetbrains/python/PyClassNameCompletionTest.java | package com.jetbrains.python;
import com.intellij.codeInsight.completion.CompletionType;
import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
import com.jetbrains.python.fixtures.PyTestCase;
/**
* @author yole
*/
public class PyClassNameCompletionTest extends PyTestCase {
public void testSimple() {
doTest();
}
public void testReuseExisting() {
doTest();
}
public void testQualified() {
doTestWithoutFromImport();
}
public void testFunction() {
doTest();
}
public void testModule() {
doTest();
}
public void testVariable() {
doTest();
}
public void testSubmodule() { // PY-7887
doTest();
}
public void testSubmoduleRegularImport() { // PY-7887
doTestWithoutFromImport();
}
private void doTestWithoutFromImport() {
final PyCodeInsightSettings settings = PyCodeInsightSettings.getInstance();
boolean oldValue = settings.PREFER_FROM_IMPORT;
settings.PREFER_FROM_IMPORT = false;
try {
doTest();
}
finally {
settings.PREFER_FROM_IMPORT = oldValue;
}
}
private void doTest() {
final String path = "/completion/className/" + getTestName(true);
myFixture.copyDirectoryToProject(path, "");
myFixture.configureFromTempProjectFile(getTestName(true) + ".py");
myFixture.complete(CompletionType.BASIC, 2);
if (myFixture.getLookupElements() != null) {
myFixture.finishLookup();
}
myFixture.checkResultByFile(path + "/" + getTestName(true) + ".after.py", true);
}
}
| SQL quoted identifiers handling reworked & IDEA-103850
| python/testSrc/com/jetbrains/python/PyClassNameCompletionTest.java | SQL quoted identifiers handling reworked & IDEA-103850 | <ide><path>ython/testSrc/com/jetbrains/python/PyClassNameCompletionTest.java
<ide> package com.jetbrains.python;
<ide>
<ide> import com.intellij.codeInsight.completion.CompletionType;
<add>import com.intellij.codeInsight.lookup.Lookup;
<ide> import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
<ide> import com.jetbrains.python.fixtures.PyTestCase;
<ide>
<ide> myFixture.configureFromTempProjectFile(getTestName(true) + ".py");
<ide> myFixture.complete(CompletionType.BASIC, 2);
<ide> if (myFixture.getLookupElements() != null) {
<del> myFixture.finishLookup();
<add> myFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
<ide> }
<ide> myFixture.checkResultByFile(path + "/" + getTestName(true) + ".after.py", true);
<ide> } |
|
Java | apache-2.0 | e9b1450d253e322fa663c124dd05056f52d851bf | 0 | hurricup/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,semonte/intellij-community,samthor/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,amith01994/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ibinti/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fnouama/intellij-community,allotria/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,slisson/intellij-community,retomerz/intellij-community,blademainer/intellij-community,slisson/intellij-community,samthor/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,allotria/intellij-community,izonder/intellij-community,asedunov/intellij-community,samthor/intellij-community,samthor/intellij-community,allotria/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kool79/intellij-community,slisson/intellij-community,amith01994/intellij-community,caot/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,FHannes/intellij-community,da1z/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,apixandru/intellij-community,hurricup/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,signed/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,allotria/intellij-community,tmpgit/intellij-community,da1z/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,caot/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,semonte/intellij-community,da1z/intellij-community,slisson/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,kool79/intellij-community,semonte/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,apixandru/intellij-community,kool79/intellij-community,blademainer/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,samthor/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,hurricup/intellij-community,fnouama/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,da1z/intellij-community,kdwink/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,izonder/intellij-community,da1z/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,supersven/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,clumsy/intellij-community,clumsy/intellij-community,asedunov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,allotria/intellij-community,clumsy/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,fnouama/intellij-community,blademainer/intellij-community,clumsy/intellij-community,xfournet/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,retomerz/intellij-community,blademainer/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,samthor/intellij-community,ibinti/intellij-community,caot/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,signed/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,supersven/intellij-community,jagguli/intellij-community,fnouama/intellij-community,caot/intellij-community,youdonghai/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,da1z/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,samthor/intellij-community,clumsy/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ibinti/intellij-community,retomerz/intellij-community,apixandru/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,signed/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,caot/intellij-community,signed/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,slisson/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,apixandru/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,da1z/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,kool79/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,supersven/intellij-community,FHannes/intellij-community,samthor/intellij-community,da1z/intellij-community,suncycheng/intellij-community,samthor/intellij-community,hurricup/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,izonder/intellij-community,semonte/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,supersven/intellij-community,blademainer/intellij-community,xfournet/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,fnouama/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,caot/intellij-community,signed/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,caot/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,semonte/intellij-community,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,xfournet/intellij-community,ibinti/intellij-community,kdwink/intellij-community,signed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,samthor/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,blademainer/intellij-community,hurricup/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,kdwink/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,allotria/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,kool79/intellij-community,izonder/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,caot/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,signed/intellij-community,vvv1559/intellij-community,slisson/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,kdwink/intellij-community,asedunov/intellij-community,izonder/intellij-community,signed/intellij-community,jagguli/intellij-community,kdwink/intellij-community | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 max
*/
package com.intellij.psi.stubs;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NotNullComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.psi.LanguageSubstitutors;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.PsiFileWithStubSupport;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import gnu.trove.THashMap;
import gnu.trove.TIntArrayList;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
@State(
name = "FileBasedIndex",
storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/stubIndex.xml", roamingType = RoamingType.DISABLED)}
)
public class StubIndexImpl extends StubIndex implements ApplicationComponent, PersistentStateComponent<StubIndexState> {
private static final AtomicReference<Boolean> ourForcedClean = new AtomicReference<Boolean>(null);
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.stubs.StubIndexImpl");
private final Map<StubIndexKey<?,?>, MyIndex<?>> myIndices = new THashMap<StubIndexKey<?,?>, MyIndex<?>>();
private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>();
private final StubProcessingHelper myStubProcessingHelper;
private StubIndexState myPreviouslyRegistered;
public StubIndexImpl(FileBasedIndex fileBasedIndex /* need this to ensure initialization order*/ ) throws IOException {
myStubProcessingHelper = new StubProcessingHelper(fileBasedIndex);
}
@Nullable
public static StubIndexImpl getInstanceOrInvalidate() {
if (ourForcedClean.compareAndSet(null, Boolean.TRUE)) {
return null;
}
return (StubIndexImpl)getInstance();
}
// todo this seems to be copy-pasted from FileBasedIndex
private <K> boolean registerIndexer(@NotNull final StubIndexExtension<K, ?> extension, final boolean forceClean) throws IOException {
final StubIndexKey<K, ?> indexKey = extension.getKey();
final int version = extension.getVersion();
myIndexIdToVersionMap.put(indexKey, version);
final File versionFile = IndexInfrastructure.getVersionFile(indexKey);
final boolean versionFileExisted = versionFile.exists();
final File indexRootDir = IndexInfrastructure.getIndexRootDir(indexKey);
boolean needRebuild = false;
if (forceClean || IndexingStamp.versionDiffers(versionFile, version)) {
final String[] children = indexRootDir.list();
// rebuild only if there exists what to rebuild
boolean indexRootHasChildren = children != null && children.length > 0;
needRebuild = !forceClean && (versionFileExisted || indexRootHasChildren);
if (needRebuild) {
LOG.info("Version has changed for stub index " + extension.getKey() + ". The index will be rebuilt.");
}
if (indexRootHasChildren) FileUtil.deleteWithRenaming(indexRootDir);
IndexingStamp.rewriteVersion(versionFile, version); // todo snapshots indices
}
for (int attempt = 0; attempt < 2; attempt++) {
try {
final MapIndexStorage<K, StubIdList> storage = new MapIndexStorage<K, StubIdList>(
IndexInfrastructure.getStorageFile(indexKey),
extension.getKeyDescriptor(),
new StubIdExternalizer(),
extension.getCacheSize(),
false,
extension instanceof StringStubIndexExtension && ((StringStubIndexExtension)extension).traceKeyHashToVirtualFileMapping()
);
final MemoryIndexStorage<K, StubIdList> memStorage = new MemoryIndexStorage<K, StubIdList>(storage);
myIndices.put(indexKey, new MyIndex<K>(memStorage));
break;
}
catch (IOException e) {
needRebuild = true;
onExceptionInstantiatingIndex(version, versionFile, indexRootDir, e);
} catch (RuntimeException e) {
//noinspection ThrowableResultOfMethodCallIgnored
Throwable cause = FileBasedIndexImpl.getCauseToRebuildIndex(e);
if (cause == null) throw e;
onExceptionInstantiatingIndex(version, versionFile, indexRootDir, e);
}
}
return needRebuild;
}
private static void onExceptionInstantiatingIndex(int version, File versionFile, File indexRootDir, Exception e) throws IOException {
LOG.info(e);
FileUtil.deleteWithRenaming(indexRootDir);
IndexingStamp.rewriteVersion(versionFile, version); // todo snapshots indices
}
private static class StubIdExternalizer implements DataExternalizer<StubIdList> {
@Override
public void save(@NotNull final DataOutput out, @NotNull final StubIdList value) throws IOException {
int size = value.size();
if (size == 0) {
DataInputOutputUtil.writeINT(out, Integer.MAX_VALUE);
}
else if (size == 1) {
DataInputOutputUtil.writeINT(out, value.get(0)); // most often case
}
else {
DataInputOutputUtil.writeINT(out, -size);
for(int i = 0; i < size; ++i) {
DataInputOutputUtil.writeINT(out, value.get(i));
}
}
}
@NotNull
@Override
public StubIdList read(@NotNull final DataInput in) throws IOException {
int size = DataInputOutputUtil.readINT(in);
if (size == Integer.MAX_VALUE) {
return new StubIdList();
}
else if (size >= 0) {
return new StubIdList(size);
}
else {
size = -size;
int[] result = new int[size];
for(int i = 0; i < size; ++i) {
result[i] = DataInputOutputUtil.readINT(in);
}
return new StubIdList(result, size);
}
}
}
@NotNull
@Override
public <Key, Psi extends PsiElement> Collection<Psi> get(@NotNull final StubIndexKey<Key, Psi> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope) {
return get(indexKey, key, project, scope, null);
}
@Override
public <Key, Psi extends PsiElement> Collection<Psi> get(@NotNull StubIndexKey<Key, Psi> indexKey,
@NotNull Key key,
@NotNull Project project,
@Nullable GlobalSearchScope scope,
IdFilter filter) {
final List<Psi> result = new SmartList<Psi>();
process(indexKey, key, project, scope, filter, new CommonProcessors.CollectProcessor<Psi>(result));
return result;
}
@Override
public <Key, Psi extends PsiElement> boolean processElements(@NotNull StubIndexKey<Key, Psi> indexKey,
@NotNull Key key,
@NotNull Project project,
@Nullable GlobalSearchScope scope,
Class<Psi> requiredClass,
@NotNull Processor<? super Psi> processor) {
return processElements(indexKey, key, project, scope, null, requiredClass, processor);
}
@Override
public <Key, Psi extends PsiElement> boolean processElements(@NotNull final StubIndexKey<Key, Psi> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope,
@Nullable IdFilter idFilter,
@NotNull final Class<Psi> requiredClass,
@NotNull final Processor<? super Psi> processor) {
return doProcessStubs(indexKey, key, project, scope, new StubIdListContainerAction(idFilter, project) {
final PersistentFS fs = (PersistentFS)ManagingFS.getInstance();
@Override
protected boolean process(int id, StubIdList value) {
final VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id);
if (file == null || scope != null && !scope.contains(file)) {
return true;
}
return myStubProcessingHelper.processStubsInFile(project, file, value, processor, requiredClass);
}
});
}
private <Key> boolean doProcessStubs(@NotNull final StubIndexKey<Key, ?> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope,
@NotNull StubIdListContainerAction action) {
final FileBasedIndexImpl fileBasedIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance();
fileBasedIndex.ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, scope);
final MyIndex<Key> index = (MyIndex<Key>)myIndices.get(indexKey);
try {
try {
// disable up-to-date check to avoid locks on attempt to acquire index write lock while holding at the same time the readLock for this index
FileBasedIndexImpl.disableUpToDateCheckForCurrentThread();
index.getReadLock().lock();
return index.getData(key).forEach(action);
}
finally {
index.getReadLock().unlock();
FileBasedIndexImpl.enableUpToDateCheckForCurrentThread();
}
}
catch (StorageException e) {
forceRebuild(e);
}
catch (RuntimeException e) {
final Throwable cause = FileBasedIndexImpl.getCauseToRebuildIndex(e);
if (cause != null) {
forceRebuild(cause);
}
else {
throw e;
}
} catch (AssertionError ae) {
forceRebuild(ae);
}
return true;
}
public void forceRebuild(@NotNull Throwable e) {
LOG.info(e);
FileBasedIndex.getInstance().scheduleRebuild(StubUpdatingIndex.INDEX_ID, e);
}
private static void requestRebuild() {
FileBasedIndex.getInstance().requestRebuild(StubUpdatingIndex.INDEX_ID);
}
@Override
@NotNull
public <K> Collection<K> getAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Project project) {
Set<K> allKeys = ContainerUtil.newTroveSet();
processAllKeys(indexKey, project, new CommonProcessors.CollectProcessor<K>(allKeys));
return allKeys;
}
@Override
public <K> boolean processAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Project project, Processor<K> processor) {
return processAllKeys(indexKey, processor, GlobalSearchScope.allScope(project), null);
}
public <K> boolean processAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Processor<K> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter) {
FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, scope.getProject(), scope);
final MyIndex<K> index = (MyIndex<K>)myIndices.get(indexKey);
try {
return index.processAllKeys(processor, scope, idFilter);
}
catch (StorageException e) {
forceRebuild(e);
}
catch (RuntimeException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException || cause instanceof StorageException) {
forceRebuild(e);
}
throw e;
}
return true;
}
@NotNull
@Override
public <Key> IdIterator getContainingIds(@NotNull StubIndexKey<Key, ?> indexKey,
@NotNull Key dataKey,
@NotNull final Project project,
@NotNull final GlobalSearchScope scope) {
final TIntArrayList result = new TIntArrayList();
doProcessStubs(indexKey, dataKey, project, scope, new StubIdListContainerAction(null, project) {
@Override
protected boolean process(int id, StubIdList value) {
result.add(id);
return true;
}
});
return new IdIterator() {
int cursor = 0;
@Override
public boolean hasNext() {
return cursor < result.size();
}
@Override
public int next() {
return result.get(cursor++);
}
@Override
public int size() {
return result.size();
}
};
}
@Override
@NotNull
public String getComponentName() {
return "Stub.IndexManager";
}
@Override
public void initComponent() {
try {
final boolean forceClean = Boolean.TRUE == ourForcedClean.getAndSet(Boolean.FALSE);
StubIndexExtension<?, ?>[] extensions = Extensions.getExtensions(StubIndexExtension.EP_NAME);
StringBuilder updated = new StringBuilder();
for (StubIndexExtension extension : extensions) {
@SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean);
if (rebuildRequested) {
updated.append(extension).append(' ');
}
}
if (updated.length() > 0) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
requestRebuild();
}
else {
final Throwable e = new Throwable(updated.toString());
// avoid direct forceRebuild as it produces dependency cycle (IDEA-105485)
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
forceRebuild(e);
}
}, ModalityState.NON_MODAL);
}
}
dropUnregisteredIndices();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void disposeComponent() {
// This index must be disposed only after StubUpdatingIndex is disposed
// To ensure this, disposing is done explicitly from StubUpdatingIndex by calling dispose() method
// do not call this method here to avoid double-disposal
}
public void dispose() {
for (UpdatableIndex index : myIndices.values()) {
index.dispose();
}
}
public void setDataBufferingEnabled(final boolean enabled) {
for (UpdatableIndex index : myIndices.values()) {
final IndexStorage indexStorage = ((MapReduceIndex)index).getStorage();
((MemoryIndexStorage)indexStorage).setBufferingEnabled(enabled);
}
}
public void cleanupMemoryStorage() {
for (UpdatableIndex index : myIndices.values()) {
final IndexStorage indexStorage = ((MapReduceIndex)index).getStorage();
index.getWriteLock().lock();
try {
((MemoryIndexStorage)indexStorage).clearMemoryMap();
}
finally {
index.getWriteLock().unlock();
}
}
}
public void clearAllIndices() {
for (UpdatableIndex index : myIndices.values()) {
try {
index.clear();
}
catch (StorageException e) {
LOG.error(e);
throw new RuntimeException(e);
}
}
}
private void dropUnregisteredIndices() {
final Set<String> indicesToDrop = new HashSet<String>(myPreviouslyRegistered != null? myPreviouslyRegistered.registeredIndices : Collections.<String>emptyList());
for (ID<?, ?> key : myIndices.keySet()) {
indicesToDrop.remove(key.toString());
}
for (String s : indicesToDrop) {
FileUtil.delete(IndexInfrastructure.getIndexRootDir(ID.create(s)));
}
}
@NotNull
@Override
public StubIndexState getState() {
return new StubIndexState(myIndices.keySet());
}
@Override
public void loadState(final StubIndexState state) {
myPreviouslyRegistered = state;
}
public final Lock getWriteLock(StubIndexKey indexKey) {
return myIndices.get(indexKey).getWriteLock();
}
public Collection<StubIndexKey> getAllStubIndexKeys() {
return Collections.<StubIndexKey>unmodifiableCollection(myIndices.keySet());
}
public void flush(StubIndexKey key) throws StorageException {
final MyIndex<?> index = myIndices.get(key);
index.flush();
}
public <K> void updateIndex(@NotNull StubIndexKey key, int fileId, @NotNull final Map<K, StubIdList> oldValues, @NotNull final Map<K, StubIdList> newValues) {
try {
final MyIndex<K> index = (MyIndex<K>)myIndices.get(key);
UpdateData<K, StubIdList> updateData;
if (MapDiffUpdateData.ourDiffUpdateEnabled) {
updateData = new MapDiffUpdateData<K, StubIdList>(key) {
@Override
public void save(int inputId) throws IOException {
}
@Override
protected Map<K, StubIdList> getNewValue() {
return newValues;
}
@Override
protected Map<K, StubIdList> getCurrentValue() throws IOException {
return oldValues;
}
};
} else {
updateData = index.new SimpleUpdateData(key, fileId, newValues, new NotNullComputable<Collection<K>>() {
@NotNull
@Override
public Collection<K> compute() {
return oldValues.keySet();
}
});
}
index.updateWithMap(fileId, updateData);
}
catch (StorageException e) {
LOG.info(e);
requestRebuild();
}
}
private static class MyIndex<K> extends MapReduceIndex<K, StubIdList, Void> {
public MyIndex(final IndexStorage<K, StubIdList> storage) throws IOException {
super(null, null, storage);
}
@Override
public void updateWithMap(final int inputId,
@NotNull UpdateData<K, StubIdList> updateData) throws StorageException {
super.updateWithMap(inputId, updateData);
}
}
@Override
protected <Psi extends PsiElement> void reportStubPsiMismatch(Psi psi, VirtualFile file, Class<Psi> requiredClass) {
if (file == null) {
super.reportStubPsiMismatch(psi, file, requiredClass);
return;
}
StringWriter writer = new StringWriter();
//noinspection IOResourceOpenedButNotSafelyClosed
PrintWriter out = new PrintWriter(writer);
out.print("Invalid stub element type in index:");
out.printf("\nfile: %s\npsiElement: %s\nrequiredClass: %s\nactualClass: %s",
file, psi, requiredClass, psi.getClass());
FileType fileType = file.getFileType();
Language language = fileType instanceof LanguageFileType ?
LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), file, psi.getProject()) :
Language.ANY;
out.printf("\nvirtualFile: size:%s; stamp:%s; modCount:%s; fileType:%s; language:%s",
file.getLength(), file.getModificationStamp(), file.getModificationCount(),
fileType.getName(), language.getID());
Document document = FileDocumentManager.getInstance().getCachedDocument(file);
if (document != null) {
boolean committed = PsiDocumentManager.getInstance(psi.getProject()).isCommitted(document);
boolean saved = !FileDocumentManager.getInstance().isDocumentUnsaved(document);
out.printf("\ndocument: size:%s; stamp:%s; committed:%s; saved:%s",
document.getTextLength(), document.getModificationStamp(), committed, saved);
}
PsiFile psiFile = psi.getManager().findFile(file);
if (psiFile != null) {
out.printf("\npsiFile: size:%s; stamp:%s; class:%s; language:%s",
psiFile.getTextLength(), psiFile.getViewProvider().getModificationStamp(), psiFile.getClass().getName(),
psiFile.getLanguage().getID());
}
StubTree stub = psiFile instanceof PsiFileWithStubSupport ? ((PsiFileWithStubSupport)psiFile).getStubTree() : null;
FileElement treeElement = stub == null && psiFile instanceof PsiFileImpl? ((PsiFileImpl)psiFile).getTreeElement() : null;
if (stub != null) {
out.printf("\nstubInfo: " + stub.getDebugInfo());
}
else if (treeElement != null) {
out.printf("\nfileAST: size:%s; parsed:%s", treeElement.getTextLength(), treeElement.isParsed());
}
out.printf("\nindexing info: " + StubUpdatingIndex.getIndexingStampInfo(file));
LOG.error(writer.toString());
}
private abstract class StubIdListContainerAction implements ValueContainer.ContainerAction<StubIdList> {
private final IdFilter myIdFilter;
StubIdListContainerAction(@Nullable IdFilter idFilter, @NotNull Project project) {
myIdFilter = idFilter != null ? idFilter : ((FileBasedIndexImpl)FileBasedIndex.getInstance()).projectIndexableFiles(project);
}
@Override
public boolean perform(final int id, @NotNull final StubIdList value) {
ProgressManager.checkCanceled();
if (myIdFilter != null && !myIdFilter.containsFileId(id)) return true;
return process(id, value);
}
protected abstract boolean process(int id, StubIdList value);
}
}
| platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 max
*/
package com.intellij.psi.stubs;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NotNullComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.psi.LanguageSubstitutors;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.PsiFileWithStubSupport;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import gnu.trove.THashMap;
import gnu.trove.TIntArrayList;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
@State(
name = "FileBasedIndex",
storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/stubIndex.xml", roamingType = RoamingType.DISABLED)}
)
public class StubIndexImpl extends StubIndex implements ApplicationComponent, PersistentStateComponent<StubIndexState> {
private static final AtomicReference<Boolean> ourForcedClean = new AtomicReference<Boolean>(null);
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.stubs.StubIndexImpl");
private final Map<StubIndexKey<?,?>, MyIndex<?>> myIndices = new THashMap<StubIndexKey<?,?>, MyIndex<?>>();
private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>();
private final StubProcessingHelper myStubProcessingHelper;
private StubIndexState myPreviouslyRegistered;
public StubIndexImpl(FileBasedIndex fileBasedIndex /* need this to ensure initialization order*/ ) throws IOException {
final boolean forceClean = Boolean.TRUE == ourForcedClean.getAndSet(Boolean.FALSE);
StubIndexExtension<?, ?>[] extensions = Extensions.getExtensions(StubIndexExtension.EP_NAME);
StringBuilder updated = new StringBuilder();
for (StubIndexExtension extension : extensions) {
@SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean);
if (rebuildRequested) {
updated.append(extension).append(' ');
}
}
if (updated.length() > 0) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
requestRebuild();
}
else {
final Throwable e = new Throwable(updated.toString());
// avoid direct forceRebuild as it produces dependency cycle (IDEA-105485)
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
forceRebuild(e);
}
}, ModalityState.NON_MODAL);
}
}
dropUnregisteredIndices();
myStubProcessingHelper = new StubProcessingHelper(fileBasedIndex);
}
@Nullable
public static StubIndexImpl getInstanceOrInvalidate() {
if (ourForcedClean.compareAndSet(null, Boolean.TRUE)) {
return null;
}
return (StubIndexImpl)getInstance();
}
// todo this seems to be copy-pasted from FileBasedIndex
private <K> boolean registerIndexer(@NotNull final StubIndexExtension<K, ?> extension, final boolean forceClean) throws IOException {
final StubIndexKey<K, ?> indexKey = extension.getKey();
final int version = extension.getVersion();
myIndexIdToVersionMap.put(indexKey, version);
final File versionFile = IndexInfrastructure.getVersionFile(indexKey);
final boolean versionFileExisted = versionFile.exists();
final File indexRootDir = IndexInfrastructure.getIndexRootDir(indexKey);
boolean needRebuild = false;
if (forceClean || IndexingStamp.versionDiffers(versionFile, version)) {
final String[] children = indexRootDir.list();
// rebuild only if there exists what to rebuild
boolean indexRootHasChildren = children != null && children.length > 0;
needRebuild = !forceClean && (versionFileExisted || indexRootHasChildren);
if (needRebuild) {
LOG.info("Version has changed for stub index " + extension.getKey() + ". The index will be rebuilt.");
}
if (indexRootHasChildren) FileUtil.deleteWithRenaming(indexRootDir);
IndexingStamp.rewriteVersion(versionFile, version); // todo snapshots indices
}
for (int attempt = 0; attempt < 2; attempt++) {
try {
final MapIndexStorage<K, StubIdList> storage = new MapIndexStorage<K, StubIdList>(
IndexInfrastructure.getStorageFile(indexKey),
extension.getKeyDescriptor(),
new StubIdExternalizer(),
extension.getCacheSize(),
false,
extension instanceof StringStubIndexExtension && ((StringStubIndexExtension)extension).traceKeyHashToVirtualFileMapping()
);
final MemoryIndexStorage<K, StubIdList> memStorage = new MemoryIndexStorage<K, StubIdList>(storage);
myIndices.put(indexKey, new MyIndex<K>(memStorage));
break;
}
catch (IOException e) {
needRebuild = true;
onExceptionInstantiatingIndex(version, versionFile, indexRootDir, e);
} catch (RuntimeException e) {
//noinspection ThrowableResultOfMethodCallIgnored
Throwable cause = FileBasedIndexImpl.getCauseToRebuildIndex(e);
if (cause == null) throw e;
onExceptionInstantiatingIndex(version, versionFile, indexRootDir, e);
}
}
return needRebuild;
}
private static void onExceptionInstantiatingIndex(int version, File versionFile, File indexRootDir, Exception e) throws IOException {
LOG.info(e);
FileUtil.deleteWithRenaming(indexRootDir);
IndexingStamp.rewriteVersion(versionFile, version); // todo snapshots indices
}
private static class StubIdExternalizer implements DataExternalizer<StubIdList> {
@Override
public void save(@NotNull final DataOutput out, @NotNull final StubIdList value) throws IOException {
int size = value.size();
if (size == 0) {
DataInputOutputUtil.writeINT(out, Integer.MAX_VALUE);
}
else if (size == 1) {
DataInputOutputUtil.writeINT(out, value.get(0)); // most often case
}
else {
DataInputOutputUtil.writeINT(out, -size);
for(int i = 0; i < size; ++i) {
DataInputOutputUtil.writeINT(out, value.get(i));
}
}
}
@NotNull
@Override
public StubIdList read(@NotNull final DataInput in) throws IOException {
int size = DataInputOutputUtil.readINT(in);
if (size == Integer.MAX_VALUE) {
return new StubIdList();
}
else if (size >= 0) {
return new StubIdList(size);
}
else {
size = -size;
int[] result = new int[size];
for(int i = 0; i < size; ++i) {
result[i] = DataInputOutputUtil.readINT(in);
}
return new StubIdList(result, size);
}
}
}
@NotNull
@Override
public <Key, Psi extends PsiElement> Collection<Psi> get(@NotNull final StubIndexKey<Key, Psi> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope) {
return get(indexKey, key, project, scope, null);
}
@Override
public <Key, Psi extends PsiElement> Collection<Psi> get(@NotNull StubIndexKey<Key, Psi> indexKey,
@NotNull Key key,
@NotNull Project project,
@Nullable GlobalSearchScope scope,
IdFilter filter) {
final List<Psi> result = new SmartList<Psi>();
process(indexKey, key, project, scope, filter, new CommonProcessors.CollectProcessor<Psi>(result));
return result;
}
@Override
public <Key, Psi extends PsiElement> boolean processElements(@NotNull StubIndexKey<Key, Psi> indexKey,
@NotNull Key key,
@NotNull Project project,
@Nullable GlobalSearchScope scope,
Class<Psi> requiredClass,
@NotNull Processor<? super Psi> processor) {
return processElements(indexKey, key, project, scope, null, requiredClass, processor);
}
@Override
public <Key, Psi extends PsiElement> boolean processElements(@NotNull final StubIndexKey<Key, Psi> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope,
@Nullable IdFilter idFilter,
@NotNull final Class<Psi> requiredClass,
@NotNull final Processor<? super Psi> processor) {
return doProcessStubs(indexKey, key, project, scope, new StubIdListContainerAction(idFilter, project) {
final PersistentFS fs = (PersistentFS)ManagingFS.getInstance();
@Override
protected boolean process(int id, StubIdList value) {
final VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id);
if (file == null || scope != null && !scope.contains(file)) {
return true;
}
return myStubProcessingHelper.processStubsInFile(project, file, value, processor, requiredClass);
}
});
}
private <Key> boolean doProcessStubs(@NotNull final StubIndexKey<Key, ?> indexKey,
@NotNull final Key key,
@NotNull final Project project,
@Nullable final GlobalSearchScope scope,
@NotNull StubIdListContainerAction action) {
final FileBasedIndexImpl fileBasedIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance();
fileBasedIndex.ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, scope);
final MyIndex<Key> index = (MyIndex<Key>)myIndices.get(indexKey);
try {
try {
// disable up-to-date check to avoid locks on attempt to acquire index write lock while holding at the same time the readLock for this index
FileBasedIndexImpl.disableUpToDateCheckForCurrentThread();
index.getReadLock().lock();
return index.getData(key).forEach(action);
}
finally {
index.getReadLock().unlock();
FileBasedIndexImpl.enableUpToDateCheckForCurrentThread();
}
}
catch (StorageException e) {
forceRebuild(e);
}
catch (RuntimeException e) {
final Throwable cause = FileBasedIndexImpl.getCauseToRebuildIndex(e);
if (cause != null) {
forceRebuild(cause);
}
else {
throw e;
}
} catch (AssertionError ae) {
forceRebuild(ae);
}
return true;
}
public void forceRebuild(@NotNull Throwable e) {
LOG.info(e);
FileBasedIndex.getInstance().scheduleRebuild(StubUpdatingIndex.INDEX_ID, e);
}
private static void requestRebuild() {
FileBasedIndex.getInstance().requestRebuild(StubUpdatingIndex.INDEX_ID);
}
@Override
@NotNull
public <K> Collection<K> getAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Project project) {
Set<K> allKeys = ContainerUtil.newTroveSet();
processAllKeys(indexKey, project, new CommonProcessors.CollectProcessor<K>(allKeys));
return allKeys;
}
@Override
public <K> boolean processAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Project project, Processor<K> processor) {
return processAllKeys(indexKey, processor, GlobalSearchScope.allScope(project), null);
}
public <K> boolean processAllKeys(@NotNull StubIndexKey<K, ?> indexKey, @NotNull Processor<K> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter) {
FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, scope.getProject(), scope);
final MyIndex<K> index = (MyIndex<K>)myIndices.get(indexKey);
try {
return index.processAllKeys(processor, scope, idFilter);
}
catch (StorageException e) {
forceRebuild(e);
}
catch (RuntimeException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException || cause instanceof StorageException) {
forceRebuild(e);
}
throw e;
}
return true;
}
@NotNull
@Override
public <Key> IdIterator getContainingIds(@NotNull StubIndexKey<Key, ?> indexKey,
@NotNull Key dataKey,
@NotNull final Project project,
@NotNull final GlobalSearchScope scope) {
final TIntArrayList result = new TIntArrayList();
doProcessStubs(indexKey, dataKey, project, scope, new StubIdListContainerAction(null, project) {
@Override
protected boolean process(int id, StubIdList value) {
result.add(id);
return true;
}
});
return new IdIterator() {
int cursor = 0;
@Override
public boolean hasNext() {
return cursor < result.size();
}
@Override
public int next() {
return result.get(cursor++);
}
@Override
public int size() {
return result.size();
}
};
}
@Override
@NotNull
public String getComponentName() {
return "Stub.IndexManager";
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
// This index must be disposed only after StubUpdatingIndex is disposed
// To ensure this, disposing is done explicitly from StubUpdatingIndex by calling dispose() method
// do not call this method here to avoid double-disposal
}
public void dispose() {
for (UpdatableIndex index : myIndices.values()) {
index.dispose();
}
}
public void setDataBufferingEnabled(final boolean enabled) {
for (UpdatableIndex index : myIndices.values()) {
final IndexStorage indexStorage = ((MapReduceIndex)index).getStorage();
((MemoryIndexStorage)indexStorage).setBufferingEnabled(enabled);
}
}
public void cleanupMemoryStorage() {
for (UpdatableIndex index : myIndices.values()) {
final IndexStorage indexStorage = ((MapReduceIndex)index).getStorage();
index.getWriteLock().lock();
try {
((MemoryIndexStorage)indexStorage).clearMemoryMap();
}
finally {
index.getWriteLock().unlock();
}
}
}
public void clearAllIndices() {
for (UpdatableIndex index : myIndices.values()) {
try {
index.clear();
}
catch (StorageException e) {
LOG.error(e);
throw new RuntimeException(e);
}
}
}
private void dropUnregisteredIndices() {
final Set<String> indicesToDrop = new HashSet<String>(myPreviouslyRegistered != null? myPreviouslyRegistered.registeredIndices : Collections.<String>emptyList());
for (ID<?, ?> key : myIndices.keySet()) {
indicesToDrop.remove(key.toString());
}
for (String s : indicesToDrop) {
FileUtil.delete(IndexInfrastructure.getIndexRootDir(ID.create(s)));
}
}
@NotNull
@Override
public StubIndexState getState() {
return new StubIndexState(myIndices.keySet());
}
@Override
public void loadState(final StubIndexState state) {
myPreviouslyRegistered = state;
}
public final Lock getWriteLock(StubIndexKey indexKey) {
return myIndices.get(indexKey).getWriteLock();
}
public Collection<StubIndexKey> getAllStubIndexKeys() {
return Collections.<StubIndexKey>unmodifiableCollection(myIndices.keySet());
}
public void flush(StubIndexKey key) throws StorageException {
final MyIndex<?> index = myIndices.get(key);
index.flush();
}
public <K> void updateIndex(@NotNull StubIndexKey key, int fileId, @NotNull final Map<K, StubIdList> oldValues, @NotNull final Map<K, StubIdList> newValues) {
try {
final MyIndex<K> index = (MyIndex<K>)myIndices.get(key);
UpdateData<K, StubIdList> updateData;
if (MapDiffUpdateData.ourDiffUpdateEnabled) {
updateData = new MapDiffUpdateData<K, StubIdList>(key) {
@Override
public void save(int inputId) throws IOException {
}
@Override
protected Map<K, StubIdList> getNewValue() {
return newValues;
}
@Override
protected Map<K, StubIdList> getCurrentValue() throws IOException {
return oldValues;
}
};
} else {
updateData = index.new SimpleUpdateData(key, fileId, newValues, new NotNullComputable<Collection<K>>() {
@NotNull
@Override
public Collection<K> compute() {
return oldValues.keySet();
}
});
}
index.updateWithMap(fileId, updateData);
}
catch (StorageException e) {
LOG.info(e);
requestRebuild();
}
}
private static class MyIndex<K> extends MapReduceIndex<K, StubIdList, Void> {
public MyIndex(final IndexStorage<K, StubIdList> storage) throws IOException {
super(null, null, storage);
}
@Override
public void updateWithMap(final int inputId,
@NotNull UpdateData<K, StubIdList> updateData) throws StorageException {
super.updateWithMap(inputId, updateData);
}
}
@Override
protected <Psi extends PsiElement> void reportStubPsiMismatch(Psi psi, VirtualFile file, Class<Psi> requiredClass) {
if (file == null) {
super.reportStubPsiMismatch(psi, file, requiredClass);
return;
}
StringWriter writer = new StringWriter();
//noinspection IOResourceOpenedButNotSafelyClosed
PrintWriter out = new PrintWriter(writer);
out.print("Invalid stub element type in index:");
out.printf("\nfile: %s\npsiElement: %s\nrequiredClass: %s\nactualClass: %s",
file, psi, requiredClass, psi.getClass());
FileType fileType = file.getFileType();
Language language = fileType instanceof LanguageFileType ?
LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), file, psi.getProject()) :
Language.ANY;
out.printf("\nvirtualFile: size:%s; stamp:%s; modCount:%s; fileType:%s; language:%s",
file.getLength(), file.getModificationStamp(), file.getModificationCount(),
fileType.getName(), language.getID());
Document document = FileDocumentManager.getInstance().getCachedDocument(file);
if (document != null) {
boolean committed = PsiDocumentManager.getInstance(psi.getProject()).isCommitted(document);
boolean saved = !FileDocumentManager.getInstance().isDocumentUnsaved(document);
out.printf("\ndocument: size:%s; stamp:%s; committed:%s; saved:%s",
document.getTextLength(), document.getModificationStamp(), committed, saved);
}
PsiFile psiFile = psi.getManager().findFile(file);
if (psiFile != null) {
out.printf("\npsiFile: size:%s; stamp:%s; class:%s; language:%s",
psiFile.getTextLength(), psiFile.getViewProvider().getModificationStamp(), psiFile.getClass().getName(),
psiFile.getLanguage().getID());
}
StubTree stub = psiFile instanceof PsiFileWithStubSupport ? ((PsiFileWithStubSupport)psiFile).getStubTree() : null;
FileElement treeElement = stub == null && psiFile instanceof PsiFileImpl? ((PsiFileImpl)psiFile).getTreeElement() : null;
if (stub != null) {
out.printf("\nstubInfo: " + stub.getDebugInfo());
}
else if (treeElement != null) {
out.printf("\nfileAST: size:%s; parsed:%s", treeElement.getTextLength(), treeElement.isParsed());
}
out.printf("\nindexing info: " + StubUpdatingIndex.getIndexingStampInfo(file));
LOG.error(writer.toString());
}
private abstract class StubIdListContainerAction implements ValueContainer.ContainerAction<StubIdList> {
private final IdFilter myIdFilter;
StubIdListContainerAction(@Nullable IdFilter idFilter, @NotNull Project project) {
myIdFilter = idFilter != null ? idFilter : ((FileBasedIndexImpl)FileBasedIndex.getInstance()).projectIndexableFiles(project);
}
@Override
public boolean perform(final int id, @NotNull final StubIdList value) {
ProgressManager.checkCanceled();
if (myIdFilter != null && !myIdFilter.containsFileId(id)) return true;
return process(id, value);
}
protected abstract boolean process(int id, StubIdList value);
}
}
| move StubIndex initialization to initComponent
| platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java | move StubIndex initialization to initComponent | <ide><path>latform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
<ide> private StubIndexState myPreviouslyRegistered;
<ide>
<ide> public StubIndexImpl(FileBasedIndex fileBasedIndex /* need this to ensure initialization order*/ ) throws IOException {
<del> final boolean forceClean = Boolean.TRUE == ourForcedClean.getAndSet(Boolean.FALSE);
<del>
<del> StubIndexExtension<?, ?>[] extensions = Extensions.getExtensions(StubIndexExtension.EP_NAME);
<del> StringBuilder updated = new StringBuilder();
<del> for (StubIndexExtension extension : extensions) {
<del> @SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean);
<del> if (rebuildRequested) {
<del> updated.append(extension).append(' ');
<del> }
<del> }
<del> if (updated.length() > 0) {
<del> if (ApplicationManager.getApplication().isUnitTestMode()) {
<del> requestRebuild();
<del> }
<del> else {
<del> final Throwable e = new Throwable(updated.toString());
<del> // avoid direct forceRebuild as it produces dependency cycle (IDEA-105485)
<del> ApplicationManager.getApplication().invokeLater(new Runnable() {
<del> @Override
<del> public void run() {
<del> forceRebuild(e);
<del> }
<del> }, ModalityState.NON_MODAL);
<del> }
<del> }
<del> dropUnregisteredIndices();
<del>
<ide> myStubProcessingHelper = new StubProcessingHelper(fileBasedIndex);
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public void initComponent() {
<add> try {
<add> final boolean forceClean = Boolean.TRUE == ourForcedClean.getAndSet(Boolean.FALSE);
<add>
<add> StubIndexExtension<?, ?>[] extensions = Extensions.getExtensions(StubIndexExtension.EP_NAME);
<add> StringBuilder updated = new StringBuilder();
<add> for (StubIndexExtension extension : extensions) {
<add> @SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean);
<add> if (rebuildRequested) {
<add> updated.append(extension).append(' ');
<add> }
<add> }
<add> if (updated.length() > 0) {
<add> if (ApplicationManager.getApplication().isUnitTestMode()) {
<add> requestRebuild();
<add> }
<add> else {
<add> final Throwable e = new Throwable(updated.toString());
<add> // avoid direct forceRebuild as it produces dependency cycle (IDEA-105485)
<add> ApplicationManager.getApplication().invokeLater(new Runnable() {
<add> @Override
<add> public void run() {
<add> forceRebuild(e);
<add> }
<add> }, ModalityState.NON_MODAL);
<add> }
<add> }
<add> dropUnregisteredIndices();
<add> } catch (IOException ex) {
<add> throw new RuntimeException(ex);
<add> }
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | e7a77b7bedb38651caad7cf85775ef3fd1f00b52 | 0 | OmniKryptec/OmniKryptec-Engine | package omnikryptec.swing;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
import omnikryptec.logger.Logger;
import omnikryptec.util.AdvancedFile;
import omnikryptec.util.Color;
/**
* PieChartGenerator
* @author Panzer1119
*/
public class PieChartGenerator {
private static final Random random = new Random();
public static final void main(String[] args) {
final ArrayList<ChartData> chartDatas = new ArrayList<>();
for(int i = 0; i < 20; i++) {
chartDatas.add(new ChartData("Test " + i, (float) (Math.random() * 10.0F)));
}
final BufferedImage image = createPieChart(chartDatas, 1600, 1600, 0.9F, 0.65F, true);
try {
final AdvancedFile file = new AdvancedFile("test.png").getAbsoluteAdvancedFile();
file.createFile();
ImageIO.write(image, "png", file.createOutputstream(false));
} catch (Exception ex) {
Logger.logErr("Error while writing Image to File: " + ex, ex);
}
}
/**
* Creates a PieChart based on the given ChartDatas
* @param chartDatas ArrayList ChartData Data
* @param width Integer Width of the Image
* @param height Integer Height of the Image
* @param diameterFactor Float Quotient of (diameter / (Math.min(width, height))) (1.0F = (diameter == Math.min(width, height)))
* @param fontSizeFactor Float Factor for the Fonts size (1.0F = normal size)
* @param withPercentage Boolean If the percentage of each ChartData should be shown beside the name
* @return BufferedImage Created PieChart
*/
public static final BufferedImage createPieChart(ArrayList<ChartData> chartDatas, int width, int height, float diameterFactor, float fontSizeFactor, boolean withPercentage) {
if(chartDatas.isEmpty() || width <= 0 || height <= 0) {
return null;
}
final int width_half = width / 2;
final int height_half = height / 2;
final int radius = (int) (Math.min(width, height) / 2.0F * diameterFactor);
final int diameter = radius * 2;
final int offset = ((Math.min(width, height)) - diameter) / 2;
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics graphics = image.createGraphics();
graphics.setColor(java.awt.Color.WHITE);
graphics.fillRect(0, 0, width, height);
float max_data = 0.0F;
for(ChartData chartData : chartDatas) {
if(chartData.getColor() == null) {
chartData.setColor(generateRandomColor());
}
max_data += chartData.getValue();
}
for(ChartData chartData : chartDatas) {
chartData.setPercentage(chartData.getValue() / max_data);
}
int last_startAngle = 0;
boolean floored = false;
for(int i = 0; i < chartDatas.size(); i++) {
final ChartData chartData = chartDatas.get(i);
float angle = 360.0F * chartData.getPercentage();
float startAngle = last_startAngle;
if(i == chartDatas.size() - 1) {
startAngle += 0.5;
angle = 360.0F - last_startAngle + 0.5F;
} else {
if(floored) {
angle += 0.5;
startAngle += 0.5;
}
}
angle = (float) Math.floor(angle);
startAngle = (float) Math.floor(startAngle);
final int angle_int = (int) angle;
final int startAngle_int = (int) startAngle;
floored = !floored;
graphics.setColor(chartData.getColor().getAWTColor());
graphics.fillArc(offset, offset, diameter, diameter, startAngle_int, angle_int);
last_startAngle += angle_int;
}
last_startAngle = 0;
for(int i = 0; i < chartDatas.size(); i++) {
final ChartData chartData = chartDatas.get(i);
float angle = 360.0F * chartData.getPercentage();
float startAngle = last_startAngle;
if(i == chartDatas.size() - 1) {
startAngle += 0.5;
angle = 360.0F - last_startAngle + 0.5F;
} else {
if(floored) {
angle += 0.5;
startAngle += 0.5;
}
}
angle = (float) Math.floor(angle);
startAngle = (float) Math.floor(startAngle);
final float angle_half_radians = (float) Math.toRadians(startAngle + angle / 2.0 - 90);
floored = !floored;
int x_middle_text = (int) (width_half - (Math.sin(angle_half_radians) * radius * 0.9F));
int y_middle_text = (int) (height_half - (Math.cos(angle_half_radians) * radius * 0.9F));
final Color color = chartData.getColor();
if(color.getVector4f().lengthSquared() < 1.2F) {
graphics.setColor(java.awt.Color.WHITE);
} else {
graphics.setColor(java.awt.Color.BLACK);
}
final String name = chartData.getName() + (withPercentage ? String.format(" (%.2f%%)", (chartData.getPercentage() * 100.0F)) : "");
final Font font = new Font("TimesRoman", Font.PLAIN, (int) (300 * Math.pow(chartData.getPercentage(), 0.25F) / Math.pow(name.length(), 0.25F) * fontSizeFactor));
graphics.setFont(font);
final int name_width = graphics.getFontMetrics().stringWidth(name);
final int name_height = graphics.getFontMetrics().getAscent() - graphics.getFontMetrics().getDescent();
if((x_middle_text - (name_width / 2)) < 0) {
x_middle_text += ((name_width / 2) - x_middle_text);
} else if((x_middle_text + (name_width / 2)) > width) {
x_middle_text -= (x_middle_text + (name_width / 2) - width);
}
if((y_middle_text - name_height) < 0) {
y_middle_text += ((name_height) - y_middle_text);
} else if((y_middle_text + name_height) > height) {
y_middle_text -= (y_middle_text + name_height - height);
}
graphics.fillRect(x_middle_text - (name_width / 2), y_middle_text - name_height - 5, name_width, name_height + 15);
graphics.setColor(color.getAWTColor());
graphics.drawString(name, x_middle_text - (name_width / 2), y_middle_text);
last_startAngle += (int) angle;
}
return image;
}
public static final Color generateRandomColor() {
return new Color(random.nextInt(256) / 255.0F, random.nextInt(256) / 255.0F, random.nextInt(256) / 255.0F);
}
}
| src/omnikryptec/swing/PieChartGenerator.java | package omnikryptec.swing;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
import omnikryptec.logger.Logger;
import omnikryptec.util.AdvancedFile;
import omnikryptec.util.Color;
/**
* PieChartGenerator
* @author Panzer1119
*/
public class PieChartGenerator {
private static final Random random = new Random();
public static final void main(String[] args) {
final ArrayList<ChartData> chartDatas = new ArrayList<>();
for(int i = 0; i < 20; i++) {
chartDatas.add(new ChartData("Test " + i, (float) (Math.random() * 10.0F)));
}
final BufferedImage image = createPieChart(chartDatas, 1600, 1600, 0.9F, 0.7F);
try {
final AdvancedFile file = new AdvancedFile("test.png").getAbsoluteAdvancedFile();
file.createFile();
ImageIO.write(image, "png", file.createOutputstream(false));
} catch (Exception ex) {
Logger.logErr("Error while writing Image to File: " + ex, ex);
}
}
/**
* Creates a PieChart based on the given ChartDatas
* @param chartDatas ArrayList ChartData Data
* @param width Integer Width of the Image
* @param height Integer Height of the Image
* @param diameterFactor Float Quotient of (diameter / (Math.min(width, height))) (1.0F = (diameter == Math.min(width, height)))
* @param fontSizeFactor Float Factor for the Fonts size (1.0F = normal size)
* @return BufferedImage Created PieChart
*/
public static final BufferedImage createPieChart(ArrayList<ChartData> chartDatas, int width, int height, float diameterFactor, float fontSizeFactor) {
if(chartDatas.isEmpty() || width <= 0 || height <= 0) {
return null;
}
final int width_half = width / 2;
final int height_half = height / 2;
final int radius = (int) (Math.min(width, height) / 2.0F * diameterFactor);
final int diameter = radius * 2;
final int offset = ((Math.min(width, height)) - diameter) / 2;
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics graphics = image.createGraphics();
graphics.setColor(java.awt.Color.WHITE);
graphics.fillRect(0, 0, width, height);
float max_data = 0.0F;
for(ChartData chartData : chartDatas) {
if(chartData.getColor() == null) {
chartData.setColor(generateRandomColor());
}
max_data += chartData.getValue();
}
for(ChartData chartData : chartDatas) {
chartData.setPercentage(chartData.getValue() / max_data);
}
int last_startAngle = 0;
boolean floored = false;
for(int i = 0; i < chartDatas.size(); i++) {
final ChartData chartData = chartDatas.get(i);
float angle = 360.0F * chartData.getPercentage();
float startAngle = last_startAngle;
if(i == chartDatas.size() - 1) {
startAngle += 0.5;
angle = 360.0F - last_startAngle + 0.5F;
} else {
if(floored) {
angle += 0.5;
startAngle += 0.5;
}
}
angle = (float) Math.floor(angle);
startAngle = (float) Math.floor(startAngle);
final int angle_int = (int) angle;
final int startAngle_int = (int) startAngle;
floored = !floored;
graphics.setColor(chartData.getColor().getAWTColor());
graphics.fillArc(offset, offset, diameter, diameter, startAngle_int, angle_int);
last_startAngle += angle_int;
}
last_startAngle = 0;
for(int i = 0; i < chartDatas.size(); i++) {
final ChartData chartData = chartDatas.get(i);
float angle = 360.0F * chartData.getPercentage();
float startAngle = last_startAngle;
if(i == chartDatas.size() - 1) {
startAngle += 0.5;
angle = 360.0F - last_startAngle + 0.5F;
} else {
if(floored) {
angle += 0.5;
startAngle += 0.5;
}
}
angle = (float) Math.floor(angle);
startAngle = (float) Math.floor(startAngle);
final float angle_half_radians = (float) Math.toRadians(startAngle + angle / 2.0 - 90);
floored = !floored;
int x_middle_text = (int) (width_half - (Math.sin(angle_half_radians) * radius * 0.9F));
int y_middle_text = (int) (height_half - (Math.cos(angle_half_radians) * radius * 0.9F));
graphics.setColor(java.awt.Color.BLACK);
final Font font = new Font("TimesRoman", Font.PLAIN, (int) (300 * Math.pow(chartData.getPercentage(), 0.25F) / Math.pow(chartData.getName().length(), 0.25F) * fontSizeFactor));
graphics.setFont(font);
final int name_width = graphics.getFontMetrics().stringWidth(chartData.getName());
final int name_height = graphics.getFontMetrics().getAscent() - graphics.getFontMetrics().getDescent();
if((x_middle_text - (name_width / 2)) < 0) {
x_middle_text += ((name_width / 2) - x_middle_text);
} else if((x_middle_text + (name_width / 2)) > width) {
x_middle_text -= (x_middle_text + (name_width / 2) - width);
}
if((y_middle_text - name_height) < 0) {
y_middle_text += ((name_height) - y_middle_text);
} else if((y_middle_text + name_height) > height) {
y_middle_text -= (y_middle_text + name_height - height);
}
graphics.fillRect(x_middle_text - (name_width / 2), y_middle_text - name_height - 5, name_width, name_height + 15);
graphics.setColor(chartData.getColor().getAWTColor());
graphics.drawString(chartData.getName(), x_middle_text - (name_width / 2), y_middle_text);
last_startAngle += (int) angle;
}
return image;
}
public static final Color generateRandomColor() {
return new Color(random.nextInt(256) / 255.0F, random.nextInt(256) / 255.0F, random.nextInt(256) / 255.0F);
}
}
| Added percentage beside the name
| src/omnikryptec/swing/PieChartGenerator.java | Added percentage beside the name | <ide><path>rc/omnikryptec/swing/PieChartGenerator.java
<ide> for(int i = 0; i < 20; i++) {
<ide> chartDatas.add(new ChartData("Test " + i, (float) (Math.random() * 10.0F)));
<ide> }
<del> final BufferedImage image = createPieChart(chartDatas, 1600, 1600, 0.9F, 0.7F);
<add> final BufferedImage image = createPieChart(chartDatas, 1600, 1600, 0.9F, 0.65F, true);
<ide> try {
<ide> final AdvancedFile file = new AdvancedFile("test.png").getAbsoluteAdvancedFile();
<ide> file.createFile();
<ide> * @param height Integer Height of the Image
<ide> * @param diameterFactor Float Quotient of (diameter / (Math.min(width, height))) (1.0F = (diameter == Math.min(width, height)))
<ide> * @param fontSizeFactor Float Factor for the Fonts size (1.0F = normal size)
<add> * @param withPercentage Boolean If the percentage of each ChartData should be shown beside the name
<ide> * @return BufferedImage Created PieChart
<ide> */
<del> public static final BufferedImage createPieChart(ArrayList<ChartData> chartDatas, int width, int height, float diameterFactor, float fontSizeFactor) {
<add> public static final BufferedImage createPieChart(ArrayList<ChartData> chartDatas, int width, int height, float diameterFactor, float fontSizeFactor, boolean withPercentage) {
<ide> if(chartDatas.isEmpty() || width <= 0 || height <= 0) {
<ide> return null;
<ide> }
<ide> floored = !floored;
<ide> int x_middle_text = (int) (width_half - (Math.sin(angle_half_radians) * radius * 0.9F));
<ide> int y_middle_text = (int) (height_half - (Math.cos(angle_half_radians) * radius * 0.9F));
<del> graphics.setColor(java.awt.Color.BLACK);
<del> final Font font = new Font("TimesRoman", Font.PLAIN, (int) (300 * Math.pow(chartData.getPercentage(), 0.25F) / Math.pow(chartData.getName().length(), 0.25F) * fontSizeFactor));
<add> final Color color = chartData.getColor();
<add> if(color.getVector4f().lengthSquared() < 1.2F) {
<add> graphics.setColor(java.awt.Color.WHITE);
<add> } else {
<add> graphics.setColor(java.awt.Color.BLACK);
<add> }
<add> final String name = chartData.getName() + (withPercentage ? String.format(" (%.2f%%)", (chartData.getPercentage() * 100.0F)) : "");
<add> final Font font = new Font("TimesRoman", Font.PLAIN, (int) (300 * Math.pow(chartData.getPercentage(), 0.25F) / Math.pow(name.length(), 0.25F) * fontSizeFactor));
<ide> graphics.setFont(font);
<del> final int name_width = graphics.getFontMetrics().stringWidth(chartData.getName());
<add> final int name_width = graphics.getFontMetrics().stringWidth(name);
<ide> final int name_height = graphics.getFontMetrics().getAscent() - graphics.getFontMetrics().getDescent();
<ide> if((x_middle_text - (name_width / 2)) < 0) {
<ide> x_middle_text += ((name_width / 2) - x_middle_text);
<ide> y_middle_text -= (y_middle_text + name_height - height);
<ide> }
<ide> graphics.fillRect(x_middle_text - (name_width / 2), y_middle_text - name_height - 5, name_width, name_height + 15);
<del> graphics.setColor(chartData.getColor().getAWTColor());
<del> graphics.drawString(chartData.getName(), x_middle_text - (name_width / 2), y_middle_text);
<add> graphics.setColor(color.getAWTColor());
<add> graphics.drawString(name, x_middle_text - (name_width / 2), y_middle_text);
<ide> last_startAngle += (int) angle;
<ide> }
<ide> return image; |
|
JavaScript | mit | 7bc890fe1901b1170843d7627aec8eca9ac50502 | 0 | timtocci/Chrome-Useful-New-Tab-Page,timtocci/Chrome-Useful-New-Tab-Page | /*
chrome.runtime.getBackgroundPage(function(bgPage) {
//bgPage[tab.url] = data;
});
*/
var search_items_array = [];
/**
* Displays Top Sites
* @param topSitesArray
*/
function displayTopSites(topSitesArray) {
var mostVisitedDiv = document.getElementById('mostVisited_div');
var ul = mostVisitedDiv.appendChild(document.createElement('ul'));
for (var i = 0; i < topSitesArray.length; i++) {
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = topSitesArray[i].url;
a.appendChild(document.createTextNode(topSitesArray[i].title));
}
}
/**
* Displays Recently Bookmarked Sites
* @param recentlyBookmarkedArray
*/
function displayRecentlyBookmarked(recentlyBookmarkedArray) {
var recentlyBookmarkedDiv = document.getElementById('recentlyBookmarked_div');
var ul = recentlyBookmarkedDiv.appendChild(document.createElement('ul'));
for (var i = 0; i < recentlyBookmarkedArray.length; i++) {
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = recentlyBookmarkedArray[i].url;
a.appendChild(document.createTextNode(recentlyBookmarkedArray[i].title));
}
}
/**
* Retrieves and displays Recently Visited Sites
*/
function getRecentlyVisited() {
var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
var oneWeekAgo = (new Date).getTime() - microsecondsPerWeek;
var recentlyVisitedDiv = document.getElementById('recentlyVisited_div');
var ul = recentlyVisitedDiv.appendChild(document.createElement('ul'));
chrome.history.search({
'text': '',
'startTime': oneWeekAgo
}, function (historyItems) {
for (var i = 0; i < historyItems.length; ++i) {
var url = historyItems[i].url;
var title = historyItems[i].title;
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = url;
if (!title) {
a.className = 'color-gray-50 smaller';
a.appendChild(document.createTextNode('-----NO TITLE-----'));
} else {
a.appendChild(document.createTextNode(title));
}
}
});
}
/**
* Handles link click inside of addon
* @param e Click Event
* @returns {boolean}
*/
function onChromeUrlClick(e) {
e.preventDefault();
chrome.tabs.create({url: e.srcElement.href});
return false;
}
/**
* Opens a new tab
* @param href
*/
function openTab(href) {
chrome.tabs.create({url: href});
}
/**
* Replaces current tab
* @param href
*/
function replaceTab(href) {
chrome.tabs.getCurrent(function (tab) {
openTab(href);
chrome.tabs.remove(tab.id);
});
}
/**
* Initializes Click Listeners for Chrome URLs
*/
function initializeNavMenu() {
var links = document.getElementsByClassName('chromeurls');
for (i = 0; i < links.length; i++) {
links[i].addEventListener('click', onChromeUrlClick);
}
}
/**
* Opens a tab set
* @param name
* @param evt
*/
function openTabSet(name, evt) {
name = name.trim();
if(name == "+"){
//$(evt.target).parent().parent().parent().children(".tabset_items").css("display", "block");
let tabitems = $(evt.target).parent().parent().parent().children(".tabset_items");
tabitems.css("display", "block");
evt.target.textContent = "-";
}else if(name == "-"){
//console.log(evt)
let tabitems = $(evt.target).parent().parent().parent().children(".tabset_items");
tabitems.css("display", "none");
evt.target.textContent = "+";
}
else{
console.log('openTabSet with ' + name);
var tabset;
chrome.runtime.getBackgroundPage(function (bgPage) {
var tabsets = bgPage.Me.db.TabSets;
if (tabsets) {
console.log(tabsets);
for (var i = 0; i < tabsets.length; i++) {
if (tabsets[i].name === name) {
tabset = tabsets[i];
var urls = tabset.urls;
for (var ii = 0; ii < urls.length; ii++) {
chrome.tabs.create({url: urls[ii]});
}
}
}
}
});
}
}
/**
* Initializes the search pane
*/
function initializeSearch() {
chrome.runtime.getBackgroundPage(function (bgPage) {
// bypass data version check for now
search_items_array = bgPage.search_item_collection.items;
var categoryArr = [];
var inserthtml = "";
// fill the category array
for (let item of search_items_array) {
if (categoryArr.lastIndexOf(item.category) === -1) {
categoryArr.push(item.category);
}
}
// create the html to insert
for (let category of categoryArr) {
inserthtml += '<label><strong>' + category + '</strong><ul class="forms-inline-list">';
for (let item of search_items_array) {
if (item.category === category) {
if (item.active) {
inserthtml += `<li><input type="checkbox" name="${item.id}" id="${item.id}" checked><label for="${item.id}">${item.label}</label></li>`;
} else {
inserthtml += `<li><input type="checkbox" name="${item.id}" id="${item.id}"><label for="${item.id}">${item.label}</label></li>`;
}
}
}
inserthtml += '</ul></label>';
}
document.getElementById('search_settings_container').innerHTML = inserthtml;
});
}
function showTabsetItems(index){
$(".tabset .tabset_items").each(function (idx) {
if(idx === index){
$(this).toggle("display")
}
});
$(".tabset .tabset_title_delete").each(function (idx) {
if(idx === index){
$(this).css("visibility", "visible")
}
});
}
function hideTabsetItems(index){
$(".tabset .tabset_items").each(function (idx) {
if(idx === index){
$(this).toggle("display")
}
});
$(".tabset .tabset_title_delete").each(function (idx) {
if(idx === index){
$(this).css("visibility", "hidden")
}
});
}
window.onload = function () {
var createbutton = document.getElementById('btnCreateSearchSet');
createbutton.addEventListener('click', function (e) {
e.preventDefault();
var objQueryInfo = {
windowType: "normal"
};
chrome.runtime.getBackgroundPage(function (bgPage) {
chrome.tabs.query(objQueryInfo, function (tabArray) {
console.log(tabArray);
//bgPage.Me.tabs = tabArray;
replaceTab('searchsets.html');
});
});
});
var createtabsetbutton = document.getElementById('btnCreateTabSet');
createtabsetbutton.addEventListener('click', function (e) {
e.preventDefault();
replaceTab('tabsets.html');
});
// ToDo: Add document nodes before this listener
$(".tabset .tabset_title_expand").each(function(idx){
$(this).bind("click", function(){
$(this).children().each(function(){
if($(this).text() === "+"){
$(this).text("-");
showTabsetItems(idx)
}else{
$(this).text("+");
hideTabsetItems(idx)
}
}) ;
})
});
// initialize search pane
initializeSearch();
// handle search button
var searchbutton = document.getElementById('btnSearch');
searchbutton.addEventListener('click', function (e) {
e.preventDefault();
var term = document.getElementById('txtSearch').value;
if (term === "" || term === 'No Empty Queries Allowed') {
document.getElementById('txtSearch').value = 'No Empty Queries Allowed';
} else {
var container = document.getElementById('search_settings_container');
var cbItems = container.getElementsByTagName('input');
for (let item of cbItems) {
if (item.type === 'checkbox' && item.checked) {
for (let sitem of search_items_array) {
if (item.id === sitem.id) {
let url = sitem.url[0] + encodeURIComponent(term);
if (sitem.url.length > 1) {
url += sitem.url[1]
}
openTab(url);
}
}
}
}
}
});
// display links
chrome.topSites.get(displayTopSites);
chrome.bookmarks.getRecent(80, displayRecentlyBookmarked);
getRecentlyVisited();
initializeNavMenu();
}; | addon.js | /*
chrome.runtime.getBackgroundPage(function(bgPage) {
//bgPage[tab.url] = data;
});
*/
var search_items_array = [];
/**
* Displays Top Sites
* @param topSitesArray
*/
function displayTopSites(topSitesArray) {
var mostVisitedDiv = document.getElementById('mostVisited_div');
var ul = mostVisitedDiv.appendChild(document.createElement('ul'));
for (var i = 0; i < topSitesArray.length; i++) {
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = topSitesArray[i].url;
a.appendChild(document.createTextNode(topSitesArray[i].title));
}
}
/**
* Displays Recently Bookmarked Sites
* @param recentlyBookmarkedArray
*/
function displayRecentlyBookmarked(recentlyBookmarkedArray) {
var recentlyBookmarkedDiv = document.getElementById('recentlyBookmarked_div');
var ul = recentlyBookmarkedDiv.appendChild(document.createElement('ul'));
for (var i = 0; i < recentlyBookmarkedArray.length; i++) {
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = recentlyBookmarkedArray[i].url;
a.appendChild(document.createTextNode(recentlyBookmarkedArray[i].title));
}
}
/**
* Retrieves and displays Recently Visited Sites
*/
function getRecentlyVisited() {
var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
var oneWeekAgo = (new Date).getTime() - microsecondsPerWeek;
var recentlyVisitedDiv = document.getElementById('recentlyVisited_div');
var ul = recentlyVisitedDiv.appendChild(document.createElement('ul'));
chrome.history.search({
'text': '',
'startTime': oneWeekAgo
}, function (historyItems) {
for (var i = 0; i < historyItems.length; ++i) {
var url = historyItems[i].url;
var title = historyItems[i].title;
var li = ul.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = url;
if (!title) {
a.className = 'color-gray-50 smaller';
a.appendChild(document.createTextNode('-----NO TITLE-----'));
} else {
a.appendChild(document.createTextNode(title));
}
}
});
}
/**
* Handles link click inside of addon
* @param e Click Event
* @returns {boolean}
*/
function onChromeUrlClick(e) {
e.preventDefault();
chrome.tabs.create({url: e.srcElement.href});
return false;
}
/**
* Opens a new tab
* @param href
*/
function openTab(href) {
chrome.tabs.create({url: href});
}
/**
* Replaces current tab
* @param href
*/
function replaceTab(href) {
chrome.tabs.getCurrent(function (tab) {
openTab(href);
chrome.tabs.remove(tab.id);
});
}
/**
* Initializes Click Listeners for Chrome URLs
*/
function initializeNavMenu() {
var links = document.getElementsByClassName('chromeurls');
for (i = 0; i < links.length; i++) {
links[i].addEventListener('click', onChromeUrlClick);
}
}
/**
* Opens a tab set
* @param name
* @param evt
*/
function openTabSet(name, evt) {
name = name.trim();
if(name == "+"){
//$(evt.target).parent().parent().parent().children(".tabset_items").css("display", "block");
let tabitems = $(evt.target).parent().parent().parent().children(".tabset_items");
tabitems.css("display", "block");
evt.target.textContent = "-";
}else if(name == "-"){
//console.log(evt)
let tabitems = $(evt.target).parent().parent().parent().children(".tabset_items");
tabitems.css("display", "none");
evt.target.textContent = "+";
}
else{
console.log('openTabSet with ' + name);
var tabset;
chrome.runtime.getBackgroundPage(function (bgPage) {
var tabsets = bgPage.Me.db.TabSets;
if (tabsets) {
console.log(tabsets);
for (var i = 0; i < tabsets.length; i++) {
if (tabsets[i].name === name) {
tabset = tabsets[i];
var urls = tabset.urls;
for (var ii = 0; ii < urls.length; ii++) {
chrome.tabs.create({url: urls[ii]});
}
}
}
}
});
}
}
/**
* Initializes the search pane
*/
function initializeSearch() {
chrome.runtime.getBackgroundPage(function (bgPage) {
// bypass data version check for now
search_items_array = bgPage.search_item_collection.items;
var categoryArr = [];
var inserthtml = "";
// fill the category array
for (let item of search_items_array) {
if (categoryArr.lastIndexOf(item.category) === -1) {
categoryArr.push(item.category);
}
}
// create the html to insert
for (let category of categoryArr) {
inserthtml += '<label><strong>' + category + '</strong><ul class="forms-inline-list">';
for (let item of search_items_array) {
if (item.category === category) {
if (item.active) {
inserthtml += `<li><input type="checkbox" name="${item.id}" id="${item.id}" checked><label for="${item.id}">${item.label}</label></li>`;
} else {
inserthtml += `<li><input type="checkbox" name="${item.id}" id="${item.id}"><label for="${item.id}">${item.label}</label></li>`;
}
}
}
inserthtml += '</ul></label>';
}
document.getElementById('search_settings_container').innerHTML = inserthtml;
});
}
function showTabsetItems(index){
$(".tabset .tabset_items").each(function (idx) {
if(idx === index){
$(this).toggle("display")
}
});
$(".tabset .tabset_title_delete").each(function (idx) {
if(idx === index){
$(this).css("visibility", "visible")
}
});
}
function hideTabsetItems(index){
$(".tabset .tabset_items").each(function (idx) {
if(idx === index){
$(this).toggle("display")
}
});
$(".tabset .tabset_title_delete").each(function (idx) {
if(idx === index){
$(this).css("visibility", "hidden")
}
});
}
window.onload = function () {
var createbutton = document.getElementById('btnCreateSearchSet');
createbutton.addEventListener('click', function (e) {
e.preventDefault();
var objQueryInfo = {
windowType: "normal"
};
chrome.runtime.getBackgroundPage(function (bgPage) {
chrome.tabs.query(objQueryInfo, function (tabArray) {
console.log(tabArray);
//bgPage.Me.tabs = tabArray;
replaceTab('searchsets.html');
});
});
});
var createtabsetbutton = document.getElementById('btnCreateTabSet');
createtabsetbutton.addEventListener('click', function (e) {
e.preventDefault();
replaceTab('tabsets.html');
});
$(".tabset .tabset_title_expand").each(function(idx){
$(this).bind("click", function(){
$(this).children().each(function(){
if($(this).text() === "+"){
$(this).text("-");
showTabsetItems(idx)
}else{
$(this).text("+");
hideTabsetItems(idx)
}
}) ;
})
});
// initialize search pane
initializeSearch();
// handle search button
var searchbutton = document.getElementById('btnSearch');
searchbutton.addEventListener('click', function (e) {
e.preventDefault();
var term = document.getElementById('txtSearch').value;
if (term === "" || term === 'No Empty Queries Allowed') {
document.getElementById('txtSearch').value = 'No Empty Queries Allowed';
} else {
var container = document.getElementById('search_settings_container');
var cbItems = container.getElementsByTagName('input');
for (let item of cbItems) {
if (item.type === 'checkbox' && item.checked) {
for (let sitem of search_items_array) {
if (item.id === sitem.id) {
let url = sitem.url[0] + encodeURIComponent(term);
if (sitem.url.length > 1) {
url += sitem.url[1]
}
openTab(url);
}
}
}
}
}
});
// display links
chrome.topSites.get(displayTopSites);
chrome.bookmarks.getRecent(80, displayRecentlyBookmarked);
getRecentlyVisited();
initializeNavMenu();
}; | white space cleaning & comment
| addon.js | white space cleaning & comment | <ide><path>ddon.js
<ide> replaceTab('tabsets.html');
<ide> });
<ide>
<add>
<add>
<add>
<add>
<add>
<add> // ToDo: Add document nodes before this listener
<ide> $(".tabset .tabset_title_expand").each(function(idx){
<ide> $(this).bind("click", function(){
<ide> $(this).children().each(function(){
<ide> $(this).text("+");
<ide> hideTabsetItems(idx)
<ide> }
<del>
<ide> }) ;
<ide> })
<ide> }); |
|
Java | apache-2.0 | 31c6acec6c335468793a79fecec7767011716e1d | 0 | 4treesCH/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,eitchnet/strolch,eitchnet/strolch,eitchnet/strolch,4treesCH/strolch | /*
* Copyright (c) 2012, Robert von Burg
*
* All rights reserved.
*
* This file is part of the Privilege.
*
* Privilege is free software: you can redistribute
* it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Privilege is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Privilege. If not, see
* <http://www.gnu.org/licenses/>.
*/
package ch.eitchnet.privilege.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.privilege.handler.DefaultEncryptionHandler;
import ch.eitchnet.privilege.handler.XmlPersistenceHandler;
import ch.eitchnet.privilege.model.IPrivilege;
import ch.eitchnet.privilege.model.UserState;
import ch.eitchnet.privilege.model.internal.PrivilegeContainerModel;
import ch.eitchnet.privilege.model.internal.PrivilegeImpl;
import ch.eitchnet.privilege.model.internal.Role;
import ch.eitchnet.privilege.model.internal.User;
import ch.eitchnet.privilege.xml.PrivilegeConfigDomWriter;
import ch.eitchnet.privilege.xml.PrivilegeConfigSaxReader;
import ch.eitchnet.privilege.xml.PrivilegeModelDomWriter;
import ch.eitchnet.privilege.xml.PrivilegeModelSaxReader;
import ch.eitchnet.utils.helper.FileHelper;
import ch.eitchnet.utils.helper.StringHelper;
import ch.eitchnet.utils.helper.XmlHelper;
/**
* @author Robert von Burg <[email protected]>
*
*/
public class XmlTest {
/**
*
*/
private static final String TARGET_TEST = "./target/test";
private static final Logger logger = LoggerFactory.getLogger(XmlTest.class);
/**
* @throws Exception
* if something goes wrong
*/
@BeforeClass
public static void init() throws Exception {
cleanUp();
File tmpDir = new File("target/test");
if (tmpDir.exists())
FileHelper.deleteFile(tmpDir, false);
tmpDir.mkdirs();
}
@AfterClass
public static void cleanUp() throws Exception {
File tmpDir = new File("target/test");
if (!tmpDir.exists())
return;
File tmpFile = new File("target/test/PrivilegeTest.xml");
if (tmpFile.exists() && !tmpFile.delete()) {
throw new RuntimeException("Tmp still exists and can not be deleted at " + tmpFile.getAbsolutePath());
}
tmpFile = new File("target/test/PrivilegeModelTest.xml");
if (tmpFile.exists() && !tmpFile.delete()) {
throw new RuntimeException("Tmp still exists and can not be deleted at " + tmpFile.getAbsolutePath());
}
// and temporary parent
if (!tmpDir.delete()) {
throw new RuntimeException("Could not remove temporary parent for tmp " + tmpFile);
}
}
@Test
public void canReadConfig() {
PrivilegeContainerModel containerModel = new PrivilegeContainerModel();
PrivilegeConfigSaxReader saxReader = new PrivilegeConfigSaxReader(containerModel);
File xmlFile = new File("config/Privilege.xml");
XmlHelper.parseDocument(xmlFile, saxReader);
logger.info(containerModel.toString());
// assert all objects read
Assert.assertNotNull(containerModel.getParameterMap());
Assert.assertNotNull(containerModel.getPolicies());
Assert.assertNotNull(containerModel.getEncryptionHandlerClassName());
Assert.assertNotNull(containerModel.getEncryptionHandlerParameterMap());
Assert.assertNotNull(containerModel.getPersistenceHandlerClassName());
Assert.assertNotNull(containerModel.getPersistenceHandlerParameterMap());
Assert.assertEquals(1, containerModel.getParameterMap().size());
Assert.assertEquals(1, containerModel.getPolicies().size());
Assert.assertEquals(1, containerModel.getEncryptionHandlerParameterMap().size());
Assert.assertEquals(2, containerModel.getPersistenceHandlerParameterMap().size());
// TODO extend assertions to actual model
}
@Test
public void canWriteConfig() {
Map<String, String> parameterMap = new HashMap<String, String>();
Map<String, String> encryptionHandlerParameterMap = new HashMap<String, String>();
Map<String, String> persistenceHandlerParameterMap = new HashMap<String, String>();
parameterMap.put("autoPersistOnPasswordChange", "true");
encryptionHandlerParameterMap.put("hashAlgorithm", "SHA-256");
persistenceHandlerParameterMap.put("basePath", TARGET_TEST);
persistenceHandlerParameterMap.put("modelXmlFile", "PrivilegeModel.xml");
PrivilegeContainerModel containerModel = new PrivilegeContainerModel();
containerModel.setParameterMap(parameterMap);
containerModel.setEncryptionHandlerClassName(DefaultEncryptionHandler.class.getName());
containerModel.setEncryptionHandlerParameterMap(encryptionHandlerParameterMap);
containerModel.setPersistenceHandlerClassName(XmlPersistenceHandler.class.getName());
containerModel.setPersistenceHandlerParameterMap(persistenceHandlerParameterMap);
containerModel.addPolicy("DefaultPrivilege", "ch.eitchnet.privilege.policy.DefaultPrivilege");
File configFile = new File("./target/test/PrivilegeTest.xml");
PrivilegeConfigDomWriter configSaxWriter = new PrivilegeConfigDomWriter(containerModel, configFile);
configSaxWriter.write();
String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(configFile));
Assert.assertEquals("2ABD3442EEC8BCEC5BEE365AAB6DB2FD4E1789325425CB1E017E900582525685", fileHash);
}
@Test
public void canReadModel() {
PrivilegeModelSaxReader xmlHandler = new PrivilegeModelSaxReader();
File xmlFile = new File("config/PrivilegeModel.xml");
XmlHelper.parseDocument(xmlFile, xmlHandler);
List<User> users = xmlHandler.getUsers();
Assert.assertNotNull(users);
List<Role> roles = xmlHandler.getRoles();
Assert.assertNotNull(roles);
Assert.assertEquals(2, users.size());
Assert.assertEquals(4, roles.size());
// TODO extend assertions to actual model
}
@Test
public void canWriteModel() {
Map<String, String> propertyMap;
Set<String> userRoles;
Map<String, IPrivilege> privilegeMap;
List<User> users = new ArrayList<User>();
propertyMap = new HashMap<String, String>();
propertyMap.put("prop1", "value1");
userRoles = new HashSet<String>();
userRoles.add("role1");
users.add(new User("1", "user1", "blabla", "Bob", "White", UserState.DISABLED, userRoles, Locale.ENGLISH,
propertyMap));
propertyMap = new HashMap<String, String>();
propertyMap.put("prop2", "value2");
userRoles = new HashSet<String>();
userRoles.add("role2");
users.add(new User("2", "user2", "haha", "Leonard", "Sheldon", UserState.ENABLED, userRoles, Locale.ENGLISH,
propertyMap));
List<Role> roles = new ArrayList<Role>();
Set<String> list = Collections.emptySet();
privilegeMap = new HashMap<String, IPrivilege>();
privilegeMap.put("priv1", new PrivilegeImpl("priv1", "DefaultPrivilege", true, list, list));
roles.add(new Role("role1", privilegeMap));
privilegeMap = new HashMap<String, IPrivilege>();
Set<String> denyList = new HashSet<String>();
denyList.add("myself");
Set<String> allowList = new HashSet<String>();
allowList.add("other");
privilegeMap.put("priv2", new PrivilegeImpl("priv2", "DefaultPrivilege", false, denyList, allowList));
roles.add(new Role("role2", privilegeMap));
File modelFile = new File("./target/test/PrivilegeModelTest.xml");
PrivilegeModelDomWriter configSaxWriter = new PrivilegeModelDomWriter(users, roles, modelFile);
configSaxWriter.write();
String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(modelFile));
Assert.assertEquals("A2127D20A61E00BCDBB61569CD2B200C4F0F111C972BAC3B1E54DF3B2FCDC8BE", fileHash);
}
}
| src/test/java/ch/eitchnet/privilege/test/XmlTest.java | /*
* Copyright (c) 2012, Robert von Burg
*
* All rights reserved.
*
* This file is part of the Privilege.
*
* Privilege is free software: you can redistribute
* it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Privilege is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Privilege. If not, see
* <http://www.gnu.org/licenses/>.
*/
package ch.eitchnet.privilege.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.privilege.handler.DefaultEncryptionHandler;
import ch.eitchnet.privilege.handler.XmlPersistenceHandler;
import ch.eitchnet.privilege.model.IPrivilege;
import ch.eitchnet.privilege.model.UserState;
import ch.eitchnet.privilege.model.internal.PrivilegeContainerModel;
import ch.eitchnet.privilege.model.internal.PrivilegeImpl;
import ch.eitchnet.privilege.model.internal.Role;
import ch.eitchnet.privilege.model.internal.User;
import ch.eitchnet.privilege.xml.PrivilegeConfigDomWriter;
import ch.eitchnet.privilege.xml.PrivilegeConfigSaxReader;
import ch.eitchnet.privilege.xml.PrivilegeModelDomWriter;
import ch.eitchnet.privilege.xml.PrivilegeModelSaxReader;
import ch.eitchnet.utils.helper.FileHelper;
import ch.eitchnet.utils.helper.StringHelper;
import ch.eitchnet.utils.helper.XmlHelper;
/**
* @author Robert von Burg <[email protected]>
*
*/
public class XmlTest {
/**
*
*/
private static final String TARGET_TEST = "./target/test";
private static final Logger logger = LoggerFactory.getLogger(XmlTest.class);
/**
* @throws Exception
* if something goes wrong
*/
@BeforeClass
public static void init() throws Exception {
destroy();
File tmpDir = new File("target/test");
if (tmpDir.exists())
FileHelper.deleteFile(tmpDir, false);
tmpDir.mkdirs();
}
//@AfterClass
public static void destroy() throws Exception {
File tmpDir = new File("target/test");
if (!tmpDir.exists())
return;
File tmpFile = new File("target/test/PrivilegeTest.xml");
if (tmpFile.exists() && !tmpFile.delete()) {
throw new RuntimeException("Tmp still exists and can not be deleted at " + tmpFile.getAbsolutePath());
}
tmpFile = new File("target/test/PrivilegeModelTest.xml");
if (tmpFile.exists() && !tmpFile.delete()) {
throw new RuntimeException("Tmp still exists and can not be deleted at " + tmpFile.getAbsolutePath());
}
// and temporary parent
if (!tmpDir.delete()) {
throw new RuntimeException("Could not remove temporary parent for tmp " + tmpFile);
}
}
@Test
public void canReadConfig() {
PrivilegeContainerModel containerModel = new PrivilegeContainerModel();
PrivilegeConfigSaxReader saxReader = new PrivilegeConfigSaxReader(containerModel);
File xmlFile = new File("config/Privilege.xml");
XmlHelper.parseDocument(xmlFile, saxReader);
logger.info(containerModel.toString());
// assert all objects read
Assert.assertNotNull(containerModel.getParameterMap());
Assert.assertNotNull(containerModel.getPolicies());
Assert.assertNotNull(containerModel.getEncryptionHandlerClassName());
Assert.assertNotNull(containerModel.getEncryptionHandlerParameterMap());
Assert.assertNotNull(containerModel.getPersistenceHandlerClassName());
Assert.assertNotNull(containerModel.getPersistenceHandlerParameterMap());
Assert.assertEquals(1, containerModel.getParameterMap().size());
Assert.assertEquals(1, containerModel.getPolicies().size());
Assert.assertEquals(1, containerModel.getEncryptionHandlerParameterMap().size());
Assert.assertEquals(2, containerModel.getPersistenceHandlerParameterMap().size());
// TODO extend assertions to actual model
}
@Test
public void canWriteConfig() {
Map<String, String> parameterMap = new HashMap<String, String>();
Map<String, String> encryptionHandlerParameterMap = new HashMap<String, String>();
Map<String, String> persistenceHandlerParameterMap = new HashMap<String, String>();
// TODO ask other questions...
parameterMap.put("autoPersistOnPasswordChange", "true");
encryptionHandlerParameterMap.put("hashAlgorithm", "SHA-256");
persistenceHandlerParameterMap.put("basePath", TARGET_TEST);
persistenceHandlerParameterMap.put("modelXmlFile", "PrivilegeModel.xml");
PrivilegeContainerModel containerModel = new PrivilegeContainerModel();
containerModel.setParameterMap(parameterMap);
containerModel.setEncryptionHandlerClassName(DefaultEncryptionHandler.class.getName());
containerModel.setEncryptionHandlerParameterMap(encryptionHandlerParameterMap);
containerModel.setPersistenceHandlerClassName(XmlPersistenceHandler.class.getName());
containerModel.setPersistenceHandlerParameterMap(persistenceHandlerParameterMap);
containerModel.addPolicy("DefaultPrivilege", "ch.eitchnet.privilege.policy.DefaultPrivilege");
File configFile = new File("./target/test/PrivilegeTest.xml");
PrivilegeConfigDomWriter configSaxWriter = new PrivilegeConfigDomWriter(containerModel, configFile);
configSaxWriter.write();
String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(configFile));
Assert.assertEquals("22D4BA39605D49C758184D9BD63BEAE5CCF8786F3DABBAB45CD9F59C2AFBCBD0", fileHash);
}
@Test
public void canReadModel() {
PrivilegeModelSaxReader xmlHandler = new PrivilegeModelSaxReader();
File xmlFile = new File("config/PrivilegeModel.xml");
XmlHelper.parseDocument(xmlFile, xmlHandler);
List<User> users = xmlHandler.getUsers();
Assert.assertNotNull(users);
List<Role> roles = xmlHandler.getRoles();
Assert.assertNotNull(roles);
Assert.assertEquals(2, users.size());
Assert.assertEquals(4, roles.size());
// TODO extend assertions to actual model
}
@Test
public void canWriteModel() {
Map<String, String> propertyMap;
Set<String> userRoles;
Map<String, IPrivilege> privilegeMap;
List<User> users = new ArrayList<User>();
propertyMap = new HashMap<String, String>();
propertyMap.put("prop1", "value1");
userRoles = new HashSet<String>();
userRoles.add("role1");
users.add(new User("1", "user1", "blabla", "Bob", "White", UserState.DISABLED, userRoles, Locale.ENGLISH,
propertyMap));
propertyMap = new HashMap<String, String>();
propertyMap.put("prop2", "value2");
userRoles = new HashSet<String>();
userRoles.add("role2");
users.add(new User("2", "user2", "haha", "Leonard", "Sheldon", UserState.ENABLED, userRoles, Locale.ENGLISH,
propertyMap));
List<Role> roles = new ArrayList<Role>();
Set<String> list = Collections.emptySet();
privilegeMap = new HashMap<String, IPrivilege>();
privilegeMap.put("priv1", new PrivilegeImpl("priv1", "DefaultPrivilege", true, list, list));
roles.add(new Role("role1", privilegeMap));
privilegeMap = new HashMap<String, IPrivilege>();
Set<String> denyList = new HashSet<String>();
denyList.add("myself");
Set<String> allowList = new HashSet<String>();
allowList.add("other");
privilegeMap.put("priv2", new PrivilegeImpl("priv2", "DefaultPrivilege", false, denyList, allowList));
roles.add(new Role("role2", privilegeMap));
File modelFile = new File("./target/test/PrivilegeModelTest.xml");
PrivilegeModelDomWriter configSaxWriter = new PrivilegeModelDomWriter(users, roles, modelFile);
configSaxWriter.write();
String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(modelFile));
Assert.assertEquals("9007F172BBD7BA51BA3E67199CE0AFCBC8645AF0AC02028ABE54BA6A2FC134B0", fileHash);
}
}
| [Minor] fixed failing test due to different formatting of xml writing | src/test/java/ch/eitchnet/privilege/test/XmlTest.java | [Minor] fixed failing test due to different formatting of xml writing | <ide><path>rc/test/java/ch/eitchnet/privilege/test/XmlTest.java
<ide>
<ide> import junit.framework.Assert;
<ide>
<add>import org.junit.AfterClass;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide> import org.slf4j.Logger;
<ide> */
<ide> @BeforeClass
<ide> public static void init() throws Exception {
<del> destroy();
<add>
<add> cleanUp();
<ide>
<ide> File tmpDir = new File("target/test");
<ide> if (tmpDir.exists())
<ide> tmpDir.mkdirs();
<ide> }
<ide>
<del> //@AfterClass
<del> public static void destroy() throws Exception {
<add> @AfterClass
<add> public static void cleanUp() throws Exception {
<ide>
<ide> File tmpDir = new File("target/test");
<ide> if (!tmpDir.exists())
<ide> Map<String, String> encryptionHandlerParameterMap = new HashMap<String, String>();
<ide> Map<String, String> persistenceHandlerParameterMap = new HashMap<String, String>();
<ide>
<del> // TODO ask other questions...
<ide> parameterMap.put("autoPersistOnPasswordChange", "true");
<ide> encryptionHandlerParameterMap.put("hashAlgorithm", "SHA-256");
<ide> persistenceHandlerParameterMap.put("basePath", TARGET_TEST);
<ide> configSaxWriter.write();
<ide>
<ide> String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(configFile));
<del> Assert.assertEquals("22D4BA39605D49C758184D9BD63BEAE5CCF8786F3DABBAB45CD9F59C2AFBCBD0", fileHash);
<add> Assert.assertEquals("2ABD3442EEC8BCEC5BEE365AAB6DB2FD4E1789325425CB1E017E900582525685", fileHash);
<ide> }
<ide>
<ide> @Test
<ide> configSaxWriter.write();
<ide>
<ide> String fileHash = StringHelper.getHexString(FileHelper.hashFileSha256(modelFile));
<del> Assert.assertEquals("9007F172BBD7BA51BA3E67199CE0AFCBC8645AF0AC02028ABE54BA6A2FC134B0", fileHash);
<add> Assert.assertEquals("A2127D20A61E00BCDBB61569CD2B200C4F0F111C972BAC3B1E54DF3B2FCDC8BE", fileHash);
<ide> }
<ide> } |
|
Java | apache-2.0 | fab2c816cf3f9a2cfde36a6334947e7ebc772c04 | 0 | kkroid/OnechatSmack,magnetsystems/message-smack,annovanvliet/Smack,ayne/Smack,dpr-odoo/Smack,igniterealtime/Smack,annovanvliet/Smack,chuangWu/Smack,lovely3x/Smack,igniterealtime/Smack,cjpx00008/Smack,kkroid/OnechatSmack,ayne/Smack,qingsong-xu/Smack,opg7371/Smack,lovely3x/Smack,dpr-odoo/Smack,xuIcream/Smack,andrey42/Smack,esl/Smack,igorexax3mal/Smack,dpr-odoo/Smack,TTalkIM/Smack,esl/Smack,chuangWu/Smack,ayne/Smack,hy9902/Smack,u20024804/Smack,vanitasvitae/Smack,igniterealtime/Smack,u20024804/Smack,vanitasvitae/smack-omemo,cjpx00008/Smack,mar-v-in/Smack,igorexax3mal/Smack,unisontech/Smack,chuangWu/Smack,Flowdalic/Smack,annovanvliet/Smack,unisontech/Smack,hy9902/Smack,qingsong-xu/Smack,vanitasvitae/smack-omemo,Tibo-lg/Smack,vito-c/Smack,andrey42/Smack,andrey42/Smack,ishan1604/Smack,xuIcream/Smack,deeringc/Smack,mar-v-in/Smack,deeringc/Smack,lovely3x/Smack,Flowdalic/Smack,TTalkIM/Smack,cjpx00008/Smack,kkroid/OnechatSmack,u20024804/Smack,deeringc/Smack,opg7371/Smack,Tibo-lg/Smack,vito-c/Smack,vanitasvitae/Smack,vanitasvitae/Smack,opg7371/Smack,igorexax3mal/Smack,Tibo-lg/Smack,magnetsystems/message-smack,qingsong-xu/Smack,esl/Smack,ishan1604/Smack,hy9902/Smack,TTalkIM/Smack,unisontech/Smack,xuIcream/Smack,magnetsystems/message-smack,Flowdalic/Smack,vanitasvitae/smack-omemo,ishan1604/Smack,mar-v-in/Smack | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2002-2003 Jive Software. All rights reserved.
* ====================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Smack" and "Jive Software" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact [email protected].
*
* 5. Products derived from this software may not be called "Smack",
* nor may "Smack" appear in their name, without prior written
* permission of Jive Software.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jivesoftware.smackx.packet;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jivesoftware.smack.packet.PacketExtension;
/**
* Represents extended presence information whose sole purpose is to signal the ability of
* the occupant to speak the MUC protocol when joining a room. If the room requires a password
* then the MUCInitialPresence should include one.<p>
*
* The amount of discussion history provided on entering a room (perhaps because the
* user is on a low-bandwidth connection or is using a small-footprint client) could be managed by
* setting a configured History instance to the MUCInitialPresence instance.
* @see MUCInitialPresence#setHistory(MUCInitialPresence.History).
*
* @author Gaston Dombiak
*/
public class MUCInitialPresence implements PacketExtension {
private String password;
private History history;
public String getElementName() {
return "x";
}
public String getNamespace() {
return "http://jabber.org/protocol/muc";
}
public String toXML() {
StringBuffer buf = new StringBuffer();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">");
if (getPassword() != null) {
buf.append("<password>").append(getPassword()).append("</password>");
}
if (getHistory() != null) {
buf.append(getHistory().toXML());
}
buf.append("</").append(getElementName()).append(">");
return buf.toString();
}
/**
* Returns the history that manages the amount of discussion history provided on
* entering a room.
*
* @return the history that manages the amount of discussion history provided on
* entering a room.
*/
public History getHistory() {
return history;
}
/**
* Returns the password to use when the room requires a password.
*
* @return the password to use when the room requires a password.
*/
public String getPassword() {
return password;
}
/**
* Sets the History that manages the amount of discussion history provided on
* entering a room.
*
* @param history that manages the amount of discussion history provided on
* entering a room.
*/
public void setHistory(History history) {
this.history = history;
}
/**
* Sets the password to use when the room requires a password.
*
* @param password the password to use when the room requires a password.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* The History class controls the number of characters or messages to receive
* when entering a room.
*
* @author Gaston Dombiak
*/
public static class History {
private int maxChars = -1;
private int maxStanzas = -1;
private int seconds = -1;
private Date since;
/**
* Returns the total number of characters to receive in the history.
*
* @return total number of characters to receive in the history.
*/
public int getMaxChars() {
return maxChars;
}
/**
* Returns the total number of messages to receive in the history.
*
* @return the total number of messages to receive in the history.
*/
public int getMaxStanzas() {
return maxStanzas;
}
/**
* Returns the number of seconds to use to filter the messages received during that time.
* In other words, only the messages received in the last "X" seconds will be included in
* the history.
*
* @return the number of seconds to use to filter the messages received during that time.
*/
public int getSeconds() {
return seconds;
}
/**
* Returns the since date to use to filter the messages received during that time.
* In other words, only the messages received since the datetime specified will be
* included in the history.
*
* @return the since date to use to filter the messages received during that time.
*/
public Date getSince() {
return since;
}
/**
* Sets the total number of characters to receive in the history.
*
* @param maxChars the total number of characters to receive in the history.
*/
public void setMaxChars(int maxChars) {
this.maxChars = maxChars;
}
/**
* Sets the total number of messages to receive in the history.
*
* @param maxStanzas the total number of messages to receive in the history.
*/
public void setMaxStanzas(int maxStanzas) {
this.maxStanzas = maxStanzas;
}
/**
* Sets the number of seconds to use to filter the messages received during that time.
* In other words, only the messages received in the last "X" seconds will be included in
* the history.
*
* @param seconds he number of seconds to use to filter the messages received during
* that time.
*/
public void setSeconds(int seconds) {
this.seconds = seconds;
}
/**
* Sets the since date to use to filter the messages received during that time.
* In other words, only the messages received since the datetime specified will be
* included in the history.
*
* @param since the since date to use to filter the messages received during that time.
*/
public void setSince(Date since) {
this.since = since;
}
public String toXML() {
StringBuffer buf = new StringBuffer();
buf.append("<history");
if (getMaxChars() != -1) {
buf.append(" maxchars=\"").append(getMaxChars()).append("\"");
}
if (getMaxStanzas() != -1) {
buf.append(" maxstanzas=\"").append(getMaxStanzas()).append("\"");
}
if (getSeconds() != -1) {
buf.append(" seconds=\"").append(getSeconds()).append("\"");
}
if (getSince() != null) {
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyyMMdd'T'hh:mm:ss");
buf.append(" seconds=\"").append(utcFormat.format(getSince())).append("\"");
}
buf.append("/>");
return buf.toString();
}
}
}
| source/org/jivesoftware/smackx/packet/MUCInitialPresence.java | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2002-2003 Jive Software. All rights reserved.
* ====================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Smack" and "Jive Software" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact [email protected].
*
* 5. Products derived from this software may not be called "Smack",
* nor may "Smack" appear in their name, without prior written
* permission of Jive Software.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jivesoftware.smackx.packet;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jivesoftware.smack.packet.PacketExtension;
/**
* Represents extended presence information whose sole purpose is to signal the ability of
* the occupant to speak the MUC protocol when joining a room. If the room requires a password
* then the MUCInitialPresence should include one.<p>
*
* The amount of discussion history provided on entering a room (perhaps because the
* user is on a low-bandwidth connection or is using a small-footprint client) could be managed by
* setting a configured History instance to the MUCInitialPresence instance.
* @see MUCInitialPresence#setHistory(MUCInitialPresence.History).
*
* @author Gaston Dombiak
*/
public class MUCInitialPresence implements PacketExtension {
private String password;
private History history;
public String getElementName() {
return "x";
}
public String getNamespace() {
return "http://jabber.org/protocol/muc";
}
public String toXML() {
StringBuffer buf = new StringBuffer();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">");
if (getPassword() != null) {
buf.append(" password=\"").append(getPassword()).append("\"");
}
if (getHistory() != null) {
buf.append(getHistory().toXML());
}
buf.append("</").append(getElementName()).append(">");
return buf.toString();
}
/**
* Returns the history that manages the amount of discussion history provided on
* entering a room.
*
* @return the history that manages the amount of discussion history provided on
* entering a room.
*/
public History getHistory() {
return history;
}
/**
* Returns the password to use when the room requires a password.
*
* @return the password to use when the room requires a password.
*/
public String getPassword() {
return password;
}
/**
* Sets the History that manages the amount of discussion history provided on
* entering a room.
*
* @param history that manages the amount of discussion history provided on
* entering a room.
*/
public void setHistory(History history) {
this.history = history;
}
/**
* Sets the password to use when the room requires a password.
*
* @param password the password to use when the room requires a password.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* The History class controls the number of characters or messages to receive
* when entering a room.
*
* @author Gaston Dombiak
*/
public static class History {
private int maxChars = -1;
private int maxStanzas = -1;
private int seconds = -1;
private Date since;
/**
* Returns the total number of characters to receive in the history.
*
* @return total number of characters to receive in the history.
*/
public int getMaxChars() {
return maxChars;
}
/**
* Returns the total number of messages to receive in the history.
*
* @return the total number of messages to receive in the history.
*/
public int getMaxStanzas() {
return maxStanzas;
}
/**
* Returns the number of seconds to use to filter the messages received during that time.
* In other words, only the messages received in the last "X" seconds will be included in
* the history.
*
* @return the number of seconds to use to filter the messages received during that time.
*/
public int getSeconds() {
return seconds;
}
/**
* Returns the since date to use to filter the messages received during that time.
* In other words, only the messages received since the datetime specified will be
* included in the history.
*
* @return the since date to use to filter the messages received during that time.
*/
public Date getSince() {
return since;
}
/**
* Sets the total number of characters to receive in the history.
*
* @param maxChars the total number of characters to receive in the history.
*/
public void setMaxChars(int maxChars) {
this.maxChars = maxChars;
}
/**
* Sets the total number of messages to receive in the history.
*
* @param maxStanzas the total number of messages to receive in the history.
*/
public void setMaxStanzas(int maxStanzas) {
this.maxStanzas = maxStanzas;
}
/**
* Sets the number of seconds to use to filter the messages received during that time.
* In other words, only the messages received in the last "X" seconds will be included in
* the history.
*
* @param seconds he number of seconds to use to filter the messages received during
* that time.
*/
public void setSeconds(int seconds) {
this.seconds = seconds;
}
/**
* Sets the since date to use to filter the messages received during that time.
* In other words, only the messages received since the datetime specified will be
* included in the history.
*
* @param since the since date to use to filter the messages received during that time.
*/
public void setSince(Date since) {
this.since = since;
}
public String toXML() {
StringBuffer buf = new StringBuffer();
buf.append("<history");
if (getMaxChars() != -1) {
buf.append(" maxchars=\"").append(getMaxChars()).append("\"");
}
if (getMaxStanzas() != -1) {
buf.append(" maxstanzas=\"").append(getMaxStanzas()).append("\"");
}
if (getSeconds() != -1) {
buf.append(" seconds=\"").append(getSeconds()).append("\"");
}
if (getSince() != null) {
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyyMMdd'T'hh:mm:ss");
buf.append(" seconds=\"").append(utcFormat.format(getSince())).append("\"");
}
buf.append("/>");
return buf.toString();
}
}
}
| Fixes the encoding of the password in the #toXML method
git-svn-id: 0d4d1bf2e47502aa0f0957c230a0ec7fa56198fd@2270 b35dd754-fafc-0310-a699-88a17e54d16e
| source/org/jivesoftware/smackx/packet/MUCInitialPresence.java | Fixes the encoding of the password in the #toXML method | <ide><path>ource/org/jivesoftware/smackx/packet/MUCInitialPresence.java
<ide> buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
<ide> "\">");
<ide> if (getPassword() != null) {
<del> buf.append(" password=\"").append(getPassword()).append("\"");
<add> buf.append("<password>").append(getPassword()).append("</password>");
<ide> }
<ide> if (getHistory() != null) {
<ide> buf.append(getHistory().toXML()); |
|
Java | apache-2.0 | 0c3b2ba6b0fd31c1d5b032d23e8d1917a4ecfdf0 | 0 | opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open | package net.floodlightcontroller.linkdiscovery;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.std.ToStringSerializer;
import org.openflow.util.HexString;
public interface ILinkDiscovery {
@JsonSerialize(using=ToStringSerializer.class)
public enum UpdateOperation {
LINK_ADDED("Link Added"), // Operation Added by ONOS
LINK_UPDATED("Link Updated"),
LINK_REMOVED("Link Removed"),
SWITCH_UPDATED("Switch Updated"),
SWITCH_REMOVED("Switch Removed"),
PORT_UP("Port Up"),
PORT_DOWN("Port Down");
private String value;
UpdateOperation(String v) {
value = v;
}
@Override
public String toString() {
return value;
}
}
public class LDUpdate {
protected long src;
protected short srcPort;
protected long dst;
protected short dstPort;
protected SwitchType srcType;
protected LinkType type;
protected UpdateOperation operation;
public LDUpdate(long src, short srcPort,
long dst, short dstPort,
ILinkDiscovery.LinkType type,
UpdateOperation operation) {
this.src = src;
this.srcPort = srcPort;
this.dst = dst;
this.dstPort = dstPort;
this.type = type;
this.operation = operation;
}
public LDUpdate(LDUpdate old) {
this.src = old.src;
this.srcPort = old.srcPort;
this.dst = old.dst;
this.dstPort = old.dstPort;
this.srcType = old.srcType;
this.type = old.type;
this.operation = old.operation;
}
// For updtedSwitch(sw)
public LDUpdate(long switchId, SwitchType stype, UpdateOperation oper ){
this.operation = oper;
this.src = switchId;
this.srcType = stype;
}
// For port up or port down.
public LDUpdate(long sw, short port, UpdateOperation operation) {
this.src = sw;
this.srcPort = port;
this.operation = operation;
}
public long getSrc() {
return src;
}
public short getSrcPort() {
return srcPort;
}
public long getDst() {
return dst;
}
public short getDstPort() {
return dstPort;
}
public SwitchType getSrcType() {
return srcType;
}
public LinkType getType() {
return type;
}
public UpdateOperation getOperation() {
return operation;
}
public void setOperation(UpdateOperation operation) {
this.operation = operation;
}
@Override
public String toString() {
switch (operation) {
case LINK_ADDED:
case LINK_REMOVED:
case LINK_UPDATED:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src)
+ ", srcPort=" + srcPort
+ ", dst=" + HexString.toHexString(dst)
+ ", dstPort=" + dstPort
+ ", type=" + type + "]";
case PORT_DOWN:
case PORT_UP:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src)
+ ", srcPort=" + srcPort + "]";
case SWITCH_REMOVED:
case SWITCH_UPDATED:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src) + "]";
default:
return "LDUpdate: Unknown update.";
}
}
}
public enum SwitchType {
BASIC_SWITCH, CORE_SWITCH
};
public enum LinkType {
INVALID_LINK {
@Override
public String toString() {
return "invalid";
}
},
DIRECT_LINK{
@Override
public String toString() {
return "internal";
}
},
MULTIHOP_LINK {
@Override
public String toString() {
return "external";
}
},
TUNNEL {
@Override
public String toString() {
return "tunnel";
}
}
};
}
| src/main/java/net/floodlightcontroller/linkdiscovery/ILinkDiscovery.java | package net.floodlightcontroller.linkdiscovery;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.std.ToStringSerializer;
import org.openflow.util.HexString;
public interface ILinkDiscovery {
@JsonSerialize(using=ToStringSerializer.class)
public enum UpdateOperation {
LINK_ADDED("Link Added"), // Operation Added by ONOS
LINK_UPDATED("Link Updated"),
LINK_REMOVED("Link Removed"),
SWITCH_UPDATED("Switch Updated"),
SWITCH_REMOVED("Switch Removed"),
PORT_UP("Port Up"),
PORT_DOWN("Port Down");
private String value;
UpdateOperation(String v) {
value = v;
}
@Override
public String toString() {
return value;
}
}
public class LDUpdate {
protected long src;
protected short srcPort;
protected long dst;
protected short dstPort;
protected SwitchType srcType;
protected LinkType type;
protected UpdateOperation operation;
public LDUpdate(long src, short srcPort,
long dst, short dstPort,
ILinkDiscovery.LinkType type,
UpdateOperation operation) {
this.src = src;
this.srcPort = srcPort;
this.dst = dst;
this.dstPort = dstPort;
this.type = type;
this.operation = operation;
}
public LDUpdate(LDUpdate old) {
this.src = old.src;
this.srcPort = old.srcPort;
this.dst = old.dst;
this.dstPort = old.dstPort;
this.srcType = old.srcType;
this.type = old.type;
this.operation = old.operation;
}
// For updtedSwitch(sw)
public LDUpdate(long switchId, SwitchType stype, UpdateOperation oper ){
this.operation = oper;
this.src = switchId;
this.srcType = stype;
}
// For port up or port down.
public LDUpdate(long sw, short port, UpdateOperation operation) {
this.src = sw;
this.srcPort = port;
this.operation = operation;
}
public long getSrc() {
return src;
}
public short getSrcPort() {
return srcPort;
}
public long getDst() {
return dst;
}
public short getDstPort() {
return dstPort;
}
public SwitchType getSrcType() {
return srcType;
}
public LinkType getType() {
return type;
}
public UpdateOperation getOperation() {
return operation;
}
public void setOperation(UpdateOperation operation) {
this.operation = operation;
}
@Override
public String toString() {
switch (operation) {
case LINK_REMOVED:
case LINK_UPDATED:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src)
+ ", srcPort=" + srcPort
+ ", dst=" + HexString.toHexString(dst)
+ ", dstPort=" + dstPort
+ ", type=" + type + "]";
case PORT_DOWN:
case PORT_UP:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src)
+ ", srcPort=" + srcPort + "]";
case SWITCH_REMOVED:
case SWITCH_UPDATED:
return "LDUpdate [operation=" + operation +
", src=" + HexString.toHexString(src) + "]";
default:
return "LDUpdate: Unknown update.";
}
}
}
public enum SwitchType {
BASIC_SWITCH, CORE_SWITCH
};
public enum LinkType {
INVALID_LINK {
@Override
public String toString() {
return "invalid";
}
},
DIRECT_LINK{
@Override
public String toString() {
return "internal";
}
},
MULTIHOP_LINK {
@Override
public String toString() {
return "external";
}
},
TUNNEL {
@Override
public String toString() {
return "tunnel";
}
}
};
}
| Add missing case for ONOS extension
| src/main/java/net/floodlightcontroller/linkdiscovery/ILinkDiscovery.java | Add missing case for ONOS extension | <ide><path>rc/main/java/net/floodlightcontroller/linkdiscovery/ILinkDiscovery.java
<ide> @Override
<ide> public String toString() {
<ide> switch (operation) {
<add> case LINK_ADDED:
<ide> case LINK_REMOVED:
<ide> case LINK_UPDATED:
<ide> return "LDUpdate [operation=" + operation + |
|
Java | lgpl-2.1 | 52f84d858dfede5033b42993622b9a3a3966f15b | 0 | svartika/ccnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,ebollens/ccnmp | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.io.content;
import java.io.IOException;
import java.util.EnumSet;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLDecoder;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLEncoder;
import org.ccnx.ccn.io.ErrorStateException;
import org.ccnx.ccn.io.CCNAbstractInputStream.FlagTypes;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* Represents a secure, authenticatable link from one part of the CCN namespace to another.
*
* CCN links are very flexible and can be used to represent a wide variety of application-level
* structures. A link can point to a specific content object (an individual block of content),
* the collection of "segments" making up a specific version of a stream or document, an aggregated
* "document" object consisting of multiple versions and their associated metadata, or to an arbitrary
* point in the name tree -- essentially saying "treat the children of this node as if they
* were my children".
*
* CCN links have authentication information associated with them, and can be made highly secure --
* by specifying who should have published (signed) the target of a given link, one can say effectively
* "what I mean by name N is whatever Tom means by name N'". The authentication information
* associated with a Link is called a LinkAuthenticator; its form and capabilities are still
* evolving, but it will at least have the ability to offer indirection -- "trust anyone whose
* key is signed by key K to have signed a valid target for this link".
*
* Links also play an important role in making up Collections, the CCN notion of a container full
* of objects or names.
*/
public class Link extends GenericXMLEncodable implements XMLEncodable, Cloneable {
/**
* A CCNNetworkObject wrapper around Link, used for easily saving and retrieving
* versioned Links to CCN. A typical pattern for using network objects to save
* objects that happen to be encodable or serializable is to incorporate such a static
* member wrapper class subclassing CCNEncodableObject, CCNSerializableObject, or
* CCNNetworkObject itself inside the main class definition.
*/
public static class LinkObject extends CCNEncodableObject<Link> {
public LinkObject(ContentName name, Link data, SaveType saveType, CCNHandle handle) throws IOException {
super(Link.class, true, name, data, saveType, handle);
}
public LinkObject(ContentName name, Link data, SaveType saveType,
PublisherPublicKeyDigest publisher,
KeyLocator keyLocator, CCNHandle handle) throws IOException {
super(Link.class, true, name, data, saveType,
publisher, keyLocator, handle);
}
public LinkObject(ContentName name, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, name, (PublisherPublicKeyDigest)null, handle);
}
public LinkObject(ContentName name, PublisherPublicKeyDigest publisher, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, name, publisher, handle);
}
public LinkObject(ContentObject firstBlock, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, firstBlock, handle);
}
public LinkObject(ContentName name, PublisherPublicKeyDigest publisher,
CCNFlowControl flowControl) throws ContentDecodingException,
IOException {
super(Link.class, true, name, publisher, flowControl);
}
public LinkObject(ContentObject firstBlock, CCNFlowControl flowControl)
throws ContentDecodingException, IOException {
super(Link.class, true, firstBlock, flowControl);
}
public LinkObject(ContentName name, Link data, PublisherPublicKeyDigest publisher,
KeyLocator keyLocator, CCNFlowControl flowControl)
throws IOException {
super(Link.class, true, name, data, publisher, keyLocator, flowControl);
}
public LinkObject(CCNEncodableObject<? extends Link> other) {
super(Link.class, other);
}
/**
* Subclasses that need to write an object of a particular type can override.
* @return Content type to use.
*/
@Override
public ContentType contentType() { return ContentType.LINK; }
public ContentName getTargetName() throws ContentGoneException, ContentNotReadyException, ErrorStateException {
Link lr = link();
if (null == lr)
return null;
return lr.targetName();
}
public LinkAuthenticator getTargetAuthenticator() throws ContentNotReadyException, ContentGoneException, ErrorStateException {
Link lr = link();
if (null == lr)
return null;
return lr.targetAuthenticator();
}
public Link link() throws ContentNotReadyException, ContentGoneException, ErrorStateException {
if (null == data())
return null;
return data();
}
public ContentObject dereference(long timeout) throws IOException {
if (null == data())
return null;
return link().dereference(timeout, _handle);
}
/**
* Modify the properties of the input streams we read to read links themselves,
* rather than dereferencing them and causing an infinite loop; must modify
* in constructor to handle passed in content objects..
*/
@Override
protected EnumSet<FlagTypes> getInputStreamFlags() {
return EnumSet.of(FlagTypes.DONT_DEREFERENCE);
}
}
protected static final String LINK_ELEMENT = "Link";
protected static final String LABEL_ELEMENT = "Label"; // overlaps with WrappedKey.LABEL_ELEMENT,
// shared dictionary entry
protected ContentName _targetName;
protected String _targetLabel;
protected LinkAuthenticator _targetAuthenticator = null;
public Link(ContentName targetName, String targetLabel, LinkAuthenticator targetAuthenticator) {
_targetName = targetName;
if ((null != targetLabel) && (targetLabel.length() == 0))
targetLabel = null;
_targetLabel = targetLabel;
_targetAuthenticator = targetAuthenticator;
}
public Link(ContentName targetName, LinkAuthenticator targetAuthenticator) {
_targetName = targetName;
_targetAuthenticator = targetAuthenticator;
}
public Link(ContentName targetName) {
this(targetName, null);
}
/**
* Decoding constructor.
*/
public Link() {}
public Link(Link other) {
_targetName = other.targetName();
_targetLabel = other.targetLabel();
_targetAuthenticator = other.targetAuthenticator();
}
public ContentName targetName() { return _targetName; }
public String targetLabel() { return _targetLabel; }
public LinkAuthenticator targetAuthenticator() { return _targetAuthenticator; }
/**
* A stab at a dereference() method. Dereferencing is not well-defined in this
* general setting -- we don't know what we'll find down below this name. A link may
* link to anything in the tree, including an intermediate node, or a name qualified
* down to the digest, and we need a way of distinguishing these things (TODO). Usually
* you'll read the target of the link using a method that knows something about what
* kind of data to find there. This is a brute-force method that hands you back a block
* underneath the link target name that meets the authentication criteria; at minimum
* it should pull an exact match if the link fully specifies digests and so on (TODO -- TBD),
* and otherwise it'll probably assume that what is below here is either a version and
* segments (get latest version) or that this is versioned and it wants segments.
*
* @param timeout How long to try for, in milliseconds.
* @param handle Handle to use. Should not be null.
* @return Returns a child object. Verifies that it meets the requirement of the link,
* and that it is signed by who it claims. Could allow caller to pass in verifier
* to verify higher-level trust and go look for another block on failure.
* @throws IOException
*/
public ContentObject dereference(long timeout, CCNHandle handle) throws IOException {
// getLatestVersion will return the latest version of an unversioned name, or the
// latest version after a given version. So if given a specific version, get that one.
if (VersioningProfile.hasTerminalVersion(targetName())) {
return handle.get(targetName(), (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null, timeout);
}
// Don't know if we are referencing a particular object, so don't look for segments.
PublisherPublicKeyDigest desiredPublisher = (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null;
ContentObject result = VersioningProfile.getLatestVersion(targetName(),
desiredPublisher, timeout, new ContentObject.SimpleVerifier(desiredPublisher), handle);
if (null != result) {
return result;
}
// Alright, last shot -- resolve link to unversioned data.
return handle.get(targetName(), (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null, timeout);
}
@Override
public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
_targetName = new ContentName();
_targetName.decode(decoder);
if (decoder.peekStartElement(LABEL_ELEMENT)) {
_targetLabel = decoder.readUTF8Element(LABEL_ELEMENT);
}
if (decoder.peekStartElement(LinkAuthenticator.LINK_AUTHENTICATOR_ELEMENT)) {
_targetAuthenticator = new LinkAuthenticator();
_targetAuthenticator.decode(decoder);
}
decoder.readEndElement();
}
@Override
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate())
throw new ContentEncodingException("Link failed to validate!");
encoder.writeStartElement(getElementLabel());
_targetName.encode(encoder);
if (null != targetLabel()) {
encoder.writeElement(LABEL_ELEMENT, targetLabel());
}
if (null != _targetAuthenticator)
_targetAuthenticator.encode(encoder);
encoder.writeEndElement();
}
@Override
public String getElementLabel() { return LINK_ELEMENT; }
@Override
public boolean validate() {
return (null != targetName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((_targetAuthenticator == null) ? 0 : _targetAuthenticator
.hashCode());
result = prime * result
+ ((_targetLabel == null) ? 0 : _targetLabel.hashCode());
result = prime * result
+ ((_targetName == null) ? 0 : _targetName.hashCode());
return result;
}
/**
* Return true if this link matches target on all fields where
* target is non-null.
* @param linkToMatch The specification of the values we want.
* @return
*/
public boolean approximates(Link linkToMatch) {
if (null != _targetName) {
if (null == linkToMatch._targetName)
return false;
if (!linkToMatch._targetName.equals(_targetName))
return false;
}
if (null != _targetLabel) {
if (null == linkToMatch._targetLabel)
return false;
if (!linkToMatch._targetLabel.equals(_targetLabel))
return false;
}
if (null != _targetAuthenticator) {
if (null == linkToMatch._targetAuthenticator)
return false;
return _targetAuthenticator.approximates(linkToMatch._targetAuthenticator);
}
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Link other = (Link) obj;
if (_targetAuthenticator == null) {
if (other._targetAuthenticator != null)
return false;
} else if (!_targetAuthenticator.equals(other._targetAuthenticator))
return false;
if (_targetLabel == null) {
if (other._targetLabel != null)
return false;
} else if (!_targetLabel.equals(other._targetLabel))
return false;
if (_targetName == null) {
if (other._targetName != null)
return false;
} else if (!_targetName.equals(other._targetName))
return false;
return true;
}
@Override
public Object clone() throws CloneNotSupportedException {
return new Link(this);
}
@Override
public String toString() {
return "Link [targetName=" + targetName() +
", targetLabel=" + targetLabel() +
", targetAuthenticator=" + targetAuthenticator() + "]";
}
}
| javasrc/src/org/ccnx/ccn/io/content/Link.java | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.io.content;
import java.io.IOException;
import java.util.EnumSet;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLDecoder;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLEncoder;
import org.ccnx.ccn.io.ErrorStateException;
import org.ccnx.ccn.io.CCNAbstractInputStream.FlagTypes;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* Represents a secure, authenticatable link from one part of the CCN namespace to another.
*
* CCN links are very flexible and can be used to represent a wide variety of application-level
* structures. A link can point to a specific content object (an individual block of content),
* the collection of "segments" making up a specific version of a stream or document, an aggregated
* "document" object consisting of multiple versions and their associated metadata, or to an arbitrary
* point in the name tree -- essentially saying "treat the children of this node as if they
* were my children".
*
* CCN links have authentication information associated with them, and can be made highly secure --
* by specifying who should have published (signed) the target of a given link, one can say effectively
* "what I mean by name N is whatever Tom means by name N'". The authentication information
* associated with a Link is called a LinkAuthenticator; its form and capabilities are still
* evolving, but it will at least have the ability to offer indirection -- "trust anyone whose
* key is signed by key K to have signed a valid target for this link".
*
* Links also play an important role in making up Collections, the CCN notion of a container full
* of objects or names.
*/
public class Link extends GenericXMLEncodable implements XMLEncodable, Cloneable {
/**
* A CCNNetworkObject wrapper around Link, used for easily saving and retrieving
* versioned Links to CCN. A typical pattern for using network objects to save
* objects that happen to be encodable or serializable is to incorporate such a static
* member wrapper class subclassing CCNEncodableObject, CCNSerializableObject, or
* CCNNetworkObject itself inside the main class definition.
*/
public static class LinkObject extends CCNEncodableObject<Link> {
public LinkObject(ContentName name, Link data, SaveType saveType, CCNHandle handle) throws IOException {
super(Link.class, true, name, data, saveType, handle);
}
public LinkObject(ContentName name, Link data, SaveType saveType,
PublisherPublicKeyDigest publisher,
KeyLocator keyLocator, CCNHandle handle) throws IOException {
super(Link.class, true, name, data, saveType,
publisher, keyLocator, handle);
}
public LinkObject(ContentName name, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, name, (PublisherPublicKeyDigest)null, handle);
}
public LinkObject(ContentName name, PublisherPublicKeyDigest publisher, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, name, publisher, handle);
}
public LinkObject(ContentObject firstBlock, CCNHandle handle)
throws ContentDecodingException, IOException {
super(Link.class, true, firstBlock, handle);
}
public LinkObject(ContentName name, PublisherPublicKeyDigest publisher,
CCNFlowControl flowControl) throws ContentDecodingException,
IOException {
super(Link.class, true, name, publisher, flowControl);
}
public LinkObject(ContentObject firstBlock, CCNFlowControl flowControl)
throws ContentDecodingException, IOException {
super(Link.class, true, firstBlock, flowControl);
}
public LinkObject(ContentName name, Link data, PublisherPublicKeyDigest publisher,
KeyLocator keyLocator, CCNFlowControl flowControl)
throws IOException {
super(Link.class, true, name, data, publisher, keyLocator, flowControl);
}
public LinkObject(CCNEncodableObject<? extends Link> other) {
super(Link.class, other);
}
/**
* Subclasses that need to write an object of a particular type can override.
* @return Content type to use.
*/
@Override
public ContentType contentType() { return ContentType.LINK; }
public ContentName getTargetName() throws ContentGoneException, ContentNotReadyException, ErrorStateException {
Link lr = link();
if (null == lr)
return null;
return lr.targetName();
}
public LinkAuthenticator getTargetAuthenticator() throws ContentNotReadyException, ContentGoneException, ErrorStateException {
Link lr = link();
if (null == lr)
return null;
return lr.targetAuthenticator();
}
public Link link() throws ContentNotReadyException, ContentGoneException, ErrorStateException {
if (null == data())
return null;
return data();
}
public ContentObject dereference(long timeout) throws IOException {
if (null == data())
return null;
return link().dereference(timeout, _handle);
}
/**
* Modify the properties of the input streams we read to read links themselves,
* rather than dereferencing them and causing an infinite loop; must modify
* in constructor to handle passed in content objects..
*/
@Override
protected EnumSet<FlagTypes> getInputStreamFlags() {
return EnumSet.of(FlagTypes.DONT_DEREFERENCE);
}
}
protected static final String LINK_ELEMENT = "Link";
protected static final String LABEL_ELEMENT = "Label"; // overlaps with WrappedKey.LABEL_ELEMENT,
// shared dictionary entry
protected ContentName _targetName;
protected String _targetLabel;
protected LinkAuthenticator _targetAuthenticator = null;
public Link(ContentName targetName, String targetLabel, LinkAuthenticator targetAuthenticator) {
_targetName = targetName;
if ((null != targetLabel) && (targetLabel.length() == 0))
targetLabel = null;
_targetLabel = targetLabel;
_targetAuthenticator = targetAuthenticator;
}
public Link(ContentName targetName, LinkAuthenticator targetAuthenticator) {
_targetName = targetName;
_targetAuthenticator = targetAuthenticator;
}
public Link(ContentName targetName) {
this(targetName, null);
}
/**
* Decoding constructor.
*/
public Link() {}
public Link(Link other) {
_targetName = other.targetName();
_targetLabel = other.targetLabel();
_targetAuthenticator = other.targetAuthenticator();
}
public ContentName targetName() { return _targetName; }
public String targetLabel() { return _targetLabel; }
public LinkAuthenticator targetAuthenticator() { return _targetAuthenticator; }
/**
* A stab at a dereference() method. Dereferencing is not well-defined in this
* general setting -- we don't know what we'll find down below this name. A link may
* link to anything in the tree, including an intermediate node, or a name qualified
* down to the digest, and we need a way of distinguishing these things (TODO). Usually
* you'll read the target of the link using a method that knows something about what
* kind of data to find there. This is a brute-force method that hands you back a block
* underneath the link target name that meets the authentication criteria; at minimum
* it should pull an exact match if the link fully specifies digests and so on (TODO -- TBD),
* and otherwise it'll probably assume that what is below here is either a version and
* segments (get latest version) or that this is versioned and it wants segments.
*
* @param timeout How long to try for, in milliseconds.
* @param handle Handle to use. Should not be null.
* @return Returns a child object. Verifies that it meets the requirement of the link,
* and that it is signed by who it claims. Could allow caller to pass in verifier
* to verify higher-level trust and go look for another block on failure.
* @throws IOException
*/
public ContentObject dereference(long timeout, CCNHandle handle) throws IOException {
// getLatestVersion will return the latest version of an unversioned name, or the
// latest version after a given version. So if given a specific version, get that one.
if (VersioningProfile.hasTerminalVersion(targetName())) {
return handle.get(targetName(), (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null, timeout);
}
// Don't know if we are referencing a particular object, so don't look for segments.
PublisherPublicKeyDigest desiredPublisher = (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null;
ContentObject result = VersioningProfile.getLatestVersion(targetName(),
desiredPublisher, timeout, new ContentObject.SimpleVerifier(desiredPublisher), handle);
if (null != result) {
return result;
}
// Alright, last shot -- resolve link to unversioned data.
return handle.get(targetName(), (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null, timeout);
}
@Override
public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
_targetName = new ContentName();
_targetName.decode(decoder);
if (decoder.peekStartElement(LABEL_ELEMENT)) {
_targetLabel = decoder.readUTF8Element(LABEL_ELEMENT);
}
if (decoder.peekStartElement(LinkAuthenticator.LINK_AUTHENTICATOR_ELEMENT)) {
_targetAuthenticator = new LinkAuthenticator();
_targetAuthenticator.decode(decoder);
}
decoder.readEndElement();
}
@Override
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate())
throw new ContentEncodingException("Link failed to validate!");
encoder.writeStartElement(getElementLabel());
_targetName.encode(encoder);
if (null != targetLabel()) {
encoder.writeElement(LABEL_ELEMENT, targetLabel());
}
if (null != _targetAuthenticator)
_targetAuthenticator.encode(encoder);
encoder.writeEndElement();
}
@Override
public String getElementLabel() { return LINK_ELEMENT; }
@Override
public boolean validate() {
return (null != targetName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((_targetAuthenticator == null) ? 0 : _targetAuthenticator
.hashCode());
result = prime * result
+ ((_targetLabel == null) ? 0 : _targetLabel.hashCode());
result = prime * result
+ ((_targetName == null) ? 0 : _targetName.hashCode());
return result;
}
/**
* Return true if this link matches target on all fields where
* target is non-null.
* @param target The specification of the values we want.
* @return
*/
public boolean approximates(Link target) {
if (null != target._targetName) {
if (null == _targetName)
return false;
if (!target._targetName.equals(_targetName))
return false;
}
if (null != target._targetLabel) {
if (null == _targetLabel)
return false;
if (!target._targetLabel.equals(_targetLabel))
return false;
}
if (null != target._targetAuthenticator) {
if (null == _targetAuthenticator)
return false;
return _targetAuthenticator.approximates(target._targetAuthenticator);
}
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Link other = (Link) obj;
if (_targetAuthenticator == null) {
if (other._targetAuthenticator != null)
return false;
} else if (!_targetAuthenticator.equals(other._targetAuthenticator))
return false;
if (_targetLabel == null) {
if (other._targetLabel != null)
return false;
} else if (!_targetLabel.equals(other._targetLabel))
return false;
if (_targetName == null) {
if (other._targetName != null)
return false;
} else if (!_targetName.equals(other._targetName))
return false;
return true;
}
@Override
public Object clone() throws CloneNotSupportedException {
return new Link(this);
}
@Override
public String toString() {
return "Link [targetName=" + targetName() +
", targetLabel=" + targetLabel() +
", targetAuthenticator=" + targetAuthenticator() + "]";
}
}
| Fixed approximate searchng.
| javasrc/src/org/ccnx/ccn/io/content/Link.java | Fixed approximate searchng. | <ide><path>avasrc/src/org/ccnx/ccn/io/content/Link.java
<ide> /**
<ide> * Return true if this link matches target on all fields where
<ide> * target is non-null.
<del> * @param target The specification of the values we want.
<add> * @param linkToMatch The specification of the values we want.
<ide> * @return
<ide> */
<del> public boolean approximates(Link target) {
<del> if (null != target._targetName) {
<del> if (null == _targetName)
<del> return false;
<del> if (!target._targetName.equals(_targetName))
<del> return false;
<del> }
<del> if (null != target._targetLabel) {
<del> if (null == _targetLabel)
<del> return false;
<del> if (!target._targetLabel.equals(_targetLabel))
<del> return false;
<del> }
<del> if (null != target._targetAuthenticator) {
<del> if (null == _targetAuthenticator)
<del> return false;
<del> return _targetAuthenticator.approximates(target._targetAuthenticator);
<add> public boolean approximates(Link linkToMatch) {
<add> if (null != _targetName) {
<add> if (null == linkToMatch._targetName)
<add> return false;
<add> if (!linkToMatch._targetName.equals(_targetName))
<add> return false;
<add> }
<add> if (null != _targetLabel) {
<add> if (null == linkToMatch._targetLabel)
<add> return false;
<add> if (!linkToMatch._targetLabel.equals(_targetLabel))
<add> return false;
<add> }
<add> if (null != _targetAuthenticator) {
<add> if (null == linkToMatch._targetAuthenticator)
<add> return false;
<add> return _targetAuthenticator.approximates(linkToMatch._targetAuthenticator);
<ide> }
<ide> return true;
<ide> } |
|
JavaScript | mit | f950dd1fa9fd138b3dda0a6df578f0eaa0ca059e | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict'
// ----------------------------------------------------------------------------
const log = require ('ololog')
, ansi = require ('ansicolor').nice
, chai = require ('chai')
, expect = chai.expect
, assert = chai.assert
/* ------------------------------------------------------------------------ */
module.exports = async (exchange) => {
if (exchange.has.fetchStatus) {
// log ('fetching status...')
const method = 'fetchStatus'
const status = await exchange[method] ()
const sampleStatus = {
'status': 'ok', // 'ok', 'shutdown', 'error', 'maintenance'
'updated': undefined, // integer, last updated timestamp in milliseconds if updated via the API
'eta': undefined, // when the maintenance or outage is expected to end
'url': undefined, // a link to a GitHub issue or to an exchange post on the subject
}
assert.containsAllKeys (status, sampleStatus)
return status
} else {
log ('fetching status not supported')
}
}
| js/test/Exchange/test.fetchStatus.js | 'use strict'
// ----------------------------------------------------------------------------
const log = require ('ololog')
, ansi = require ('ansicolor').nice
, chai = require ('chai')
, expect = chai.expect
, assert = chai.assert
/* ------------------------------------------------------------------------ */
module.exports = async (exchange) => {
if (exchange.has.fetchStatus) {
// log ('fetching status...')
const method = 'fetchStatus'
const status = await exchange[method] ()
expect (status).to.have.key('status')
expect (status).to.have.key('updated')
expect (status).to.have.key('eta')
expect (status).to.have.key('url')
return status
} else {
log ('fetching status not supported')
}
}
| proper checks in test.fetchStatus.js | js/test/Exchange/test.fetchStatus.js | proper checks in test.fetchStatus.js | <ide><path>s/test/Exchange/test.fetchStatus.js
<ide> const method = 'fetchStatus'
<ide> const status = await exchange[method] ()
<ide>
<del> expect (status).to.have.key('status')
<del> expect (status).to.have.key('updated')
<del> expect (status).to.have.key('eta')
<del> expect (status).to.have.key('url')
<add> const sampleStatus = {
<add> 'status': 'ok', // 'ok', 'shutdown', 'error', 'maintenance'
<add> 'updated': undefined, // integer, last updated timestamp in milliseconds if updated via the API
<add> 'eta': undefined, // when the maintenance or outage is expected to end
<add> 'url': undefined, // a link to a GitHub issue or to an exchange post on the subject
<add> }
<add>
<add> assert.containsAllKeys (status, sampleStatus)
<add>
<ide> return status
<ide>
<ide> } else {
<ide> log ('fetching status not supported')
<ide> }
<ide> }
<del> |
|
Java | apache-2.0 | 0f42bbe7257aa26f4d728093ad545c9cd1e44ccd | 0 | hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform | //
// Copyright 2019 SenX S.A.S.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package io.warp10.script;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract class to inherit when a function can be called on a single element or a list of elements.
* For instance for a function working on GTSs, GTSEncoders and lists thereof, including lists with mixed types.
* The idea is to generate a function using the parameters on the stack and then to apply this function on the element
* or the list of elements.
* This is similar to GTSStackFunction for GTSs but it is a tad faster if the function uses some parameters as this
* implementation does not use a Map for parameters.
*/
public abstract class ElementOrListStackFunction extends NamedWarpScriptFunction implements WarpScriptStackFunction {
/**
* Interface defining the function to be generated which is applied to each element.
* This method should check the type of the given element and throw a WarpScriptException if the element is of
* unexpected type.
*/
@FunctionalInterface
public interface ElementStackFunction {
public Object applyOnElement(Object element) throws WarpScriptException;
}
/**
* Generates the function to be applied on the element(s) using the parameters on the stack.
* @param stack The stack to be used for parameters retrieval.
* @return An ElementStackFunction which will be applied on each given elements or on the given element.
* @throws WarpScriptException
*/
public abstract ElementStackFunction generateFunction(WarpScriptStack stack) throws WarpScriptException;
public ElementOrListStackFunction(String name) {
super(name);
}
public Object apply(WarpScriptStack stack) throws WarpScriptException {
ElementStackFunction function = generateFunction(stack);
Object o = stack.pop();
// Case of a list
if (o instanceof List) {
List list = (List) o;
// Build the result list which will be as long a the given list
ArrayList<Object> result = new ArrayList<Object>(list.size());
for (Object element: list) {
result.add(function.applyOnElement(element));
}
stack.push(result);
} else { // Case of a single element
stack.push(function.applyOnElement(o));
}
return stack;
}
}
| warp10/src/main/java/io/warp10/script/ElementOrListStackFunction.java | //
// Copyright 2019 SenX S.A.S.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package io.warp10.script;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract class to inherit when a function can be called on a single element or a list of elements.
* For instance for a function working on GTSs, GTSEncoders and lists thereof, including lists with mixed types.
* The idea is to generate a function using the parameters on the stack and then to apply this function on the element
* or the list of elements.
* This is similar to GTSStackFunction for GTSs but it is a tad faster if the function uses some parameters as this
* implementation does not use a Map for parameters.
*/
public abstract class ElementOrListStackFunction extends NamedWarpScriptFunction implements WarpScriptStackFunction {
/**
* Interface defining the function to be generated which is applied to each element.
* This method should check the type of the given element and throw a WarpScriptException if the element is of
* unexpected type.
*/
@FunctionalInterface
public interface ElementStackFunction {
Object applyOnElement(Object element) throws WarpScriptException;
}
/**
* Generates the function to be applied on the element(s) using the parameters on the stack.
* @param stack The stack to be used for parameters retrieval.
* @return An ElementStackFunction which will be applied on each given elements or on the given element.
* @throws WarpScriptException
*/
public abstract ElementStackFunction generateFunction(WarpScriptStack stack) throws WarpScriptException;
public ElementOrListStackFunction(String name) {
super(name);
}
public Object apply(WarpScriptStack stack) throws WarpScriptException {
ElementStackFunction function = generateFunction(stack);
Object o = stack.pop();
// Case of a list
if (o instanceof List) {
List list = (List) o;
// Build the result list which will be as long a the given list
ArrayList<Object> result = new ArrayList<Object>(list.size());
for (Object element: list) {
result.add(function.applyOnElement(element));
}
stack.push(result);
} else { // Case of a single element
stack.push(function.applyOnElement(o));
}
return stack;
}
}
| Add public modifier to interface method for clarity
| warp10/src/main/java/io/warp10/script/ElementOrListStackFunction.java | Add public modifier to interface method for clarity | <ide><path>arp10/src/main/java/io/warp10/script/ElementOrListStackFunction.java
<ide> */
<ide> @FunctionalInterface
<ide> public interface ElementStackFunction {
<del> Object applyOnElement(Object element) throws WarpScriptException;
<add> public Object applyOnElement(Object element) throws WarpScriptException;
<ide> }
<ide>
<ide> /** |
|
Java | mit | de8563593a64d48e5a82e4d97496d337375faaa8 | 0 | madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.action;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.gluu.oxtrust.ldap.service.ApplianceService;
import org.gluu.oxtrust.ldap.service.AuthenticationService;
import org.gluu.oxtrust.ldap.service.IPersonService;
import org.gluu.oxtrust.ldap.service.SecurityService;
import org.gluu.oxtrust.model.GluuAppliance;
import org.gluu.oxtrust.model.GluuCustomPerson;
import org.gluu.oxtrust.model.User;
import org.gluu.oxtrust.security.OauthData;
import org.gluu.oxtrust.service.AuthenticationSessionService;
import org.gluu.oxtrust.service.OpenIdService;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.site.ldap.persistence.exception.AuthenticationException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.log.Log;
import org.jboss.seam.navigation.Pages;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.SimplePrincipal;
import org.xdi.config.oxtrust.ApplicationConfiguration;
import org.xdi.ldap.model.GluuStatus;
import org.xdi.model.GluuUserRole;
import org.xdi.oxauth.client.OpenIdConfigurationResponse;
import org.xdi.oxauth.client.TokenClient;
import org.xdi.oxauth.client.TokenResponse;
import org.xdi.oxauth.client.UserInfoClient;
import org.xdi.oxauth.client.UserInfoResponse;
import org.xdi.oxauth.client.ValidateTokenClient;
import org.xdi.oxauth.client.ValidateTokenResponse;
import org.xdi.oxauth.model.jwt.JwtClaimName;
import org.xdi.util.ArrayHelper;
import org.xdi.util.StringHelper;
import org.xdi.util.security.StringEncrypter;
import org.xdi.util.security.StringEncrypter.EncryptionException;
/**
* Provides authentication using oAuth
*
* @author Reda Zerrad Date: 05.11.2012
* @author Yuriy Movchan Date: 02.12.2013
*/
@Name("authenticator")
@Scope(ScopeType.SESSION)
public class Authenticator implements Serializable {
private static final long serialVersionUID = -3975272457541385597L;
@Logger
private Log log;
@In
private Identity identity;
@In
private AuthenticationService authenticationService;
@In
private Credentials credentials;
@In
Redirect redirect;
@In
private IPersonService personService;
@In
private SecurityService securityService;
@In(create = true)
private SsoLoginAction ssoLoginAction;
@In
private ApplianceService applianceService;
@In
private OpenIdService openIdService;
@In
private FacesMessages facesMessages;
String viewIdBeforeLoginRedirect;
@In(create = true)
@Out(scope = ScopeType.SESSION, required = false)
private OauthData oauthData;
@In(value = "#{oxTrustConfiguration.applicationConfiguration}")
private ApplicationConfiguration applicationConfiguration;
@In(value = "#{oxTrustConfiguration.cryptoConfigurationSalt}")
private String cryptoConfigurationSalt;
public boolean preAuthenticate() throws IOException, Exception {
boolean result = true;
if (!identity.isLoggedIn()) {
result = oAuthLogin();
}
return result;
}
public boolean authenticate() {
String userName = null;
try {
userName = oauthData.getUserUid();
identity.getCredentials().setUsername(userName);
log.info("Authenticating user '{0}'", userName);
User user = findUserByUserName(userName);
if (user == null) {
log.error("Person '{0}' not found in LDAP", userName);
return false;
}else if(GluuStatus.EXPIRED.getValue().equals(user.getAttribute("gluuStatus")) || GluuStatus.REGISTER.getValue().equals(user.getAttribute("gluuStatus"))){
redirect.setViewId("/register.xhtml");
redirect.setParameter("inum", user.getInum());
redirect.execute();
return false;
}
postLogin(user);
log.info("User '{0}' authenticated successfully", userName);
} catch (Exception ex) {
log.error("Failed to authenticate user '{0}'", ex, userName);
return false;
}
return true;
}
public boolean authenticateBasicWebService() {
String userName = identity.getCredentials().getUsername();
log.info("Authenticating user '{0}'", userName);
boolean authenticated = false;
try {
authenticated = this.authenticationService.authenticate(userName, this.credentials.getPassword());
} catch (AuthenticationException ex) {
this.log.error("Failed to authenticate user: '{0}'", ex, userName);
}
if (!authenticated) {
return false;
}
return postAuthenticateWebService(userName);
}
public boolean authenticateBearerWebService() {
String userName = identity.getCredentials().getUsername();
log.info("Authenticating user '{0}'", userName);
return postAuthenticateWebService(userName);
}
public boolean postAuthenticateWebService(String userName) {
try {
User user = findUserByUserName(userName);
if (user == null) {
log.error("Person '{0}' not found in LDAP", userName);
return false;
}
Principal principal = new SimplePrincipal(userName);
identity.acceptExternallyAuthenticatedPrincipal(principal);
identity.quietLogin();
postLogin(user);
log.info("User '{0}' authenticated successfully", userName);
return true;
} catch (Exception ex) {
log.error("Failed to authenticate user '{0}'", ex, userName);
}
return false;
}
/**
* Set session variables after user login
*
* @throws Exception
*/
private void postLogin(User user) {
log.debug("Configuring application after user '{0}' login", user.getUid());
GluuCustomPerson person = findPersonByDn(user.getDn());
Contexts.getSessionContext().set(OxTrustConstants.CURRENT_PERSON, person);
// Set user roles
GluuUserRole[] userRoles = securityService.getUserRoles(user);
if (ArrayHelper.isNotEmpty(userRoles)) {
log.debug("Get '{0}' user roles", Arrays.toString(userRoles));
} else {
log.debug("Get 0 user roles");
}
for (GluuUserRole userRole : userRoles) {
identity.addRole(userRole.getRoleName());
}
if (log.isDebugEnabled()) {
for (Group sg : identity.getSubject().getPrincipals(java.security.acl.Group.class)) {
if ("Roles".equals(sg.getName())) {
log.debug("Using next user roles: '{0}'", sg.members());
break;
}
}
}
}
private User findUserByUserName(String userName) {
User user = null;
try {
user = personService.getUserByUid(userName);
} catch (Exception ex) {
log.error("Failed to find user '{0}' in ldap", ex, userName);
}
return user;
}
private GluuCustomPerson findPersonByDn(String userDn) {
GluuCustomPerson person = null;
try {
person = personService.getPersonByDn(userDn);
} catch (Exception ex) {
log.error("Failed to find person '{0}' in ldap", ex, userDn);
}
return person;
}
public void processLogout() throws Exception {
ssoLoginAction.logout();
oAuthlLogout();
postLogout();
}
public String postLogout() {
if (identity.isLoggedIn()) {
identity.logout();
}
return OxTrustConstants.RESULT_SUCCESS;
}
public void oAuthlLogout() throws Exception {
if (StringHelper.isEmpty(oauthData.getUserUid())) {
return;
}
ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getEndSessionEndpoint());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_SESSION_STATE, oauthData.getSessionState());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_ID_TOKEN_HINT, oauthData.getIdToken());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_POST_LOGOUT_REDIRECT_URI, applicationConfiguration.getLogoutRedirectUrl());
// Clean up OAuth token
oauthData.setUserUid(null);
oauthData.setIdToken(null);
oauthData.setSessionState(null);
oauthData = null;
FacesContext.getCurrentInstance().getExternalContext().redirect(clientRequest.getUri());
}
/**
* Authenticate using credentials passed from web request header
*/
public boolean Shibboleth3Authenticate() {
log.debug("Checking if user authenticated with shibboleth already");
boolean result = false;
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String authType = request.getAuthType();
String userUid = request.getHeader("REMOTE_USER");
String userUidlower = request.getHeader("remote_user");
Enumeration<?> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
log.trace(headerName + "-->" + request.getHeader(headerName));
}
log.debug("Username is " + userUid);
log.debug("UsernameLower is " + userUidlower);
log.debug("AuthType is " + authType);
Map<String, String[]> headers = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderValuesMap();
for (String name : headers.keySet()) {
log.trace(name + "==>" + StringUtils.join(headers.get(name)));
}
if (StringHelper.isEmpty(userUid) || StringHelper.isEmpty(authType) || !authType.equals("shibboleth")) {
result = false;
return result;
}
Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
Matcher matcher = pattern.matcher(userUid);
User user = null;
if (matcher.matches()) {
// Find user by uid
user = personService.getPersonByEmail(userUid);
} else {
// Find user by uid
user = personService.getUserByUid(userUid);
}
if (user == null) {
result = false;
return result;
}
log.debug("Person Inum is " + user.getInum());
if (GluuStatus.ACTIVE.getValue().equals(user.getAttribute("gluuStatus"))){
credentials.setUsername(user.getUid());
// credentials.setPassword("");
Principal principal = new SimplePrincipal(user.getUid());
log.debug("Principal is " + principal.toString());
identity.acceptExternallyAuthenticatedPrincipal(principal);
log.info("User '{0}' authenticated with shibboleth already", userUid);
identity.quietLogin();
postLogin(user);
Contexts.getSessionContext().set(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE,
OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH3);
result = true;
if (Events.exists()) {
facesMessages.clear();
Events.instance().raiseEvent(Identity.EVENT_LOGIN_SUCCESSFUL);
}
}else{
result = false;
}
return result;
}
/**
* Main entry point for oAuth authentication.
* @throws IOException
*
* @throws Exception
*/
public boolean oAuthLogin() throws IOException, Exception {
ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getAuthorizationEndpoint());
String clientId = applicationConfiguration.getOxAuthClientId();
String scope = applicationConfiguration.getOxAuthClientScope();
String responseType = "code+id_token";
String nonce = "nonce";
clientRequest.queryParameter(OxTrustConstants.OXAUTH_CLIENT_ID, clientId);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_REDIRECT_URI, applicationConfiguration.getLoginRedirectUrl());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_RESPONSE_TYPE, responseType);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_SCOPE, scope);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_NONCE, nonce);
GluuAppliance appliance = applianceService.getAppliance(new String[] {"oxTrustAuthenticationMode"});
String acrValues = appliance.getOxTrustAuthenticationMode();
if (StringHelper.isNotEmpty(acrValues)) {
clientRequest.queryParameter(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues);
// Store request authentication method
Contexts.getSessionContext().set(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues);
}
if (viewIdBeforeLoginRedirect != null) {
clientRequest.queryParameter(OxTrustConstants.OXAUTH_STATE, viewIdBeforeLoginRedirect);
}
FacesContext.getCurrentInstance().getExternalContext().redirect(clientRequest.getUri().replaceAll("%2B", "+"));
return true;
}
/**
* After successful login, oxAuth will redirect user to this method. Obtains
* access token using authorization code and verifies if access token is
* valid
*
* @return
* @throws JSONException
*/
public String oAuthGetAccessToken() throws JSONException {
String oxAuthAuthorizeUrl = openIdService.getOpenIdConfiguration().getAuthorizationEndpoint();
String oxAuthHost = getOxAuthHost(oxAuthAuthorizeUrl);
if (StringHelper.isEmpty(oxAuthHost)) {
log.info("Failed to determine oxAuth host using oxAuthAuthorizeUrl: '{0}'", oxAuthAuthorizeUrl);
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
Map<String, Object> requestCookieMap = FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap();
String authorizationCode = requestParameterMap.get(OxTrustConstants.OXAUTH_CODE);
Object sessionStateCookie = requestCookieMap.get(OxTrustConstants.OXAUTH_SESSION_STATE);
String sessionState = null;
if (sessionStateCookie != null) {
sessionState = ((Cookie) sessionStateCookie).getValue();
}
String idToken = requestParameterMap.get(OxTrustConstants.OXAUTH_ID_TOKEN);
if (authorizationCode == null) {
String error = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR);
String errorDescription = requestParameterMap
.get(OxTrustConstants.OXAUTH_ERROR_DESCRIPTION);
log.info("No authorization code sent. Error: " + error + ". Error description: " + errorDescription);
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
if (viewIdBeforeLoginRedirect != null && !viewIdBeforeLoginRedirect.equals("")) {
Redirect.instance().setViewId(viewIdBeforeLoginRedirect);
viewIdBeforeLoginRedirect = "";
}
// todo hardcoded for now. Once clients are dynamically registered with
// oxAuth, change this
// String credentials = applicationConfiguration.getOxAuthClientId() +
// ":secret";
// String credentials = applicationConfiguration.getOxAuthClientId() + ":5967d41c-ce9c-4137-9068-42578df0c606";
// String clientCredentials =
// applicationConfiguration.getOxAuthClientCredentials();
log.info("authorizationCode : " + authorizationCode);
String scopes = requestParameterMap.get(OxTrustConstants.OXAUTH_SCOPE);
log.info(" scopes : " + scopes);
String clientID = applicationConfiguration.getOxAuthClientId();
log.info("clientID : " + clientID);
String clientPassword = applicationConfiguration.getOxAuthClientPassword();
if (clientPassword != null) {
try {
clientPassword = StringEncrypter.defaultInstance().decrypt(clientPassword, cryptoConfigurationSalt);
} catch (EncryptionException ex) {
log.error("Failed to decrypt client password", ex);
}
}
String result = requestAccessToken(oxAuthHost, authorizationCode, sessionState, idToken, scopes, clientID, clientPassword);
return result;
}
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String idToken, String scopes,
String clientID, String clientPassword) {
OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
// 1. Request access token using the authorization code.
TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());
log.info("Sending request to token endpoint");
String redirectURL = applicationConfiguration.getLoginRedirectUrl();
log.info("redirectURI : " + redirectURL);
TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID, clientPassword);
log.debug(" tokenResponse : " + tokenResponse);
if (tokenResponse == null) {
log.error("Get empty token response. User rcan't log into application");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());
String accessToken = tokenResponse.getAccessToken();
log.debug(" accessToken : " + accessToken);
// 2. Validate the access token
ValidateTokenClient validateTokenClient = new ValidateTokenClient(openIdConfiguration.getValidateTokenEndpoint());
ValidateTokenResponse response3 = validateTokenClient.execValidateToken(accessToken);
log.debug(" response3.getStatus() : " + response3.getStatus());
log.debug("validate check session status:" + response3.getStatus());
if (response3.getErrorDescription() != null) {
log.debug("validate token status message:" + response3.getErrorDescription());
}
if (response3.getStatus() == 200) {
log.info("Session validation successful. User is logged in");
UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
this.oauthData.setHost(oxAuthHost);
// Determine uid
List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
if ((uidValues == null) || (uidValues.size() == 0)) {
log.error("User info response doesn't contains uid claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
// Store request authentication method
if (Contexts.getSessionContext().isSet(OxTrustConstants.OXAUTH_ACR_VALUES)) {
String requestAcrValues = (String) Contexts.getSessionContext().get(OxTrustConstants.OXAUTH_ACR_VALUES);
List<String> acrValues = userInfoResponse.getClaims().get(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) {
log.error("User info response doesn't contains acr claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
if (!acrValues.contains(requestAcrValues)) {
log.error("User info response contains acr='{0}' claim but expected acr='{1}'", acrValues, requestAcrValues);
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
}
this.oauthData.setUserUid(uidValues.get(0));
this.oauthData.setAccessToken(accessToken);
this.oauthData.setAccessTokenExpirationInSeconds(response3.getExpiresIn());
this.oauthData.setScopes(scopes);
this.oauthData.setIdToken(idToken);
this.oauthData.setSessionState(sessionState);
log.info("user uid:" + oauthData.getUserUid());
// Create session scope authentication service
Component.getInstance(AuthenticationSessionService.class);
return OxTrustConstants.RESULT_SUCCESS;
}
log.info("Token validation failed. User is NOT logged in");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
private String getOxAuthHost(String oxAuthAuthorizeUrl) {
try {
URL url = new URL(oxAuthAuthorizeUrl);
return String.format("%s://%s:%s", url.getProtocol(), url.getHost(), url.getPort());
} catch (MalformedURLException ex) {
log.error("Invalid oxAuth authorization URI: '{0}'", ex, oxAuthAuthorizeUrl);
}
return null;
}
/**
* Used to remember the view user tried to access prior to login. This is
* the view user will be redirected after successful login.
*/
public void captureCurrentView() {
FacesContext context = FacesContext.getCurrentInstance();
// If this isn't a faces request then just return
if (context == null)
return;
viewIdBeforeLoginRedirect = Pages.getViewId(context);
}
public static Authenticator instance() {
return (Authenticator) Component.getInstance(Authenticator.class, true);
}
}
| server/src/main/java/org/gluu/oxtrust/action/Authenticator.java | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.action;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.gluu.oxtrust.ldap.service.ApplianceService;
import org.gluu.oxtrust.ldap.service.AuthenticationService;
import org.gluu.oxtrust.ldap.service.IPersonService;
import org.gluu.oxtrust.ldap.service.SecurityService;
import org.gluu.oxtrust.model.GluuAppliance;
import org.gluu.oxtrust.model.GluuCustomPerson;
import org.gluu.oxtrust.model.User;
import org.gluu.oxtrust.security.OauthData;
import org.gluu.oxtrust.service.AuthenticationSessionService;
import org.gluu.oxtrust.service.OpenIdService;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.site.ldap.persistence.exception.AuthenticationException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.log.Log;
import org.jboss.seam.navigation.Pages;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.SimplePrincipal;
import org.xdi.config.oxtrust.ApplicationConfiguration;
import org.xdi.ldap.model.GluuStatus;
import org.xdi.model.GluuUserRole;
import org.xdi.oxauth.client.OpenIdConfigurationResponse;
import org.xdi.oxauth.client.TokenClient;
import org.xdi.oxauth.client.TokenResponse;
import org.xdi.oxauth.client.UserInfoClient;
import org.xdi.oxauth.client.UserInfoResponse;
import org.xdi.oxauth.client.ValidateTokenClient;
import org.xdi.oxauth.client.ValidateTokenResponse;
import org.xdi.oxauth.model.jwt.JwtClaimName;
import org.xdi.util.ArrayHelper;
import org.xdi.util.StringHelper;
import org.xdi.util.security.StringEncrypter;
import org.xdi.util.security.StringEncrypter.EncryptionException;
/**
* Provides authentication using oAuth
*
* @author Reda Zerrad Date: 05.11.2012
* @author Yuriy Movchan Date: 02.12.2013
*/
@Name("authenticator")
@Scope(ScopeType.SESSION)
public class Authenticator implements Serializable {
private static final long serialVersionUID = -3975272457541385597L;
@Logger
private Log log;
@In
private Identity identity;
@In
private AuthenticationService authenticationService;
@In
private Credentials credentials;
@In
Redirect redirect;
@In
private IPersonService personService;
@In
private SecurityService securityService;
@In(create = true)
private SsoLoginAction ssoLoginAction;
@In
private ApplianceService applianceService;
@In
private OpenIdService openIdService;
@In
private FacesMessages facesMessages;
String viewIdBeforeLoginRedirect;
@In(create = true)
@Out(scope = ScopeType.SESSION, required = false)
private OauthData oauthData;
@In(value = "#{oxTrustConfiguration.applicationConfiguration}")
private ApplicationConfiguration applicationConfiguration;
@In(value = "#{oxTrustConfiguration.cryptoConfigurationSalt}")
private String cryptoConfigurationSalt;
public boolean preAuthenticate() throws IOException, Exception {
boolean result = true;
if (!identity.isLoggedIn()) {
result = oAuthLogin();
}
return result;
}
public boolean authenticate() {
String userName = null;
try {
userName = oauthData.getUserUid();
identity.getCredentials().setUsername(userName);
log.info("Authenticating user '{0}'", userName);
User user = findUserByUserName(userName);
if (user == null) {
log.error("Person '{0}' not found in LDAP", userName);
return false;
}else if(GluuStatus.EXPIRED.getValue().equals(user.getAttribute("gluuStatus")) || GluuStatus.REGISTER.getValue().equals(user.getAttribute("gluuStatus"))){
redirect.setViewId("/register.xhtml");
redirect.setParameter("inum", user.getInum());
redirect.execute();
return false;
}
postLogin(user);
log.info("User '{0}' authenticated successfully", userName);
} catch (Exception ex) {
log.error("Failed to authenticate user '{0}'", ex, userName);
return false;
}
return true;
}
public boolean authenticateBasicWebService() {
String userName = identity.getCredentials().getUsername();
log.info("Authenticating user '{0}'", userName);
boolean authenticated = false;
try {
authenticated = this.authenticationService.authenticate(userName, this.credentials.getPassword());
} catch (AuthenticationException ex) {
this.log.error("Failed to authenticate user: '{0}'", ex, userName);
}
if (!authenticated) {
return false;
}
return postAuthenticateWebService(userName);
}
public boolean authenticateBearerWebService() {
String userName = identity.getCredentials().getUsername();
log.info("Authenticating user '{0}'", userName);
return postAuthenticateWebService(userName);
}
public boolean postAuthenticateWebService(String userName) {
try {
User user = findUserByUserName(userName);
if (user == null) {
log.error("Person '{0}' not found in LDAP", userName);
return false;
}
Principal principal = new SimplePrincipal(userName);
identity.acceptExternallyAuthenticatedPrincipal(principal);
identity.quietLogin();
postLogin(user);
log.info("User '{0}' authenticated successfully", userName);
return true;
} catch (Exception ex) {
log.error("Failed to authenticate user '{0}'", ex, userName);
}
return false;
}
/**
* Set session variables after user login
*
* @throws Exception
*/
private void postLogin(User user) {
log.debug("Configuring application after user '{0}' login", user.getUid());
GluuCustomPerson person = findPersonByDn(user.getDn());
Contexts.getSessionContext().set(OxTrustConstants.CURRENT_PERSON, person);
// Set user roles
GluuUserRole[] userRoles = securityService.getUserRoles(user);
if (ArrayHelper.isNotEmpty(userRoles)) {
log.debug("Get '{0}' user roles", Arrays.toString(userRoles));
} else {
log.debug("Get 0 user roles");
}
for (GluuUserRole userRole : userRoles) {
identity.addRole(userRole.getRoleName());
}
if (log.isDebugEnabled()) {
for (Group sg : identity.getSubject().getPrincipals(java.security.acl.Group.class)) {
if ("Roles".equals(sg.getName())) {
log.debug("Using next user roles: '{0}'", sg.members());
break;
}
}
}
}
private User findUserByUserName(String userName) {
User user = null;
try {
user = personService.getUserByUid(userName);
} catch (Exception ex) {
log.error("Failed to find user '{0}' in ldap", ex, userName);
}
return user;
}
private GluuCustomPerson findPersonByDn(String userDn) {
GluuCustomPerson person = null;
try {
person = personService.getPersonByDn(userDn);
} catch (Exception ex) {
log.error("Failed to find person '{0}' in ldap", ex, userDn);
}
return person;
}
public void processLogout() throws Exception {
ssoLoginAction.logout();
oAuthlLogout();
postLogout();
}
public String postLogout() {
if (identity.isLoggedIn()) {
identity.logout();
}
return OxTrustConstants.RESULT_SUCCESS;
}
public void oAuthlLogout() throws Exception {
if (StringHelper.isEmpty(oauthData.getUserUid())) {
return;
}
ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getEndSessionEndpoint());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_SESSION_STATE, oauthData.getSessionState());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_ID_TOKEN_HINT, oauthData.getIdToken());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_POST_LOGOUT_REDIRECT_URI, applicationConfiguration.getLogoutRedirectUrl());
// Clean up OAuth token
oauthData.setUserUid(null);
oauthData.setIdToken(null);
oauthData.setSessionState(null);
oauthData = null;
FacesContext.getCurrentInstance().getExternalContext().redirect(clientRequest.getUri());
}
/**
* Authenticate using credentials passed from web request header
*/
public boolean Shibboleth3Authenticate() {
log.debug("Checking if user authenticated with shibboleth already");
boolean result = false;
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String authType = request.getAuthType();
String userUid = request.getHeader("REMOTE_USER");
String userUidlower = request.getHeader("remote_user");
Enumeration<?> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
log.trace(headerName + "-->" + request.getHeader(headerName));
}
log.debug("Username is " + userUid);
log.debug("UsernameLower is " + userUidlower);
log.debug("AuthType is " + authType);
Map<String, String[]> headers = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderValuesMap();
for (String name : headers.keySet()) {
log.trace(name + "==>" + StringUtils.join(headers.get(name)));
}
if (StringHelper.isEmpty(userUid) || StringHelper.isEmpty(authType) || !authType.equals("shibboleth")) {
result = false;
return result;
}
Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
Matcher matcher = pattern.matcher(userUid);
User user = null;
if (matcher.matches()) {
// Find user by uid
user = personService.getPersonByEmail(userUid);
} else {
// Find user by uid
user = personService.getUserByUid(userUid);
}
if (user == null) {
result = false;
return result;
}
log.debug("Person Inum is " + user.getInum());
if (GluuStatus.ACTIVE.getValue().equals(user.getAttribute("gluuStatus"))){
credentials.setUsername(user.getUid());
// credentials.setPassword("");
Principal principal = new SimplePrincipal(user.getUid());
log.debug("Principal is " + principal.toString());
identity.acceptExternallyAuthenticatedPrincipal(principal);
log.info("User '{0}' authenticated with shibboleth already", userUid);
identity.quietLogin();
postLogin(user);
Contexts.getSessionContext().set(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE,
OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH3);
result = true;
if (Events.exists()) {
facesMessages.clear();
Events.instance().raiseEvent(Identity.EVENT_LOGIN_SUCCESSFUL);
}
}else{
result = false;
}
return result;
}
/**
* Main entry point for oAuth authentication.
* @throws IOException
*
* @throws Exception
*/
public boolean oAuthLogin() throws IOException, Exception {
ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getAuthorizationEndpoint());
String clientId = applicationConfiguration.getOxAuthClientId();
String scope = applicationConfiguration.getOxAuthClientScope();
String responseType = "code+id_token";
String nonce = "nonce";
clientRequest.queryParameter(OxTrustConstants.OXAUTH_CLIENT_ID, clientId);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_REDIRECT_URI, applicationConfiguration.getLoginRedirectUrl());
clientRequest.queryParameter(OxTrustConstants.OXAUTH_RESPONSE_TYPE, responseType);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_SCOPE, scope);
clientRequest.queryParameter(OxTrustConstants.OXAUTH_NONCE, nonce);
GluuAppliance appliance = applianceService.getAppliance(new String[] {"oxTrustAuthenticationMode"});
String authenticationMode = appliance.getOxTrustAuthenticationMode();
if (StringHelper.isNotEmpty(authenticationMode)) {
clientRequest.queryParameter(OxTrustConstants.OXAUTH_ACR_VALUES, authenticationMode);
}
if (viewIdBeforeLoginRedirect != null) {
clientRequest.queryParameter(OxTrustConstants.OXAUTH_STATE, viewIdBeforeLoginRedirect);
}
FacesContext.getCurrentInstance().getExternalContext().redirect(clientRequest.getUri().replaceAll("%2B", "+"));
return true;
}
/**
* After successful login, oxAuth will redirect user to this method. Obtains
* access token using authorization code and verifies if access token is
* valid
*
* @return
* @throws JSONException
*/
public String oAuthGetAccessToken() throws JSONException {
String oxAuthAuthorizeUrl = openIdService.getOpenIdConfiguration().getAuthorizationEndpoint();
String oxAuthHost = getOxAuthHost(oxAuthAuthorizeUrl);
if (StringHelper.isEmpty(oxAuthHost)) {
log.info("Failed to determine oxAuth host using oxAuthAuthorizeUrl: '{0}'", oxAuthAuthorizeUrl);
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
Map<String, Object> requestCookieMap = FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap();
String authorizationCode = requestParameterMap.get(OxTrustConstants.OXAUTH_CODE);
Object sessionStateCookie = requestCookieMap.get(OxTrustConstants.OXAUTH_SESSION_STATE);
String sessionState = null;
if (sessionStateCookie != null) {
sessionState = ((Cookie) sessionStateCookie).getValue();
}
String idToken = requestParameterMap.get(OxTrustConstants.OXAUTH_ID_TOKEN);
if (authorizationCode == null) {
String error = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR);
String errorDescription = requestParameterMap
.get(OxTrustConstants.OXAUTH_ERROR_DESCRIPTION);
log.info("No authorization code sent. Error: " + error + ". Error description: " + errorDescription);
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
if (viewIdBeforeLoginRedirect != null && !viewIdBeforeLoginRedirect.equals("")) {
Redirect.instance().setViewId(viewIdBeforeLoginRedirect);
viewIdBeforeLoginRedirect = "";
}
// todo hardcoded for now. Once clients are dynamically registered with
// oxAuth, change this
// String credentials = applicationConfiguration.getOxAuthClientId() +
// ":secret";
// String credentials = applicationConfiguration.getOxAuthClientId() + ":5967d41c-ce9c-4137-9068-42578df0c606";
// String clientCredentials =
// applicationConfiguration.getOxAuthClientCredentials();
log.info("authorizationCode : " + authorizationCode);
String scopes = requestParameterMap.get(OxTrustConstants.OXAUTH_SCOPE);
log.info(" scopes : " + scopes);
String clientID = applicationConfiguration.getOxAuthClientId();
log.info("clientID : " + clientID);
String clientPassword = applicationConfiguration.getOxAuthClientPassword();
if (clientPassword != null) {
try {
clientPassword = StringEncrypter.defaultInstance().decrypt(clientPassword, cryptoConfigurationSalt);
} catch (EncryptionException ex) {
log.error("Failed to decrypt client password", ex);
}
}
String result = requestAccessToken(oxAuthHost, authorizationCode, sessionState, idToken, scopes, clientID, clientPassword);
return result;
}
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String idToken, String scopes,
String clientID, String clientPassword) {
OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
// 1. Request access token using the authorization code.
TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());
log.info("Sending request to token endpoint");
String redirectURL = applicationConfiguration.getLoginRedirectUrl();
log.info("redirectURI : " + redirectURL);
TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID, clientPassword);
log.debug(" tokenResponse : " + tokenResponse);
if (tokenResponse == null) {
log.error("Get empty token response. User rcan't log into application");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());
String accessToken = tokenResponse.getAccessToken();
log.debug(" accessToken : " + accessToken);
// 2. Validate the access token
ValidateTokenClient validateTokenClient = new ValidateTokenClient(openIdConfiguration.getValidateTokenEndpoint());
ValidateTokenResponse response3 = validateTokenClient.execValidateToken(accessToken);
log.debug(" response3.getStatus() : " + response3.getStatus());
log.debug("validate check session status:" + response3.getStatus());
if (response3.getErrorDescription() != null) {
log.debug("validate token status message:" + response3.getErrorDescription());
}
if (response3.getStatus() == 200) {
log.info("Session validation successful. User is logged in");
UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
this.oauthData.setHost(oxAuthHost);
// Determine uid
List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
if ((uidValues == null) || (uidValues.size() == 0)) {
log.error("User info response doesn't contains uid claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
this.oauthData.setUserUid(uidValues.get(0));
this.oauthData.setAccessToken(accessToken);
this.oauthData.setAccessTokenExpirationInSeconds(response3.getExpiresIn());
this.oauthData.setScopes(scopes);
this.oauthData.setIdToken(idToken);
this.oauthData.setSessionState(sessionState);
log.info("user uid:" + oauthData.getUserUid());
// Create session scope authentication service
Component.getInstance(AuthenticationSessionService.class);
return OxTrustConstants.RESULT_SUCCESS;
}
log.info("Token validation failed. User is NOT logged in");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
private String getOxAuthHost(String oxAuthAuthorizeUrl) {
try {
URL url = new URL(oxAuthAuthorizeUrl);
return String.format("%s://%s:%s", url.getProtocol(), url.getHost(), url.getPort());
} catch (MalformedURLException ex) {
log.error("Invalid oxAuth authorization URI: '{0}'", ex, oxAuthAuthorizeUrl);
}
return null;
}
/**
* Used to remember the view user tried to access prior to login. This is
* the view user will be redirected after successful login.
*/
public void captureCurrentView() {
FacesContext context = FacesContext.getCurrentInstance();
// If this isn't a faces request then just return
if (context == null)
return;
viewIdBeforeLoginRedirect = Pages.getViewId(context);
}
public static Authenticator instance() {
return (Authenticator) Component.getInstance(Authenticator.class, true);
}
}
| Validate if user used request acr_values to log in | server/src/main/java/org/gluu/oxtrust/action/Authenticator.java | Validate if user used request acr_values to log in | <ide><path>erver/src/main/java/org/gluu/oxtrust/action/Authenticator.java
<ide> clientRequest.queryParameter(OxTrustConstants.OXAUTH_NONCE, nonce);
<ide>
<ide> GluuAppliance appliance = applianceService.getAppliance(new String[] {"oxTrustAuthenticationMode"});
<del> String authenticationMode = appliance.getOxTrustAuthenticationMode();
<del> if (StringHelper.isNotEmpty(authenticationMode)) {
<del> clientRequest.queryParameter(OxTrustConstants.OXAUTH_ACR_VALUES, authenticationMode);
<add> String acrValues = appliance.getOxTrustAuthenticationMode();
<add> if (StringHelper.isNotEmpty(acrValues)) {
<add> clientRequest.queryParameter(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues);
<add>
<add> // Store request authentication method
<add> Contexts.getSessionContext().set(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues);
<ide> }
<ide>
<ide> if (viewIdBeforeLoginRedirect != null) {
<ide> return OxTrustConstants.RESULT_NO_PERMISSIONS;
<ide> }
<ide>
<add> // Store request authentication method
<add> if (Contexts.getSessionContext().isSet(OxTrustConstants.OXAUTH_ACR_VALUES)) {
<add> String requestAcrValues = (String) Contexts.getSessionContext().get(OxTrustConstants.OXAUTH_ACR_VALUES);
<add> List<String> acrValues = userInfoResponse.getClaims().get(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
<add> if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) {
<add> log.error("User info response doesn't contains acr claim");
<add> return OxTrustConstants.RESULT_NO_PERMISSIONS;
<add> }
<add> if (!acrValues.contains(requestAcrValues)) {
<add> log.error("User info response contains acr='{0}' claim but expected acr='{1}'", acrValues, requestAcrValues);
<add> return OxTrustConstants.RESULT_NO_PERMISSIONS;
<add> }
<add> }
<add>
<ide> this.oauthData.setUserUid(uidValues.get(0));
<ide> this.oauthData.setAccessToken(accessToken);
<ide> this.oauthData.setAccessTokenExpirationInSeconds(response3.getExpiresIn()); |
|
JavaScript | bsd-3-clause | d33fdea3941223676d4b035139469768ed213258 | 0 | eduardolundgren/alloy-ui,zsagia/alloy-ui,ipeychev/alloy-ui,peterborkuti/alloy-ui,dsanz/alloy-ui,crimago/alloy-ui,seedtigo/alloy-ui,zenorocha/alloy-ui,zxdgoal/alloy-ui,inacionery/alloy-ui,4talesa/alloy-ui,BryanEngler/alloy-ui,samanzanedo/alloy-ui,westonhancock/alloy-ui,crimago/alloy-ui,ericyanLr/alloy-ui,mthadley/alloy-ui,dsanz/alloy-ui,ambrinchaudhary/alloy-ui,dsanz/alloy-ui,modulexcite/alloy-ui,antoniopol06/alloy-ui,zsagia/alloy-ui,zsigmondrab/alloy-ui,henvic/alloy-ui,mthadley/alloy-ui,4talesa/alloy-ui,ampratt/alloy-ui,ericchin/alloy-ui,ericchin/alloy-ui,henvic/alloy-ui,dsanz/alloy-ui,pei-jung/alloy-ui,BryanEngler/alloy-ui,jonathanmccann/alloy-ui,drewbrokke/alloy-ui,zenorocha/alloy-ui,Khamull/alloy-ui,zsigmondrab/alloy-ui,ipeychev/alloy-ui,inacionery/alloy-ui,fernandosouza/alloy-ui,peterborkuti/alloy-ui,Preston-Crary/alloy-ui,Khamull/alloy-ui,ambrinchaudhary/alloy-ui,zxdgoal/alloy-ui,seedtigo/alloy-ui,westonhancock/alloy-ui,thiago-rocha/alloy-ui,ericyanLr/alloy-ui,thiago-rocha/alloy-ui,antoniopol06/alloy-ui,jonathanmccann/alloy-ui,pei-jung/alloy-ui,mairatma/alloy-ui,Preston-Crary/alloy-ui,modulexcite/alloy-ui,bryceosterhaus/alloy-ui,brianchandotcom/alloy-ui,drewbrokke/alloy-ui,mairatma/alloy-ui,fernandosouza/alloy-ui,bryceosterhaus/alloy-ui,ampratt/alloy-ui | /**
* The Form Validator Component
*
* @module aui-form-validator
*/
// API inspired on the amazing jQuery Form Validation -
// http://jquery.bassistance.de/validate/
var Lang = A.Lang,
AObject = A.Object,
isBoolean = Lang.isBoolean,
isDate = Lang.isDate,
isEmpty = AObject.isEmpty,
isFunction = Lang.isFunction,
isObject = Lang.isObject,
isString = Lang.isString,
trim = Lang.trim,
defaults = A.namespace('config.FormValidator'),
getRegExp = A.DOM._getRegExp,
getCN = A.getClassName,
CSS_FORM_GROUP = getCN('form', 'group'),
CSS_HAS_ERROR = getCN('has', 'error'),
CSS_ERROR_FIELD = getCN('error', 'field'),
CSS_HAS_SUCCESS = getCN('has', 'success'),
CSS_SUCCESS_FIELD = getCN('success', 'field'),
CSS_HELP_BLOCK = getCN('help', 'block'),
CSS_STACK = getCN('form-validator', 'stack'),
TPL_MESSAGE = '<div role="alert"></div>',
TPL_STACK_ERROR = '<div class="' + [CSS_STACK, CSS_HELP_BLOCK].join(' ') + '"></div>';
A.mix(defaults, {
STRINGS: {
DEFAULT: 'Please fix this field.',
acceptFiles: 'Please enter a value with a valid extension ({0}).',
alpha: 'Please enter only alpha characters.',
alphanum: 'Please enter only alphanumeric characters.',
date: 'Please enter a valid date.',
digits: 'Please enter only digits.',
email: 'Please enter a valid email address.',
equalTo: 'Please enter the same value again.',
iri: 'Please enter a valid IRI.',
max: 'Please enter a value less than or equal to {0}.',
maxLength: 'Please enter no more than {0} characters.',
min: 'Please enter a value greater than or equal to {0}.',
minLength: 'Please enter at least {0} characters.',
number: 'Please enter a valid number.',
range: 'Please enter a value between {0} and {1}.',
rangeLength: 'Please enter a value between {0} and {1} characters long.',
required: 'This field is required.',
url: 'Please enter a valid URL.'
},
REGEX: {
alpha: /^[a-z_]+$/i,
alphanum: /^\w+$/,
digits: /^\d+$/,
// Regex from Scott Gonzalez Email Address Validation:
// http://projects.scottsplayground.com/email_address_validation/
email: new RegExp('^((([a-z]|\\d|[!#\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#' +
'\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF' +
'\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20' +
'|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\' +
'x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])' +
'|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-' +
'\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\' +
'x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$', 'i'),
// Regex from Scott Gonzalez IRI:
// http://projects.scottsplayground.com/iri/demo/
iri: new RegExp('^([a-z]([a-z]|\\d|\\+|-|\\.)*):(\\/\\/(((([a-z]|\\d|' +
'-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[' +
'\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:)*@)?((\\[(|(v[\\da-f]{1' +
',}\\.(([a-z]|\\d|-|\\.|_|~)|[!\\$&\'\\(\\)\\*\\+,;=]|:)+))\\])' +
'|((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1' +
'\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d' +
'|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|' +
'(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-' +
'\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=])*)(:\\d*)?)' +
'(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)*)' +
'*|(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)+' +
'(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|' +
'@)*)*)?)|((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\' +
'+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\' +
'(\\)\\*\\+,;=]|:|@)*)*)|((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\' +
'uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\' +
'$&\'\\(\\)\\*\\+,;=]|:|@)){0})(\\?((([a-z]|\\d|-|\\.|_|~|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]' +
'{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|' +
'\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\' +
'+,;=]|:|@)|\\/|\\?)*)?$', 'i'),
number: /^[+\-]?(\d+([.,]\d+)?)+([eE][+-]?\d+)?$/,
// Regex from Scott Gonzalez Common URL:
// http://projects.scottsplayground.com/iri/demo/common.html
url: new RegExp('^(https?|ftp):\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})' +
'|[!\\$&\'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|' +
'2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25' +
'[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.' +
'(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d' +
'|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\' +
'd|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|' +
'-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*' +
'([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\' +
'.)*(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|' +
'(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]' +
'|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])' +
'*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)' +
'(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]' +
'|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF' +
'\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)*)' +
'*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|' +
':|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})' +
'|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$', 'i')
},
RULES: {
acceptFiles: function(val, node, ruleValue) {
var regex = null;
if (isString(ruleValue)) {
var extensions = ruleValue.replace(/\./g, '').split(/,\s*|\b\s*/);
extensions = A.Array.map(extensions, A.Escape.regex);
regex = getRegExp('[.](' + extensions.join('|') + ')$', 'i');
}
return regex && regex.test(val);
},
date: function(val) {
var date = new Date(val);
return (isDate(date) && (date !== 'Invalid Date') && !isNaN(date));
},
equalTo: function(val, node, ruleValue) {
var comparator = A.one(ruleValue);
return comparator && (trim(comparator.val()) === val);
},
max: function(val, node, ruleValue) {
return (Lang.toFloat(val) <= ruleValue);
},
maxLength: function(val, node, ruleValue) {
return (val.length <= ruleValue);
},
min: function(val, node, ruleValue) {
return (Lang.toFloat(val) >= ruleValue);
},
minLength: function(val, node, ruleValue) {
return (val.length >= ruleValue);
},
range: function(val, node, ruleValue) {
var num = Lang.toFloat(val);
return (num >= ruleValue[0]) && (num <= ruleValue[1]);
},
rangeLength: function(val, node, ruleValue) {
var length = val.length;
return (length >= ruleValue[0]) && (length <= ruleValue[1]);
},
required: function(val, node) {
var instance = this;
if (A.FormValidator.isCheckable(node)) {
var name = node.get('name'),
elements = A.all(instance.getFieldsByName(name));
return (elements.filter(':checked').size() > 0);
}
else {
return !!val;
}
}
}
});
/**
* A base class for `A.FormValidator`.
*
* @class A.FormValidator
* @extends Base
* @param {Object} config Object literal specifying widget configuration
* properties.
* @constructor
* @include http://alloyui.com/examples/form-validator/basic-markup.html
* @include http://alloyui.com/examples/form-validator/basic.js
*/
var FormValidator = A.Component.create({
/**
* Static property provides a string to identify the class.
*
* @property NAME
* @type String
* @static
*/
NAME: 'form-validator',
/**
* Static property used to define the default attribute
* configuration for the `A.FormValidator`.
*
* @property ATTRS
* @type Object
* @static
*/
ATTRS: {
/**
* The widget's outermost node, used for sizing and positioning.
*
* @attribute boundingBox
*/
boundingBox: {
setter: A.one
},
/**
* Container for the CSS error class.
*
* @attribute containerErrorClass
* @type String
*/
containerErrorClass: {
value: CSS_HAS_ERROR,
validator: isString
},
/**
* Container for the CSS valid class.
*
* @attribute containerValidClass
* @type String
*/
containerValidClass: {
value: CSS_HAS_SUCCESS,
validator: isString
},
/**
* Defines the CSS error class.
*
* @attribute errorClass
* @type String
*/
errorClass: {
value: CSS_ERROR_FIELD,
validator: isString
},
/**
* If `true` the validation rules are extracted from the DOM.
*
* @attribute extractRules
* @default true
* @type Boolean
*/
extractRules: {
value: true,
validator: isBoolean
},
/**
* Container for a field.
*
* @attribute fieldContainer
* @type String
*/
fieldContainer: {
value: '.' + CSS_FORM_GROUP
},
/**
* Collection of strings used on a field.
*
* @attribute fieldStrings
* @default {}
* @type Object
*/
fieldStrings: {
value: {},
validator: isObject
},
/**
* The CSS class for `<label>`.
*
* @attribute labelCssClass
* @default 'control-label'
* @type String
*/
labelCssClass: {
validator: isString,
value: 'control-label'
},
/**
* Container for the form message.
*
* @attribute messageContainer
* @default '<div role="alert"></div>'
*/
messageContainer: {
getter: function(val) {
return A.Node.create(val).clone();
},
value: TPL_MESSAGE
},
/**
* Collection of strings used to label elements of the UI.
*
* @attribute strings
* @type Object
*/
strings: {
valueFn: function() {
return defaults.STRINGS;
}
},
/**
* Collection of rules to validate fields.
*
* @attribute rules
* @default {}
* @type Object
*/
rules: {
getter: function(val) {
var instance = this;
if (!instance._rulesAlreadyExtracted) {
instance._extractRulesFromMarkup(val);
}
return val;
},
validator: isObject,
value: {}
},
/**
* Defines if the text will be selected or not after validation.
*
* @attribute selectText
* @default true
* @type Boolean
*/
selectText: {
value: true,
validator: isBoolean
},
/**
* Defines if the validation messages will be showed or not.
*
* @attribute showMessages
* @default true
* @type Boolean
*/
showMessages: {
value: true,
validator: isBoolean
},
/**
* Defines if all validation messages will be showed or not.
*
* @attribute showAllMessages
* @default false
* @type Boolean
*/
showAllMessages: {
value: false,
validator: isBoolean
},
/**
* Defines a container for the stack errors.
*
* @attribute stackErrorContainer
*/
stackErrorContainer: {
getter: function(val) {
return A.Node.create(val).clone();
},
value: TPL_STACK_ERROR
},
/**
* If `true` the field will be validated on blur event.
*
* @attribute validateOnBlur
* @default true
* @type Boolean
*/
validateOnBlur: {
value: true,
validator: isBoolean
},
/**
* If `true` the field will be validated on input event.
*
* @attribute validateOnInput
* @default false
* @type Boolean
*/
validateOnInput: {
value: false,
validator: isBoolean
},
/**
* Defines the CSS valid class.
*
* @attribute validClass
* @type String
*/
validClass: {
value: CSS_SUCCESS_FIELD,
validator: isString
}
},
/**
* Checks if a node is a checkbox or radio input.
*
* @method isCheckable
* @param node
* @private
* @return {Boolean}
*/
isCheckable: function(node) {
var nodeType = node.get('type').toLowerCase();
return (nodeType === 'checkbox' || nodeType === 'radio');
},
/**
* Static property used to define which component it extends.
*
* @property EXTENDS
* @type Object
* @static
*/
EXTENDS: A.Base,
prototype: {
/**
* Construction logic executed during `A.FormValidator` instantiation.
* Lifecycle.
*
* @method initializer
* @protected
*/
initializer: function() {
var instance = this;
instance.errors = {};
instance._blurHandlers = null;
instance._inputHandlers = null;
instance._rulesAlreadyExtracted = false;
instance._stackErrorContainers = {};
instance.bindUI();
instance._uiSetValidateOnBlur(instance.get('validateOnBlur'));
instance._uiSetValidateOnInput(instance.get('validateOnInput'));
},
/**
* Bind the events on the `A.FormValidator` UI. Lifecycle.
*
* @method bindUI
* @protected
*/
bindUI: function() {
var instance = this,
boundingBox = instance.get('boundingBox');
var onceFocusHandler = boundingBox.delegate('focus', function() {
instance._setARIARoles();
onceFocusHandler.detach();
}, 'input,select,textarea,button');
instance.publish({
errorField: {
defaultFn: instance._defErrorFieldFn
},
validField: {
defaultFn: instance._defValidFieldFn
},
validateField: {
defaultFn: instance._defValidateFieldFn
}
});
boundingBox.on({
reset: A.bind(instance._onFormReset, instance),
submit: A.bind(instance._onFormSubmit, instance)
});
instance.after({
extractRulesChange: instance._afterExtractRulesChange,
validateOnBlurChange: instance._afterValidateOnBlurChange,
validateOnInputChange: instance._afterValidateOnInputChange
});
},
/**
* Adds a validation error in the field.
*
* @method addFieldError
* @param field
* @param ruleName
*/
addFieldError: function(field, ruleName) {
var instance = this,
errors = instance.errors,
name = field.get('name');
if (!errors[name]) {
errors[name] = [];
}
errors[name].push(ruleName);
},
/**
* Removes a validation error in the field.
*
* @method clearFieldError
* @param field
*/
clearFieldError: function(field) {
var instance = this;
delete instance.errors[field.get('name')];
},
/**
* Executes a function to each rule.
*
* @method eachRule
* @param fn
*/
eachRule: function(fn) {
var instance = this;
A.each(
instance.get('rules'),
function(rule, fieldName) {
if (isFunction(fn)) {
fn.apply(instance, [rule, fieldName]);
}
}
);
},
/**
* Gets the ancestor of a given field.
*
* @method findFieldContainer
* @param field
* @return {Node}
*/
findFieldContainer: function(field) {
var instance = this,
fieldContainer = instance.get('fieldContainer');
if (fieldContainer) {
return field.ancestor(fieldContainer);
}
},
/**
* Focus on the invalid field.
*
* @method focusInvalidField
*/
focusInvalidField: function() {
var instance = this,
boundingBox = instance.get('boundingBox'),
field = boundingBox.one('.' + CSS_ERROR_FIELD);
if (field) {
if (instance.get('selectText')) {
field.selectText();
}
field.focus();
field.scrollIntoView();
}
},
/**
* Gets a field from the form.
*
* @method getField
* @param fieldOrFieldName
* @return {Node}
*/
getField: function(fieldOrFieldName) {
var instance = this;
if (isString(fieldOrFieldName)) {
fieldOrFieldName = instance.getFieldsByName(fieldOrFieldName);
if (fieldOrFieldName && fieldOrFieldName.length && !fieldOrFieldName.name) {
fieldOrFieldName = fieldOrFieldName[0];
}
}
return A.one(fieldOrFieldName);
},
/**
* Gets a list of fields based on its name.
*
* @method getFieldsByName
* @param fieldName
* @return {NodeList}
*/
getFieldsByName: function(fieldName) {
var instance = this,
domBoundingBox = instance.get('boundingBox').getDOM();
return domBoundingBox.elements[fieldName];
},
/**
* Gets a list of fields with errors.
*
* @method getFieldError
* @param field
* @return {String}
*/
getFieldError: function(field) {
var instance = this;
return instance.errors[field.get('name')];
},
/**
* Gets the stack error container of a field.
*
* @method getFieldStackErrorContainer
* @param field
*/
getFieldStackErrorContainer: function(field) {
var instance = this,
name = field.get('name'),
stackContainers = instance._stackErrorContainers;
if (!stackContainers[name]) {
stackContainers[name] = instance.get('stackErrorContainer');
}
return stackContainers[name];
},
/**
* Gets the error message of a field.
*
* @method getFieldErrorMessage
* @param field
* @param rule
* @return {String}
*/
getFieldErrorMessage: function(field, rule) {
var instance = this,
fieldName = field.get('name'),
fieldStrings = instance.get('fieldStrings')[fieldName] || {},
fieldRules = instance.get('rules')[fieldName],
strings = instance.get('strings'),
substituteRulesMap = {};
if (rule in fieldRules) {
var ruleValue = A.Array(fieldRules[rule]);
A.each(
ruleValue,
function(value, index) {
substituteRulesMap[index] = [value].join('');
}
);
}
var message = (fieldStrings[rule] || strings[rule] || strings.DEFAULT);
return Lang.sub(message, substituteRulesMap);
},
/**
* Returns `true` if there are errors.
*
* @method hasErrors
* @return {Boolean}
*/
hasErrors: function() {
var instance = this;
return !isEmpty(instance.errors);
},
/**
* Highlights a field with error or success.
*
* @method highlight
* @param field
* @param valid
*/
highlight: function(field, valid) {
var instance = this,
fieldContainer = instance.findFieldContainer(field);
instance._highlightHelper(
field,
instance.get('errorClass'),
instance.get('validClass'),
valid
);
instance._highlightHelper(
fieldContainer,
instance.get('containerErrorClass'),
instance.get('containerValidClass'),
valid
);
},
/**
* Normalizes rule value.
*
* @method normalizeRuleValue
* @param ruleValue
*/
normalizeRuleValue: function(ruleValue) {
var instance = this;
return isFunction(ruleValue) ? ruleValue.apply(instance) : ruleValue;
},
/**
* Removes the highlight of a field.
*
* @method unhighlight
* @param field
*/
unhighlight: function(field) {
var instance = this;
instance.highlight(field, true);
},
/**
* Prints the stack error messages into a container.
*
* @method printStackError
* @param field
* @param container
* @param errors
*/
printStackError: function(field, container, errors) {
var instance = this;
if (!instance.get('showAllMessages')) {
errors = errors.slice(0, 1);
}
container.empty();
A.Array.each(
errors,
function(error) {
var message = instance.getFieldErrorMessage(field, error),
messageEl = instance.get('messageContainer').addClass(error);
container.append(
messageEl.html(message)
);
}
);
},
/**
* Resets the CSS class and content of all fields.
*
* @method resetAllFields
*/
resetAllFields: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
var field = instance.getField(fieldName);
instance.resetField(field);
}
);
},
/**
* Resets the CSS class and content of a field.
*
* @method resetField
* @param field
*/
resetField: function(field) {
var instance = this,
stackContainer = instance.getFieldStackErrorContainer(field);
stackContainer.remove();
instance.resetFieldCss(field);
instance.clearFieldError(field);
},
/**
* Removes the CSS classes of a field.
*
* @method resetFieldCss
* @param field
*/
resetFieldCss: function(field) {
var instance = this,
fieldContainer = instance.findFieldContainer(field);
var removeClasses = function(elem, classAttrs) {
if (elem) {
A.each(classAttrs, function(attrName) {
elem.removeClass(
instance.get(attrName)
);
});
}
};
removeClasses(field, ['validClass', 'errorClass']);
removeClasses(fieldContainer, ['containerValidClass', 'containerErrorClass']);
},
/**
* Checks if a field can be validated or not.
*
* @method validatable
* @param field
* @return {Boolean}
*/
validatable: function(field) {
var instance = this,
validatable = false,
fieldRules = instance.get('rules')[field.get('name')];
if (fieldRules) {
var required = instance.normalizeRuleValue(fieldRules.required);
validatable = (required || (!required && defaults.RULES.required.apply(instance, [field.val(),
field])) || fieldRules.custom);
}
return !!validatable;
},
/**
* Validates all fields.
*
* @method validate
*/
validate: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
instance.validateField(fieldName);
}
);
instance.focusInvalidField();
},
/**
* Validates a single field.
*
* @method validateField
* @param field
*/
validateField: function(field) {
var instance = this,
fieldNode = instance.getField(field);
if (fieldNode) {
var validatable = instance.validatable(fieldNode);
instance.resetField(fieldNode);
if (validatable) {
instance.fire('validateField', {
validator: {
field: fieldNode
}
});
}
}
},
/**
* Fires after `extractRules` attribute change.
*
* @method _afterExtractRulesChange
* @param event
* @protected
*/
_afterExtractRulesChange: function(event) {
var instance = this;
instance._uiSetExtractRules(event.newVal);
},
/**
* Fires after `validateOnInput` attribute change.
*
* @method _afterValidateOnInputChange
* @param event
* @protected
*/
_afterValidateOnInputChange: function(event) {
var instance = this;
instance._uiSetValidateOnInput(event.newVal);
},
/**
* Fires after `validateOnBlur` attribute change.
*
* @method _afterValidateOnBlurChange
* @param event
* @protected
*/
_afterValidateOnBlurChange: function(event) {
var instance = this;
instance._uiSetValidateOnBlur(event.newVal);
},
/**
* Defines an error field.
*
* @method _defErrorFieldFn
* @param event
* @protected
*/
_defErrorFieldFn: function(event) {
var instance = this,
ancestor,
field,
label,
nextSibling,
stackContainer,
target,
validator;
label = instance.get('labelCssClass');
validator = event.validator;
field = validator.field;
instance.highlight(field);
if (instance.get('showMessages')) {
target = field;
stackContainer = instance.getFieldStackErrorContainer(field);
nextSibling = field.get('nextSibling');
if (nextSibling && nextSibling.get('nodeType') === 3) {
ancestor = field.ancestor();
if (ancestor) {
if (ancestor.hasClass(label)) {
target = nextSibling;
}
else if (A.FormValidator.isCheckable(target)) {
label = ancestor.previous('.' + label);
target = label;
}
}
}
target.placeAfter(stackContainer);
instance.printStackError(
field,
stackContainer,
validator.errors
);
}
},
/**
* Defines a valid field.
*
* @method _defValidFieldFn
* @param event
* @protected
*/
_defValidFieldFn: function(event) {
var instance = this;
var field = event.validator.field;
instance.unhighlight(field);
},
/**
* Defines the validation of a field.
*
* @method _defValidateFieldFn
* @param event
* @protected
*/
_defValidateFieldFn: function(event) {
var instance = this;
var field = event.validator.field;
var fieldRules = instance.get('rules')[field.get('name')];
A.each(
fieldRules,
function(ruleValue, ruleName) {
var rule = defaults.RULES[ruleName];
var fieldValue = trim(field.val());
ruleValue = instance.normalizeRuleValue(ruleValue);
if (isFunction(rule) && !rule.apply(instance, [fieldValue, field, ruleValue])) {
instance.addFieldError(field, ruleName);
}
}
);
var fieldErrors = instance.getFieldError(field);
if (fieldErrors) {
instance.fire('errorField', {
validator: {
field: field,
errors: fieldErrors
}
});
}
else {
instance.fire('validField', {
validator: {
field: field
}
});
}
},
/**
* Sets the error/success CSS classes based on the validation of a
* field.
*
* @method _highlightHelper
* @param field
* @param errorClass
* @param validClass
* @param valid
* @protected
*/
_highlightHelper: function(field, errorClass, validClass, valid) {
if (field) {
if (valid) {
field.removeClass(errorClass).addClass(validClass);
}
else {
field.removeClass(validClass).addClass(errorClass);
}
}
},
/**
* Extracts form rules from the DOM.
*
* @method _extractRulesFromMarkup
* @param rules
* @protected
*/
_extractRulesFromMarkup: function(rules) {
var instance = this,
domBoundingBox = instance.get('boundingBox').getDOM(),
elements = domBoundingBox.elements,
defaultRulesKeys = AObject.keys(defaults.RULES),
defaultRulesJoin = defaultRulesKeys.join('|'),
regex = getRegExp('field-(' + defaultRulesJoin + ')', 'g'),
i,
length,
ruleNameMatch = [],
ruleMatcher = function(m1, m2) {
ruleNameMatch.push(m2);
};
for (i = 0, length = elements.length; i < length; i++) {
var el = elements[i],
fieldName = el.name;
el.className.replace(regex, ruleMatcher);
if (ruleNameMatch.length) {
var fieldRules = rules[fieldName],
j,
ruleNameLength;
if (!fieldRules) {
fieldRules = {};
rules[fieldName] = fieldRules;
}
for (j = 0, ruleNameLength = ruleNameMatch.length; j < ruleNameLength; j++) {
var rule = ruleNameMatch[j];
if (!(rule in fieldRules)) {
fieldRules[rule] = true;
}
}
ruleNameMatch.length = 0;
}
}
instance._rulesAlreadyExtracted = true;
},
/**
* Triggers when there's an input in the field.
*
* @method _onFieldInput
* @param event
* @protected
*/
_onFieldInput: function(event) {
var instance = this;
instance.validateField(event.target);
},
/**
* Triggers when the form is submitted.
*
* @method _onFormSubmit
* @param event
* @protected
*/
_onFormSubmit: function(event) {
var instance = this;
var data = {
validator: {
formEvent: event
}
};
instance.validate();
if (instance.hasErrors()) {
data.validator.errors = instance.errors;
instance.fire('submitError', data);
event.halt();
}
else {
instance.fire('submit', data);
}
},
/**
* Triggers when the form is reseted.
*
* @method _onFormReset
* @param event
* @protected
*/
_onFormReset: function() {
var instance = this;
instance.resetAllFields();
},
/**
* Sets the aria roles.
*
* @method _setARIARoles
* @protected
*/
_setARIARoles: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
if (rule.required) {
var field = instance.getField(fieldName);
if (field && !field.attr('aria-required')) {
field.attr('aria-required', true);
}
}
}
);
},
/**
* Sets the `extractRules` attribute on the UI.
*
* @method _uiSetExtractRules
* @param val
* @protected
*/
_uiSetExtractRules: function(val) {
var instance = this;
if (val) {
instance._extractRulesFromMarkup(instance.get('rules'));
}
},
/**
* Sets the `validateOnInput` attribute on the UI.
*
* @method _uiSetValidateOnInput
* @param val
* @protected
*/
_uiSetValidateOnInput: function(val) {
var instance = this,
boundingBox = instance.get('boundingBox');
if (val) {
if (!instance._inputHandlers) {
instance._inputHandlers = boundingBox.delegate('input', instance._onFieldInput,
'input,select,textarea,button', instance);
}
}
else {
if (instance._inputHandlers) {
instance._inputHandlers.detach();
}
}
},
/**
* Sets the `validateOnBlur` attribute on the UI.
*
* @method _uiSetValidateOnBlur
* @param val
* @protected
*/
_uiSetValidateOnBlur: function(val) {
var instance = this,
boundingBox = instance.get('boundingBox');
if (val) {
if (!instance._blurHandlers) {
instance._blurHandlers = boundingBox.delegate('blur', instance._onFieldInput,
'input,select,textarea,button', instance);
}
}
else {
if (instance._blurHandlers) {
instance._blurHandlers.detach();
}
}
}
}
});
A.each(
defaults.REGEX,
function(regex, key) {
defaults.RULES[key] = function(val) {
return defaults.REGEX[key].test(val);
};
}
);
A.FormValidator = FormValidator;
| src/aui-form-validator/js/aui-form-validator.js | /**
* The Form Validator Component
*
* @module aui-form-validator
*/
// API inspired on the amazing jQuery Form Validation -
// http://jquery.bassistance.de/validate/
var Lang = A.Lang,
AObject = A.Object,
isBoolean = Lang.isBoolean,
isDate = Lang.isDate,
isEmpty = AObject.isEmpty,
isFunction = Lang.isFunction,
isObject = Lang.isObject,
isString = Lang.isString,
trim = Lang.trim,
defaults = A.namespace('config.FormValidator'),
getRegExp = A.DOM._getRegExp,
getCN = A.getClassName,
CSS_FORM_GROUP = getCN('form', 'group'),
CSS_HAS_ERROR = getCN('has', 'error'),
CSS_ERROR_FIELD = getCN('error', 'field'),
CSS_HAS_SUCCESS = getCN('has', 'success'),
CSS_SUCCESS_FIELD = getCN('success', 'field'),
CSS_HELP_BLOCK = getCN('help', 'block'),
CSS_STACK = getCN('form-validator', 'stack'),
TPL_MESSAGE = '<div role="alert"></div>',
TPL_STACK_ERROR = '<div class="' + [CSS_STACK, CSS_HELP_BLOCK].join(' ') + '"></div>';
A.mix(defaults, {
STRINGS: {
DEFAULT: 'Please fix this field.',
acceptFiles: 'Please enter a value with a valid extension ({0}).',
alpha: 'Please enter only alpha characters.',
alphanum: 'Please enter only alphanumeric characters.',
date: 'Please enter a valid date.',
digits: 'Please enter only digits.',
email: 'Please enter a valid email address.',
equalTo: 'Please enter the same value again.',
iri: 'Please enter a valid IRI.',
max: 'Please enter a value less than or equal to {0}.',
maxLength: 'Please enter no more than {0} characters.',
min: 'Please enter a value greater than or equal to {0}.',
minLength: 'Please enter at least {0} characters.',
number: 'Please enter a valid number.',
range: 'Please enter a value between {0} and {1}.',
rangeLength: 'Please enter a value between {0} and {1} characters long.',
required: 'This field is required.',
url: 'Please enter a valid URL.'
},
REGEX: {
alpha: /^[a-z_]+$/i,
alphanum: /^\w+$/,
digits: /^\d+$/,
// Regex from Scott Gonzalez Email Address Validation:
// http://projects.scottsplayground.com/email_address_validation/
email: new RegExp('^((([a-z]|\\d|[!#\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#' +
'\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF' +
'\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20' +
'|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\' +
'x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])' +
'|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-' +
'\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\' +
'x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$', 'i'),
// Regex from Scott Gonzalez IRI:
// http://projects.scottsplayground.com/iri/demo/
iri: new RegExp('^([a-z]([a-z]|\\d|\\+|-|\\.)*):(\\/\\/(((([a-z]|\\d|' +
'-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[' +
'\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:)*@)?((\\[(|(v[\\da-f]{1' +
',}\\.(([a-z]|\\d|-|\\.|_|~)|[!\\$&\'\\(\\)\\*\\+,;=]|:)+))\\])' +
'|((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1' +
'\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d' +
'|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|' +
'(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-' +
'\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=])*)(:\\d*)?)' +
'(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)*)' +
'*|(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)+' +
'(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\' +
'uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|' +
'@)*)*)?)|((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\' +
'+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\' +
'uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\' +
'(\\)\\*\\+,;=]|:|@)*)*)|((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\' +
'uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\' +
'$&\'\\(\\)\\*\\+,;=]|:|@)){0})(\\?((([a-z]|\\d|-|\\.|_|~|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]' +
'{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|' +
'\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\' +
'+,;=]|:|@)|\\/|\\?)*)?$', 'i'),
number: /^[+\-]?(\d+([.,]\d+)?)+([eE][+-]?\d+)?$/,
// Regex from Scott Gonzalez Common URL:
// http://projects.scottsplayground.com/iri/demo/common.html
url: new RegExp('^(https?|ftp):\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\' +
'u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})' +
'|[!\\$&\'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|' +
'2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25' +
'[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.' +
'(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d' +
'|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\' +
'd|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|' +
'-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*' +
'([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\' +
'.)*(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|' +
'(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]' +
'|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])' +
'*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)' +
'(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]' +
'|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF' +
'\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)*)' +
'*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\' +
'uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&\'\\(\\)\\*\\+,;=]|' +
':|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|' +
'[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})' +
'|[!\\$&\'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$', 'i')
},
RULES: {
acceptFiles: function(val, node, ruleValue) {
var regex = null;
if (isString(ruleValue)) {
var extensions = ruleValue.replace(/\./g, '').split(/,\s*|\b\s*/);
extensions = A.Array.map(extensions, A.Escape.regex);
regex = getRegExp('[.](' + extensions.join('|') + ')$', 'i');
}
return regex && regex.test(val);
},
date: function(val) {
var date = new Date(val);
return (isDate(date) && (date !== 'Invalid Date') && !isNaN(date));
},
equalTo: function(val, node, ruleValue) {
var comparator = A.one(ruleValue);
return comparator && (trim(comparator.val()) === val);
},
max: function(val, node, ruleValue) {
return (Lang.toFloat(val) <= ruleValue);
},
maxLength: function(val, node, ruleValue) {
return (val.length <= ruleValue);
},
min: function(val, node, ruleValue) {
return (Lang.toFloat(val) >= ruleValue);
},
minLength: function(val, node, ruleValue) {
return (val.length >= ruleValue);
},
range: function(val, node, ruleValue) {
var num = Lang.toFloat(val);
return (num >= ruleValue[0]) && (num <= ruleValue[1]);
},
rangeLength: function(val, node, ruleValue) {
var length = val.length;
return (length >= ruleValue[0]) && (length <= ruleValue[1]);
},
required: function(val, node) {
var instance = this;
if (A.FormValidator.isCheckable(node)) {
var name = node.get('name'),
elements = A.all(instance.getFieldsByName(name));
return (elements.filter(':checked').size() > 0);
}
else {
return !!val;
}
}
}
});
/**
* A base class for `A.FormValidator`.
*
* @class A.FormValidator
* @extends Base
* @param {Object} config Object literal specifying widget configuration
* properties.
* @constructor
* @include http://alloyui.com/examples/form-validator/basic-markup.html
* @include http://alloyui.com/examples/form-validator/basic.js
*/
var FormValidator = A.Component.create({
/**
* Static property provides a string to identify the class.
*
* @property NAME
* @type String
* @static
*/
NAME: 'form-validator',
/**
* Static property used to define the default attribute
* configuration for the `A.FormValidator`.
*
* @property ATTRS
* @type Object
* @static
*/
ATTRS: {
/**
* The widget's outermost node, used for sizing and positioning.
*
* @attribute boundingBox
*/
boundingBox: {
setter: A.one
},
/**
* Container for the CSS error class.
*
* @attribute containerErrorClass
* @type String
*/
containerErrorClass: {
value: CSS_HAS_ERROR,
validator: isString
},
/**
* Container for the CSS valid class.
*
* @attribute containerValidClass
* @type String
*/
containerValidClass: {
value: CSS_HAS_SUCCESS,
validator: isString
},
/**
* Defines the CSS error class.
*
* @attribute errorClass
* @type String
*/
errorClass: {
value: CSS_ERROR_FIELD,
validator: isString
},
/**
* If `true` the validation rules are extracted from the DOM.
*
* @attribute extractRules
* @default true
* @type Boolean
*/
extractRules: {
value: true,
validator: isBoolean
},
/**
* Container for a field.
*
* @attribute fieldContainer
* @type String
*/
fieldContainer: {
value: '.' + CSS_FORM_GROUP
},
/**
* Collection of strings used on a field.
*
* @attribute fieldStrings
* @default {}
* @type Object
*/
fieldStrings: {
value: {},
validator: isObject
},
/**
* The CSS class for `<label>`.
*
* @attribute labelCssClass
* @default 'control-label'
* @type String
*/
labelCssClass: {
validator: isString,
value: 'control-label'
},
/**
* Container for the form message.
*
* @attribute messageContainer
* @default '<div role="alert"></div>'
*/
messageContainer: {
getter: function(val) {
return A.Node.create(val).clone();
},
value: TPL_MESSAGE
},
/**
* Collection of strings used to label elements of the UI.
*
* @attribute strings
* @type Object
*/
strings: {
valueFn: function() {
return defaults.STRINGS;
}
},
/**
* Collection of rules to validate fields.
*
* @attribute rules
* @default {}
* @type Object
*/
rules: {
getter: function(val) {
var instance = this;
if (!instance._rulesAlreadyExtracted) {
instance._extractRulesFromMarkup(val);
}
return val;
},
validator: isObject,
value: {}
},
/**
* Defines if the text will be selected or not after validation.
*
* @attribute selectText
* @default true
* @type Boolean
*/
selectText: {
value: true,
validator: isBoolean
},
/**
* Defines if the validation messages will be showed or not.
*
* @attribute showMessages
* @default true
* @type Boolean
*/
showMessages: {
value: true,
validator: isBoolean
},
/**
* Defines if all validation messages will be showed or not.
*
* @attribute showAllMessages
* @default false
* @type Boolean
*/
showAllMessages: {
value: false,
validator: isBoolean
},
/**
* Defines a container for the stack errors.
*
* @attribute stackErrorContainer
*/
stackErrorContainer: {
getter: function(val) {
return A.Node.create(val).clone();
},
value: TPL_STACK_ERROR
},
/**
* If `true` the field will be validated on blur event.
*
* @attribute validateOnBlur
* @default true
* @type Boolean
*/
validateOnBlur: {
value: true,
validator: isBoolean
},
/**
* If `true` the field will be validated on input event.
*
* @attribute validateOnInput
* @default false
* @type Boolean
*/
validateOnInput: {
value: false,
validator: isBoolean
},
/**
* Defines the CSS valid class.
*
* @attribute validClass
* @type String
*/
validClass: {
value: CSS_SUCCESS_FIELD,
validator: isString
}
},
/**
* Checks if a node is a checkbox or radio input.
*
* @method isCheckable
* @param node
* @private
* @return {Boolean}
*/
isCheckable: function(node) {
var nodeType = node.get('type').toLowerCase();
return (nodeType === 'checkbox' || nodeType === 'radio');
},
/**
* Static property used to define which component it extends.
*
* @property EXTENDS
* @type Object
* @static
*/
EXTENDS: A.Base,
prototype: {
/**
* Construction logic executed during `A.FormValidator` instantiation.
* Lifecycle.
*
* @method initializer
* @protected
*/
initializer: function() {
var instance = this;
instance.errors = {};
instance._blurHandlers = null;
instance._inputHandlers = null;
instance._rulesAlreadyExtracted = false;
instance._stackErrorContainers = {};
instance.bindUI();
instance._uiSetValidateOnBlur(instance.get('validateOnBlur'));
instance._uiSetValidateOnInput(instance.get('validateOnInput'));
},
/**
* Bind the events on the `A.FormValidator` UI. Lifecycle.
*
* @method bindUI
* @protected
*/
bindUI: function() {
var instance = this,
boundingBox = instance.get('boundingBox');
var onceFocusHandler = boundingBox.delegate('focus', function() {
instance._setARIARoles();
onceFocusHandler.detach();
}, 'input,select,textarea,button');
instance.publish({
errorField: {
defaultFn: instance._defErrorFieldFn
},
validField: {
defaultFn: instance._defValidFieldFn
},
validateField: {
defaultFn: instance._defValidateFieldFn
}
});
boundingBox.on({
reset: A.bind(instance._onFormReset, instance),
submit: A.bind(instance._onFormSubmit, instance)
});
instance.after({
extractRulesChange: instance._afterExtractRulesChange,
validateOnBlurChange: instance._afterValidateOnBlurChange,
validateOnInputChange: instance._afterValidateOnInputChange
});
},
/**
* Adds a validation error in the field.
*
* @method addFieldError
* @param field
* @param ruleName
*/
addFieldError: function(field, ruleName) {
var instance = this,
errors = instance.errors,
name = field.get('name');
if (!errors[name]) {
errors[name] = [];
}
errors[name].push(ruleName);
},
/**
* Removes a validation error in the field.
*
* @method clearFieldError
* @param field
*/
clearFieldError: function(field) {
var instance = this;
delete instance.errors[field.get('name')];
},
/**
* Executes a function to each rule.
*
* @method eachRule
* @param fn
*/
eachRule: function(fn) {
var instance = this;
A.each(
instance.get('rules'),
function(rule, fieldName) {
if (isFunction(fn)) {
fn.apply(instance, [rule, fieldName]);
}
}
);
},
/**
* Gets the ancestor of a given field.
*
* @method findFieldContainer
* @param field
* @return {Node}
*/
findFieldContainer: function(field) {
var instance = this,
fieldContainer = instance.get('fieldContainer');
if (fieldContainer) {
return field.ancestor(fieldContainer);
}
},
/**
* Focus on the invalid field.
*
* @method focusInvalidField
*/
focusInvalidField: function() {
var instance = this,
boundingBox = instance.get('boundingBox'),
field = boundingBox.one('.' + CSS_HAS_ERROR);
if (field) {
if (instance.get('selectText')) {
field.selectText();
}
field.focus();
field.scrollIntoView();
}
},
/**
* Gets a field from the form.
*
* @method getField
* @param fieldOrFieldName
* @return {Node}
*/
getField: function(fieldOrFieldName) {
var instance = this;
if (isString(fieldOrFieldName)) {
fieldOrFieldName = instance.getFieldsByName(fieldOrFieldName);
if (fieldOrFieldName && fieldOrFieldName.length && !fieldOrFieldName.name) {
fieldOrFieldName = fieldOrFieldName[0];
}
}
return A.one(fieldOrFieldName);
},
/**
* Gets a list of fields based on its name.
*
* @method getFieldsByName
* @param fieldName
* @return {NodeList}
*/
getFieldsByName: function(fieldName) {
var instance = this,
domBoundingBox = instance.get('boundingBox').getDOM();
return domBoundingBox.elements[fieldName];
},
/**
* Gets a list of fields with errors.
*
* @method getFieldError
* @param field
* @return {String}
*/
getFieldError: function(field) {
var instance = this;
return instance.errors[field.get('name')];
},
/**
* Gets the stack error container of a field.
*
* @method getFieldStackErrorContainer
* @param field
*/
getFieldStackErrorContainer: function(field) {
var instance = this,
name = field.get('name'),
stackContainers = instance._stackErrorContainers;
if (!stackContainers[name]) {
stackContainers[name] = instance.get('stackErrorContainer');
}
return stackContainers[name];
},
/**
* Gets the error message of a field.
*
* @method getFieldErrorMessage
* @param field
* @param rule
* @return {String}
*/
getFieldErrorMessage: function(field, rule) {
var instance = this,
fieldName = field.get('name'),
fieldStrings = instance.get('fieldStrings')[fieldName] || {},
fieldRules = instance.get('rules')[fieldName],
strings = instance.get('strings'),
substituteRulesMap = {};
if (rule in fieldRules) {
var ruleValue = A.Array(fieldRules[rule]);
A.each(
ruleValue,
function(value, index) {
substituteRulesMap[index] = [value].join('');
}
);
}
var message = (fieldStrings[rule] || strings[rule] || strings.DEFAULT);
return Lang.sub(message, substituteRulesMap);
},
/**
* Returns `true` if there are errors.
*
* @method hasErrors
* @return {Boolean}
*/
hasErrors: function() {
var instance = this;
return !isEmpty(instance.errors);
},
/**
* Highlights a field with error or success.
*
* @method highlight
* @param field
* @param valid
*/
highlight: function(field, valid) {
var instance = this,
fieldContainer = instance.findFieldContainer(field);
instance._highlightHelper(
field,
instance.get('errorClass'),
instance.get('validClass'),
valid
);
instance._highlightHelper(
fieldContainer,
instance.get('containerErrorClass'),
instance.get('containerValidClass'),
valid
);
},
/**
* Normalizes rule value.
*
* @method normalizeRuleValue
* @param ruleValue
*/
normalizeRuleValue: function(ruleValue) {
var instance = this;
return isFunction(ruleValue) ? ruleValue.apply(instance) : ruleValue;
},
/**
* Removes the highlight of a field.
*
* @method unhighlight
* @param field
*/
unhighlight: function(field) {
var instance = this;
instance.highlight(field, true);
},
/**
* Prints the stack error messages into a container.
*
* @method printStackError
* @param field
* @param container
* @param errors
*/
printStackError: function(field, container, errors) {
var instance = this;
if (!instance.get('showAllMessages')) {
errors = errors.slice(0, 1);
}
container.empty();
A.Array.each(
errors,
function(error) {
var message = instance.getFieldErrorMessage(field, error),
messageEl = instance.get('messageContainer').addClass(error);
container.append(
messageEl.html(message)
);
}
);
},
/**
* Resets the CSS class and content of all fields.
*
* @method resetAllFields
*/
resetAllFields: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
var field = instance.getField(fieldName);
instance.resetField(field);
}
);
},
/**
* Resets the CSS class and content of a field.
*
* @method resetField
* @param field
*/
resetField: function(field) {
var instance = this,
stackContainer = instance.getFieldStackErrorContainer(field);
stackContainer.remove();
instance.resetFieldCss(field);
instance.clearFieldError(field);
},
/**
* Removes the CSS classes of a field.
*
* @method resetFieldCss
* @param field
*/
resetFieldCss: function(field) {
var instance = this,
fieldContainer = instance.findFieldContainer(field);
var removeClasses = function(elem, classAttrs) {
if (elem) {
A.each(classAttrs, function(attrName) {
elem.removeClass(
instance.get(attrName)
);
});
}
};
removeClasses(field, ['validClass', 'errorClass']);
removeClasses(fieldContainer, ['containerValidClass', 'containerErrorClass']);
},
/**
* Checks if a field can be validated or not.
*
* @method validatable
* @param field
* @return {Boolean}
*/
validatable: function(field) {
var instance = this,
validatable = false,
fieldRules = instance.get('rules')[field.get('name')];
if (fieldRules) {
var required = instance.normalizeRuleValue(fieldRules.required);
validatable = (required || (!required && defaults.RULES.required.apply(instance, [field.val(),
field])) || fieldRules.custom);
}
return !!validatable;
},
/**
* Validates all fields.
*
* @method validate
*/
validate: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
instance.validateField(fieldName);
}
);
instance.focusInvalidField();
},
/**
* Validates a single field.
*
* @method validateField
* @param field
*/
validateField: function(field) {
var instance = this,
fieldNode = instance.getField(field);
if (fieldNode) {
var validatable = instance.validatable(fieldNode);
instance.resetField(fieldNode);
if (validatable) {
instance.fire('validateField', {
validator: {
field: fieldNode
}
});
}
}
},
/**
* Fires after `extractRules` attribute change.
*
* @method _afterExtractRulesChange
* @param event
* @protected
*/
_afterExtractRulesChange: function(event) {
var instance = this;
instance._uiSetExtractRules(event.newVal);
},
/**
* Fires after `validateOnInput` attribute change.
*
* @method _afterValidateOnInputChange
* @param event
* @protected
*/
_afterValidateOnInputChange: function(event) {
var instance = this;
instance._uiSetValidateOnInput(event.newVal);
},
/**
* Fires after `validateOnBlur` attribute change.
*
* @method _afterValidateOnBlurChange
* @param event
* @protected
*/
_afterValidateOnBlurChange: function(event) {
var instance = this;
instance._uiSetValidateOnBlur(event.newVal);
},
/**
* Defines an error field.
*
* @method _defErrorFieldFn
* @param event
* @protected
*/
_defErrorFieldFn: function(event) {
var instance = this,
ancestor,
field,
label,
nextSibling,
stackContainer,
target,
validator;
label = instance.get('labelCssClass');
validator = event.validator;
field = validator.field;
instance.highlight(field);
if (instance.get('showMessages')) {
target = field;
stackContainer = instance.getFieldStackErrorContainer(field);
nextSibling = field.get('nextSibling');
if (nextSibling && nextSibling.get('nodeType') === 3) {
ancestor = field.ancestor();
if (ancestor) {
if (ancestor.hasClass(label)) {
target = nextSibling;
}
else if (A.FormValidator.isCheckable(target)) {
label = ancestor.previous('.' + label);
target = label;
}
}
}
target.placeAfter(stackContainer);
instance.printStackError(
field,
stackContainer,
validator.errors
);
}
},
/**
* Defines a valid field.
*
* @method _defValidFieldFn
* @param event
* @protected
*/
_defValidFieldFn: function(event) {
var instance = this;
var field = event.validator.field;
instance.unhighlight(field);
},
/**
* Defines the validation of a field.
*
* @method _defValidateFieldFn
* @param event
* @protected
*/
_defValidateFieldFn: function(event) {
var instance = this;
var field = event.validator.field;
var fieldRules = instance.get('rules')[field.get('name')];
A.each(
fieldRules,
function(ruleValue, ruleName) {
var rule = defaults.RULES[ruleName];
var fieldValue = trim(field.val());
ruleValue = instance.normalizeRuleValue(ruleValue);
if (isFunction(rule) && !rule.apply(instance, [fieldValue, field, ruleValue])) {
instance.addFieldError(field, ruleName);
}
}
);
var fieldErrors = instance.getFieldError(field);
if (fieldErrors) {
instance.fire('errorField', {
validator: {
field: field,
errors: fieldErrors
}
});
}
else {
instance.fire('validField', {
validator: {
field: field
}
});
}
},
/**
* Sets the error/success CSS classes based on the validation of a
* field.
*
* @method _highlightHelper
* @param field
* @param errorClass
* @param validClass
* @param valid
* @protected
*/
_highlightHelper: function(field, errorClass, validClass, valid) {
if (field) {
if (valid) {
field.removeClass(errorClass).addClass(validClass);
}
else {
field.removeClass(validClass).addClass(errorClass);
}
}
},
/**
* Extracts form rules from the DOM.
*
* @method _extractRulesFromMarkup
* @param rules
* @protected
*/
_extractRulesFromMarkup: function(rules) {
var instance = this,
domBoundingBox = instance.get('boundingBox').getDOM(),
elements = domBoundingBox.elements,
defaultRulesKeys = AObject.keys(defaults.RULES),
defaultRulesJoin = defaultRulesKeys.join('|'),
regex = getRegExp('field-(' + defaultRulesJoin + ')', 'g'),
i,
length,
ruleNameMatch = [],
ruleMatcher = function(m1, m2) {
ruleNameMatch.push(m2);
};
for (i = 0, length = elements.length; i < length; i++) {
var el = elements[i],
fieldName = el.name;
el.className.replace(regex, ruleMatcher);
if (ruleNameMatch.length) {
var fieldRules = rules[fieldName],
j,
ruleNameLength;
if (!fieldRules) {
fieldRules = {};
rules[fieldName] = fieldRules;
}
for (j = 0, ruleNameLength = ruleNameMatch.length; j < ruleNameLength; j++) {
var rule = ruleNameMatch[j];
if (!(rule in fieldRules)) {
fieldRules[rule] = true;
}
}
ruleNameMatch.length = 0;
}
}
instance._rulesAlreadyExtracted = true;
},
/**
* Triggers when there's an input in the field.
*
* @method _onFieldInput
* @param event
* @protected
*/
_onFieldInput: function(event) {
var instance = this;
instance.validateField(event.target);
},
/**
* Triggers when the form is submitted.
*
* @method _onFormSubmit
* @param event
* @protected
*/
_onFormSubmit: function(event) {
var instance = this;
var data = {
validator: {
formEvent: event
}
};
instance.validate();
if (instance.hasErrors()) {
data.validator.errors = instance.errors;
instance.fire('submitError', data);
event.halt();
}
else {
instance.fire('submit', data);
}
},
/**
* Triggers when the form is reseted.
*
* @method _onFormReset
* @param event
* @protected
*/
_onFormReset: function() {
var instance = this;
instance.resetAllFields();
},
/**
* Sets the aria roles.
*
* @method _setARIARoles
* @protected
*/
_setARIARoles: function() {
var instance = this;
instance.eachRule(
function(rule, fieldName) {
if (rule.required) {
var field = instance.getField(fieldName);
if (field && !field.attr('aria-required')) {
field.attr('aria-required', true);
}
}
}
);
},
/**
* Sets the `extractRules` attribute on the UI.
*
* @method _uiSetExtractRules
* @param val
* @protected
*/
_uiSetExtractRules: function(val) {
var instance = this;
if (val) {
instance._extractRulesFromMarkup(instance.get('rules'));
}
},
/**
* Sets the `validateOnInput` attribute on the UI.
*
* @method _uiSetValidateOnInput
* @param val
* @protected
*/
_uiSetValidateOnInput: function(val) {
var instance = this,
boundingBox = instance.get('boundingBox');
if (val) {
if (!instance._inputHandlers) {
instance._inputHandlers = boundingBox.delegate('input', instance._onFieldInput,
'input,select,textarea,button', instance);
}
}
else {
if (instance._inputHandlers) {
instance._inputHandlers.detach();
}
}
},
/**
* Sets the `validateOnBlur` attribute on the UI.
*
* @method _uiSetValidateOnBlur
* @param val
* @protected
*/
_uiSetValidateOnBlur: function(val) {
var instance = this,
boundingBox = instance.get('boundingBox');
if (val) {
if (!instance._blurHandlers) {
instance._blurHandlers = boundingBox.delegate('blur', instance._onFieldInput,
'input,select,textarea,button', instance);
}
}
else {
if (instance._blurHandlers) {
instance._blurHandlers.detach();
}
}
}
}
});
A.each(
defaults.REGEX,
function(regex, key) {
defaults.RULES[key] = function(val) {
return defaults.REGEX[key].test(val);
};
}
);
A.FormValidator = FormValidator;
| AUI-1356 focusInvalidField uses the wrong css class to get error field
| src/aui-form-validator/js/aui-form-validator.js | AUI-1356 focusInvalidField uses the wrong css class to get error field | <ide><path>rc/aui-form-validator/js/aui-form-validator.js
<ide> focusInvalidField: function() {
<ide> var instance = this,
<ide> boundingBox = instance.get('boundingBox'),
<del> field = boundingBox.one('.' + CSS_HAS_ERROR);
<add> field = boundingBox.one('.' + CSS_ERROR_FIELD);
<ide>
<ide> if (field) {
<ide> if (instance.get('selectText')) { |
|
Java | bsd-3-clause | 21f88053fb758744b876963801dd6eb4b017a7a1 | 0 | NCIP/camod,NCIP/camod,NCIP/camod,NCIP/camod | package gov.nih.nci.camod.webapp.servlet;
import gov.nih.nci.common.persistence.Search;
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class RedirectOldRequestsServlet extends HttpServlet {
private static final long serialVersionUID = 3257296453788404151L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String theRedirectUrl = request.getContextPath() + "/SimpleSearchPopulateAction.do?unprotected_method=populate";
// Get the modelId attribute. If it's not null, we will map it to
// the new ID and
// forward to the new view page, otherwise we simply send them to
// the search page.
// to the model id page.
String theModelId = request.getParameter("modelId");
if (theModelId != null) {
ResultSet theResultSet = null;
try {
String theSQLString = "select abs_cancer_model_id from abs_cancer_model_tmp where modeluid = ?";
Object[] theParams = new Object[1];
theParams[0] = theModelId;
theResultSet = Search.query(theSQLString, theParams);
if (theResultSet.next()) {
long theNewModelId = theResultSet.getLong(1);
theRedirectUrl = request.getContextPath() + "/ViewModelAction.do?aModelID="
+ Long.toString(theNewModelId) + "&unprotected_method=populateModelCharacteristics";
}
} catch (Exception e) {
// Not able to do anything
} finally {
if (theResultSet != null) {
try {
theResultSet.close();
} catch (Exception e) {
}
}
}
}
response.sendRedirect(theRedirectUrl);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| src/gov/nih/nci/camod/webapp/servlet/RedirectOldRequestsServlet.java | package gov.nih.nci.camod.webapp.servlet;
import gov.nih.nci.common.persistence.Search;
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class RedirectOldRequestsServlet extends HttpServlet {
private static final long serialVersionUID = 3257296453788404151L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String theRedirectUrl = request.getContextPath() + "/searchSimple.do";
// Get the modelId attribute. If it's not null, we will map it to
// the new ID and
// forward to the new view page, otherwise we simply send them to
// the search page.
// to the model id page.
String theModelId = request.getParameter("modelId");
if (theModelId != null) {
ResultSet theResultSet = null;
try {
String theSQLString = "select abs_cancer_model_id from abs_cancer_model_tmp where modeluid = ?";
Object[] theParams = new Object[1];
theParams[0] = theModelId;
theResultSet = Search.query(theSQLString, theParams);
if (theResultSet.next()) {
long theNewModelId = theResultSet.getLong(1);
theRedirectUrl = request.getContextPath() + "/ViewModelAction.do?aModelID="
+ Long.toString(theNewModelId) + "&unprotected_method=populateModelCharacteristics";
}
} catch (Exception e) {
// Not able to do anything
} finally {
if (theResultSet != null) {
try {
theResultSet.close();
} catch (Exception e) {
}
}
}
}
response.sendRedirect(theRedirectUrl);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| Added redirect servlet for mmhcc requests
SVN-Revision: 1519
| src/gov/nih/nci/camod/webapp/servlet/RedirectOldRequestsServlet.java | Added redirect servlet for mmhcc requests | <ide><path>rc/gov/nih/nci/camod/webapp/servlet/RedirectOldRequestsServlet.java
<ide>
<ide> public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
<ide>
<del> String theRedirectUrl = request.getContextPath() + "/searchSimple.do";
<add> String theRedirectUrl = request.getContextPath() + "/SimpleSearchPopulateAction.do?unprotected_method=populate";
<ide>
<ide> // Get the modelId attribute. If it's not null, we will map it to
<ide> // the new ID and |
|
Java | mit | eaefd2d2f1bfb24d8e43af5475c26d5e9b4a21d2 | 0 | games647/ChangeSkin | package com.github.games647.changeskin.core;
import com.github.games647.changeskin.core.model.GameProfile;
import com.github.games647.changeskin.core.model.UUIDTypeAdapter;
import com.github.games647.changeskin.core.model.skin.SkinModel;
import com.github.games647.changeskin.core.model.skin.SkinProperty;
import com.github.games647.changeskin.core.model.skin.TexturesModel;
import com.google.common.collect.Iterables;
import com.google.common.io.CharStreams;
import com.google.common.net.HostAndPort;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import static com.github.games647.changeskin.core.CommonUtil.getConnection;
import static java.util.stream.Collectors.toList;
public class MojangSkinApi {
private static final int RATE_LIMIT_ID = 429;
private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/";
private static final String SKIN_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s" +
"?unsigned=false";
private final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
private final Pattern validNamePattern = Pattern.compile("^\\w{2,16}$");
private final Iterator<Proxy> proxies;
private final Logger logger;
private final int rateLimit;
private final Map<Object, Object> requests = CommonUtil.buildCache(10, -1);
private final Map<UUID, Object> crackedUUID = CommonUtil.buildCache(60, -1);
private Instant lastRateLimit = Instant.now().minus(10, ChronoUnit.MINUTES);
public MojangSkinApi(Logger logger, int rateLimit, Collection<HostAndPort> proxies) {
this.rateLimit = Math.max(rateLimit, 600);
this.logger = logger;
List<Proxy> proxyBuilder = proxies.stream()
.map(proxy -> new InetSocketAddress(proxy.getHostText(), proxy.getPort()))
.map(sa -> new Proxy(Type.HTTP, sa))
.collect(toList());
this.proxies = Iterables.cycle(proxyBuilder).iterator();
}
public Optional<UUID> getUUID(String playerName) throws NotPremiumException, RateLimitException {
logger.debug("Making UUID->Name request for {}", playerName);
if (!validNamePattern.matcher(playerName).matches()) {
throw new NotPremiumException(playerName);
}
Proxy proxy = null;
try {
HttpURLConnection connection;
if (requests.size() >= rateLimit || Duration.between(lastRateLimit, Instant.now()).getSeconds() < 60 * 10) {
synchronized (proxies) {
if (proxies.hasNext()) {
proxy = proxies.next();
connection = getConnection(UUID_URL + playerName, proxy);
} else {
return Optional.empty();
}
}
} else {
requests.put(new Object(), new Object());
connection = getConnection(UUID_URL + playerName);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
throw new NotPremiumException(playerName);
} else if (responseCode == RATE_LIMIT_ID) {
logger.info("Mojang's rate-limit reached. The public IPv4 address of this server issued more than 600" +
" Name -> UUID requests within 10 minutes. Once those 10 minutes ended we could make requests" +
" again. In the meanwhile new skins can only be downloaded using the UUID directly." +
" If you are using BungeeCord, consider adding a caching server in order to prevent multiple" +
" spigot servers creating the same requests against Mojang's servers.");
lastRateLimit = Instant.now();
if (!connection.usingProxy()) {
return getUUID(playerName);
} else {
throw new RateLimitException("Rate-Limit hit on request name->uuid of " + playerName);
}
}
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
GameProfile playerProfile = gson.fromJson(reader, GameProfile.class);
return Optional.of(playerProfile.getId());
}
} else {
logger.error("Received response code: {} for {} using proxy: {}", responseCode, playerName, proxy);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
logger.error("Error stream: {}", CharStreams.toString(reader));
}
}
} catch (IOException ioEx) {
logger.error("Tried converting player name: {} to uuid", playerName, ioEx);
}
return Optional.empty();
}
public Optional<SkinModel> downloadSkin(UUID ownerUUID) {
if (crackedUUID.containsKey(ownerUUID)) {
return Optional.empty();
}
//unsigned is needed in order to receive the signature
String uuidString = UUIDTypeAdapter.toMojangId(ownerUUID);
try {
HttpURLConnection httpConnection = getConnection(String.format(SKIN_URL, uuidString));
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
crackedUUID.put(ownerUUID, new Object());
return Optional.empty();
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8))) {
TexturesModel texturesModel = gson.fromJson(reader, TexturesModel.class);
SkinProperty[] properties = texturesModel.getProperties();
if (properties != null && properties.length > 0) {
SkinProperty propertiesModel = properties[0];
//base64 encoded skin data
String encodedSkin = propertiesModel.getValue();
String signature = propertiesModel.getSignature();
return Optional.of(SkinModel.createSkinFromEncoded(encodedSkin, signature));
}
}
} catch (IOException ex) {
logger.error("Tried downloading skin data of: {} from Mojang", ownerUUID, ex);
}
return Optional.empty();
}
}
| core/src/main/java/com/github/games647/changeskin/core/MojangSkinApi.java | package com.github.games647.changeskin.core;
import com.github.games647.changeskin.core.model.GameProfile;
import com.github.games647.changeskin.core.model.UUIDTypeAdapter;
import com.github.games647.changeskin.core.model.skin.SkinModel;
import com.github.games647.changeskin.core.model.skin.SkinProperty;
import com.github.games647.changeskin.core.model.skin.TexturesModel;
import com.google.common.collect.Iterables;
import com.google.common.net.HostAndPort;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import static com.github.games647.changeskin.core.CommonUtil.getConnection;
import static java.util.stream.Collectors.toList;
public class MojangSkinApi {
private static final int RATE_LIMIT_ID = 429;
private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/";
private static final String SKIN_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s" +
"?unsigned=false";
private final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
private final Pattern validNamePattern = Pattern.compile("^\\w{2,16}$");
private final Iterator<Proxy> proxies;
private final Logger logger;
private final int rateLimit;
private final Map<Object, Object> requests = CommonUtil.buildCache(10, -1);
private final Map<UUID, Object> crackedUUID = CommonUtil.buildCache(60, -1);
private Instant lastRateLimit = Instant.now().minus(10, ChronoUnit.MINUTES);
public MojangSkinApi(Logger logger, int rateLimit, Collection<HostAndPort> proxies) {
this.rateLimit = Math.max(rateLimit, 600);
this.logger = logger;
List<Proxy> proxyBuilder = proxies.stream()
.map(proxy -> new InetSocketAddress(proxy.getHostText(), proxy.getPort()))
.map(sa -> new Proxy(Type.HTTP, sa))
.collect(toList());
this.proxies = Iterables.cycle(proxyBuilder).iterator();
}
public Optional<UUID> getUUID(String playerName) throws NotPremiumException, RateLimitException {
logger.debug("Making UUID->Name request for {}", playerName);
if (!validNamePattern.matcher(playerName).matches()) {
throw new NotPremiumException(playerName);
}
Proxy proxy = null;
try {
HttpURLConnection connection;
if (requests.size() >= rateLimit || Duration.between(lastRateLimit, Instant.now()).getSeconds() < 60 * 10) {
synchronized (proxies) {
if (proxies.hasNext()) {
proxy = proxies.next();
connection = getConnection(UUID_URL + playerName, proxy);
} else {
return Optional.empty();
}
}
} else {
requests.put(new Object(), new Object());
connection = getConnection(UUID_URL + playerName);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
throw new NotPremiumException(playerName);
} else if (responseCode == RATE_LIMIT_ID) {
logger.info("Mojang's rate-limit reached. The public IPv4 address of this server issued more than 600" +
" Name -> UUID requests within 10 minutes. Once those 10 minutes ended we could make requests" +
" again. In the meanwhile new skins can only be downloaded using the UUID directly." +
" If you are using BungeeCord, consider adding a caching server in order to prevent multiple" +
" spigot servers creating the same requests against Mojang's servers.");
lastRateLimit = Instant.now();
if (!connection.usingProxy()) {
return getUUID(playerName);
} else {
throw new RateLimitException("Rate-Limit hit on request name->uuid of " + playerName);
}
}
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
GameProfile playerProfile = gson.fromJson(reader, GameProfile.class);
return Optional.of(playerProfile.getId());
}
} else {
logger.error("Received invalid response code: {} for playername: {} using proxy: {}",
responseCode, playerName, proxy);
}
} catch (IOException ioEx) {
logger.error("Tried converting player name: {} to uuid", playerName, ioEx);
}
return Optional.empty();
}
public Optional<SkinModel> downloadSkin(UUID ownerUUID) {
if (crackedUUID.containsKey(ownerUUID)) {
return Optional.empty();
}
//unsigned is needed in order to receive the signature
String uuidString = UUIDTypeAdapter.toMojangId(ownerUUID);
try {
HttpURLConnection httpConnection = getConnection(String.format(SKIN_URL, uuidString));
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
crackedUUID.put(ownerUUID, new Object());
return Optional.empty();
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8))) {
TexturesModel texturesModel = gson.fromJson(reader, TexturesModel.class);
SkinProperty[] properties = texturesModel.getProperties();
if (properties != null && properties.length > 0) {
SkinProperty propertiesModel = properties[0];
//base64 encoded skin data
String encodedSkin = propertiesModel.getValue();
String signature = propertiesModel.getSignature();
return Optional.of(SkinModel.createSkinFromEncoded(encodedSkin, signature));
}
}
} catch (IOException ex) {
logger.error("Tried downloading skin data of: {} from Mojang", ownerUUID, ex);
}
return Optional.empty();
}
}
| Document error stream content for #113
| core/src/main/java/com/github/games647/changeskin/core/MojangSkinApi.java | Document error stream content for #113 | <ide><path>ore/src/main/java/com/github/games647/changeskin/core/MojangSkinApi.java
<ide> import com.github.games647.changeskin.core.model.skin.SkinProperty;
<ide> import com.github.games647.changeskin.core.model.skin.TexturesModel;
<ide> import com.google.common.collect.Iterables;
<add>import com.google.common.io.CharStreams;
<ide> import com.google.common.net.HostAndPort;
<ide> import com.google.gson.Gson;
<ide> import com.google.gson.GsonBuilder;
<ide> return Optional.of(playerProfile.getId());
<ide> }
<ide> } else {
<del> logger.error("Received invalid response code: {} for playername: {} using proxy: {}",
<del> responseCode, playerName, proxy);
<add> logger.error("Received response code: {} for {} using proxy: {}", responseCode, playerName, proxy);
<add> try (BufferedReader reader = new BufferedReader(
<add> new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
<add> logger.error("Error stream: {}", CharStreams.toString(reader));
<add> }
<ide> }
<ide> } catch (IOException ioEx) {
<ide> logger.error("Tried converting player name: {} to uuid", playerName, ioEx); |
|
Java | apache-2.0 | ea272c81ee5668080abb719be35edee1a341fab1 | 0 | PedroGomes/TPCw-benchmark | /*
* *********************************************************************
* Copyright (c) 2010 Pedro Gomes and Universidade do Minho.
* All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ********************************************************************
*/
package org.uminho.gsd.benchmarks.benchmark;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.uminho.gsd.benchmarks.helpers.JsonUtil;
import org.uminho.gsd.benchmarks.interfaces.executor.AbstractDatabaseExecutorFactory;
import org.uminho.gsd.benchmarks.interfaces.populator.AbstractBenchmarkPopulator;
import java.io.*;
import java.util.Map;
import java.util.Map.Entry;
public class BenchmarkMain {
private static Logger logger = Logger.getLogger(BenchmarkMain.class);
public static double distribution_factor = -1;
public static long thinkTime = -1;
private BenchmarkExecutor executor;
private String populatorClass;
private Class worload;
private Class databaseExecutor;
private AbstractBenchmarkPopulator populator;
private static BenchmarkNodeID id;
//Files
private String populator_conf;
private String executor_conf;
private String workload_conf;
private static int SlavePort;
private int number_threads;
private int operation_number;
private Map<String, Object> benchmarkExecutorSlaves;
public static void main(String[] args) {
boolean populate = false;//Populate
boolean cleanDB = false; //Full clean
boolean cleanFB = false; //Clean for benchmark execution
boolean slave = false;
boolean master = false;
boolean ocp = false; //only clean and populate
String workload_alias = "";
String database_alias = "";
int num_thread = -1;
int num_operations = -1;
double distributionFactor = -1;
initLogger();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equalsIgnoreCase("-w")) {
if ((i + 1) != args.length) {
workload_alias = args[i + 1].trim().toLowerCase();
i++;
} else {
System.out.println("[ERROR:] Workload alias option doesn't contain associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-d")) {
if ((i + 1) != args.length) {
database_alias = args[i + 1].trim().toLowerCase();
i++;
} else {
System.out.println("[ERROR:] Data alias option doesn't contain associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-t")) {
if ((i + 1) != args.length) {
try {
num_thread = Integer.parseInt(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the number of threads");
return;
}
i++;
} else {
System.out.println("[ERROR:] Thread number option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-o")) {
if ((i + 1) != args.length) {
try {
num_operations = Integer.parseInt(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the number of operations");
return;
}
i++;
} else {
System.out.println("[ERROR:] Operation number option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-df")) {
if ((i + 1) != args.length) {
try {
distributionFactor = Double.parseDouble(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the distribution factor");
return;
}
i++;
} else {
System.out.println("[ERROR:] Distribution factor option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-tt")) {
if ((i + 1) != args.length) {
try {
thinkTime = Long.parseLong(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the think time");
return;
}
i++;
} else {
System.out.println("[ERROR:] The think time option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-cb")) {
cleanFB = true;
} else if (arg.equalsIgnoreCase("-p")) {
populate = true;
} else if (arg.equalsIgnoreCase("-pop")) {
ocp = true;
} else if (arg.equalsIgnoreCase("-c")) {
cleanDB = true;
} else if (arg.equalsIgnoreCase("-h")) {
System.out.println(">>Available options:");
System.out.println("------------------------------------------------------");
System.out.println(" -w <Workload alias> : a defined workload alias ");
System.out.println(" -d <Database alias> : a defined database alias ");
System.out.println(" -t <Num Threads> : number of executing threads ");
System.out.println(" -o <Num Operations> : number of operations to be executed per thread ");
System.out.println(" -df <distribution factor> : a distribution factor that influences the power law skew on product selection");
System.out.println(" -tt <time milliseconds> : override the default TPC-W think time to the defined value");
System.out.println("------------------------------------------------------");
System.out.println(" -c : clean the database");
System.out.println(" -cb : special clean (outdated)");
System.out.println(" -p : populate");
System.out.println(" -pop : populate and return (can be used with -c) ");
System.out.println("------------------------------------------------------");
System.out.println(" -m : run as master");
System.out.println(" -s <port> : run as slave in the defined port");
return;
} else if (arg.equalsIgnoreCase("-s")) {
slave = true;
if ((i + 1) != args.length) {
try {
SlavePort = Integer.parseInt(args[i + 1]);
} catch (Exception e) {
System.out.println("[ERROR:] ERROR PARSING SLAVE PORT");
return;
}
i++;
} else {
System.out.println("[ERROR:] SLAVE WITH NO AVAILABLE PORT");
return;
}
if (cleanDB || populate) {
logger.debug("SLAVE DOES NOT ALLOW CLEAN OR POPULATION OPTIONS ");
}
} else if (arg.equalsIgnoreCase("-m")) {
master = true;
} else {
System.out.println("[WARNING:] OPTION NOT RECOGNIZED: " + arg);
}
}
new BenchmarkMain(master, slave, cleanDB, cleanFB, populate, ocp, workload_alias, database_alias, num_thread, num_operations, distributionFactor);
}
public BenchmarkMain(boolean master, boolean slave, boolean cleanDB, boolean cleanFB, boolean populateDatabase, boolean cap,
String workload, String database, int thread_number, int operation_number, double distribution_fact) {
distribution_factor = distribution_fact;
boolean success = loadDescriptor(workload, database, thread_number, operation_number);
if (!success) {
logger.fatal("ERROR LOADING FILE");
return;
}
try {
run(master, slave, cleanDB, cleanFB, populateDatabase, cap);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void run(boolean master, boolean slave, boolean cleanDB, boolean cleanFB, boolean populate, boolean cap) throws Exception {
//to avoid extra instantiations.
// if(cap || populate || cleanFB || cleanFB){
populator = (AbstractBenchmarkPopulator) Class.forName(populatorClass).getConstructor(AbstractDatabaseExecutorFactory.class, String.class).newInstance(executor.getDatabaseInterface(), populator_conf);
// }
if (slave) {
BenchmarkSlave slaveHandler = new BenchmarkSlave(SlavePort, executor);
slaveHandler.run();
} else {
if (cleanDB) {
populator.cleanDB();
}
if (cap) {
populator.populate();
return;
}
if (populate) {
boolean population_success = populator.populate();
if(!population_success) {
return;
}
}
if (cleanFB) {
if (cleanDB && populate) {
logger.info("[INFO:] BENCHMARK CLEANING IS UNNECESSARY, IGNORED");
} else {
populator.BenchmarkClean();
}
}
if (!populate && cleanDB) {
// logger.fatal("THE DATABASE IS PROBABLY EMPTY, ABORTING");
return;
}
if (master) {//master, signal slaves
logger.info("[INFO:] EXECUTING IN MASTER MODE");
BenchmarkMaster masterHandler = new BenchmarkMaster(executor, benchmarkExecutorSlaves);
masterHandler.run();
} else { //single node run
logger.info("[INFO:] EXECUTING IN SINGLE NODE MODE");
executor.prepare();
executor.run(new BenchmarkNodeID(1));
executor.consolidate();
}
}
}
public boolean loadDescriptor(String work_alias, String data_alias, int num_threads, int num_operations) {
try {
FileInputStream in = null;
String jsonString_r = "";
try {
in = new FileInputStream("conf/Benchmark.json");
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String s = "";
StringBuilder sb = new StringBuilder();
while (s != null) {
sb.append(s);
s = bin.readLine();
}
jsonString_r = sb.toString().replace("\n", "");
bin.close();
in.close();
} catch (FileNotFoundException ex) {
logger.error("", ex);
} catch (IOException ex) {
logger.error("", ex);
} finally {
try {
in.close();
} catch (IOException ex) {
logger.error("", ex);
}
}
Map<String, Map<String, Object>> map = JsonUtil.getMapMapFromJsonString(jsonString_r);
Map<String, Object> info = map.get("BenchmarkInfo");
if (!map.containsKey("BenchmarkInterfaces")) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE FOUND, ABORTING");
return false;
}
if (!map.containsKey("BenchmarkInfo")) {
logger.fatal("[ERROR] NO CONFIGURATION FILES INFO FOUND");
return false;
}
Map<String, Object> databaseInfo = map.get("BenchmarkInterfaces");
String databaseClass = "";
populatorClass = "";
if (data_alias == null || data_alias.isEmpty()) {
databaseClass = (String) databaseInfo.get("DataEngineInterface");
if (databaseClass == null || databaseClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE EXECUTOR");
return false;
}
logger.info("DEFAULT CHOSEN DATABASE ENGINE: " + databaseClass);
populatorClass = (String) databaseInfo.get("BenchmarkPopulator");
if (populatorClass == null || populatorClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE POPULATOR");
return false;
}
logger.debug("DEFAULT CHOSEN BENCHMARK POPULATOR: " + populatorClass);
executor_conf = (String) info.get("databaseExecutorConfiguration");
if (executor_conf == null || executor_conf.isEmpty()) {
logger.fatal("[ERROR:] NO DEFAULT CONFIGURATION FILE FOR DATABASE EXECUTOR");
return false;
}
} else {
if (!map.containsKey("Database_alias")) {
logger.fatal("No available data alias");
return false;
}
Map<String,Object> database_alias = map.get("Database_alias");
if (!database_alias.containsKey(data_alias)) {
logger.fatal("Data alias " + data_alias + " does not exists");
return false;
}
Map<String, String> alias_info = (Map<String, String>) database_alias.get(data_alias);
// Map<String, String> alias_info = JsonUtil.getMapFromJsonString(alias);
databaseClass = alias_info.get("DataEngineInterface");
if (databaseClass == null || databaseClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE EXECUTOR");
return false;
}
logger.info("CHOSEN DATABASE ENGINE FROM ALIAS: " + databaseClass);
populatorClass = alias_info.get("BenchmarkPopulator");
if (populatorClass == null || populatorClass.isEmpty()) {
logger.debug("[ERROR:] NO INFORMATION ABOUT THE POPULATOR");
return false;
}
logger.debug("CHOSEN BENCHMARK POPULATOR FROM ALIAS: " + populatorClass);
executor_conf = alias_info.get("databaseExecutorConfiguration");
if (executor_conf == null || executor_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR DATABASE EXECUTOR ON ALIAS: " + data_alias);
return false;
}
}
databaseExecutor = Class.forName(databaseClass);
String benchmarkWorkloadClass = "";
if (work_alias == null || work_alias.isEmpty()) {
benchmarkWorkloadClass = (String) databaseInfo.get("BenchmarkWorkload");
if (benchmarkWorkloadClass == null || benchmarkWorkloadClass.isEmpty()) {
logger.debug("[ERROR:] NO INFORMATION ABOUT THE WORKLOAD GENERATOR ON DEFAULT INFO");
return false;
}
workload_conf = (String) info.get("workloadConfiguration");
if (workload_conf == null || workload_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR WORKLOAD ON DEFAULT INFO");
return false;
}
} else {
if (!map.containsKey("Workload_alias")) {
logger.fatal("No available workload alias");
return false;
}
Map<String, Object> workload_alias = map.get("Workload_alias");
if (!workload_alias.containsKey(work_alias)) {
logger.fatal("Workload alias " + work_alias + " does not exists");
return false;
}
Map<String, String> alias_info = (Map<String, String>) workload_alias.get(work_alias);
// Map<String, String> alias_info = JsonUtil.getMapFromJsonString(alias);
benchmarkWorkloadClass = alias_info.get("BenchmarkWorkload");
if (benchmarkWorkloadClass == null || benchmarkWorkloadClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE WORKLOAD GENERATOR ON ALIAS " + work_alias);
return false;
}
workload_conf = alias_info.get("workloadConfiguration");
if (workload_conf == null || workload_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR WORKLOAD ON ALIAS " + work_alias);
return false;
}
}
worload = Class.forName(benchmarkWorkloadClass);
populator_conf = (String) info.get("populatorConfiguration");
if (populator_conf == null || populator_conf.isEmpty()) {
logger.debug("[ERROR:] NO CONFIGURATION FILE FOR POPULATOR");
return false;
}
if (num_threads == -1) {
if (!info.containsKey("thread_number")) {
number_threads = 1;
logger.warn("[WARNING:] ONE THREAD USED WHEN EXECUTING");
} else {
number_threads = Integer.parseInt((String) info.get("thread_number"));
}
} else {
number_threads = num_threads;
}
if (num_operations == -1) {
if (!info.containsKey("operation_number")) {
operation_number = 1000;
logger.debug("[WARNING:] 1000 OPERATION EXECUTED AS DEFAULT");
} else {
operation_number = Integer.parseInt((String) info.get("operation_number"));
logger.debug("[INFO:] NUMBER OF OPERATIONS -> " + operation_number);
}
} else {
operation_number = num_operations;
}
if (!map.containsKey("BenchmarkSlaves")) {
logger.debug("[WARNING:] NO SLAVES DEFINED");
} else {
Map<String, Object> slave_info = map.get("BenchmarkSlaves");
for(Entry<String,Object> slave : slave_info.entrySet() ){
System.out.println("Running Slave: "+slave.getKey() + " : "+slave.getValue().toString());
}
System.out.println();
benchmarkExecutorSlaves = slave_info;
}
System.out.println(">>Selected Database: " +databaseClass);
System.out.println(">>Selected Workload class: " +worload.getSimpleName());
System.out.println(">>Selected Workload configuration file: " +workload_conf);
System.out.println(">>Selected Populator: "+populatorClass);
System.out.println("-------------------------------------");
System.out.println(">>Num Threads: " +num_threads);
System.out.println(">>Num Operations: "+num_operations);
System.out.println("-------------------------------------");
System.out.println(">>Think Time: "+thinkTime);
System.out.println(">>Distribution factor: "+distribution_factor);
executor = new BenchmarkExecutor(worload, workload_conf, databaseExecutor, executor_conf, operation_number, number_threads);
return true;
} catch (ClassNotFoundException ex) {
logger.error("", ex);
}
logger.debug("ERROR: THERE IS SOME PROBLEM WITH THE DEFINITIONS FILE OR THE LOADED INTERFACES");
return false;
}
public static void initLogger() {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);//INFO
}
}
| src/org/uminho/gsd/benchmarks/benchmark/BenchmarkMain.java | /*
* *********************************************************************
* Copyright (c) 2010 Pedro Gomes and Universidade do Minho.
* All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ********************************************************************
*/
package org.uminho.gsd.benchmarks.benchmark;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.uminho.gsd.benchmarks.helpers.JsonUtil;
import org.uminho.gsd.benchmarks.interfaces.executor.AbstractDatabaseExecutorFactory;
import org.uminho.gsd.benchmarks.interfaces.populator.AbstractBenchmarkPopulator;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class BenchmarkMain {
private static Logger logger = Logger.getLogger(BenchmarkMain.class);
public static double distribution_factor = -1;
public static long thinkTime = -1;
private BenchmarkExecutor executor;
private String populatorClass;
private Class worload;
private Class databaseExecutor;
private AbstractBenchmarkPopulator populator;
private static BenchmarkNodeID id;
//Files
private String populator_conf;
private String executor_conf;
private String workload_conf;
private static int SlavePort;
private int number_threads;
private int operation_number;
private Map<String, Object> benchmarkExecutorSlaves;
public static void main(String[] args) {
boolean populate = false;//Populate
boolean cleanDB = false; //Full clean
boolean cleanFB = false; //Clean for benchmark execution
boolean slave = false;
boolean master = false;
boolean ocp = false; //only clean and populate
String workload_alias = "";
String database_alias = "";
int num_thread = -1;
int num_operations = -1;
double distributionFactor = -1;
initLogger();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equalsIgnoreCase("-w")) {
if ((i + 1) != args.length) {
workload_alias = args[i + 1].trim().toLowerCase();
i++;
} else {
System.out.println("[ERROR:] Workload alias option doesn't contain associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-d")) {
if ((i + 1) != args.length) {
database_alias = args[i + 1].trim().toLowerCase();
i++;
} else {
System.out.println("[ERROR:] Data alias option doesn't contain associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-t")) {
if ((i + 1) != args.length) {
try {
num_thread = Integer.parseInt(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the number of threads");
return;
}
i++;
} else {
System.out.println("[ERROR:] Thread number option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-o")) {
if ((i + 1) != args.length) {
try {
num_operations = Integer.parseInt(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the number of operations");
return;
}
i++;
} else {
System.out.println("[ERROR:] Operation number option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-df")) {
if ((i + 1) != args.length) {
try {
distributionFactor = Double.parseDouble(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the distribution factor");
return;
}
i++;
} else {
System.out.println("[ERROR:] Distribution factor option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-tt")) {
if ((i + 1) != args.length) {
try {
thinkTime = Long.parseLong(args[i + 1].trim());
} catch (Exception e) {
System.out.println("[ERROR:] An error occurred when parsing the think time");
return;
}
i++;
} else {
System.out.println("[ERROR:] The think time option doesn't contain the associated parameter");
return;
}
}
else if (arg.equalsIgnoreCase("-cb")) {
cleanFB = true;
} else if (arg.equalsIgnoreCase("-p")) {
populate = true;
} else if (arg.equalsIgnoreCase("-pop")) {
ocp = true;
} else if (arg.equalsIgnoreCase("-c")) {
cleanDB = true;
} else if (arg.equalsIgnoreCase("-h")) {
System.out.println(">>Available options:");
System.out.println("------------------------------------------------------");
System.out.println(" -w <Workload alias> : a defined workload alias ");
System.out.println(" -d <Database alias> : a defined database alias ");
System.out.println(" -t <Num Threads> : number of executing threads ");
System.out.println(" -o <Num Operations> : number of operations to be executed per thread ");
System.out.println(" -df <distribution factor> : a distribution factor that influences the power law skew on product selection");
System.out.println(" -tt <time milliseconds> : override the default TPC-W think time to the defined value");
System.out.println("------------------------------------------------------");
System.out.println(" -c : clean the database");
System.out.println(" -cb : special clean (outdated)");
System.out.println(" -p : populate");
System.out.println(" -pop : populate and return (can be used with -c) ");
System.out.println("------------------------------------------------------");
System.out.println(" -m : run as master");
System.out.println(" -s <port> : run as slave in the defined port");
return;
} else if (arg.equalsIgnoreCase("-s")) {
slave = true;
if ((i + 1) != args.length) {
try {
SlavePort = Integer.parseInt(args[i + 1]);
} catch (Exception e) {
System.out.println("[ERROR:] ERROR PARSING SLAVE PORT");
return;
}
i++;
} else {
System.out.println("[ERROR:] SLAVE WITH NO AVAILABLE PORT");
return;
}
if (cleanDB || populate) {
logger.debug("SLAVE DOES NOT ALLOW CLEAN OR POPULATION OPTIONS ");
}
} else if (arg.equalsIgnoreCase("-m")) {
master = true;
} else {
System.out.println("[WARNING:] OPTION NOT RECOGNIZED: " + arg);
}
}
new BenchmarkMain(master, slave, cleanDB, cleanFB, populate, ocp, workload_alias, database_alias, num_thread, num_operations, distributionFactor);
}
public BenchmarkMain(boolean master, boolean slave, boolean cleanDB, boolean cleanFB, boolean populateDatabase, boolean cap,
String workload, String database, int thread_number, int operation_number, double distribution_fact) {
distribution_factor = distribution_fact;
boolean success = loadDescriptor(workload, database, thread_number, operation_number);
if (!success) {
logger.fatal("ERROR LOADING FILE");
return;
}
try {
run(master, slave, cleanDB, cleanFB, populateDatabase, cap);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void run(boolean master, boolean slave, boolean cleanDB, boolean cleanFB, boolean populate, boolean cap) throws Exception {
//to avoid extra instantiations.
// if(cap || populate || cleanFB || cleanFB){
populator = (AbstractBenchmarkPopulator) Class.forName(populatorClass).getConstructor(AbstractDatabaseExecutorFactory.class, String.class).newInstance(executor.getDatabaseInterface(), populator_conf);
// }
if (slave) {
BenchmarkSlave slaveHandler = new BenchmarkSlave(SlavePort, executor);
slaveHandler.run();
} else {
if (cleanDB) {
populator.cleanDB();
}
if (cap) {
populator.populate();
return;
}
if (populate) {
boolean population_success = populator.populate();
if(!population_success) {
return;
}
}
if (cleanFB) {
if (cleanDB && populate) {
logger.info("[INFO:] BENCHMARK CLEANING IS UNNECESSARY, IGNORED");
} else {
populator.BenchmarkClean();
}
}
if (!populate && cleanDB) {
logger.fatal("THE DATABASE IS PROBABLY EMPTY, ABORTING");
return;
}
if (master) {//master, signal slaves
logger.info("[INFO:] EXECUTING IN MASTER MODE");
BenchmarkMaster masterHandler = new BenchmarkMaster(executor, benchmarkExecutorSlaves);
masterHandler.run();
} else { //single node run
logger.info("[INFO:] EXECUTING IN SINGLE NODE MODE");
executor.prepare();
executor.run(new BenchmarkNodeID(1));
executor.consolidate();
}
}
}
public boolean loadDescriptor(String work_alias, String data_alias, int num_threads, int num_operations) {
try {
FileInputStream in = null;
String jsonString_r = "";
try {
in = new FileInputStream("conf/Benchmark.json");
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String s = "";
StringBuilder sb = new StringBuilder();
while (s != null) {
sb.append(s);
s = bin.readLine();
}
jsonString_r = sb.toString().replace("\n", "");
bin.close();
in.close();
} catch (FileNotFoundException ex) {
logger.error("", ex);
} catch (IOException ex) {
logger.error("", ex);
} finally {
try {
in.close();
} catch (IOException ex) {
logger.error("", ex);
}
}
Map<String, Map<String, Object>> map = JsonUtil.getMapMapFromJsonString(jsonString_r);
Map<String, Object> info = map.get("BenchmarkInfo");
if (!map.containsKey("BenchmarkInterfaces")) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE FOUND, ABORTING");
return false;
}
if (!map.containsKey("BenchmarkInfo")) {
logger.fatal("[ERROR] NO CONFIGURATION FILES INFO FOUND");
return false;
}
Map<String, Object> databaseInfo = map.get("BenchmarkInterfaces");
String databaseClass = "";
populatorClass = "";
if (data_alias == null || data_alias.isEmpty()) {
databaseClass = (String) databaseInfo.get("DataEngineInterface");
if (databaseClass == null || databaseClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE EXECUTOR");
return false;
}
logger.info("DEFAULT CHOSEN DATABASE ENGINE: " + databaseClass);
populatorClass = (String) databaseInfo.get("BenchmarkPopulator");
if (populatorClass == null || populatorClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE POPULATOR");
return false;
}
logger.debug("DEFAULT CHOSEN BENCHMARK POPULATOR: " + populatorClass);
executor_conf = (String) info.get("databaseExecutorConfiguration");
if (executor_conf == null || executor_conf.isEmpty()) {
logger.fatal("[ERROR:] NO DEFAULT CONFIGURATION FILE FOR DATABASE EXECUTOR");
return false;
}
} else {
if (!map.containsKey("Database_alias")) {
logger.fatal("No available data alias");
return false;
}
Map<String,Object> database_alias = map.get("Database_alias");
if (!database_alias.containsKey(data_alias)) {
logger.fatal("Data alias " + data_alias + " does not exists");
return false;
}
Map<String, String> alias_info = (Map<String, String>) database_alias.get(data_alias);
// Map<String, String> alias_info = JsonUtil.getMapFromJsonString(alias);
databaseClass = alias_info.get("DataEngineInterface");
if (databaseClass == null || databaseClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE DATA ENGINE EXECUTOR");
return false;
}
logger.info("CHOSEN DATABASE ENGINE FROM ALIAS: " + databaseClass);
populatorClass = alias_info.get("BenchmarkPopulator");
if (populatorClass == null || populatorClass.isEmpty()) {
logger.debug("[ERROR:] NO INFORMATION ABOUT THE POPULATOR");
return false;
}
logger.debug("CHOSEN BENCHMARK POPULATOR FROM ALIAS: " + populatorClass);
executor_conf = alias_info.get("databaseExecutorConfiguration");
if (executor_conf == null || executor_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR DATABASE EXECUTOR ON ALIAS: " + data_alias);
return false;
}
}
databaseExecutor = Class.forName(databaseClass);
String benchmarkWorkloadClass = "";
if (work_alias == null || work_alias.isEmpty()) {
benchmarkWorkloadClass = (String) databaseInfo.get("BenchmarkWorkload");
if (benchmarkWorkloadClass == null || benchmarkWorkloadClass.isEmpty()) {
logger.debug("[ERROR:] NO INFORMATION ABOUT THE WORKLOAD GENERATOR ON DEFAULT INFO");
return false;
}
workload_conf = (String) info.get("workloadConfiguration");
if (workload_conf == null || workload_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR WORKLOAD ON DEFAULT INFO");
return false;
}
} else {
if (!map.containsKey("Workload_alias")) {
logger.fatal("No available workload alias");
return false;
}
Map<String, Object> workload_alias = map.get("Workload_alias");
if (!workload_alias.containsKey(work_alias)) {
logger.fatal("Workload alias " + work_alias + " does not exists");
return false;
}
Map<String, String> alias_info = (Map<String, String>) workload_alias.get(work_alias);
// Map<String, String> alias_info = JsonUtil.getMapFromJsonString(alias);
benchmarkWorkloadClass = alias_info.get("BenchmarkWorkload");
if (benchmarkWorkloadClass == null || benchmarkWorkloadClass.isEmpty()) {
logger.fatal("[ERROR:] NO INFORMATION ABOUT THE WORKLOAD GENERATOR ON ALIAS " + work_alias);
return false;
}
workload_conf = alias_info.get("workloadConfiguration");
if (workload_conf == null || workload_conf.isEmpty()) {
logger.fatal("[ERROR:] NO CONFIGURATION FILE FOR WORKLOAD ON ALIAS " + work_alias);
return false;
}
}
worload = Class.forName(benchmarkWorkloadClass);
populator_conf = (String) info.get("populatorConfiguration");
if (populator_conf == null || populator_conf.isEmpty()) {
logger.debug("[ERROR:] NO CONFIGURATION FILE FOR POPULATOR");
return false;
}
if (num_threads == -1) {
if (!info.containsKey("thread_number")) {
number_threads = 1;
logger.warn("[WARNING:] ONE THREAD USED WHEN EXECUTING");
} else {
number_threads = Integer.parseInt((String) info.get("thread_number"));
}
} else {
number_threads = num_threads;
}
if (num_operations == -1) {
if (!info.containsKey("operation_number")) {
operation_number = 1000;
logger.debug("[WARNING:] 1000 OPERATION EXECUTED AS DEFAULT");
} else {
operation_number = Integer.parseInt((String) info.get("operation_number"));
logger.debug("[INFO:] NUMBER OF OPERATIONS -> " + operation_number);
}
} else {
operation_number = num_operations;
}
if (!map.containsKey("BenchmarkSlaves")) {
logger.debug("[WARNING:] NO SLAVES DEFINED");
} else {
Map<String, Object> slave_info = map.get("BenchmarkSlaves");
for(Entry<String,Object> slave : slave_info.entrySet() ){
System.out.println("Running Slave: "+slave.getKey() + " : "+slave.getValue().toString());
}
System.out.println();
benchmarkExecutorSlaves = slave_info;
}
System.out.println(">>Selected Database: " +databaseClass);
System.out.println(">>Selected Workload class: " +worload.getSimpleName());
System.out.println(">>Selected Workload configuration file: " +workload_conf);
System.out.println(">>Selected Populator: "+populatorClass);
System.out.println("-------------------------------------");
System.out.println(">>Num Threads: " +num_threads);
System.out.println(">>Num Operations: "+num_operations);
System.out.println("-------------------------------------");
System.out.println(">>Think Time: "+thinkTime);
System.out.println(">>Distribution factor: "+distribution_factor);
executor = new BenchmarkExecutor(worload, workload_conf, databaseExecutor, executor_conf, operation_number, number_threads);
return true;
} catch (ClassNotFoundException ex) {
logger.error("", ex);
}
logger.debug("ERROR: THERE IS SOME PROBLEM WITH THE DEFINITIONS FILE OR THE LOADED INTERFACES");
return false;
}
public static void initLogger() {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);//INFO
}
}
| Removed bad warning when only cleaning
| src/org/uminho/gsd/benchmarks/benchmark/BenchmarkMain.java | Removed bad warning when only cleaning | <ide><path>rc/org/uminho/gsd/benchmarks/benchmark/BenchmarkMain.java
<ide> import org.uminho.gsd.benchmarks.interfaces.populator.AbstractBenchmarkPopulator;
<ide>
<ide> import java.io.*;
<del>import java.lang.reflect.InvocationTargetException;
<del>import java.util.Iterator;
<ide> import java.util.Map;
<ide> import java.util.Map.Entry;
<ide>
<ide> }
<ide>
<ide> if (!populate && cleanDB) {
<del> logger.fatal("THE DATABASE IS PROBABLY EMPTY, ABORTING");
<add> // logger.fatal("THE DATABASE IS PROBABLY EMPTY, ABORTING");
<ide> return;
<ide> }
<ide> |
|
Java | apache-2.0 | 85e8407a8cedf8031c117fdec0d82b98d68fd56f | 0 | realityforge/replicant,realityforge/replicant | package replicant;
import arez.Disposable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.intellij.lang.annotations.Language;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import replicant.messages.ChangeSet;
import replicant.messages.ChannelChange;
import replicant.messages.EntityChange;
import replicant.messages.EntityChangeData;
import replicant.messages.EntityChannel;
import replicant.spy.AreaOfInterestStatusUpdatedEvent;
import replicant.spy.ConnectFailureEvent;
import replicant.spy.ConnectedEvent;
import replicant.spy.DisconnectFailureEvent;
import replicant.spy.DisconnectedEvent;
import replicant.spy.InSyncEvent;
import replicant.spy.MessageProcessFailureEvent;
import replicant.spy.MessageProcessedEvent;
import replicant.spy.MessageReadFailureEvent;
import replicant.spy.OutOfSyncEvent;
import replicant.spy.RestartEvent;
import replicant.spy.SubscribeCompletedEvent;
import replicant.spy.SubscribeFailedEvent;
import replicant.spy.SubscribeRequestQueuedEvent;
import replicant.spy.SubscribeStartedEvent;
import replicant.spy.SubscriptionCreatedEvent;
import replicant.spy.SubscriptionDisposedEvent;
import replicant.spy.SubscriptionUpdateCompletedEvent;
import replicant.spy.SubscriptionUpdateFailedEvent;
import replicant.spy.SubscriptionUpdateRequestQueuedEvent;
import replicant.spy.SubscriptionUpdateStartedEvent;
import replicant.spy.SyncFailureEvent;
import replicant.spy.SyncRequestEvent;
import replicant.spy.UnsubscribeCompletedEvent;
import replicant.spy.UnsubscribeFailedEvent;
import replicant.spy.UnsubscribeRequestQueuedEvent;
import replicant.spy.UnsubscribeStartedEvent;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
@SuppressWarnings( { "NonJREEmulationClassesInClientCode", "Duplicates" } )
public class ConnectorTest
extends AbstractReplicantTest
{
@Test
public void construct()
throws Exception
{
final Disposable schedulerLock = pauseScheduler();
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema =
new SystemSchema( ValueUtil.randomInt(),
ValueUtil.randomString(),
new ChannelSchema[ 0 ],
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
assertEquals( connector.getSchema(), schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantRuntime(), runtime );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), true );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
schedulerLock.dispose();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void dispose()
{
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), true );
Disposable.dispose( connector );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), false );
}
@Test
public void testToString()
throws Exception
{
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
assertEquals( connector.toString(), "Connector[" + schema.getName() + "]" );
ReplicantTestUtil.disableNames();
assertEquals( connector.toString(), "replicant.Arez_Connector@" + Integer.toHexString( connector.hashCode() ) );
}
@Test
public void setConnection_whenConnectorProcessingMessage()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 0 );
final Subscription subscription = createSubscription( address, null, true );
connector.onConnection( ValueUtil.randomString() );
// Connection not swapped yet but will do one MessageProcess completes
assertEquals( Disposable.isDisposed( subscription ), false );
assertEquals( connector.getConnection(), connection );
assertNotNull( connector.getPostMessageResponseAction() );
}
@Test
public void setConnection_whenExistingConnection()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
connector.recordLastRxRequestId( ValueUtil.randomInt() );
connector.recordLastTxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncRxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncTxRequestId( ValueUtil.randomInt() );
connector.recordSyncInFlight( true );
connector.recordPendingResponseQueueEmpty( false );
assertEquals( Disposable.isDisposed( connection ), false );
assertEquals( connector.getConnection(), connection );
final String newConnectionId = ValueUtil.randomString();
connector.onConnection( newConnectionId );
assertEquals( Disposable.isDisposed( connection ), true );
assertEquals( connector.ensureConnection().getConnectionId(), newConnectionId );
safeAction( () -> assertEquals( connector.getLastRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastTxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncTxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
}
@Test
public void connect()
{
pauseScheduler();
final Connector connector = createConnector();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
safeAction( connector::connect );
verify( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void connect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) );
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::connect ) );
assertEquals( actual, exception );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void transportDisconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.transportDisconnect();
verify( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( connector::disconnect );
verify( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
verify( connector.getTransport(), never() ).unbind();
}
@Test
public void disconnect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::disconnect ) );
assertEquals( actual, exception );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
reset( connector.getTransport() );
connector.onDisconnected();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.DISCONNECTED ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onDisconnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onDisconnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onConnected()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = new Connection( connector, ValueUtil.randomString() );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
final Field field = Connector.class.getDeclaredField( "_connection" );
field.setAccessible( true );
field.set( connector, connection );
connector.onConnected();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTED ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTED ) );
verify( connector.getTransport() ).bind( connection.getTransportContext(), Replicant.context() );
}
@Test
public void onConnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onConnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onConnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onConnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReceived()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final String rawJsonData = ValueUtil.randomString();
pauseScheduler();
connector.pauseMessageScheduler();
assertEquals( connection.getUnparsedResponses().size(), 0 );
assertEquals( connector.isSchedulerActive(), false );
connector.onMessageReceived( rawJsonData );
assertEquals( connection.getUnparsedResponses().size(), 1 );
assertEquals( connection.getUnparsedResponses().get( 0 ).getRawJsonData(), rawJsonData );
assertEquals( connector.isSchedulerActive(), true );
}
@Test
public void onMessageProcessed()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final MessageResponse response = new MessageResponse( "" );
response.recordChangeSet( ChangeSet.create( 47, null, null ), null );
connector.onMessageProcessed( response );
verify( connector.getTransport() ).onMessageProcessed();
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getDataLoadStatus().getSequence(), 47 );
} );
}
@Test
public void onMessageProcessFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageProcessFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageProcessFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageProcessFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void disconnectIfPossible()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnectIfPossible_noActionAsConnecting()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 0 );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void disconnectIfPossible_generatesSpyEvent()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( RestartEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReadFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageReadFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageReadFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageReadFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageReadFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOAD_FAILED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onUnsubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscriptionUpdateStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATE_FAILED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void areaOfInterestRequestPendingQueries()
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
final Connection connection = newConnection( connector );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
connection.requestSubscribe( address, filter );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), true );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
1 );
}
@Test
public void connection()
{
final Connector connector = createConnector();
assertEquals( connector.getConnection(), null );
final Connection connection = newConnection( connector );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
assertEquals( connector.getConnection(), connection );
assertEquals( connector.ensureConnection(), connection );
assertEquals( Disposable.isDisposed( subscription1 ), false );
connector.onDisconnection();
assertEquals( connector.getConnection(), null );
assertEquals( Disposable.isDisposed( subscription1 ), true );
}
@Test
public void ensureConnection_WhenNoConnection()
{
final Connector connector = createConnector();
final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::ensureConnection );
assertEquals( exception.getMessage(),
"Replicant-0031: Connector.ensureConnection() when no connection is present." );
}
@Test
public void purgeSubscriptions()
{
final Connector connector1 = createConnector( newSchema( 1 ) );
createConnector( newSchema( 2 ) );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
final Subscription subscription2 = createSubscription( new ChannelAddress( 1, 1, 2 ), null, true );
// The next two are from a different Connector
final Subscription subscription3 = createSubscription( new ChannelAddress( 2, 0, 1 ), null, true );
final Subscription subscription4 = createSubscription( new ChannelAddress( 2, 0, 2 ), null, true );
assertEquals( Disposable.isDisposed( subscription1 ), false );
assertEquals( Disposable.isDisposed( subscription2 ), false );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
connector1.purgeSubscriptions();
assertEquals( Disposable.isDisposed( subscription1 ), true );
assertEquals( Disposable.isDisposed( subscription2 ), true );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
}
@Test
public void progressMessages()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelChange[] channelChanges = { ChannelChange.create( 0, ChannelChange.Action.ADD, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertNull( connector.getSchedulerLock() );
connector.resumeMessageScheduler();
//response needs processing of channel messages
final boolean result0 = connector.progressMessages();
assertEquals( result0, true );
final Disposable schedulerLock0 = connector.getSchedulerLock();
assertNotNull( schedulerLock0 );
//response needs worldValidated
final boolean result1 = connector.progressMessages();
assertEquals( result1, true );
assertNull( connector.getSchedulerLock() );
assertTrue( Disposable.isDisposed( schedulerLock0 ) );
final boolean result2 = connector.progressMessages();
assertEquals( result2, true );
// Current message should be nulled and completed processing now
assertNull( connection.getCurrentMessageResponse() );
final boolean result3 = connector.progressMessages();
assertEquals( result3, false );
assertNull( connector.getSchedulerLock() );
}
@Test
public void progressMessages_whenConnectionHasBeenDisconnectedInMeantime()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelChange[] channelChanges = { ChannelChange.create( 0, ChannelChange.Action.ADD, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final AtomicInteger callCount = new AtomicInteger();
connector.setPostMessageResponseAction( callCount::incrementAndGet );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
connector.resumeMessageScheduler();
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
assertEquals( connector.progressMessages(), true );
assertEquals( callCount.get(), 0 );
assertNotNull( connector.getSchedulerLock() );
safeAction( () -> {
connector.setState( ConnectorState.ERROR );
connector.setConnection( null );
} );
// The rest of the message has been skipped as no connection left
assertEquals( connector.progressMessages(), false );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 1 );
}
@Test
public void progressMessages_withError()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 0, 0 ),
AreaOfInterestRequest.Type.REMOVE,
null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.resumeMessageScheduler();
final boolean result2 = connector.progressMessages();
assertEquals( result2, false );
assertNull( connector.getSchedulerLock() );
handler.assertEventCountAtLeast( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError().getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 0.0 but not subscribed to channel." );
} );
}
@Test
public void requestSubscribe()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscribe( address, null );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
( f, e ) -> true,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscriptionUpdate( address, null );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate_ChannelNot_DYNAMIC_Filter()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> connector.requestSubscriptionUpdate( address, null ) );
assertEquals( exception.getMessage(),
"Replicant-0082: Connector.requestSubscriptionUpdate invoked for channel 1.0 but channel does not have a dynamic filter." );
}
@Test
public void requestUnsubscribe()
throws Exception
{
final Connector connector = createConnector();
pauseScheduler();
connector.pauseMessageScheduler();
newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
createSubscription( address, null, true );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestUnsubscribe( address );
Thread.sleep( 100 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void updateSubscriptionForFilteredEntities()
{
final SubscriptionUpdateEntityFilter<?> filter = ( f, entity ) -> entity.getId() > 0;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final Subscription subscription2 = createSubscription( address2, ValueUtil.randomString(), true );
// Use Integer and String as arbitrary types for our entities...
// Anything with id below 0 will be removed during update ...
final Entity entity1 = findOrCreateEntity( Integer.class, -1 );
final Entity entity2 = findOrCreateEntity( Integer.class, -2 );
final Entity entity3 = findOrCreateEntity( Integer.class, -3 );
final Entity entity4 = findOrCreateEntity( Integer.class, -4 );
final Entity entity5 = findOrCreateEntity( String.class, 5 );
final Entity entity6 = findOrCreateEntity( String.class, 6 );
safeAction( () -> {
entity1.linkToSubscription( subscription1 );
entity2.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription1 );
entity4.linkToSubscription( subscription1 );
entity5.linkToSubscription( subscription1 );
entity6.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription2 );
entity4.linkToSubscription( subscription2 );
assertEquals( subscription1.getEntities().size(), 2 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 4 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) );
safeAction( () -> {
assertEquals( Disposable.isDisposed( entity1 ), true );
assertEquals( Disposable.isDisposed( entity2 ), true );
assertEquals( Disposable.isDisposed( entity3 ), false );
assertEquals( Disposable.isDisposed( entity4 ), false );
assertEquals( Disposable.isDisposed( entity5 ), false );
assertEquals( Disposable.isDisposed( entity6 ), false );
assertEquals( subscription1.getEntities().size(), 1 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 0 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
}
@Test
public void updateSubscriptionForFilteredEntities_badFilterType()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) ) );
assertEquals( exception.getMessage(),
"Replicant-0079: Connector.updateSubscriptionForFilteredEntities invoked for address 1.0.1 but the channel does not have a DYNAMIC filter." );
}
@Test
public void toAddress()
{
final Connector connector = createConnector();
assertEquals( connector.toAddress( ChannelChange.create( 0, ChannelChange.Action.ADD, null ) ),
new ChannelAddress( 1, 0 ) );
assertEquals( connector.toAddress( ChannelChange.create( 1, 2, ChannelChange.Action.ADD, null ) ),
new ChannelAddress( 1, 1, 2 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
final Linkable userObject2 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 1 );
final Subscription subscription = createSubscription( address, null, true );
// This entity is to be updated
final Entity entity2 = findOrCreateEntity( Linkable.class, 2 );
safeAction( () -> entity2.setUserObject( userObject2 ) );
// It is already subscribed to channel and that should be fine
safeAction( () -> entity2.linkToSubscription( subscription ) );
// This entity is to be removed
final Entity entity3 = findOrCreateEntity( Linkable.class, 3 );
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChangeData data2 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
// Update changes
EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 ),
EntityChange.create( 2, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data2 ),
// Remove change
EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } )
};
final ChangeSet changeSet = ChangeSet.create( ValueUtil.randomInt(), null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
assertEquals( response.getUpdatedEntities().size(), 0 );
assertEquals( response.getEntityUpdateCount(), 0 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, never() ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 1 );
assertEquals( response.getUpdatedEntities().contains( userObject1 ), true );
assertEquals( response.getEntityUpdateCount(), 1 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 2 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, times( 1 ) ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 2 );
assertEquals( response.getUpdatedEntities().contains( userObject1 ), true );
assertEquals( response.getUpdatedEntities().contains( userObject2 ), true );
assertEquals( response.getEntityUpdateCount(), 2 );
assertEquals( response.getEntityRemoveCount(), 1 );
assertEquals( Disposable.isDisposed( entity2 ), false );
assertEquals( Disposable.isDisposed( entity3 ), true );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges_referenceNonExistentSubscription()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 )
};
final ChangeSet changeSet = ChangeSet.create( 42, null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processEntityChanges );
assertEquals( exception.getMessage(),
"Replicant-0069: ChangeSet 42 contained an EntityChange message referencing channel 1.1 but no such subscription exists locally." );
}
@Test
public void processEntityChanges_deleteNonExistingEntity()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class, ( i, d ) -> new MyEntity(), null );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChange[] entityChanges = {
// Remove change
EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } )
};
final ChangeSet changeSet = ChangeSet.create( 23, null, entityChanges );
response.recordChangeSet( changeSet, null );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
assertEquals( response.getEntityRemoveCount(), 0 );
}
@Test
public void processEntityLinks()
{
final Connector connector = createConnector();
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable entity1 = mock( Linkable.class );
final Linkable entity2 = mock( Linkable.class );
final Linkable entity3 = mock( Linkable.class );
final Linkable entity4 = mock( Linkable.class );
response.changeProcessed( entity1 );
response.changeProcessed( entity2 );
response.changeProcessed( entity3 );
response.changeProcessed( entity4 );
verify( entity1, never() ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
assertEquals( response.getEntityLinkCount(), 0 );
connector.setLinksToProcessPerTick( 1 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 1 );
verify( entity1, times( 1 ) ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
connector.setLinksToProcessPerTick( 2 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 3 );
verify( entity1, times( 1 ) ).link();
verify( entity2, times( 1 ) ).link();
verify( entity3, times( 1 ) ).link();
verify( entity4, never() ).link();
}
@Test
public void completeAreaOfInterestRequest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 1, 0 ),
AreaOfInterestRequest.Type.ADD,
null ) );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.completeAreaOfInterestRequest();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
}
@Test
public void processChannelChanges_add()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_add_withCorrespondingAreaOfInterest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = ValueUtil.randomString();
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, filter ) );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_addConvertingImplicitToExplicit()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String filter = ValueUtil.randomString();
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, filter ) );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
connection.injectCurrentAreaOfInterestRequest( request );
request.markAsInProgress();
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelAddCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelAddCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_remove()
{
final Connector connector = createConnector();
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String filter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final Subscription initialSubscription = createSubscription( address, filter, true );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelRemoveCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNull( subscription );
assertEquals( Disposable.isDisposed( initialSubscription ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionDisposedEvent.class,
e -> assertEquals( e.getSubscription().getAddress(), address ) );
}
@Test
public void processChannelChanges_remove_WithMissingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 72 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelRemoveCount(), 0 );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_update()
{
final SubscriptionUpdateEntityFilter<?> filter = mock( SubscriptionUpdateEntityFilter.class );
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), String.class, ( i, d ) -> "", null );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final Subscription initialSubscription = createSubscription( address, oldFilter, true );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelUpdateCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( Disposable.isDisposed( initialSubscription ), false );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_update_forNonDYNAMICChannel()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 2223 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
createSubscription( address, oldFilter, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertEquals( exception.getMessage(),
"Replicant-0078: Received ChannelChange of type UPDATE for address 1.0.2223 but the channel does not have a DYNAMIC filter." );
}
@Test
public void processChannelChanges_update_missingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 42 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
assertEquals( exception.getMessage(),
"Replicant-0033: Received ChannelChange of type UPDATE for address 1.0.42 but no such subscription exists." );
handler.assertEventCount( 0 );
}
@Test
public void removeExplicitSubscriptions()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ) );
final Subscription subscription1 = createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
connector.removeExplicitSubscriptions( requests );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
}
@Test
public void removeExplicitSubscriptions_passedBadAction()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ) );
createSubscription( address1, null, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeExplicitSubscriptions( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request with type that is not REMOVE. Request: AreaOfInterestRequest[Type=ADD Address=1.1.1]" );
}
@Test
public void removeUnneededAddRequests_upgradeExisting()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, null );
requests.add( request1 );
requests.add( request2 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
// Address1 is implicitly subscribed
final Subscription subscription1 = createSubscription( address1, null, false );
connector.removeUnneededAddRequests( requests );
assertEquals( requests.size(), 1 );
assertEquals( requests.contains( request2 ), true );
assertEquals( request1.isInProgress(), false );
assertEquals( request2.isInProgress(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
}
@Test
public void removeUnneededAddRequests_explicitAlreadyPresent()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededAddRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0030: Request to add channel at address 1.1.1 but already explicitly subscribed to channel." );
}
@Test
public void removeUnneededRemoveRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededRemoveRequests( requests );
assertEquals( requests.size(), 1 );
assertEquals( requests.contains( request1 ), true );
assertEquals( request1.isInProgress(), true );
assertEquals( request2.isInProgress(), false );
assertEquals( request3.isInProgress(), false );
}
@Test
public void removeUnneededRemoveRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void removeUnneededRemoveRequests_implicitSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0047: Request to unsubscribe from channel at address 1.1.1 but subscription is not an explicit subscription." );
}
@Test
public void removeUnneededUpdateRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededUpdateRequests( requests );
assertEquals( requests.size(), 2 );
assertEquals( requests.contains( request1 ), true );
assertEquals( requests.contains( request2 ), true );
assertEquals( request1.isInProgress(), true );
assertEquals( request2.isInProgress(), true );
assertEquals( request3.isInProgress(), false );
}
@Test
public void removeUnneededUpdateRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededUpdateRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0048: Request to update channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void validateWorld_invalidEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), false );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::validateWorld );
assertEquals( exception.getMessage(),
"Replicant-0065: Entity failed to verify during validation process. Entity = MyEntity/1" );
assertEquals( response.hasWorldBeenValidated(), true );
}
@Test
public void validateWorld_invalidEntity_ignoredIfCOmpileSettingDisablesValidation()
{
ReplicantTestUtil.noValidateEntitiesOnLoad();
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), true );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
connector.validateWorld();
assertEquals( response.hasWorldBeenValidated(), true );
}
@Test
public void validateWorld_validEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), false );
final EntityService entityService = Replicant.context().getEntityService();
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
connector.validateWorld();
assertEquals( response.hasWorldBeenValidated(), true );
}
static class MyEntity
implements Verifiable
{
@Nullable
private final Exception _exception;
MyEntity()
{
this( null );
}
MyEntity( @Nullable final Exception exception )
{
_exception = exception;
}
@Override
public void verify()
throws Exception
{
if ( null != _exception )
{
throw _exception;
}
}
}
@Test
public void parseMessageResponse_basicMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_requestPresent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_cacheResult()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
final String rawJsonData =
"{\"last_id\": 1" +
", \"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
final String cacheKey = "RC-1.0";
final CacheEntry entry = cacheService.lookup( cacheKey );
assertNotNull( entry );
assertEquals( entry.getKey(), cacheKey );
assertEquals( entry.getETag(), etag );
assertEquals( entry.getContent(), rawJsonData );
}
@Test
public void parseMessageResponse_eTagWhenNotCacheCandidate()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
final String rawJsonData =
"{\"last_id\": 1" +
", \"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"}, { \"cid\": 1, \"scid\": 1, \"action\": \"add\"} ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0072: eTag in reply for ChangeSet 1 but ChangeSet is not a candidate for caching." );
}
@Test
public void parseMessageResponse_oob()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}";
final SafeProcedure oobCompletionAction = () -> {
};
final MessageResponse response = new MessageResponse( rawJsonData, oobCompletionAction );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_invalidRequestId()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": 22}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0066: Unable to locate request with id '22' specified for ChangeSet with sequence 1. Existing Requests: {}" );
}
@Test
public void completeMessageResponse()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_hasContent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet =
ChangeSet.create( 23, new ChannelChange[]{ ChannelChange.create( 1, ChannelChange.Action.ADD, null ) }, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
handler.assertNextEvent( SyncRequestEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void completeMessageResponse_stillMessagesPending()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
response.recordChangeSet( ChangeSet.create( 23, null, null ), null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
connection.enqueueResponse( ValueUtil.randomString() );
connector.completeMessageResponse();
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), false ) );
}
@Test
public void completeMessageResponse_withPostAction()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final AtomicInteger postActionCallCount = new AtomicInteger();
connector.setPostMessageResponseAction( postActionCallCount::incrementAndGet );
assertEquals( postActionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( postActionCallCount.get(), 1 );
}
@Test
public void completeMessageResponse_OOBMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final AtomicInteger completionCallCount = new AtomicInteger();
final MessageResponse response = new MessageResponse( "", completionCallCount::incrementAndGet );
final ChangeSet changeSet = ChangeSet.create( 23, 1234, null, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( completionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( completionCallCount.get(), 1 );
assertEquals( connection.getLastRxSequence(), 22 );
assertEquals( connection.getCurrentMessageResponse(), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
entry.setNormalCompletion( true );
entry.setCompletionAction( completionCalled::incrementAndGet );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( entry.haveResultsArrived(), false );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertEquals( entry.haveResultsArrived(), true );
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( completionCalled.get(), 1 );
assertEquals( connection.getRequest( requestId ), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCNotComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( entry.haveResultsArrived(), false );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertEquals( entry.haveResultsArrived(), true );
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@SuppressWarnings( { "ResultOfMethodCallIgnored", "unchecked" } )
@Test
public void progressResponseProcessing()
{
/*
* This test steps through each stage of a message processing.
*/
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData =
"{" +
"\"last_id\": 1, " +
// Add Channel 0
"\"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ], " +
// Add Entity 1 of type 0 from channel 0
"\"changes\": [{\"id\": 1,\"type\":0,\"channels\":[{\"cid\": 0}], \"data\":{}}] " +
"}";
connection.enqueueResponse( rawJsonData );
final MessageResponse response = connection.getUnparsedResponses().get( 0 );
{
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( connection.getUnparsedResponses().size(), 1 );
// Select response
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getUnparsedResponses().size(), 0 );
}
{
assertEquals( response.getRawJsonData(), rawJsonData );
assertThrows( response::getChangeSet );
assertEquals( response.needsParsing(), true );
assertEquals( connection.getPendingResponses().size(), 0 );
// Parse response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.getRawJsonData(), null );
assertNotNull( response.getChangeSet() );
assertEquals( response.needsParsing(), false );
}
{
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( connection.getPendingResponses().size(), 1 );
// Pickup parsed response and set it as current
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getPendingResponses().size(), 0 );
}
{
assertEquals( response.needsChannelChangesProcessed(), true );
// Process Channel Changes in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.needsChannelChangesProcessed(), false );
}
{
assertEquals( response.areEntityChangesPending(), true );
when( creator.createEntity( anyInt(), any( EntityChangeData.class ) ) ).thenReturn( mock( Linkable.class ) );
// Process Entity Changes in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.areEntityChangesPending(), false );
}
{
assertEquals( response.areEntityLinksPending(), true );
// Process Entity Links in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.areEntityLinksPending(), false );
}
{
assertEquals( response.hasWorldBeenValidated(), false );
// Validate World
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.hasWorldBeenValidated(), true );
}
{
assertEquals( connection.getCurrentMessageResponse(), response );
// Complete message
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), null );
}
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueNotInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
connection.injectCurrentAreaOfInterestRequest( request );
Replicant.context().setCacheService( new TestCacheService() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestCacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final String key = "1.0";
final String eTag = "";
cacheService.store( key, eTag, ValueUtil.randomString() );
final AtomicReference<SafeProcedure> onCacheValid = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
assertEquals( i.getArguments()[ 2 ], eTag );
assertNotNull( i.getArguments()[ 3 ] );
onCacheValid.set( (SafeProcedure) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any(),
any( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
assertEquals( connector.isSchedulerActive(), false );
assertEquals( connection.getOutOfBandResponses().size(), 0 );
onCacheValid.get().call();
assertEquals( connector.isSchedulerActive(), true );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertEquals( connection.getOutOfBandResponses().size(), 1 );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address1 ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address1 ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address1 ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Noop()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_InProgress()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
request1.markAsInProgress();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Add()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Update()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Remove()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@Test
public void pauseMessageScheduler()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
assertEquals( connector.isSchedulerPaused(), true );
assertEquals( connector.isSchedulerActive(), false );
connector.requestSubscribe( new ChannelAddress( 1, 0, 1 ), null );
assertEquals( connector.isSchedulerActive(), true );
connector.resumeMessageScheduler();
assertEquals( connector.isSchedulerPaused(), false );
assertEquals( connector.isSchedulerActive(), false );
connector.pauseMessageScheduler();
assertEquals( connector.isSchedulerPaused(), true );
assertEquals( connector.isSchedulerActive(), false );
// No progress
assertEquals( connector.progressMessages(), false );
Disposable.dispose( connector );
assertEquals( connector.isSchedulerActive(), false );
assertEquals( connector.isSchedulerPaused(), true );
assertNull( connector.getSchedulerLock() );
}
@Test
public void isSynchronized_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void shouldRequestSync_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void onInSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onInSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( InSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onOutOfSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onOutOfSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( OutOfSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onSyncError()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
final Throwable error = new Throwable();
connector.onSyncError( error );
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncFailureEvent.class,
e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void requestSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
connector.requestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), true ) );
verify( connector.getTransport() ).requestSync( any( SafeProcedure.class ),
any( SafeProcedure.class ),
(Consumer<Throwable>) any( Consumer.class ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncRequestEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void maybeRequestSync()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.maybeRequestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
connector.maybeRequestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), true ) );
}
}
| client/src/test/java/replicant/ConnectorTest.java | package replicant;
import arez.Disposable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.intellij.lang.annotations.Language;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import replicant.messages.ChangeSet;
import replicant.messages.ChannelChange;
import replicant.messages.EntityChange;
import replicant.messages.EntityChangeData;
import replicant.messages.EntityChannel;
import replicant.spy.AreaOfInterestStatusUpdatedEvent;
import replicant.spy.ConnectFailureEvent;
import replicant.spy.ConnectedEvent;
import replicant.spy.DataLoadStatus;
import replicant.spy.DisconnectFailureEvent;
import replicant.spy.DisconnectedEvent;
import replicant.spy.InSyncEvent;
import replicant.spy.MessageProcessFailureEvent;
import replicant.spy.MessageProcessedEvent;
import replicant.spy.MessageReadFailureEvent;
import replicant.spy.OutOfSyncEvent;
import replicant.spy.RestartEvent;
import replicant.spy.SubscribeCompletedEvent;
import replicant.spy.SubscribeFailedEvent;
import replicant.spy.SubscribeRequestQueuedEvent;
import replicant.spy.SubscribeStartedEvent;
import replicant.spy.SubscriptionCreatedEvent;
import replicant.spy.SubscriptionDisposedEvent;
import replicant.spy.SubscriptionUpdateCompletedEvent;
import replicant.spy.SubscriptionUpdateFailedEvent;
import replicant.spy.SubscriptionUpdateRequestQueuedEvent;
import replicant.spy.SubscriptionUpdateStartedEvent;
import replicant.spy.SyncFailureEvent;
import replicant.spy.SyncRequestEvent;
import replicant.spy.UnsubscribeCompletedEvent;
import replicant.spy.UnsubscribeFailedEvent;
import replicant.spy.UnsubscribeRequestQueuedEvent;
import replicant.spy.UnsubscribeStartedEvent;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
@SuppressWarnings( { "NonJREEmulationClassesInClientCode", "Duplicates" } )
public class ConnectorTest
extends AbstractReplicantTest
{
@Test
public void construct()
throws Exception
{
final Disposable schedulerLock = pauseScheduler();
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema =
new SystemSchema( ValueUtil.randomInt(),
ValueUtil.randomString(),
new ChannelSchema[ 0 ],
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
assertEquals( connector.getSchema(), schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantRuntime(), runtime );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), true );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
schedulerLock.dispose();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void dispose()
{
final ReplicantRuntime runtime = Replicant.context().getRuntime();
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), true );
Disposable.dispose( connector );
safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) );
assertEquals( connector.getReplicantContext().getSchemaService().getSchemas().contains( schema ), false );
}
@Test
public void testToString()
throws Exception
{
final SystemSchema schema = newSchema();
final Connector connector = createConnector( schema );
assertEquals( connector.toString(), "Connector[" + schema.getName() + "]" );
ReplicantTestUtil.disableNames();
assertEquals( connector.toString(), "replicant.Arez_Connector@" + Integer.toHexString( connector.hashCode() ) );
}
@Test
public void setConnection_whenConnectorProcessingMessage()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 0 );
final Subscription subscription = createSubscription( address, null, true );
connector.onConnection( ValueUtil.randomString() );
// Connection not swapped yet but will do one MessageProcess completes
assertEquals( Disposable.isDisposed( subscription ), false );
assertEquals( connector.getConnection(), connection );
assertNotNull( connector.getPostMessageResponseAction() );
}
@Test
public void setConnection_whenExistingConnection()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
connector.recordLastRxRequestId( ValueUtil.randomInt() );
connector.recordLastTxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncRxRequestId( ValueUtil.randomInt() );
connector.recordLastSyncTxRequestId( ValueUtil.randomInt() );
connector.recordSyncInFlight( true );
connector.recordPendingResponseQueueEmpty( false );
assertEquals( Disposable.isDisposed( connection ), false );
assertEquals( connector.getConnection(), connection );
final String newConnectionId = ValueUtil.randomString();
connector.onConnection( newConnectionId );
assertEquals( Disposable.isDisposed( connection ), true );
assertEquals( connector.ensureConnection().getConnectionId(), newConnectionId );
safeAction( () -> assertEquals( connector.getLastRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastTxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncRxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.getLastSyncTxRequestId(), 0 ) );
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
}
@Test
public void connect()
{
pauseScheduler();
final Connector connector = createConnector();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
safeAction( connector::connect );
verify( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void connect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) );
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::connect ) );
assertEquals( actual, exception );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void transportDisconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.transportDisconnect();
verify( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnect()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( connector::disconnect );
verify( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
verify( connector.getTransport(), never() ).unbind();
}
@Test
public void disconnect_causesError()
{
pauseScheduler();
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
reset( connector.getTransport() );
final IllegalStateException exception = new IllegalStateException();
doAnswer( i -> {
throw exception;
} ).when( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) );
final IllegalStateException actual =
expectThrows( IllegalStateException.class, () -> safeAction( connector::disconnect ) );
assertEquals( actual, exception );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
reset( connector.getTransport() );
connector.onDisconnected();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.DISCONNECTED ) );
verify( connector.getTransport() ).unbind();
}
@Test
public void onDisconnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onDisconnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onDisconnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onDisconnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( DisconnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onConnected()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = new Connection( connector, ValueUtil.randomString() );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
// Pause scheduler so runtime does not try to update state
pauseScheduler();
final Field field = Connector.class.getDeclaredField( "_connection" );
field.setAccessible( true );
field.set( connector, connection );
connector.onConnected();
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTED ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTED ) );
verify( connector.getTransport() ).bind( connection.getTransportContext(), Replicant.context() );
}
@Test
public void onConnected_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onConnected();
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectedEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onConnectFailure()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.CONNECTING ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) );
safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(),
RuntimeState.ERROR ) );
}
@Test
public void onConnectFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onConnectFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( ConnectFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReceived()
throws Exception
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final String rawJsonData = ValueUtil.randomString();
pauseScheduler();
connector.pauseMessageScheduler();
assertEquals( connection.getUnparsedResponses().size(), 0 );
assertEquals( connector.isSchedulerActive(), false );
connector.onMessageReceived( rawJsonData );
assertEquals( connection.getUnparsedResponses().size(), 1 );
assertEquals( connection.getUnparsedResponses().get( 0 ).getRawJsonData(), rawJsonData );
assertEquals( connector.isSchedulerActive(), true );
}
@Test
public void onMessageProcessed()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final DataLoadStatus status =
new DataLoadStatus( ValueUtil.randomInt(),
ValueUtil.randomInt(),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 10 ),
ValueUtil.getRandom().nextInt( 100 ),
ValueUtil.getRandom().nextInt( 100 ),
ValueUtil.getRandom().nextInt( 10 ) );
connector.onMessageProcessed( status );
verify( connector.getTransport() ).onMessageProcessed();
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getDataLoadStatus(), status );
} );
}
@Test
public void onMessageProcessFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageProcessFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageProcessFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageProcessFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void disconnectIfPossible()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void disconnectIfPossible_noActionAsConnecting()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 0 );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) );
}
@Test
public void disconnectIfPossible_generatesSpyEvent()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
safeAction( () -> connector.disconnectIfPossible( error ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( RestartEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onMessageReadFailure()
throws Exception
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
final Throwable error = new Throwable();
// Pause scheduler so runtime does not try to update state
pauseScheduler();
connector.onMessageReadFailure( error );
safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) );
}
@Test
public void onMessageReadFailure_generatesSpyMessage()
throws Exception
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.CONNECTING ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final Throwable error = new Throwable();
connector.onMessageReadFailure( error );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageReadFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscribeFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOAD_FAILED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onUnsubscribeStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onUnsubscribeFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onUnsubscribeFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void onSubscriptionUpdateStarted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateStarted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATING ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateCompleted()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateCompleted( address );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@Test
public void onSubscriptionUpdateFailed()
throws Exception
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterest areaOfInterest =
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), null ) );
final Throwable error = new Throwable();
final Subscription subscription = createSubscription( address, null, true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.onSubscriptionUpdateFailed( address, error );
safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATE_FAILED ) );
safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) );
safeAction( () -> assertEquals( areaOfInterest.getError(), error ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class,
e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@Test
public void areaOfInterestRequestPendingQueries()
{
final Connector connector = createConnector();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
final Connection connection = newConnection( connector );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
-1 );
connection.requestSubscribe( address, filter );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), true );
assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ),
1 );
}
@Test
public void connection()
{
final Connector connector = createConnector();
assertEquals( connector.getConnection(), null );
final Connection connection = newConnection( connector );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
assertEquals( connector.getConnection(), connection );
assertEquals( connector.ensureConnection(), connection );
assertEquals( Disposable.isDisposed( subscription1 ), false );
connector.onDisconnection();
assertEquals( connector.getConnection(), null );
assertEquals( Disposable.isDisposed( subscription1 ), true );
}
@Test
public void ensureConnection_WhenNoConnection()
{
final Connector connector = createConnector();
final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::ensureConnection );
assertEquals( exception.getMessage(),
"Replicant-0031: Connector.ensureConnection() when no connection is present." );
}
@Test
public void purgeSubscriptions()
{
final Connector connector1 = createConnector( newSchema( 1 ) );
createConnector( newSchema( 2 ) );
final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true );
final Subscription subscription2 = createSubscription( new ChannelAddress( 1, 1, 2 ), null, true );
// The next two are from a different Connector
final Subscription subscription3 = createSubscription( new ChannelAddress( 2, 0, 1 ), null, true );
final Subscription subscription4 = createSubscription( new ChannelAddress( 2, 0, 2 ), null, true );
assertEquals( Disposable.isDisposed( subscription1 ), false );
assertEquals( Disposable.isDisposed( subscription2 ), false );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
connector1.purgeSubscriptions();
assertEquals( Disposable.isDisposed( subscription1 ), true );
assertEquals( Disposable.isDisposed( subscription2 ), true );
assertEquals( Disposable.isDisposed( subscription3 ), false );
assertEquals( Disposable.isDisposed( subscription4 ), false );
}
@Test
public void progressMessages()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelChange[] channelChanges = { ChannelChange.create( 0, ChannelChange.Action.ADD, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertNull( connector.getSchedulerLock() );
connector.resumeMessageScheduler();
//response needs processing of channel messages
final boolean result0 = connector.progressMessages();
assertEquals( result0, true );
final Disposable schedulerLock0 = connector.getSchedulerLock();
assertNotNull( schedulerLock0 );
//response needs worldValidated
final boolean result1 = connector.progressMessages();
assertEquals( result1, true );
assertNull( connector.getSchedulerLock() );
assertTrue( Disposable.isDisposed( schedulerLock0 ) );
final boolean result2 = connector.progressMessages();
assertEquals( result2, true );
// Current message should be nulled and completed processing now
assertNull( connection.getCurrentMessageResponse() );
final boolean result3 = connector.progressMessages();
assertEquals( result3, false );
assertNull( connector.getSchedulerLock() );
}
@Test
public void progressMessages_whenConnectionHasBeenDisconnectedInMeantime()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelChange[] channelChanges = { ChannelChange.create( 0, ChannelChange.Action.ADD, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final AtomicInteger callCount = new AtomicInteger();
connector.setPostMessageResponseAction( callCount::incrementAndGet );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
connector.resumeMessageScheduler();
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 0 );
assertEquals( connector.progressMessages(), true );
assertEquals( callCount.get(), 0 );
assertNotNull( connector.getSchedulerLock() );
safeAction( () -> {
connector.setState( ConnectorState.ERROR );
connector.setConnection( null );
} );
// The rest of the message has been skipped as no connection left
assertEquals( connector.progressMessages(), false );
assertNull( connector.getSchedulerLock() );
assertEquals( callCount.get(), 1 );
}
@Test
public void progressMessages_withError()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 0, 0 ),
AreaOfInterestRequest.Type.REMOVE,
null ) );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.resumeMessageScheduler();
final boolean result2 = connector.progressMessages();
assertEquals( result2, false );
assertNull( connector.getSchedulerLock() );
handler.assertEventCountAtLeast( 1 );
handler.assertNextEvent( MessageProcessFailureEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError().getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 0.0 but not subscribed to channel." );
} );
}
@Test
public void requestSubscribe()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscribe( address, null );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
( f, e ) -> true,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestSubscriptionUpdate( address, null );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void requestSubscriptionUpdate_ChannelNot_DYNAMIC_Filter()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> connector.requestSubscriptionUpdate( address, null ) );
assertEquals( exception.getMessage(),
"Replicant-0082: Connector.requestSubscriptionUpdate invoked for channel 1.0 but channel does not have a dynamic filter." );
}
@Test
public void requestUnsubscribe()
throws Exception
{
final Connector connector = createConnector();
pauseScheduler();
connector.pauseMessageScheduler();
newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
createSubscription( address, null, true );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), false );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.requestUnsubscribe( address );
Thread.sleep( 100 );
assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeRequestQueuedEvent.class,
e -> assertEquals( e.getAddress(), address ) );
}
@Test
public void updateSubscriptionForFilteredEntities()
{
final SubscriptionUpdateEntityFilter<?> filter = ( f, entity ) -> entity.getId() > 0;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final Subscription subscription2 = createSubscription( address2, ValueUtil.randomString(), true );
// Use Integer and String as arbitrary types for our entities...
// Anything with id below 0 will be removed during update ...
final Entity entity1 = findOrCreateEntity( Integer.class, -1 );
final Entity entity2 = findOrCreateEntity( Integer.class, -2 );
final Entity entity3 = findOrCreateEntity( Integer.class, -3 );
final Entity entity4 = findOrCreateEntity( Integer.class, -4 );
final Entity entity5 = findOrCreateEntity( String.class, 5 );
final Entity entity6 = findOrCreateEntity( String.class, 6 );
safeAction( () -> {
entity1.linkToSubscription( subscription1 );
entity2.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription1 );
entity4.linkToSubscription( subscription1 );
entity5.linkToSubscription( subscription1 );
entity6.linkToSubscription( subscription1 );
entity3.linkToSubscription( subscription2 );
entity4.linkToSubscription( subscription2 );
assertEquals( subscription1.getEntities().size(), 2 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 4 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) );
safeAction( () -> {
assertEquals( Disposable.isDisposed( entity1 ), true );
assertEquals( Disposable.isDisposed( entity2 ), true );
assertEquals( Disposable.isDisposed( entity3 ), false );
assertEquals( Disposable.isDisposed( entity4 ), false );
assertEquals( Disposable.isDisposed( entity5 ), false );
assertEquals( Disposable.isDisposed( entity6 ), false );
assertEquals( subscription1.getEntities().size(), 1 );
assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 0 );
assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 );
assertEquals( subscription2.getEntities().size(), 1 );
assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 );
} );
}
@Test
public void updateSubscriptionForFilteredEntities_badFilterType()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) ) );
assertEquals( exception.getMessage(),
"Replicant-0079: Connector.updateSubscriptionForFilteredEntities invoked for address 1.0.1 but the channel does not have a DYNAMIC filter." );
}
@Test
public void toAddress()
{
final Connector connector = createConnector();
assertEquals( connector.toAddress( ChannelChange.create( 0, ChannelChange.Action.ADD, null ) ),
new ChannelAddress( 1, 0 ) );
assertEquals( connector.toAddress( ChannelChange.create( 1, 2, ChannelChange.Action.ADD, null ) ),
new ChannelAddress( 1, 1, 2 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
final Linkable userObject2 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 1 );
final Subscription subscription = createSubscription( address, null, true );
// This entity is to be updated
final Entity entity2 = findOrCreateEntity( Linkable.class, 2 );
safeAction( () -> entity2.setUserObject( userObject2 ) );
// It is already subscribed to channel and that should be fine
safeAction( () -> entity2.linkToSubscription( subscription ) );
// This entity is to be removed
final Entity entity3 = findOrCreateEntity( Linkable.class, 3 );
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChangeData data2 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
// Update changes
EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 ),
EntityChange.create( 2, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data2 ),
// Remove change
EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } )
};
final ChangeSet changeSet = ChangeSet.create( ValueUtil.randomInt(), null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
assertEquals( response.getUpdatedEntities().size(), 0 );
assertEquals( response.getEntityUpdateCount(), 0 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, never() ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 1 );
assertEquals( response.getUpdatedEntities().contains( userObject1 ), true );
assertEquals( response.getEntityUpdateCount(), 1 );
assertEquals( response.getEntityRemoveCount(), 0 );
connector.setChangesToProcessPerTick( 2 );
connector.processEntityChanges();
verify( creator, times( 1 ) ).createEntity( 1, data1 );
verify( updater, never() ).updateEntity( userObject1, data1 );
verify( creator, never() ).createEntity( 2, data2 );
verify( updater, times( 1 ) ).updateEntity( userObject2, data2 );
assertEquals( response.getUpdatedEntities().size(), 2 );
assertEquals( response.getUpdatedEntities().contains( userObject1 ), true );
assertEquals( response.getUpdatedEntities().contains( userObject2 ), true );
assertEquals( response.getEntityUpdateCount(), 2 );
assertEquals( response.getEntityRemoveCount(), 1 );
assertEquals( Disposable.isDisposed( entity2 ), false );
assertEquals( Disposable.isDisposed( entity3 ), true );
}
@SuppressWarnings( "unchecked" )
@Test
public void processEntityChanges_referenceNonExistentSubscription()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable userObject1 = mock( Linkable.class );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChangeData data1 = mock( EntityChangeData.class );
final EntityChange[] entityChanges = {
EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 )
};
final ChangeSet changeSet = ChangeSet.create( 42, null, entityChanges );
response.recordChangeSet( changeSet, null );
when( creator.createEntity( 1, data1 ) ).thenReturn( userObject1 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processEntityChanges );
assertEquals( exception.getMessage(),
"Replicant-0069: ChangeSet 42 contained an EntityChange message referencing channel 1.1 but no such subscription exists locally." );
}
@Test
public void processEntityChanges_deleteNonExistingEntity()
{
final int schemaId = 1;
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class, ( i, d ) -> new MyEntity(), null );
final SystemSchema schema =
new SystemSchema( schemaId,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
// Pause scheduler to avoid converge of subscriptions
pauseScheduler();
final EntityChange[] entityChanges = {
// Remove change
EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } )
};
final ChangeSet changeSet = ChangeSet.create( 23, null, entityChanges );
response.recordChangeSet( changeSet, null );
connector.setChangesToProcessPerTick( 1 );
connector.processEntityChanges();
assertEquals( response.getEntityRemoveCount(), 0 );
}
@Test
public void processEntityLinks()
{
final Connector connector = createConnector();
connector.setLinksToProcessPerTick( 1 );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final Linkable entity1 = mock( Linkable.class );
final Linkable entity2 = mock( Linkable.class );
final Linkable entity3 = mock( Linkable.class );
final Linkable entity4 = mock( Linkable.class );
response.changeProcessed( entity1 );
response.changeProcessed( entity2 );
response.changeProcessed( entity3 );
response.changeProcessed( entity4 );
verify( entity1, never() ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
assertEquals( response.getEntityLinkCount(), 0 );
connector.setLinksToProcessPerTick( 1 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 1 );
verify( entity1, times( 1 ) ).link();
verify( entity2, never() ).link();
verify( entity3, never() ).link();
verify( entity4, never() ).link();
connector.setLinksToProcessPerTick( 2 );
connector.processEntityLinks();
assertEquals( response.getEntityLinkCount(), 3 );
verify( entity1, times( 1 ) ).link();
verify( entity2, times( 1 ) ).link();
verify( entity3, times( 1 ) ).link();
verify( entity4, never() ).link();
}
@Test
public void completeAreaOfInterestRequest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 1, 0 ),
AreaOfInterestRequest.Type.ADD,
null ) );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.completeAreaOfInterestRequest();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
}
@Test
public void processChannelChanges_add()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_add_withCorrespondingAreaOfInterest()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final int channelId = 0;
final int subChannelId = ValueUtil.randomInt();
final String filter = ValueUtil.randomString();
final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId );
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, filter ) );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_addConvertingImplicitToExplicit()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
connector.pauseMessageScheduler();
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String filter = ValueUtil.randomString();
safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, filter ) );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
connection.injectCurrentAreaOfInterestRequest( request );
request.markAsInProgress();
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelAddCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelAddCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( subscription.getAddress(), address );
safeAction( () -> assertEquals( subscription.getFilter(), filter ) );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> {
assertEquals( e.getSubscription().getAddress(), address );
safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) );
} );
}
@Test
public void processChannelChanges_remove()
{
final Connector connector = createConnector();
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String filter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final Subscription initialSubscription = createSubscription( address, filter, true );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelRemoveCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNull( subscription );
assertEquals( Disposable.isDisposed( initialSubscription ), true );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionDisposedEvent.class,
e -> assertEquals( e.getSubscription().getAddress(), address ) );
}
@Test
public void processChannelChanges_remove_WithMissingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 72 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelRemoveCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelRemoveCount(), 0 );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_update()
{
final SubscriptionUpdateEntityFilter<?> filter = mock( SubscriptionUpdateEntityFilter.class );
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
filter,
true, true,
Collections.emptyList() );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), String.class, ( i, d ) -> "", null );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
connector.pauseMessageScheduler();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
final Subscription initialSubscription = createSubscription( address, oldFilter, true );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.processChannelChanges();
assertEquals( response.needsChannelChangesProcessed(), false );
assertEquals( response.getChannelUpdateCount(), 1 );
final Subscription subscription =
safeAction( () -> Replicant.context().findSubscription( address ) );
assertNotNull( subscription );
assertEquals( Disposable.isDisposed( initialSubscription ), false );
handler.assertEventCount( 0 );
}
@Test
public void processChannelChanges_update_forNonDYNAMICChannel()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 2223 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String oldFilter = ValueUtil.randomString();
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
createSubscription( address, oldFilter, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertEquals( exception.getMessage(),
"Replicant-0078: Received ChannelChange of type UPDATE for address 1.0.2223 but the channel does not have a DYNAMIC filter." );
}
@Test
public void processChannelChanges_update_missingSubscription()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connection.setCurrentMessageResponse( response );
final ChannelAddress address = new ChannelAddress( 1, 0, 42 );
final int channelId = address.getChannelId();
final int subChannelId = Objects.requireNonNull( address.getId() );
final String newFilter = ValueUtil.randomString();
final ChannelChange[] channelChanges =
new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) };
response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::processChannelChanges );
assertEquals( response.needsChannelChangesProcessed(), true );
assertEquals( response.getChannelUpdateCount(), 0 );
assertEquals( exception.getMessage(),
"Replicant-0033: Received ChannelChange of type UPDATE for address 1.0.42 but no such subscription exists." );
handler.assertEventCount( 0 );
}
@Test
public void removeExplicitSubscriptions()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ) );
requests.add( new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ) );
final Subscription subscription1 = createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
connector.removeExplicitSubscriptions( requests );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
}
@Test
public void removeExplicitSubscriptions_passedBadAction()
{
// Pause converger
pauseScheduler();
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ) );
createSubscription( address1, null, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeExplicitSubscriptions( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request with type that is not REMOVE. Request: AreaOfInterestRequest[Type=ADD Address=1.1.1]" );
}
@Test
public void removeUnneededAddRequests_upgradeExisting()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, null );
requests.add( request1 );
requests.add( request2 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
// Address1 is implicitly subscribed
final Subscription subscription1 = createSubscription( address1, null, false );
connector.removeUnneededAddRequests( requests );
assertEquals( requests.size(), 1 );
assertEquals( requests.contains( request2 ), true );
assertEquals( request1.isInProgress(), false );
assertEquals( request2.isInProgress(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
}
@Test
public void removeUnneededAddRequests_explicitAlreadyPresent()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededAddRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0030: Request to add channel at address 1.1.1 but already explicitly subscribed to channel." );
}
@Test
public void removeUnneededRemoveRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededRemoveRequests( requests );
assertEquals( requests.size(), 1 );
assertEquals( requests.contains( request1 ), true );
assertEquals( request1.isInProgress(), true );
assertEquals( request2.isInProgress(), false );
assertEquals( request3.isInProgress(), false );
}
@Test
public void removeUnneededRemoveRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0046: Request to unsubscribe from channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void removeUnneededRemoveRequests_implicitSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0047: Request to unsubscribe from channel at address 1.1.1 but subscription is not an explicit subscription." );
}
@Test
public void removeUnneededUpdateRequests_whenInvariantsDisabled()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.add( request2 );
requests.add( request3 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
createSubscription( address1, null, true );
// Address2 is already implicit ...
createSubscription( address2, null, false );
// Address3 has no subscription ... maybe not converged yet
ReplicantTestUtil.noCheckInvariants();
connector.removeUnneededUpdateRequests( requests );
assertEquals( requests.size(), 2 );
assertEquals( requests.contains( request1 ), true );
assertEquals( requests.contains( request2 ), true );
assertEquals( request1.isInProgress(), true );
assertEquals( request2.isInProgress(), true );
assertEquals( request3.isInProgress(), false );
}
@Test
public void removeUnneededUpdateRequests_noSubscription()
{
final Connector connector = createConnector();
final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null );
requests.add( request1 );
requests.forEach( AreaOfInterestRequest::markAsInProgress );
final IllegalStateException exception =
expectThrows( IllegalStateException.class,
() -> safeAction( () -> connector.removeUnneededUpdateRequests( requests ) ) );
assertEquals( exception.getMessage(),
"Replicant-0048: Request to update channel at address 1.1.1 but not subscribed to channel." );
}
@Test
public void validateWorld_invalidEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), false );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::validateWorld );
assertEquals( exception.getMessage(),
"Replicant-0065: Entity failed to verify during validation process. Entity = MyEntity/1" );
assertEquals( response.hasWorldBeenValidated(), true );
}
@Test
public void validateWorld_invalidEntity_ignoredIfCOmpileSettingDisablesValidation()
{
ReplicantTestUtil.noValidateEntitiesOnLoad();
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), true );
final EntityService entityService = Replicant.context().getEntityService();
final Entity entity1 =
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
final Exception error = new Exception();
safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) );
connector.validateWorld();
assertEquals( response.hasWorldBeenValidated(), true );
}
@Test
public void validateWorld_validEntity()
{
final Connector connector = createConnector();
newConnection( connector );
final MessageResponse response = new MessageResponse( ValueUtil.randomString() );
connector.ensureConnection().setCurrentMessageResponse( response );
assertEquals( response.hasWorldBeenValidated(), false );
final EntityService entityService = Replicant.context().getEntityService();
safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) );
connector.validateWorld();
assertEquals( response.hasWorldBeenValidated(), true );
}
static class MyEntity
implements Verifiable
{
@Nullable
private final Exception _exception;
MyEntity()
{
this( null );
}
MyEntity( @Nullable final Exception exception )
{
_exception = exception;
}
@Override
public void verify()
throws Exception
{
if ( null != _exception )
{
throw _exception;
}
}
}
@Test
public void parseMessageResponse_basicMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_requestPresent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_cacheResult()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
true,
true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
final String rawJsonData =
"{\"last_id\": 1" +
", \"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertEquals( response.getRequest(), request.getEntry() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
final String cacheKey = "RC-1.0";
final CacheEntry entry = cacheService.lookup( cacheKey );
assertNotNull( entry );
assertEquals( entry.getKey(), cacheKey );
assertEquals( entry.getETag(), etag );
assertEquals( entry.getContent(), rawJsonData );
}
@Test
public void parseMessageResponse_eTagWhenNotCacheCandidate()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
final String etag = ValueUtil.randomString();
final String rawJsonData =
"{\"last_id\": 1" +
", \"requestId\": " + requestId +
", \"etag\": \"" + etag + "\"" +
", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"}, { \"cid\": 1, \"scid\": 1, \"action\": \"add\"} ] }";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final CacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
assertNull( cacheService.lookup( ValueUtil.randomString() ) );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0072: eTag in reply for ChangeSet 1 but ChangeSet is not a candidate for caching." );
}
@Test
public void parseMessageResponse_oob()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final int requestId = request.getRequestId();
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}";
final SafeProcedure oobCompletionAction = () -> {
};
final MessageResponse response = new MessageResponse( rawJsonData, oobCompletionAction );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
connector.parseMessageResponse();
assertEquals( response.getRawJsonData(), null );
final ChangeSet changeSet = response.getChangeSet();
assertNotNull( changeSet );
assertEquals( changeSet.getSequence(), 1 );
assertNull( response.getRequest() );
assertEquals( connection.getPendingResponses().size(), 1 );
assertEquals( connection.getCurrentMessageResponse(), null );
}
@Test
public void parseMessageResponse_invalidRequestId()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData = "{\"last_id\": 1, \"requestId\": 22}";
final MessageResponse response = new MessageResponse( rawJsonData );
connection.setCurrentMessageResponse( response );
assertEquals( connection.getPendingResponses().size(), 0 );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, connector::parseMessageResponse );
assertEquals( exception.getMessage(),
"Replicant-0066: Unable to locate request with id '22' specified for ChangeSet with sequence 1. Existing Requests: {}" );
}
@Test
public void completeMessageResponse()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_hasContent()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet =
ChangeSet.create( 23, new ChannelChange[]{ ChannelChange.create( 1, ChannelChange.Action.ADD, null ) }, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
connector.completeMessageResponse();
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
handler.assertNextEvent( SyncRequestEvent.class, e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void completeMessageResponse_stillMessagesPending()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
response.recordChangeSet( ChangeSet.create( 23, null, null ), null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
connection.enqueueResponse( ValueUtil.randomString() );
connector.completeMessageResponse();
safeAction( () -> assertEquals( connector.isPendingResponseQueueEmpty(), false ) );
}
@Test
public void completeMessageResponse_withPostAction()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final AtomicInteger postActionCallCount = new AtomicInteger();
connector.setPostMessageResponseAction( postActionCallCount::incrementAndGet );
assertEquals( postActionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( postActionCallCount.get(), 1 );
}
@Test
public void completeMessageResponse_OOBMessage()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final AtomicInteger completionCallCount = new AtomicInteger();
final MessageResponse response = new MessageResponse( "", completionCallCount::incrementAndGet );
final ChangeSet changeSet = ChangeSet.create( 23, 1234, null, null, null );
response.recordChangeSet( changeSet, null );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( completionCallCount.get(), 0 );
connector.completeMessageResponse();
assertEquals( completionCallCount.get(), 1 );
assertEquals( connection.getLastRxSequence(), 22 );
assertEquals( connection.getCurrentMessageResponse(), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
entry.setNormalCompletion( true );
entry.setCompletionAction( completionCalled::incrementAndGet );
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( entry.haveResultsArrived(), false );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertEquals( entry.haveResultsArrived(), true );
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( completionCalled.get(), 1 );
assertEquals( connection.getRequest( requestId ), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@Test
public void completeMessageResponse_MessageWithRequest_RPCNotComplete()
{
final Connector connector = createConnector();
final Connection connection = newConnection( connector );
final Request request = connection.newRequest( "SomeAction" );
final AtomicInteger completionCalled = new AtomicInteger();
final int requestId = request.getRequestId();
final RequestEntry entry = request.getEntry();
final MessageResponse response = new MessageResponse( "" );
final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null );
response.recordChangeSet( changeSet, entry );
connection.setLastRxSequence( 22 );
connection.setCurrentMessageResponse( response );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( entry.haveResultsArrived(), false );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), entry );
connector.completeMessageResponse();
assertEquals( entry.haveResultsArrived(), true );
assertEquals( connection.getLastRxSequence(), 23 );
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( completionCalled.get(), 0 );
assertEquals( connection.getRequest( requestId ), null );
handler.assertEventCount( 1 );
handler.assertNextEvent( MessageProcessedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getSchemaName(), connector.getSchema().getName() );
assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
} );
}
@SuppressWarnings( { "ResultOfMethodCallIgnored", "unchecked" } )
@Test
public void progressResponseProcessing()
{
/*
* This test steps through each stage of a message processing.
*/
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final EntitySchema.Creator<Linkable> creator = mock( EntitySchema.Creator.class );
final EntitySchema.Updater<Linkable> updater = mock( EntitySchema.Updater.class );
final EntitySchema entitySchema =
new EntitySchema( 0, ValueUtil.randomString(), Linkable.class, creator, updater );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{ entitySchema } );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
@Language( "json" )
final String rawJsonData =
"{" +
"\"last_id\": 1, " +
// Add Channel 0
"\"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ], " +
// Add Entity 1 of type 0 from channel 0
"\"changes\": [{\"id\": 1,\"type\":0,\"channels\":[{\"cid\": 0}], \"data\":{}}] " +
"}";
connection.enqueueResponse( rawJsonData );
final MessageResponse response = connection.getUnparsedResponses().get( 0 );
{
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( connection.getUnparsedResponses().size(), 1 );
// Select response
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getUnparsedResponses().size(), 0 );
}
{
assertEquals( response.getRawJsonData(), rawJsonData );
assertThrows( response::getChangeSet );
assertEquals( response.needsParsing(), true );
assertEquals( connection.getPendingResponses().size(), 0 );
// Parse response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.getRawJsonData(), null );
assertNotNull( response.getChangeSet() );
assertEquals( response.needsParsing(), false );
}
{
assertEquals( connection.getCurrentMessageResponse(), null );
assertEquals( connection.getPendingResponses().size(), 1 );
// Pickup parsed response and set it as current
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), response );
assertEquals( connection.getPendingResponses().size(), 0 );
}
{
assertEquals( response.needsChannelChangesProcessed(), true );
// Process Channel Changes in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.needsChannelChangesProcessed(), false );
}
{
assertEquals( response.areEntityChangesPending(), true );
when( creator.createEntity( anyInt(), any( EntityChangeData.class ) ) ).thenReturn( mock( Linkable.class ) );
// Process Entity Changes in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.areEntityChangesPending(), false );
}
{
assertEquals( response.areEntityLinksPending(), true );
// Process Entity Links in response
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.areEntityLinksPending(), false );
}
{
assertEquals( response.hasWorldBeenValidated(), false );
// Validate World
assertTrue( connector.progressResponseProcessing() );
assertEquals( response.hasWorldBeenValidated(), true );
}
{
assertEquals( connection.getCurrentMessageResponse(), response );
// Complete message
assertTrue( connector.progressResponseProcessing() );
assertEquals( connection.getCurrentMessageResponse(), null );
}
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueNotInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
connector.pauseMessageScheduler();
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
connection.injectCurrentAreaOfInterestRequest( request );
Replicant.context().setCacheService( new TestCacheService() );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onSuccess_CachedValueInLocalCache()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
true, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestCacheService cacheService = new TestCacheService();
Replicant.context().setCacheService( cacheService );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final String key = "1.0";
final String eTag = "";
cacheService.store( key, eTag, ValueUtil.randomString() );
final AtomicReference<SafeProcedure> onCacheValid = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
assertEquals( i.getArguments()[ 2 ], eTag );
assertNotNull( i.getArguments()[ 3 ] );
onCacheValid.set( (SafeProcedure) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any(),
any( SafeProcedure.class ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
assertEquals( connector.isSchedulerActive(), false );
assertEquals( connection.getOutOfBandResponses().size(), 0 );
onCacheValid.get().call();
assertEquals( connector.isSchedulerActive(), true );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertEquals( connection.getOutOfBandResponses().size(), 1 );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestAddRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestAddRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscribe( eq( address1 ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestAddRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connector.pauseMessageScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscribe( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestAddRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request =
new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestUpdateRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestUpdateRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestSubscriptionUpdate( eq( address1 ), eq( filter ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestUpdateRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ),
eq( filter ),
any( SafeProcedure.class ),
any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestUpdateRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequest_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
null,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address = new ChannelAddress( 1, 0 );
final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription = createSubscription( address, null, true );
connection.injectCurrentAreaOfInterestRequest( request );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
assertEquals( i.getArguments()[ 0 ], address );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRemoveRequest( request );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onSuccess()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
onSuccess.get().call();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressBulkAreaOfInterestRemoveRequests_onFailure()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request3 =
new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
final Subscription subscription3 = createSubscription( address3, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
connection.injectCurrentAreaOfInterestRequest( request3 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
assertEquals( addresses.contains( address3 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) );
handler.assertEventCount( 3 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) );
handler.assertEventCount( 6 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address3 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_singleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestUnsubscribe( eq( address1 ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_zeroRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
// Pass in empty requests list to simulate that they are all filtered out
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRemoveRequests_onFailure_multipleRequests()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
final AreaOfInterestRequest request2 =
new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
final Subscription subscription1 = createSubscription( address1, null, true );
final Subscription subscription2 = createSubscription( address2, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
connection.injectCurrentAreaOfInterestRequest( request2 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>();
final AtomicInteger callCount = new AtomicInteger();
doAnswer( i -> {
callCount.incrementAndGet();
final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ];
assertEquals( addresses.contains( address1 ), true );
assertEquals( addresses.contains( address2 ), true );
onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] );
return null;
} )
.when( connector.getTransport() )
.requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() );
assertEquals( callCount.get(), 0 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>();
requests.add( request1 );
requests.add( request2 );
connector.progressAreaOfInterestRemoveRequests( requests );
assertEquals( callCount.get(), 1 );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) );
handler.assertEventCount( 2 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
} );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
} );
final Throwable error = new Throwable();
onFailure.get().accept( error );
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) );
safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) );
handler.assertEventCount( 4 );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address1 );
assertEquals( e.getError(), error );
} );
handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getAddress(), address2 );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Noop()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
pauseScheduler();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_InProgress()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
request1.markAsInProgress();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Add()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.STATIC,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter );
pauseScheduler();
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Update()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.DYNAMIC,
mock( SubscriptionUpdateEntityFilter.class ),
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final String filter = ValueUtil.randomString();
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@SuppressWarnings( "unchecked" )
@Test
public void progressAreaOfInterestRequestProcessing_Remove()
{
final ChannelSchema channelSchema =
new ChannelSchema( 0,
ValueUtil.randomString(),
String.class,
ChannelSchema.FilterType.NONE,
null,
false, true,
Collections.emptyList() );
final SystemSchema schema =
new SystemSchema( 1,
ValueUtil.randomString(),
new ChannelSchema[]{ channelSchema },
new EntitySchema[]{} );
final Connector connector = createConnector( schema );
final Connection connection = newConnection( connector );
final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 );
final AreaOfInterestRequest request1 =
new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null );
pauseScheduler();
createSubscription( address1, null, true );
connection.injectCurrentAreaOfInterestRequest( request1 );
final TestSpyEventHandler handler = registerTestSpyEventHandler();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
connector.progressAreaOfInterestRequestProcessing();
assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false );
handler.assertEventCount( 1 );
handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) );
}
@Test
public void pauseMessageScheduler()
{
final Connector connector = createConnector();
newConnection( connector );
connector.pauseMessageScheduler();
assertEquals( connector.isSchedulerPaused(), true );
assertEquals( connector.isSchedulerActive(), false );
connector.requestSubscribe( new ChannelAddress( 1, 0, 1 ), null );
assertEquals( connector.isSchedulerActive(), true );
connector.resumeMessageScheduler();
assertEquals( connector.isSchedulerPaused(), false );
assertEquals( connector.isSchedulerActive(), false );
connector.pauseMessageScheduler();
assertEquals( connector.isSchedulerPaused(), true );
assertEquals( connector.isSchedulerActive(), false );
// No progress
assertEquals( connector.progressMessages(), false );
Disposable.dispose( connector );
assertEquals( connector.isSchedulerActive(), false );
assertEquals( connector.isSchedulerPaused(), true );
assertNull( connector.getSchedulerLock() );
}
@Test
public void isSynchronized_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertTrue( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void isSynchronized_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertFalse( connector.isSynchronized() ) );
}
@Test
public void shouldRequestSync_notConnected()
{
final Connector connector = createConnector();
safeAction( () -> connector.setState( ConnectorState.DISCONNECTED ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_connected()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedRequestResponse_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_sentSyncRequest_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( true ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponse_Synced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseButResponsesQueued_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncRxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( false ) );
safeAction( () -> assertFalse( connector.shouldRequestSync() ) );
}
@Test
public void shouldRequestSync_receivedSyncRequestResponseErrored_NotSynced()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> connector.setLastSyncTxRequestId( 2 ) );
safeAction( () -> connector.setSyncInFlight( false ) );
safeAction( () -> connector.setPendingResponseQueueEmpty( true ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
}
@Test
public void onInSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onInSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( InSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onOutOfSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
connector.onOutOfSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( OutOfSyncEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void onSyncError()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> connector.setSyncInFlight( true ) );
final Throwable error = new Throwable();
connector.onSyncError( error );
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncFailureEvent.class,
e -> {
assertEquals( e.getSchemaId(), connector.getSchema().getId() );
assertEquals( e.getError(), error );
} );
}
@SuppressWarnings( "unchecked" )
@Test
public void requestSync()
{
final Connector connector = createConnector();
final TestSpyEventHandler handler = registerTestSpyEventHandler();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
connector.requestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), true ) );
verify( connector.getTransport() ).requestSync( any( SafeProcedure.class ),
any( SafeProcedure.class ),
(Consumer<Throwable>) any( Consumer.class ) );
handler.assertEventCount( 1 );
handler.assertNextEvent( SyncRequestEvent.class,
e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
}
@Test
public void maybeRequestSync()
{
final Connector connector = createConnector();
newConnection( connector );
safeAction( () -> connector.setState( ConnectorState.CONNECTED ) );
connector.maybeRequestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), false ) );
safeAction( () -> connector.setLastTxRequestId( 2 ) );
safeAction( () -> connector.setLastRxRequestId( 2 ) );
safeAction( () -> assertTrue( connector.shouldRequestSync() ) );
connector.maybeRequestSync();
safeAction( () -> assertEquals( connector.isSyncInFlight(), true ) );
}
}
| Fix test
| client/src/test/java/replicant/ConnectorTest.java | Fix test | <ide><path>lient/src/test/java/replicant/ConnectorTest.java
<ide> import replicant.spy.AreaOfInterestStatusUpdatedEvent;
<ide> import replicant.spy.ConnectFailureEvent;
<ide> import replicant.spy.ConnectedEvent;
<del>import replicant.spy.DataLoadStatus;
<ide> import replicant.spy.DisconnectFailureEvent;
<ide> import replicant.spy.DisconnectedEvent;
<ide> import replicant.spy.InSyncEvent;
<ide>
<ide> final TestSpyEventHandler handler = registerTestSpyEventHandler();
<ide>
<del> final DataLoadStatus status =
<del> new DataLoadStatus( ValueUtil.randomInt(),
<del> ValueUtil.randomInt(),
<del> ValueUtil.getRandom().nextInt( 10 ),
<del> ValueUtil.getRandom().nextInt( 10 ),
<del> ValueUtil.getRandom().nextInt( 10 ),
<del> ValueUtil.getRandom().nextInt( 100 ),
<del> ValueUtil.getRandom().nextInt( 100 ),
<del> ValueUtil.getRandom().nextInt( 10 ) );
<del>
<del> connector.onMessageProcessed( status );
<add> final MessageResponse response = new MessageResponse( "" );
<add> response.recordChangeSet( ChangeSet.create( 47, null, null ), null );
<add> connector.onMessageProcessed( response );
<ide>
<ide> verify( connector.getTransport() ).onMessageProcessed();
<ide>
<ide>
<ide> handler.assertNextEvent( MessageProcessedEvent.class, e -> {
<ide> assertEquals( e.getSchemaId(), connector.getSchema().getId() );
<del> assertEquals( e.getDataLoadStatus(), status );
<add> assertEquals( e.getDataLoadStatus().getSequence(), 47 );
<ide> } );
<ide> }
<ide>
<ide> assertEquals( e.getSchemaName(), connector.getSchema().getName() );
<ide> assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() );
<ide> } );
<del> handler.assertNextEvent( SyncRequestEvent.class, e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
<add> handler.assertNextEvent( SyncRequestEvent.class,
<add> e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) );
<ide> }
<ide>
<ide> @Test |
|
Java | mit | 658ebf2e078731cb3614fcae7608987cac0e3494 | 0 | CiccioTecchio/simrankJava | package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import calculator.SimCalculator;
public class Test {
private static SimCalculator calculator;
private static HashMap<String,Double> score;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
double c=Double.parseDouble(args[1]);
if(c<=0.0 || c>=1.00) throw new RuntimeException();
FileReader file= new FileReader(args[0]);
BufferedReader b= new BufferedReader(file);
String s=b.readLine();
calculator=new SimCalculator();
while(s!=null) {
calculator.initStructures(s);
s=b.readLine();
}
calculator.initScore(c);
//acquisizione info terminata
//gli stessi risultati del paper di Windom,Jeh si trovano con 7 iterazioni
int numIter=Integer.parseInt(args[2]);
if(numIter<=0) throw new RuntimeException();
printInstance();
score=calculator.simScore(numIter);
System.out.println("----------SCORE FINALI----------\n");
System.out.println(calculator.toStringMap(score)+"\n");
System.out.println("----------SCORE FINALI----------\n");
}catch(IOException e) {e.getMessage();
e.printStackTrace();}
catch(RuntimeException e) {e.getMessage();
e.printStackTrace();}
}
public static void printInstance() {
System.out.println("----------NOMI----------\n");
System.out.println(calculator.getNomi()+"\n");
System.out.println("----------NOMI----------\n");
System.out.println("----------MATRICE DI ADIACENZA----------\n");
System.out.println(calculator.getMatrix());
System.out.println("----------MATRICE DI ADIACENZA----------\n");
System.out.println("----------SCORE INIZIALI----------\n");
System.out.println(calculator.toStringMap(calculator.getScore())+"\n");
System.out.println("----------SCORE INIZIALI----------\n");
System.out.println("----------COEFF----------\n");
System.out.println(calculator.toStringMap(calculator.getCoeff())+"\n");
System.out.println("----------COEFF----------\n");
}
}
| src/test/Test.java | package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import calculator.SimCalculator;
public class Test {
private static SimCalculator calculator;
private static HashMap<String,Double> score;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
double c=Double.parseDouble(args[1]);
if(c<=0.0 || c>=1.00) throw new RuntimeException();
FileReader file= new FileReader(args[0]);
BufferedReader b= new BufferedReader(file);
String s=b.readLine();
calculator=new SimCalculator();
while(s!=null) {
calculator.initStructures(s);
s=b.readLine();
}
calculator.initScore(c);
//acquisizione info terminata
//gli stessi risultati del paper di Windom,Jeh si trovano con 7 iterazioni
int numIter=Integer.parseInt(args[2]);
printInstance();
score=calculator.simScore(7);
System.out.println("----------SCORE FINALI----------\n");
System.out.println(calculator.toStringMap(score)+"\n");
System.out.println("----------SCORE FINALI----------\n");
}catch(IOException e) {e.getMessage();
e.printStackTrace();}
catch(RuntimeException e) {e.getMessage();
e.printStackTrace();}
}
public static void printInstance() {
System.out.println("----------NOMI----------\n");
System.out.println(calculator.getNomi()+"\n");
System.out.println("----------NOMI----------\n");
System.out.println("----------MATRICE DI ADIACENZA----------\n");
System.out.println(calculator.getMatrix());
System.out.println("----------MATRICE DI ADIACENZA----------\n");
System.out.println("----------SCORE INIZIALI----------\n");
System.out.println(calculator.toStringMap(calculator.getScore())+"\n");
System.out.println("----------SCORE INIZIALI----------\n");
System.out.println("----------COEFF----------\n");
System.out.println(calculator.toStringMap(calculator.getCoeff())+"\n");
System.out.println("----------COEFF----------\n");
}
}
| aggiunto controllo sul numero di iterazioni
| src/test/Test.java | aggiunto controllo sul numero di iterazioni | <ide><path>rc/test/Test.java
<ide> //acquisizione info terminata
<ide> //gli stessi risultati del paper di Windom,Jeh si trovano con 7 iterazioni
<ide> int numIter=Integer.parseInt(args[2]);
<add> if(numIter<=0) throw new RuntimeException();
<ide> printInstance();
<del> score=calculator.simScore(7);
<add> score=calculator.simScore(numIter);
<ide> System.out.println("----------SCORE FINALI----------\n");
<ide> System.out.println(calculator.toStringMap(score)+"\n");
<ide> System.out.println("----------SCORE FINALI----------\n"); |
|
JavaScript | mit | 866026b1abbc3fe4fa84a65fdb1509eacf022fe6 | 0 | christoga/cepatsembuh,christoga/cepatsembuh,christoga/cepatsembuh,christoga/cepatsembuh,mercysmart/cepatsembuh,cepatsembuh/cordova,mercysmart/cepatsembuh,cepatsembuh/cordova,cepatsembuh/cordova,cepatsembuh/cordova,christoga/cepatsembuh,mercysmart/cepatsembuh,cepatsembuh/cordova,mercysmart/cepatsembuh,mercysmart/cepatsembuh | function login() {
var nama = document.pesan.nama.value;
var no-bpjs = document.pesan.no-bpjs.value;
var name = "Andre Christoga";
var bpjs-no = "";
if ((nama == name) && (no-bpjs == bpjs-no)) {
window.location.href = "rs.html";
return false;
};
else {
alert("Harap mendaftar terlebih dahulu")
}
}
| www/js/main.js | Login function
| www/js/main.js | Login function | <ide><path>ww/js/main.js
<add>function login() {
<add> var nama = document.pesan.nama.value;
<add> var no-bpjs = document.pesan.no-bpjs.value;
<add> var name = "Andre Christoga";
<add> var bpjs-no = "";
<add>
<add> if ((nama == name) && (no-bpjs == bpjs-no)) {
<add> window.location.href = "rs.html";
<add> return false;
<add> };
<add> else {
<add> alert("Harap mendaftar terlebih dahulu")
<add> }
<add>} |
||
Java | apache-2.0 | e834950b1dc651cfa7bf20b247bb1935bb344516 | 0 | chat-sdk/chat-sdk-android,chat-sdk/chat-sdk-android | package co.chatsdk.firebase.social_login;
import android.content.Context;
import co.chatsdk.core.session.ChatSDK;
/**
* Created by ben on 9/5/17.
*/
public class FirebaseSocialLoginModule {
public static void activate (Context context) {
ChatSDK.a().socialLogin = new FirebaseSocialLoginHandler(context);
}
}
| chat-sdk-firebase-social-login/src/main/java/co/chatsdk/firebase/social_login/FirebaseSocialLoginModule.java | package co.chatsdk.firebase.social_login;
import android.content.Context;
/**
* Created by ben on 9/5/17.
*/
public class FirebaseSocialLoginModule {
public static void activate (Context context) {
NetworkManager.shared().a.socialLogin = new FirebaseSocialLoginHandler(context);
}
}
| Fix small import issue
| chat-sdk-firebase-social-login/src/main/java/co/chatsdk/firebase/social_login/FirebaseSocialLoginModule.java | Fix small import issue | <ide><path>hat-sdk-firebase-social-login/src/main/java/co/chatsdk/firebase/social_login/FirebaseSocialLoginModule.java
<ide> package co.chatsdk.firebase.social_login;
<ide>
<ide> import android.content.Context;
<add>
<add>import co.chatsdk.core.session.ChatSDK;
<ide>
<ide> /**
<ide> * Created by ben on 9/5/17.
<ide> public class FirebaseSocialLoginModule {
<ide>
<ide> public static void activate (Context context) {
<del> NetworkManager.shared().a.socialLogin = new FirebaseSocialLoginHandler(context);
<add> ChatSDK.a().socialLogin = new FirebaseSocialLoginHandler(context);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 5b0857d6bff599214a852d1369c199264eb66e8b | 0 | balage1551/jsprit,muzuro/jsprit,sinhautkarsh2014/winter_jsprit,michalmac/jsprit,HeinrichFilter/jsprit,graphhopper/jsprit | /*******************************************************************************
* Copyright (c) 2011 Stefan Schroeder.
* eMail: [email protected]
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Stefan Schroeder - initial API and implementation
******************************************************************************/
package algorithms;
import java.util.Collection;
import basics.Job;
import basics.route.VehicleRoute;
/**
*
* @author stefan schroeder
*
*/
interface RuinStrategy {
/**
* Listener that listens to the ruin-process. It informs whoever is interested about start, end and about a removal of a job.
*
* @author schroeder
*
*/
public static interface RuinListener {
/**
* informs about ruin-start.
*
* @param routes
*/
public void ruinStarts(Collection<VehicleRoute> routes);
/**
* informs about ruin-end.
*
* @param routes
* @param unassignedJobs
*/
public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs);
/**
* informs if a {@link Job} has been removed from a {@link VehicleRoute}.
*
* @param job
* @param fromRoute
*/
public void removed(Job job, VehicleRoute fromRoute);
}
/**
* Ruins a current solution, i.e. a collection of vehicle-routes and
* returns a collection of removed and thus unassigned jobs.
*
* @param {@link VehicleRoute}
* @return Collection of {@link Job}
*/
public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes);
/**
* Removes targetJob as well as its neighbors with a size of (nOfJobs2BeRemoved-1).
*/
public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes, Job targetJob, int nOfJobs2BeRemoved);
/**
* Adds a ruin-listener.
*
* @param {@link RuinListener}
*/
public void addListener(RuinListener ruinListener);
}
| jsprit-core/src/main/java/algorithms/RuinStrategy.java | /*******************************************************************************
* Copyright (c) 2011 Stefan Schroeder.
* eMail: [email protected]
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Stefan Schroeder - initial API and implementation
******************************************************************************/
package algorithms;
import java.util.Collection;
import basics.Job;
import basics.route.VehicleRoute;
/**
*
* @author stefan schroeder
*
*/
interface RuinStrategy {
public static interface RuinListener {
public void ruinStarts(Collection<VehicleRoute> routes);
public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs);
public void removed(Job job, VehicleRoute fromRoute);
}
/**
* Ruins a current solution, i.e. removes jobs from service providers and
* returns a collection of these removed, and thus unassigned, jobs.
*
* @param vehicleRoutes
* @return
*/
public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes);
public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes, Job targetJob, int nOfJobs2BeRemoved);
public void addListener(RuinListener ruinListener);
}
| add javaDoc to RuinStrategy | jsprit-core/src/main/java/algorithms/RuinStrategy.java | add javaDoc to RuinStrategy | <ide><path>sprit-core/src/main/java/algorithms/RuinStrategy.java
<ide>
<ide> interface RuinStrategy {
<ide>
<add> /**
<add> * Listener that listens to the ruin-process. It informs whoever is interested about start, end and about a removal of a job.
<add> *
<add> * @author schroeder
<add> *
<add> */
<ide> public static interface RuinListener {
<ide>
<add> /**
<add> * informs about ruin-start.
<add> *
<add> * @param routes
<add> */
<ide> public void ruinStarts(Collection<VehicleRoute> routes);
<ide>
<add> /**
<add> * informs about ruin-end.
<add> *
<add> * @param routes
<add> * @param unassignedJobs
<add> */
<ide> public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs);
<ide>
<add> /**
<add> * informs if a {@link Job} has been removed from a {@link VehicleRoute}.
<add> *
<add> * @param job
<add> * @param fromRoute
<add> */
<ide> public void removed(Job job, VehicleRoute fromRoute);
<ide>
<ide> }
<ide>
<ide> /**
<del> * Ruins a current solution, i.e. removes jobs from service providers and
<del> * returns a collection of these removed, and thus unassigned, jobs.
<add> * Ruins a current solution, i.e. a collection of vehicle-routes and
<add> * returns a collection of removed and thus unassigned jobs.
<ide> *
<del> * @param vehicleRoutes
<del> * @return
<add> * @param {@link VehicleRoute}
<add> * @return Collection of {@link Job}
<ide> */
<ide> public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes);
<ide>
<add> /**
<add> * Removes targetJob as well as its neighbors with a size of (nOfJobs2BeRemoved-1).
<add> */
<ide> public Collection<Job> ruin(Collection<VehicleRoute> vehicleRoutes, Job targetJob, int nOfJobs2BeRemoved);
<ide>
<add> /**
<add> * Adds a ruin-listener.
<add> *
<add> * @param {@link RuinListener}
<add> */
<ide> public void addListener(RuinListener ruinListener);
<ide>
<ide> } |
|
Java | mit | 38bb1e541e3a74242efc2dd54d2211d1e89b7bd4 | 0 | Figglewatts/constant-candy-cruncher | package figglewatts.constantcandycruncher.entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import figglewatts.constantcandycruncher.ConstantCandyCruncher;
public class Player extends Entity {
// THESE STATS ARE UNMODIFYABLE WITH UPGRADES
// THEY ARE CHANGED BY THE GAME
private int health = 100;
private int lives = 3;
// THESE STATS ARE MODIFYABLE WITH UPGRADES
private int maxHealth = 100;
private float moveSpeed = 2.4f;
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLives() {
return lives;
}
public void setLives(int lives) {
this.lives = lives;
}
public Player() {
super(new Texture(Gdx.files.internal("data/playerTexture.png")), "Player");
this.health = maxHealth;
}
@Override
public void update(double delta) {
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
this.getSprite().translateX(-moveSpeed);
ConstantCandyCruncher.playGameScreen.background.modifyBackgroundOffset(-0.01f);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 0);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 1);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 2);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 3);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
this.getSprite().translateX(moveSpeed);
ConstantCandyCruncher.playGameScreen.background.modifyBackgroundOffset(0.01f);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 0);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 1);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 2);
ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 3);
}
}
}
| constant-candy-cruncher/src/figglewatts/constantcandycruncher/entity/Player.java | package figglewatts.constantcandycruncher.entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
public class Player extends Entity {
// THESE STATS ARE UNMODIFYABLE WITH UPGRADES
// THEY ARE CHANGED BY THE GAME
private int health = 100;
private int lives = 3;
// THESE STATS ARE MODIFYABLE WITH UPGRADES
private int maxHealth = 100;
private float moveSpeed = 2.4f;
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLives() {
return lives;
}
public void setLives(int lives) {
this.lives = lives;
}
public Player() {
super(new Texture(Gdx.files.internal("data/playerTexture.png")), "Player");
this.health = maxHealth;
}
@Override
public void update(double delta) {
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
this.getSprite().translateX(-moveSpeed);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
this.getSprite().translateX(moveSpeed);
}
}
}
| Added parallax offsets to Player class
| constant-candy-cruncher/src/figglewatts/constantcandycruncher/entity/Player.java | Added parallax offsets to Player class | <ide><path>onstant-candy-cruncher/src/figglewatts/constantcandycruncher/entity/Player.java
<ide> import com.badlogic.gdx.Gdx;
<ide> import com.badlogic.gdx.Input;
<ide> import com.badlogic.gdx.graphics.Texture;
<add>
<add>import figglewatts.constantcandycruncher.ConstantCandyCruncher;
<ide>
<ide> public class Player extends Entity {
<ide> // THESE STATS ARE UNMODIFYABLE WITH UPGRADES
<ide> public void update(double delta) {
<ide> if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
<ide> this.getSprite().translateX(-moveSpeed);
<add> ConstantCandyCruncher.playGameScreen.background.modifyBackgroundOffset(-0.01f);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 0);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 1);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 2);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(-0.05f, 3);
<ide> }
<ide> if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
<ide> this.getSprite().translateX(moveSpeed);
<add> ConstantCandyCruncher.playGameScreen.background.modifyBackgroundOffset(0.01f);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 0);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 1);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 2);
<add> ConstantCandyCruncher.playGameScreen.background.modifyParallaxOffset(0.05f, 3);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 86785ea9a06252c09aab51091e08e8933879395e | 0 | uqlibrary/uqlibrary-reusable-components,uqlibrary/uqlibrary-reusable-components,uqlibrary/uqlibrary-reusable-components | /*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var argv = require('yargs').argv;
var del = require('del');
var runSequence = require('run-sequence');
//var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
//var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var awspublish = require('gulp-awspublish');
var gutil = require('gulp-util');
var rename = require('gulp-rename');
var taskList = require('gulp-task-listing');
var cssmin = require('gulp-cssmin');
var jsonlint = require('gulp-jsonlint');
var cloudfront = require('gulp-invalidate-cloudfront');
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
var config = {
applications: 'applications',
elements: 'elements',
dependencies: 'bower_components',
resources: 'resources',
demo: 'elements/demo'
};
// Lint JavaScript
gulp.task('jshint', function () {
return gulp.src([
config.applications + '/**/*.js',
config.elements + '/**/*.js'
])
//.pipe(reload({stream: true, once: true}))
.pipe($.jshint.extract()) // Extract JS from .html files
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
//.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// Lint JSON
gulp.task('jsonlint', function () {
return gulp.src([
config.resources + '/**/*.json',
config.applications + '/**/*.json',
config.elements + '/**/*.json'
])
.pipe(jsonlint())
.pipe(jsonlint.failAfterError())
.pipe(jsonlint.reporter());
});
// Vulcanize imports
gulp.task('vulcanize', ['clean:vulcanize', 'copy:vulcanize'], function () {
return gulp.src(config.elements + '/elements.vulcanized.html')
.pipe($.vulcanize({
dest: config.elements,
strip: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(gulp.dest(config.elements))
.pipe($.size({title: 'vulcanize'}));
});
// delete old vulcanized file
gulp.task('clean:vulcanize', function (done) {
del([
config.elements + '/elements.vulcanized.html'
], done);
});
// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:vulcanize', function () {
var vulcanized = gulp.src([config.elements + '/elements.html'])
.pipe($.rename('elements.vulcanized.html'))
.pipe(gulp.dest(config.elements));
return merge(vulcanized)
.pipe($.size({title: 'copy'}));
});
// optimize files
gulp.task('optimize', function () {
gulp.src(config.applications + '/**/*.css')
.pipe(cssmin())
.pipe(gulp.dest(config.applications));
});
// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:aws', function () {
var vulcanized = gulp.src([config.elements + '/elements.vulcanized.html'])
.pipe(gulp.dest(config.applications));
var dependencies = gulp.src([config.dependencies + '/webcomponentsjs/**/*'])
.pipe(gulp.dest(config.applications + '/webcomponentsjs'));
var resources = gulp.src([config.resources + '/**/*'])
.pipe(gulp.dest(config.applications + '/resources'));
var demo = gulp.src([config.demo + '/**/*'])
.pipe(gulp.dest(config.applications + '/elements/demo'));
return merge(vulcanized, dependencies, resources, demo)
.pipe($.size({title: 'copy'}));
});
/**
* Command line param:
* --bucketSubDir {INVALIDATION_PATH}
*
* If no bucket subdir passed will invalidate production subdir
*/
gulp.task('invalidate', function () {
var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
var invalidatePath = '';
if (argv.bucketSubDir) {
invalidatePath = argv.bucketSubDir + '/*';
} else {
invalidatePath += '/reusable-components/*';
}
var invalidationBatch = {
CallerReference: new Date().toString(),
Paths: {
Quantity: 1,
Items: [
invalidatePath
]
}
};
var awsSettings = {
credentials: {
accessKeyId: awsConfig.accessKeyId,
secretAccessKey: awsConfig.secretAccessKey
},
distributionId: awsConfig.params.distribution,
region: awsConfig.params.region
};
return gulp.src([
config.applications + '/*',
config.elements + '/*',
config.dependencies + '/*',
config.resources + '/*'
]).pipe(cloudfront(invalidationBatch, awsSettings));
});
// upload package to S3
gulp.task('publish', ['copy:aws'], function () {
// create a new publisher using S3 options
var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
var publisher = awspublish.create(awsConfig);
// define custom headers
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./' + config.applications + '/**')
.pipe(rename(function (path) {
path.dirname = awsConfig.params.bucketSubDir + '/' + path.dirname;
}))
// gzip, Set Content-Encoding headers
.pipe(awspublish.gzip())
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe(awspublish.reporter());
});
gulp.task('syntax', [
'jshint',
'jsonlint'
]);
gulp.task('build', [
'syntax',
'optimize',
'vulcanize'
]);
// display a list of available tasks
gulp.task('help', taskList);
gulp.task('default', ['help']);
// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
try {
require('web-component-tester').gulp.init(gulp);
}
catch (err) {
}
//// Load custom tasks from the `tasks` directory
//try { require('require-dir')('tasks'); } catch (err) {}
| gulpfile.js | /*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var argv = require('yargs').argv;
var del = require('del');
var runSequence = require('run-sequence');
//var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
//var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var awspublish = require('gulp-awspublish');
var gutil = require('gulp-util');
var rename = require('gulp-rename');
var taskList = require('gulp-task-listing');
var cssmin = require('gulp-cssmin');
var jsonlint = require('gulp-jsonlint');
var cloudfront = require('gulp-invalidate-cloudfront');
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
var config = {
applications: 'applications',
elements: 'elements',
dependencies: 'bower_components',
resources: 'resources',
demo: 'elements/demo'
};
// Lint JavaScript
gulp.task('jshint', function () {
return gulp.src([
config.applications + '/**/*.js',
config.elements + '/**/*.js'
])
//.pipe(reload({stream: true, once: true}))
.pipe($.jshint.extract()) // Extract JS from .html files
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
//.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// Lint JSON
gulp.task('jsonlint', function () {
return gulp.src([
config.resources + '/**/*.json',
config.applications + '/**/*.json',
config.elements + '/**/*.json'
])
.pipe(jsonlint())
.pipe(jsonlint.failAfterError())
.pipe(jsonlint.reporter());
});
// Vulcanize imports
gulp.task('vulcanize', ['clean:vulcanize', 'copy:vulcanize'], function () {
return gulp.src(config.elements + '/elements.vulcanized.html')
.pipe($.vulcanize({
dest: config.elements,
strip: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(gulp.dest(config.elements))
.pipe($.size({title: 'vulcanize'}));
});
// delete old vulcanized file
gulp.task('clean:vulcanize', function (done) {
del([
config.elements + '/elements.vulcanized.html'
], done);
});
// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:vulcanize', function () {
var vulcanized = gulp.src([config.elements + '/elements.html'])
.pipe($.rename('elements.vulcanized.html'))
.pipe(gulp.dest(config.elements));
return merge(vulcanized)
.pipe($.size({title: 'copy'}));
});
// optimize files
gulp.task('optimize', function () {
gulp.src(config.applications + '/**/*.css')
.pipe(cssmin())
.pipe(gulp.dest(config.applications));
});
// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:aws', function () {
var vulcanized = gulp.src([config.elements + '/elements.vulcanized.html'])
.pipe(gulp.dest(config.applications));
var dependencies = gulp.src([config.dependencies + '/webcomponentsjs/**/*'])
.pipe(gulp.dest(config.applications + '/webcomponentsjs'));
var resources = gulp.src([config.resources + '/**/*'])
.pipe(gulp.dest(config.applications + '/resources'));
var demo = gulp.src([config.demo + '/**/*'])
.pipe(gulp.dest(config.applications + '/elements/demo'));
return merge(vulcanized, dependencies, resources, demo)
.pipe($.size({title: 'copy'}));
});
/**
* Command line param:
* --bucketSubDir {CI_BRANCH}
*
* If no bucket subdir passed will invalidate production subdir
*/
gulp.task('invalidate', function () {
var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
var invalidatePath = '';
if (argv.bucketSubDir) {
invalidatePath = argv.bucketSubDir + '/*';
} else {
invalidatePath += '/reusable-components/*';
}
var invalidationBatch = {
CallerReference: new Date().toString(),
Paths: {
Quantity: 1,
Items: [
invalidatePath
]
}
};
var awsSettings = {
credentials: {
accessKeyId: awsConfig.accessKeyId,
secretAccessKey: awsConfig.secretAccessKey
},
distributionId: awsConfig.params.distribution,
region: awsConfig.params.region
};
return gulp.src([
config.applications + '/*',
config.elements + '/*',
config.dependencies + '/*',
config.resources + '/*'
]).pipe(cloudfront(invalidationBatch, awsSettings));
});
// upload package to S3
gulp.task('publish', ['copy:aws'], function () {
// create a new publisher using S3 options
var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
var publisher = awspublish.create(awsConfig);
// define custom headers
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./' + config.applications + '/**')
.pipe(rename(function (path) {
path.dirname = awsConfig.params.bucketSubDir + '/' + path.dirname;
}))
// gzip, Set Content-Encoding headers
.pipe(awspublish.gzip())
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe(awspublish.reporter());
});
gulp.task('syntax', [
'jshint',
'jsonlint'
]);
gulp.task('build', [
'syntax',
'optimize',
'vulcanize'
]);
// display a list of available tasks
gulp.task('help', taskList);
gulp.task('default', ['help']);
// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
try {
require('web-component-tester').gulp.init(gulp);
}
catch (err) {
}
//// Load custom tasks from the `tasks` directory
//try { require('require-dir')('tasks'); } catch (err) {}
| Changing param name
| gulpfile.js | Changing param name | <ide><path>ulpfile.js
<ide>
<ide> /**
<ide> * Command line param:
<del> * --bucketSubDir {CI_BRANCH}
<add> * --bucketSubDir {INVALIDATION_PATH}
<ide> *
<ide> * If no bucket subdir passed will invalidate production subdir
<ide> */ |
|
Java | epl-1.0 | e978558b7c453fe157edb59fc8d178413dc5b139 | 0 | pecko/limpet,pecko/limpet,pecko/limpet,debrief/limpet,debrief/limpet,debrief/limpet | package info.limpet.stackedcharts.ui.view;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.math3.analysis.interpolation.LinearInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRendererState;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.util.LineUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
public class WrappingRenderer extends XYLineAndShapeRenderer
{
/**
* /** An interface for creating custom logic for drawing lines between points for
* XYLineAndShapeRenderer.
*/
public static interface OverflowCondition
{
/**
* Custom logic for detecting overflow between points.
*
* @param y0
* previous y
* @param x0
* previous x
* @param y1
* current y
* @param x1
* current x
* @return true, if you there is an overflow detected. Otherwise, return false
*/
public boolean isOverflow(double y0, double x0, double y1, double x1);
}
/**
*
*/
private static final long serialVersionUID = 1L;
final double min;
final double max;
final double range;
LinearInterpolator interpolator = new LinearInterpolator();
final OverflowCondition overflowCondition;
public WrappingRenderer(final double min, final double max)
{
this.min = min;
this.max = max;
this.range = max - min;
overflowCondition = new OverflowCondition()
{
@Override
public boolean isOverflow(double y0, double x0, double y1, double x1)
{
return Math.abs(y1 - y0) > 180d;
}
};
}
@Override
protected void
drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2,
XYPlot plot, XYDataset dataset, int pass, int series, int item,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea)
{
// get the data point...
State s = (State) state;
try
{
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(x1) && Double.isNaN(y1))
{
s.setLastPointGood(false);
return;
}
if (!s.isLastPointGood())
{
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
s.setLastPointGood(true);
return;
}
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
if (overflowCondition.isOverflow(y0, x0, y1, x1))
{
boolean overflowAtMax = y1 < y0;
if (overflowAtMax)
{
// double check values valid (not greater than max)
y0 = y0 > max ? y0 - range : y0;
y1 = y1 > max ? y1 - range : y1;
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y0, y1 + range}, new double[]
{x0, x1});
double xmid = psf.value(max);
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, xmid, max);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
else
{
// double check values valid (not less than min)
y0 = y0 < min ? y0 + range : y0;
y1 = y1 < min ? y1 + range : y1;
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y1 - range, y0}, new double[]
{x1, x0});
double xmid = psf.value(min);
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, xmid, min);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
}
else
{
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
s.setLastPointGood(true);
}
finally
{
// if this is the last item, draw the path ...
if (item == s.getLastItemIndex())
{
// draw path
drawFirstPassShape(g2, pass, series, item, s.seriesPath);
}
}
}
private ImmutablePair<Float, Float> translate(XYPlot plot,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea,
double x, double y)
{
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX1 = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
// update path to reflect latest point
float xtrans = (float) transX1;
float ytrans = (float) transY1;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL)
{
xtrans = (float) transY1;
ytrans = (float) transX1;
}
return new ImmutablePair<>(xtrans, ytrans);
}
@Override
protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2,
XYPlot plot, XYDataset dataset, int pass, int series, int item,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea)
{
if (item == 0)
{
return;
}
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(y1) || Double.isNaN(x1))
{
return;
}
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
if (Double.isNaN(y0) || Double.isNaN(x0))
{
return;
}
if (overflowCondition.isOverflow(y0, x0, y1, x1))
{
boolean overflowAtMax = y1 < y0;
if (overflowAtMax)
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y0, y1 + (max-min)}, new double[]
{x0, x1});
double xmid = psf.value(max);
drawPrimaryLine(state, g2, plot, x0, y0, xmid, max, pass, series, item,
domainAxis, rangeAxis, dataArea);
drawPrimaryLine(state, g2, plot, xmid, min, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
else
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y1 - (max-min), y0}, new double[]
{x1, x0});
double xmid = psf.value(min);
drawPrimaryLine(state, g2, plot, x0, y0, xmid, min, pass, series, item,
domainAxis, rangeAxis, dataArea);
drawPrimaryLine(state, g2, plot, xmid, max, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
}
else
{
drawPrimaryLine(state, g2, plot, x0, y0, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
}
private void drawPrimaryLine(XYItemRendererState state, Graphics2D g2,
XYPlot plot, double x0, double y0, double x1, double y1, int pass,
int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis,
Rectangle2D dataArea)
{
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
// only draw if we have good values
if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
|| Double.isNaN(transY1))
{
return;
}
PlotOrientation orientation = plot.getOrientation();
boolean visible;
if (orientation == PlotOrientation.HORIZONTAL)
{
state.workingLine.setLine(transY0, transX0, transY1, transX1);
}
else if (orientation == PlotOrientation.VERTICAL)
{
state.workingLine.setLine(transX0, transY0, transX1, transY1);
}
visible = LineUtilities.clipLine(state.workingLine, dataArea);
if (visible)
{
drawFirstPassShape(g2, pass, series, item, state.workingLine);
}
}
}
| info.limpet.stackedcharts.ui/src/info/limpet/stackedcharts/ui/view/WrappingRenderer.java | package info.limpet.stackedcharts.ui.view;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.math3.analysis.interpolation.LinearInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRendererState;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.util.LineUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
public class WrappingRenderer extends XYLineAndShapeRenderer
{
/**
* /** An interface for creating custom logic for drawing lines between points for
* XYLineAndShapeRenderer.
*/
public static interface OverflowCondition
{
/**
* Custom logic for detecting overflow between points.
*
* @param y0
* previous y
* @param x0
* previous x
* @param y1
* current y
* @param x1
* current x
* @return true, if you there is an overflow detected. Otherwise, return false
*/
public boolean isOverflow(double y0, double x0, double y1, double x1);
}
/**
*
*/
private static final long serialVersionUID = 1L;
final double min;
final double max;
LinearInterpolator interpolator = new LinearInterpolator();
final OverflowCondition overflowCondition;
public WrappingRenderer(final double min, final double max)
{
this.min = min;
this.max = max;
overflowCondition = new OverflowCondition()
{
@Override
public boolean isOverflow(double y0, double x0, double y1, double x1)
{
return Math.abs(y1 - y0) > 180d;
}
};
}
@Override
protected void
drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2,
XYPlot plot, XYDataset dataset, int pass, int series, int item,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea)
{
// get the data point...
State s = (State) state;
try
{
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(x1) && Double.isNaN(y1))
{
s.setLastPointGood(false);
return;
}
if (!s.isLastPointGood())
{
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
s.setLastPointGood(true);
return;
}
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
if (overflowCondition.isOverflow(y0, x0, y1, x1))
{
boolean overflowAtMax = y1 < y0;
if (overflowAtMax)
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y0, y1 + (max-min)}, new double[]
{x0, x1});
double xmid = psf.value(max);
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, xmid, max);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
else
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y1 - (max - min), y0}, new double[]
{x1, x0});
double xmid = psf.value(min);
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, xmid, min);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max);
s.seriesPath.moveTo(xy.getLeft(), xy.getRight());
xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
}
else
{
ImmutablePair<Float, Float> xy =
translate(plot, domainAxis, rangeAxis, dataArea, x1, y1);
s.seriesPath.lineTo(xy.getLeft(), xy.getRight());
}
s.setLastPointGood(true);
}
finally
{
// if this is the last item, draw the path ...
if (item == s.getLastItemIndex())
{
// draw path
drawFirstPassShape(g2, pass, series, item, s.seriesPath);
}
}
}
private ImmutablePair<Float, Float> translate(XYPlot plot,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea,
double x, double y)
{
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX1 = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
// update path to reflect latest point
float xtrans = (float) transX1;
float ytrans = (float) transY1;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL)
{
xtrans = (float) transY1;
ytrans = (float) transX1;
}
return new ImmutablePair<>(xtrans, ytrans);
}
@Override
protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2,
XYPlot plot, XYDataset dataset, int pass, int series, int item,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea)
{
if (item == 0)
{
return;
}
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(y1) || Double.isNaN(x1))
{
return;
}
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
if (Double.isNaN(y0) || Double.isNaN(x0))
{
return;
}
if (overflowCondition.isOverflow(y0, x0, y1, x1))
{
boolean overflowAtMax = y1 < y0;
if (overflowAtMax)
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y0, y1 + (max-min)}, new double[]
{x0, x1});
double xmid = psf.value(max);
drawPrimaryLine(state, g2, plot, x0, y0, xmid, max, pass, series, item,
domainAxis, rangeAxis, dataArea);
drawPrimaryLine(state, g2, plot, xmid, min, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
else
{
PolynomialSplineFunction psf = interpolator.interpolate(new double[]
{y1 - (max-min), y0}, new double[]
{x1, x0});
double xmid = psf.value(min);
drawPrimaryLine(state, g2, plot, x0, y0, xmid, min, pass, series, item,
domainAxis, rangeAxis, dataArea);
drawPrimaryLine(state, g2, plot, xmid, max, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
}
else
{
drawPrimaryLine(state, g2, plot, x0, y0, x1, y1, pass, series, item,
domainAxis, rangeAxis, dataArea);
}
}
private void drawPrimaryLine(XYItemRendererState state, Graphics2D g2,
XYPlot plot, double x0, double y0, double x1, double y1, int pass,
int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis,
Rectangle2D dataArea)
{
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
// only draw if we have good values
if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
|| Double.isNaN(transY1))
{
return;
}
PlotOrientation orientation = plot.getOrientation();
boolean visible;
if (orientation == PlotOrientation.HORIZONTAL)
{
state.workingLine.setLine(transY0, transX0, transY1, transX1);
}
else if (orientation == PlotOrientation.VERTICAL)
{
state.workingLine.setLine(transX0, transY0, transX1, transY1);
}
visible = LineUtilities.clipLine(state.workingLine, dataArea);
if (visible)
{
drawFirstPassShape(g2, pass, series, item, state.workingLine);
}
}
}
| special handling for out-of-cycle data points
| info.limpet.stackedcharts.ui/src/info/limpet/stackedcharts/ui/view/WrappingRenderer.java | special handling for out-of-cycle data points | <ide><path>nfo.limpet.stackedcharts.ui/src/info/limpet/stackedcharts/ui/view/WrappingRenderer.java
<ide> private static final long serialVersionUID = 1L;
<ide> final double min;
<ide> final double max;
<add> final double range;
<ide> LinearInterpolator interpolator = new LinearInterpolator();
<ide> final OverflowCondition overflowCondition;
<ide>
<ide> {
<ide> this.min = min;
<ide> this.max = max;
<add> this.range = max - min;
<ide>
<ide> overflowCondition = new OverflowCondition()
<ide> {
<ide> boolean overflowAtMax = y1 < y0;
<ide> if (overflowAtMax)
<ide> {
<add> // double check values valid (not greater than max)
<add> y0 = y0 > max ? y0 - range : y0;
<add> y1 = y1 > max ? y1 - range : y1;
<add>
<ide> PolynomialSplineFunction psf = interpolator.interpolate(new double[]
<del> {y0, y1 + (max-min)}, new double[]
<add> {y0, y1 + range}, new double[]
<ide> {x0, x1});
<ide> double xmid = psf.value(max);
<ide> ImmutablePair<Float, Float> xy =
<ide> }
<ide> else
<ide> {
<add> // double check values valid (not less than min)
<add> y0 = y0 < min ? y0 + range : y0;
<add> y1 = y1 < min ? y1 + range : y1;
<add>
<ide> PolynomialSplineFunction psf = interpolator.interpolate(new double[]
<del> {y1 - (max - min), y0}, new double[]
<add> {y1 - range, y0}, new double[]
<ide> {x1, x0});
<ide> double xmid = psf.value(min);
<ide> ImmutablePair<Float, Float> xy = |
|
Java | apache-2.0 | e31b5224ceb3041bf8c80beb70205f2fa564dfc1 | 0 | googleinterns/step256-2020,googleinterns/step256-2020,googleinterns/step256-2020 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gson.Gson;
import com.google.sps.GoogleShoppingQuerier;
import com.google.sps.ImageTextDectector;
import com.google.sps.PhotoDetectionException;
import com.google.sps.ShoppingQuerierConnectionException;
import com.google.sps.TextDetectionAPIImpl;
import com.google.sps.data.Product;
import com.google.sps.data.ShoppingQueryInput;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* When the user submits the form for image uploading, Blobstore processes the file upload and
* forwards the request to this servlet, which returns the product shopping results for the
* respective photo, in JSON format, along with the shopping query used to search.
*/
@WebServlet("/handle-photo-shopping")
public class HandlePhotoShoppingServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the BlobKey that points to the image uploaded by the user.
BlobKey uploadedImageBlobKey = getBlobKey(request, "photo");
// Send an error if the user did not upload a file.
if (uploadedImageBlobKey == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing input image file.");
return;
}
// Get the photo category (i.e. product, shopping-list or barcode) entered by the user.
String photoCategory = request.getParameter("photo-category");
if (photoCategory.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing photo category.");
return;
}
// Get the image the user uploaded as bytes.
byte[] uploadedImageBytes = getBlobBytes(uploadedImageBlobKey);
// Call GoogleShoppingQuerier to return the extracted products data.
// First, build the shopping query input.
String shoppingQuery;
try {
shoppingQuery = getQuery(request.getParameter("photo-category"), uploadedImageBytes);
} catch (IllegalArgumentException | PhotoDetectionException exception) {
response.sendError(SC_INTERNAL_SERVER_ERROR, exception.getMessage());
return;
}
ShoppingQueryInput shoppingQueryInput =
new ShoppingQueryInput.Builder(shoppingQuery).language("en").maxResultsNumber(24).build();
// Initialize the Google Shopping querier.
GoogleShoppingQuerier querier = new GoogleShoppingQuerier();
List<Product> shoppingQuerierResults = new ArrayList<>();
try {
shoppingQuerierResults = querier.query(shoppingQueryInput);
} catch (IllegalArgumentException
| ShoppingQuerierConnectionException
| IOException exception) {
response.sendError(SC_INTERNAL_SERVER_ERROR, exception.getMessage());
return;
}
// Convert {@code shoppingQuery} and products List - {@code shoppingQuerierResults} - into JSON
// strings
// using Gson library and send a JSON array with both of the JSON strings as response.
Gson gson = new Gson();
String shoppingQueryJSON = gson.toJson(shoppingQuery);
String shoppingQuerierResultsJSON = gson.toJson(shoppingQuerierResults);
response.setContentType("application/json;");
response.getWriter().write("[" + shoppingQueryJSON + "," + shoppingQuerierResultsJSON + "]");
}
/**
* Returns the shopping query by calling methods from the photo content detection classes, based
* on the {@code photoCategory}, passing {@code uploadedImageBytes} as argument.
*/
private String getQuery(String photoCategory, byte[] uploadedImageBytes)
throws IllegalArgumentException, PhotoDetectionException {
switch (photoCategory) {
case "product":
return "Fountain pen";
case "shopping-list":
TextDetectionAPIImpl textDetectionAPI = new TextDetectionAPIImpl();
ImageTextDectector imageTextDectector = new ImageTextDectector(textDetectionAPI);
String shoppingQuery;
try {
shoppingQuery = imageTextDectector.extractShoppingList(uploadedImageBytes);
} catch (PhotoDetectionException exception) {
throw exception;
} catch (IOException e) {
throw new PhotoDetectionException("Error while getting shopping query.", e);
}
return shoppingQuery;
case "barcode":
return "Running shoes";
default:
throw new IllegalArgumentException(
"Photo category has to be either product, shopping-list or barcode.");
}
}
/**
* Returns the BlobKey corresponding to the file uploaded by the user, or null if the user did not
* upload a file.
*/
private BlobKey getBlobKey(HttpServletRequest request, String formFileInputElementName) {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get(formFileInputElementName);
// User submitted form without selecting a file. (dev server)
if (blobKeys.equals(Optional.empty()) || blobKeys.isEmpty()) {
return null;
}
// The form only contains a single file input, so get the first index.
BlobKey blobKey = blobKeys.get(0);
// User submitted form without selecting a file, so the BlobKey is empty. (live server)
BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
if (blobInfo.getSize() == 0) {
blobstoreService.delete(blobKey);
return null;
}
return blobKey;
}
/**
* Blobstore stores files as binary data. This function retrieves the image represented by the
* binary data stored at the BlobKey parameter.
*/
private byte[] getBlobBytes(BlobKey blobKey) throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
int fetchSize = BlobstoreService.MAX_BLOB_FETCH_SIZE;
long currentByteIndex = 0;
boolean continueReading = true;
while (continueReading) {
// End index is inclusive, therefore subtract 1 to get fetchSize bytes.
byte[] b =
blobstoreService.fetchData(blobKey, currentByteIndex, currentByteIndex + fetchSize - 1);
outputBytes.write(b);
// If fewer bytes than requested have been read, the end is reached.
if (b.length < fetchSize) {
continueReading = false;
}
currentByteIndex += fetchSize;
}
return outputBytes.toByteArray();
}
}
| src/main/java/com/google/sps/servlets/HandlePhotoShoppingServlet.java | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gson.Gson;
import com.google.sps.GoogleShoppingQuerier;
import com.google.sps.ImageTextDectector;
import com.google.sps.PhotoDetectionException;
import com.google.sps.ShoppingQuerierConnectionException;
import com.google.sps.TextDetectionAPIImpl;
import com.google.sps.data.Product;
import com.google.sps.data.ShoppingQueryInput;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* When the user submits the form for image uploading, Blobstore processes the file upload and
* forwards the request to this servlet, which returns the product shopping results for the
* respective photo, in JSON format, along with the shopping query used to search.
*/
@WebServlet("/handle-photo-shopping")
public class HandlePhotoShoppingServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the BlobKey that points to the image uploaded by the user.
BlobKey uploadedImageBlobKey = getBlobKey(request, "photo");
// Send an error if the user did not upload a file.
if (uploadedImageBlobKey == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing input image file.");
return;
}
// Get the photo category (i.e. product, shopping-list or barcode) entered by the user.
String photoCategory = request.getParameter("photo-category");
if (photoCategory.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing photo category.");
return;
}
// Get the image the user uploaded as bytes.
byte[] uploadedImageBytes = getBlobBytes(uploadedImageBlobKey);
// Call GoogleShoppingQuerier to return the extracted products data.
// First, build the shopping query input.
String shoppingQuery;
try {
shoppingQuery = getQuery(request.getParameter("photo-category"), uploadedImageBytes);
} catch (IllegalArgumentException | PhotoDetectionException exception) {
response.sendError(SC_INTERNAL_SERVER_ERROR, exception.getMessage());
return;
}
ShoppingQueryInput shoppingQueryInput =
new ShoppingQueryInput.Builder(shoppingQuery).language("en").maxResultsNumber(24).build();
// Initialize the Google Shopping querier.
GoogleShoppingQuerier querier = new GoogleShoppingQuerier();
List<Product> shoppingQuerierResults = new ArrayList<>();
try {
shoppingQuerierResults = querier.query(shoppingQueryInput);
} catch (IllegalArgumentException
| ShoppingQuerierConnectionException
| IOException exception) {
response.sendError(SC_INTERNAL_SERVER_ERROR, exception.getMessage());
return;
}
// Convert {@code shoppingQuery} and products List - {@code shoppingQuerierResults} - into JSON
// strings
// using Gson library and send a JSON array with both of the JSON strings as response.
Gson gson = new Gson();
String shoppingQueryJSON = gson.toJson(shoppingQuery);
String shoppingQuerierResultsJSON = gson.toJson(shoppingQuerierResults);
response.setContentType("application/json;");
response.getWriter().write("[" + shoppingQueryJSON + "," + shoppingQuerierResultsJSON + "]");
}
/**
* Returns the shopping query by calling methods from the photo content detection classes, based
* on the {@code photoCategory}, passing {@code uploadedImageBytes} as argument.
*/
private String getQuery(String photoCategory, byte[] uploadedImageBytes)
throws IllegalArgumentException, PhotoDetectionException {
switch (photoCategory) {
case "product":
return "Fountain pen";
case "shopping-list":
TextDetectionAPIImpl textDetectionAPI = new TextDetectionAPIImpl();
ImageTextDectector imageTextDectector = new ImageTextDectector(textDetectionAPI);
String shoppingQuery;
try {
shoppingQuery = imageTextDectector.imageToShoppingListExtractor(uploadedImageBytes);
} catch (PhotoDetectionException exception) {
throw exception;
} catch (IOException e) {
throw new PhotoDetectionException("Error while getting shopping query.", e);
}
return shoppingQuery;
case "barcode":
return "Running shoes";
default:
throw new IllegalArgumentException(
"Photo category has to be either product, shopping-list or barcode.");
}
}
/**
* Returns the BlobKey corresponding to the file uploaded by the user, or null if the user did not
* upload a file.
*/
private BlobKey getBlobKey(HttpServletRequest request, String formFileInputElementName) {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get(formFileInputElementName);
// User submitted form without selecting a file. (dev server)
if (blobKeys.equals(Optional.empty()) || blobKeys.isEmpty()) {
return null;
}
// The form only contains a single file input, so get the first index.
BlobKey blobKey = blobKeys.get(0);
// User submitted form without selecting a file, so the BlobKey is empty. (live server)
BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
if (blobInfo.getSize() == 0) {
blobstoreService.delete(blobKey);
return null;
}
return blobKey;
}
/**
* Blobstore stores files as binary data. This function retrieves the image represented by the
* binary data stored at the BlobKey parameter.
*/
private byte[] getBlobBytes(BlobKey blobKey) throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
int fetchSize = BlobstoreService.MAX_BLOB_FETCH_SIZE;
long currentByteIndex = 0;
boolean continueReading = true;
while (continueReading) {
// End index is inclusive, therefore subtract 1 to get fetchSize bytes.
byte[] b =
blobstoreService.fetchData(blobKey, currentByteIndex, currentByteIndex + fetchSize - 1);
outputBytes.write(b);
// If fewer bytes than requested have been read, the end is reached.
if (b.length < fetchSize) {
continueReading = false;
}
currentByteIndex += fetchSize;
}
return outputBytes.toByteArray();
}
}
| Update method name
| src/main/java/com/google/sps/servlets/HandlePhotoShoppingServlet.java | Update method name | <ide><path>rc/main/java/com/google/sps/servlets/HandlePhotoShoppingServlet.java
<ide> ImageTextDectector imageTextDectector = new ImageTextDectector(textDetectionAPI);
<ide> String shoppingQuery;
<ide> try {
<del> shoppingQuery = imageTextDectector.imageToShoppingListExtractor(uploadedImageBytes);
<add> shoppingQuery = imageTextDectector.extractShoppingList(uploadedImageBytes);
<ide> } catch (PhotoDetectionException exception) {
<ide> throw exception;
<ide> } catch (IOException e) { |
|
JavaScript | mit | d3c0cca004348bae21c218e42109474f33f82718 | 0 | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,runarberg/eslint-plugin-meteor,Hansoft/meteor,dferber90/eslint-plugin-meteor,Hansoft/meteor,Hansoft/meteor | import path from 'path'
import getMeteorMeta from './getMeteorMeta'
import getEnvFromComments from './getEnvFromComments'
import getRelativePath from './getRelativePath'
import memoize from 'lodash.memoize'
const memoizedGetMeteorMeta = memoize(getMeteorMeta)
const memoizedGetRelativePath = memoize(getRelativePath)
export default function getMeta (context) {
const filename = context && context.getFilename()
let normalizedFilename = filename
// Received a relative path. This is probably from SublimeLinter
if (filename[0] !== path.sep && filename !== '<input>') {
normalizedFilename = path.join(process.cwd(), path.basename(filename))
}
const meta = memoizedGetMeteorMeta(memoizedGetRelativePath(normalizedFilename))
const envFromComments = getEnvFromComments(context.getSourceCode().getAllComments())
if (envFromComments) {
meta.env = envFromComments
}
return meta
}
| lib/util/meta/getMeta.js | import path from 'path'
import getMeteorMeta from './getMeteorMeta'
import getEnvFromComments from './getEnvFromComments'
import getRelativePath from './getRelativePath'
import memoize from 'lodash.memoize'
const memoizedGetMeteorMeta = memoize(getMeteorMeta)
const memoizedGetRelativePath = memoize(getRelativePath)
export default function getMeta (context) {
const filename = context && context.getFilename()
let normalizedFilename = filename
console.log(filename)
// Received a relative path. This is probably from SublimeLinter
if (filename[0] !== path.sep && filename !== '<input>') {
normalizedFilename = path.join(process.cwd(), path.basename(filename))
}
const meta = memoizedGetMeteorMeta(memoizedGetRelativePath(normalizedFilename))
const envFromComments = getEnvFromComments(context.getSourceCode().getAllComments())
if (envFromComments) {
meta.env = envFromComments
}
return meta
}
| fix(internal): Remove console statement
| lib/util/meta/getMeta.js | fix(internal): Remove console statement | <ide><path>ib/util/meta/getMeta.js
<ide>
<ide> let normalizedFilename = filename
<ide>
<del> console.log(filename)
<ide> // Received a relative path. This is probably from SublimeLinter
<ide> if (filename[0] !== path.sep && filename !== '<input>') {
<ide> normalizedFilename = path.join(process.cwd(), path.basename(filename)) |
|
Java | apache-2.0 | 437a69dacea727d10cc8ab05cc037078501d99b9 | 0 | werval/werval,werval/werval,werval/werval,werval/werval | /**
* Copyright (c) 2013 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qiweb.runtime.routes;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.qiweb.api.controllers.Outcome;
import org.qiweb.api.exceptions.IllegalRouteException;
import org.qiweb.api.exceptions.ParameterBinderException;
import org.qiweb.api.http.RequestHeader;
import org.qiweb.api.http.QueryString;
import org.qiweb.api.routes.ParameterBinders;
import org.qiweb.api.routes.Route;
import org.qiweb.runtime.routes.ControllerParams.ControllerParam;
import static org.qiweb.api.exceptions.NullArgumentException.ensureNotEmpty;
import static org.qiweb.api.exceptions.NullArgumentException.ensureNotNull;
import static org.qiweb.runtime.util.Iterables.addAll;
import static org.qiweb.runtime.util.Iterables.toList;
/**
* Instance of a Route.
*/
// TODO Support quoted parameter forced values in routes.conf
/* package */ final class RouteInstance
implements Route
{
private final String httpMethod;
private final String path;
private final Class<?> controllerType;
private Method controllerMethod;
private final String controllerMethodName;
private final ControllerParams controllerParams;
private final Set<String> modifiers;
private final Pattern pathRegex;
/* package */ RouteInstance( String httpMethod, String path,
Class<?> controllerType,
String controllerMethodName,
ControllerParams controllerParams,
Set<String> modifiers )
{
ensureNotNull( "HTTP Method", httpMethod );
ensureNotEmpty( "Path", path );
ensureNotNull( "Controller Type", controllerType );
ensureNotEmpty( "Controller Method Name", controllerMethodName );
this.httpMethod = httpMethod;
this.path = path;
this.controllerType = controllerType;
this.controllerMethodName = controllerMethodName;
this.controllerParams = controllerParams;
this.modifiers = new LinkedHashSet<>( modifiers );
validateRoute();
this.pathRegex = Pattern.compile( generatePathRegex() );
}
private void validateRoute()
{
if( !path.startsWith( "/" ) )
{
throw new IllegalRouteException( toString(), "Invalid path: " + path );
}
Iterable<String> controllerParamsNames = controllerParams.names();
List<String> pathParamsNames = new ArrayList<>();
for( String pathSegment : path.substring( 1 ).split( "/" ) )
{
if( pathSegment.startsWith( ":" ) || pathSegment.startsWith( "*" ) )
{
pathParamsNames.add( pathSegment.substring( 1 ) );
}
}
// Disallow multiple occurences of a single parameter name in the path
for( String paramName : pathParamsNames )
{
if( Collections.frequency( pathParamsNames, paramName ) > 1 )
{
throw new IllegalRouteException( toString(),
"Parameter '" + paramName + "' is present several times in path." );
}
}
// Ensure all parameters in path are bound to controller parameters and "vice et versa".
// Allow params absent from path that should come form QueryString
Set<String> allParamsNames = new LinkedHashSet<>();
addAll( allParamsNames, controllerParamsNames );
addAll( allParamsNames, pathParamsNames );
for( String paramName : allParamsNames )
{
boolean found = false;
for( String controllerParamName : controllerParamsNames )
{
if( paramName.equals( controllerParamName ) )
{
found = true;
continue;
}
}
if( !found )
{
throw new IllegalRouteException( toString(),
"Parameter '" + paramName + "' is present in path but not bound." );
}
}
// Ensure controller method exists and return an Outcome
Class<?>[] controllerParamsTypes = controllerParams.types();
try
{
controllerMethod = controllerType.getMethod( controllerMethodName, controllerParamsTypes );
if( !controllerMethod.getReturnType().isAssignableFrom( Outcome.class ) )
{
throw new IllegalRouteException( toString(), "Controller Method '" + controllerType.getSimpleName()
+ "#" + controllerMethodName
+ "( " + Arrays.toString( controllerParamsTypes ) + " )' "
+ "do not return an Outcome." );
}
}
catch( NoSuchMethodException ex )
{
throw new IllegalRouteException( toString(), "Controller Method '" + controllerType.getSimpleName()
+ "#" + controllerMethodName
+ "( " + Arrays.toString( controllerParamsTypes ) + " )' "
+ "not found.", ex );
}
}
/**
* @return Regex for parameter extraction from path with one named group per path parameter
*/
private String generatePathRegex()
{
StringBuilder regex = new StringBuilder( "/" );
String[] pathElements = path.substring( 1 ).split( "/" );
for( int idx = 0; idx < pathElements.length; idx++ )
{
String pathElement = pathElements[idx];
if( pathElement.length() > 1 )
{
switch( pathElement.substring( 0, 1 ) )
{
case ":":
regex.append( "(?<" ).append( pathElement.substring( 1 ) ).append( ">[^/]+)" );
break;
case "*":
regex.append( "(?<" ).append( pathElement.substring( 1 ) ).append( ">.+)" );
break;
default:
regex.append( pathElement );
break;
}
}
else
{
regex.append( pathElement );
}
if( idx + 1 < pathElements.length )
{
regex.append( "/" );
}
}
return regex.toString();
}
@Override
public boolean satisfiedBy( RequestHeader requestHeader )
{
if( !httpMethod.equals( requestHeader.method() ) )
{
return false;
}
return pathRegex.matcher( requestHeader.path() ).matches();
}
@Override
public String httpMethod()
{
return httpMethod;
}
@Override
public String path()
{
return path;
}
@Override
public Class<?> controllerType()
{
return controllerType;
}
@Override
public Method controllerMethod()
{
return controllerMethod;
}
@Override
public String controllerMethodName()
{
return controllerMethodName;
}
@Override
public Set<String> modifiers()
{
return Collections.unmodifiableSet( modifiers );
}
@Override
// TODO Fix multiple query string parameter values handling
public Map<String, Object> bindParameters( ParameterBinders parameterBinders, String path, QueryString queryString )
{
Matcher matcher = pathRegex.matcher( path );
if( !matcher.matches() )
{
throw new IllegalArgumentException( "Unable to bind, Route is not satisfied by path: " + path );
}
Map<String, Object> boundParams = new LinkedHashMap<>();
for( ControllerParam param : controllerParams )
{
if( param.hasForcedValue() )
{
boundParams.put( param.name(), param.forcedValue() );
}
else
{
String unboundValue = null;
try
{
unboundValue = matcher.group( param.name() );
}
catch( IllegalArgumentException noMatchingGroupInPath )
{
if( queryString.names().contains( param.name() ) )
{
// FIXME first or last value!
unboundValue = queryString.singleValue( param.name() );
}
}
if( unboundValue == null )
{
throw new ParameterBinderException( "Parameter named '" + param.name()
+ "' not found in path nor in query string." );
}
boundParams.put( param.name(), parameterBinders.bind( param.type(), param.name(), unboundValue ) );
}
}
return boundParams;
}
@Override
@SuppressWarnings( "unchecked" )
public String unbindParameters( ParameterBinders parameterBinders, Map<String, Object> parameters )
{
List<String> paramsToUnbind = toList( controllerParams.names() );
StringBuilder unboundPath = new StringBuilder( "/" );
// Unbinding path
String[] pathElements = path.substring( 1 ).split( "/" );
for( int idx = 0; idx < pathElements.length; idx++ )
{
String pathElement = pathElements[idx];
if( pathElement.length() > 1 )
{
switch( pathElement.substring( 0, 1 ) )
{
case ":":
case "*":
ControllerParam controllerParam = controllerParams.get( pathElement.substring( 1 ) );
Object value = controllerParam.hasForcedValue()
? controllerParam.forcedValue()
: parameters.get( controllerParam.name() );
unboundPath.append( parameterBinders.unbind( (Class<Object>) controllerParam.type(),
controllerParam.name(),
value ) );
paramsToUnbind.remove( controllerParam.name() );
break;
default:
unboundPath.append( pathElement );
break;
}
}
else
{
unboundPath.append( pathElement );
}
if( idx + 1 < pathElements.length )
{
unboundPath.append( "/" );
}
}
// Unbinding query string
// WARN Only controller parameters are unbound, not all given parameters
if( !paramsToUnbind.isEmpty() )
{
unboundPath.append( "?" );
Iterator<String> qsit = paramsToUnbind.iterator();
while( qsit.hasNext() )
{
String qsParam = qsit.next();
ControllerParam controllerParam = controllerParams.get( qsParam );
Object value = controllerParam.hasForcedValue()
? controllerParam.forcedValue()
: parameters.get( controllerParam.name() );
unboundPath.append( qsParam ).append( "=" );
unboundPath.append( parameterBinders.unbind( (Class<Object>) controllerParam.type(),
controllerParam.name(),
value ) );
if( qsit.hasNext() )
{
unboundPath.append( "&" );
}
}
}
return unboundPath.toString();
}
public ControllerParams controllerParams()
{
return controllerParams;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( httpMethod ).append( " " ).append( path ).append( " " ).
append( controllerType.getName() ).append( "." ).append( controllerMethodName ).append( "(" );
Iterator<ControllerParam> it = controllerParams.iterator();
if( it.hasNext() )
{
sb.append( " " );
while( it.hasNext() )
{
ControllerParam param = it.next();
sb.append( param.type().getSimpleName() ).append( " " ).append( param.name() );
if( param.hasForcedValue() )
{
sb.append( " = '" ).append( param.forcedValue() ).append( "'" );
}
if( it.hasNext() )
{
sb.append( ", " );
}
}
sb.append( " " );
}
sb.append( ")" );
Iterator<String> modifiersIt = modifiers.iterator();
if( modifiersIt.hasNext() )
{
sb.append( " " );
while( modifiersIt.hasNext() )
{
sb.append( modifiersIt.next() );
if( modifiersIt.hasNext() )
{
sb.append( " " );
}
}
}
return sb.toString();
}
@Override
public int hashCode()
{
// CHECKSTYLE:OFF
int hash = 7;
hash = 59 * hash + ( this.httpMethod != null ? this.httpMethod.hashCode() : 0 );
hash = 59 * hash + ( this.path != null ? this.path.hashCode() : 0 );
hash = 59 * hash + ( this.controllerType != null ? this.controllerType.hashCode() : 0 );
hash = 59 * hash + ( this.controllerMethodName != null ? this.controllerMethodName.hashCode() : 0 );
hash = 59 * hash + ( this.controllerParams != null ? this.controllerParams.hashCode() : 0 );
hash = 59 * hash + ( this.modifiers != null ? this.modifiers.hashCode() : 0 );
return hash;
// CHECKSTYLE:ON
}
@Override
@SuppressWarnings( "AccessingNonPublicFieldOfAnotherObject" )
public boolean equals( Object obj )
{
// CHECKSTYLE:OFF
if( obj == null )
{
return false;
}
if( getClass() != obj.getClass() )
{
return false;
}
final RouteInstance other = (RouteInstance) obj;
if( this.httpMethod != other.httpMethod && ( this.httpMethod == null || !this.httpMethod.equals( other.httpMethod ) ) )
{
return false;
}
if( ( this.path == null ) ? ( other.path != null ) : !this.path.equals( other.path ) )
{
return false;
}
if( this.controllerType != other.controllerType && ( this.controllerType == null || !this.controllerType.equals( other.controllerType ) ) )
{
return false;
}
if( ( this.controllerMethodName == null ) ? ( other.controllerMethodName != null ) : !this.controllerMethodName.equals( other.controllerMethodName ) )
{
return false;
}
if( this.controllerParams != other.controllerParams && ( this.controllerParams == null || !this.controllerParams.equals( other.controllerParams ) ) )
{
return false;
}
if( this.modifiers != other.modifiers && ( this.modifiers == null || !this.modifiers.equals( other.modifiers ) ) )
{
return false;
}
return true;
// CHECKSTYLE:ON
}
}
| org.qiweb/org.qiweb.runtime/src/main/java/org/qiweb/runtime/routes/RouteInstance.java | /**
* Copyright (c) 2013 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qiweb.runtime.routes;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.qiweb.api.controllers.Outcome;
import org.qiweb.api.exceptions.IllegalRouteException;
import org.qiweb.api.http.RequestHeader;
import org.qiweb.api.http.QueryString;
import org.qiweb.api.routes.ParameterBinders;
import org.qiweb.api.routes.Route;
import org.qiweb.runtime.routes.ControllerParams.ControllerParam;
import static org.qiweb.api.exceptions.NullArgumentException.ensureNotEmpty;
import static org.qiweb.api.exceptions.NullArgumentException.ensureNotNull;
import static org.qiweb.runtime.util.Iterables.addAll;
import static org.qiweb.runtime.util.Iterables.toList;
/**
* Instance of a Route.
*/
// TODO Support quoted parameter forced values in routes.conf
/* package */ final class RouteInstance
implements Route
{
private final String httpMethod;
private final String path;
private final Class<?> controllerType;
private Method controllerMethod;
private final String controllerMethodName;
private final ControllerParams controllerParams;
private final Set<String> modifiers;
private final Pattern pathRegex;
/* package */ RouteInstance( String httpMethod, String path,
Class<?> controllerType,
String controllerMethodName,
ControllerParams controllerParams,
Set<String> modifiers )
{
ensureNotNull( "HTTP Method", httpMethod );
ensureNotEmpty( "Path", path );
ensureNotNull( "Controller Type", controllerType );
ensureNotEmpty( "Controller Method Name", controllerMethodName );
this.httpMethod = httpMethod;
this.path = path;
this.controllerType = controllerType;
this.controllerMethodName = controllerMethodName;
this.controllerParams = controllerParams;
this.modifiers = new LinkedHashSet<>( modifiers );
validateRoute();
this.pathRegex = Pattern.compile( generatePathRegex() );
}
private void validateRoute()
{
if( !path.startsWith( "/" ) )
{
throw new IllegalRouteException( toString(), "Invalid path: " + path );
}
Iterable<String> controllerParamsNames = controllerParams.names();
List<String> pathParamsNames = new ArrayList<>();
for( String pathSegment : path.substring( 1 ).split( "/" ) )
{
if( pathSegment.startsWith( ":" ) || pathSegment.startsWith( "*" ) )
{
pathParamsNames.add( pathSegment.substring( 1 ) );
}
}
// Disallow multiple occurences of a single parameter name in the path
for( String paramName : pathParamsNames )
{
if( Collections.frequency( pathParamsNames, paramName ) > 1 )
{
throw new IllegalRouteException( toString(),
"Parameter '" + paramName + "' is present several times in path." );
}
}
// Ensure all parameters in path are bound to controller parameters and "vice et versa".
// Allow params absent from path that should come form QueryString
Set<String> allParamsNames = new LinkedHashSet<>();
addAll( allParamsNames, controllerParamsNames );
addAll( allParamsNames, pathParamsNames );
for( String paramName : allParamsNames )
{
boolean found = false;
for( String controllerParamName : controllerParamsNames )
{
if( paramName.equals( controllerParamName ) )
{
found = true;
continue;
}
}
if( !found )
{
throw new IllegalRouteException( toString(),
"Parameter '" + paramName + "' is present in path but not bound." );
}
}
// Ensure controller method exists and return an Outcome
Class<?>[] controllerParamsTypes = controllerParams.types();
try
{
controllerMethod = controllerType.getMethod( controllerMethodName, controllerParamsTypes );
if( !controllerMethod.getReturnType().isAssignableFrom( Outcome.class ) )
{
throw new IllegalRouteException( toString(), "Controller Method '" + controllerType.getSimpleName()
+ "#" + controllerMethodName
+ "( " + Arrays.toString( controllerParamsTypes ) + " )' "
+ "do not return an Outcome." );
}
}
catch( NoSuchMethodException ex )
{
throw new IllegalRouteException( toString(), "Controller Method '" + controllerType.getSimpleName()
+ "#" + controllerMethodName
+ "( " + Arrays.toString( controllerParamsTypes ) + " )' "
+ "not found.", ex );
}
}
/**
* @return Regex for parameter extraction from path with one named group per path parameter
*/
private String generatePathRegex()
{
StringBuilder regex = new StringBuilder( "/" );
String[] pathElements = path.substring( 1 ).split( "/" );
for( int idx = 0; idx < pathElements.length; idx++ )
{
String pathElement = pathElements[idx];
if( pathElement.length() > 1 )
{
switch( pathElement.substring( 0, 1 ) )
{
case ":":
regex.append( "(?<" ).append( pathElement.substring( 1 ) ).append( ">[^/]+)" );
break;
case "*":
regex.append( "(?<" ).append( pathElement.substring( 1 ) ).append( ">.+)" );
break;
default:
regex.append( pathElement );
break;
}
}
else
{
regex.append( pathElement );
}
if( idx + 1 < pathElements.length )
{
regex.append( "/" );
}
}
return regex.toString();
}
@Override
public boolean satisfiedBy( RequestHeader requestHeader )
{
if( !httpMethod.equals( requestHeader.method() ) )
{
return false;
}
return pathRegex.matcher( requestHeader.path() ).matches();
}
@Override
public String httpMethod()
{
return httpMethod;
}
@Override
public String path()
{
return path;
}
@Override
public Class<?> controllerType()
{
return controllerType;
}
@Override
public Method controllerMethod()
{
return controllerMethod;
}
@Override
public String controllerMethodName()
{
return controllerMethodName;
}
@Override
public Set<String> modifiers()
{
return Collections.unmodifiableSet( modifiers );
}
@Override
// TODO Fix multiple query string parameter values handling
public Map<String, Object> bindParameters( ParameterBinders parameterBinders, String path, QueryString queryString )
{
Matcher matcher = pathRegex.matcher( path );
if( !matcher.matches() )
{
throw new IllegalArgumentException( "Unable to bind, Route is not satisfied by path: " + path );
}
Map<String, Object> boundParams = new LinkedHashMap<>();
for( ControllerParam param : controllerParams )
{
if( param.hasForcedValue() )
{
boundParams.put( param.name(), param.forcedValue() );
}
else
{
String unboundValue = null;
try
{
unboundValue = matcher.group( param.name() );
}
catch( IllegalArgumentException noMatchingGroupInPath )
{
if( queryString.names().contains( param.name() ) )
{
// FIXME first or last value!
unboundValue = queryString.singleValue( param.name() );
}
}
if( unboundValue == null )
{
throw new IllegalArgumentException( "Parameter named '" + param.name()
+ "' not found in path nor in query string." );
}
boundParams.put( param.name(), parameterBinders.bind( param.type(), param.name(), unboundValue ) );
}
}
return boundParams;
}
@Override
@SuppressWarnings( "unchecked" )
public String unbindParameters( ParameterBinders parameterBinders, Map<String, Object> parameters )
{
List<String> paramsToUnbind = toList( controllerParams.names() );
StringBuilder unboundPath = new StringBuilder( "/" );
// Unbinding path
String[] pathElements = path.substring( 1 ).split( "/" );
for( int idx = 0; idx < pathElements.length; idx++ )
{
String pathElement = pathElements[idx];
if( pathElement.length() > 1 )
{
switch( pathElement.substring( 0, 1 ) )
{
case ":":
case "*":
ControllerParam controllerParam = controllerParams.get( pathElement.substring( 1 ) );
Object value = controllerParam.hasForcedValue()
? controllerParam.forcedValue()
: parameters.get( controllerParam.name() );
unboundPath.append( parameterBinders.unbind( (Class<Object>) controllerParam.type(),
controllerParam.name(),
value ) );
paramsToUnbind.remove( controllerParam.name() );
break;
default:
unboundPath.append( pathElement );
break;
}
}
else
{
unboundPath.append( pathElement );
}
if( idx + 1 < pathElements.length )
{
unboundPath.append( "/" );
}
}
// Unbinding query string
// WARN Only controller parameters are unbound, not all given parameters
if( !paramsToUnbind.isEmpty() )
{
unboundPath.append( "?" );
Iterator<String> qsit = paramsToUnbind.iterator();
while( qsit.hasNext() )
{
String qsParam = qsit.next();
ControllerParam controllerParam = controllerParams.get( qsParam );
Object value = controllerParam.hasForcedValue()
? controllerParam.forcedValue()
: parameters.get( controllerParam.name() );
unboundPath.append( qsParam ).append( "=" );
unboundPath.append( parameterBinders.unbind( (Class<Object>) controllerParam.type(),
controllerParam.name(),
value ) );
if( qsit.hasNext() )
{
unboundPath.append( "&" );
}
}
}
return unboundPath.toString();
}
public ControllerParams controllerParams()
{
return controllerParams;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( httpMethod ).append( " " ).append( path ).append( " " ).
append( controllerType.getName() ).append( "." ).append( controllerMethodName ).append( "(" );
Iterator<ControllerParam> it = controllerParams.iterator();
if( it.hasNext() )
{
sb.append( " " );
while( it.hasNext() )
{
ControllerParam param = it.next();
sb.append( param.type().getSimpleName() ).append( " " ).append( param.name() );
if( param.hasForcedValue() )
{
sb.append( " = '" ).append( param.forcedValue() ).append( "'" );
}
if( it.hasNext() )
{
sb.append( ", " );
}
}
sb.append( " " );
}
sb.append( ")" );
Iterator<String> modifiersIt = modifiers.iterator();
if( modifiersIt.hasNext() )
{
sb.append( " " );
while( modifiersIt.hasNext() )
{
sb.append( modifiersIt.next() );
if( modifiersIt.hasNext() )
{
sb.append( " " );
}
}
}
return sb.toString();
}
@Override
public int hashCode()
{
// CHECKSTYLE:OFF
int hash = 7;
hash = 59 * hash + ( this.httpMethod != null ? this.httpMethod.hashCode() : 0 );
hash = 59 * hash + ( this.path != null ? this.path.hashCode() : 0 );
hash = 59 * hash + ( this.controllerType != null ? this.controllerType.hashCode() : 0 );
hash = 59 * hash + ( this.controllerMethodName != null ? this.controllerMethodName.hashCode() : 0 );
hash = 59 * hash + ( this.controllerParams != null ? this.controllerParams.hashCode() : 0 );
hash = 59 * hash + ( this.modifiers != null ? this.modifiers.hashCode() : 0 );
return hash;
// CHECKSTYLE:ON
}
@Override
@SuppressWarnings( "AccessingNonPublicFieldOfAnotherObject" )
public boolean equals( Object obj )
{
// CHECKSTYLE:OFF
if( obj == null )
{
return false;
}
if( getClass() != obj.getClass() )
{
return false;
}
final RouteInstance other = (RouteInstance) obj;
if( this.httpMethod != other.httpMethod && ( this.httpMethod == null || !this.httpMethod.equals( other.httpMethod ) ) )
{
return false;
}
if( ( this.path == null ) ? ( other.path != null ) : !this.path.equals( other.path ) )
{
return false;
}
if( this.controllerType != other.controllerType && ( this.controllerType == null || !this.controllerType.equals( other.controllerType ) ) )
{
return false;
}
if( ( this.controllerMethodName == null ) ? ( other.controllerMethodName != null ) : !this.controllerMethodName.equals( other.controllerMethodName ) )
{
return false;
}
if( this.controllerParams != other.controllerParams && ( this.controllerParams == null || !this.controllerParams.equals( other.controllerParams ) ) )
{
return false;
}
if( this.modifiers != other.modifiers && ( this.modifiers == null || !this.modifiers.equals( other.modifiers ) ) )
{
return false;
}
return true;
// CHECKSTYLE:ON
}
}
| Routes: return 400 BadRequest when required parameter is not present
Instead of 500 …. thanks Quentin for pointing this out.
| org.qiweb/org.qiweb.runtime/src/main/java/org/qiweb/runtime/routes/RouteInstance.java | Routes: return 400 BadRequest when required parameter is not present | <ide><path>rg.qiweb/org.qiweb.runtime/src/main/java/org/qiweb/runtime/routes/RouteInstance.java
<ide> import java.util.regex.Pattern;
<ide> import org.qiweb.api.controllers.Outcome;
<ide> import org.qiweb.api.exceptions.IllegalRouteException;
<add>import org.qiweb.api.exceptions.ParameterBinderException;
<ide> import org.qiweb.api.http.RequestHeader;
<ide> import org.qiweb.api.http.QueryString;
<ide> import org.qiweb.api.routes.ParameterBinders;
<ide> }
<ide> if( unboundValue == null )
<ide> {
<del> throw new IllegalArgumentException( "Parameter named '" + param.name()
<add> throw new ParameterBinderException( "Parameter named '" + param.name()
<ide> + "' not found in path nor in query string." );
<ide> }
<ide> boundParams.put( param.name(), parameterBinders.bind( param.type(), param.name(), unboundValue ) ); |
|
Java | lgpl-2.1 | 900e330fcc1babff8cf9083f92b649df4dfe151f | 0 | jamezp/wildfly-core,darranl/wildfly-core,JiriOndrusek/wildfly-core,darranl/wildfly-core,ivassile/wildfly-core,bstansberry/wildfly-core,luck3y/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core,yersan/wildfly-core,soul2zimate/wildfly-core,yersan/wildfly-core,jfdenise/wildfly-core,jfdenise/wildfly-core,soul2zimate/wildfly-core,bstansberry/wildfly-core,JiriOndrusek/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core,JiriOndrusek/wildfly-core,darranl/wildfly-core,aloubyansky/wildfly-core,jfdenise/wildfly-core,yersan/wildfly-core,aloubyansky/wildfly-core,jamezp/wildfly-core,ivassile/wildfly-core,luck3y/wildfly-core,ivassile/wildfly-core,aloubyansky/wildfly-core | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.controller.operations.common;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH;
import static org.jboss.as.controller.descriptions.common.PathDescription.RELATIVE_TO;
import java.util.Locale;
import org.jboss.as.controller.Cancellable;
import org.jboss.as.controller.ModelAddOperationHandler;
import org.jboss.as.controller.NewOperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ResultHandler;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.common.PathDescription;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Handler for the path resource add operation.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class PathAddHandler implements ModelAddOperationHandler, DescriptionProvider {
public static final String OPERATION_NAME = ADD;
public static ModelNode getAddPathOperation(ModelNode address, ModelNode path, ModelNode relativeTo) {
ModelNode op = new ModelNode();
op.get(OP).set(OPERATION_NAME);
op.get(OP_ADDR).set(address);
if (path.isDefined()) {
op.get(PATH).set(path);
}
if (relativeTo.isDefined()) {
op.get(RELATIVE_TO).set(relativeTo);
}
return op;
}
public static final PathAddHandler NAMED_INSTANCE = new PathAddHandler(false);
public static final PathAddHandler SPECIFIED_INSTANCE = new PathAddHandler(true);
private final boolean specified;
private final StringLengthValidator pathValidator;
private final ModelTypeValidator relativeToValidator = new ModelTypeValidator(ModelType.STRING, true);
/**
* Create the PathAddHandler
*/
protected PathAddHandler(boolean specified) {
this.specified = specified;
this.pathValidator = new StringLengthValidator(1, !specified);
}
/**
* {@inheritDoc}
*/
@Override
public Cancellable execute(NewOperationContext context, ModelNode operation, ResultHandler resultHandler) {
try {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
String name = address.getLastElement().getValue();
ModelNode model = context.getSubModel();
model.get(NAME).set(name);
ModelNode pathNode = operation.get(PATH);
String failure = pathValidator.validateParameter(PATH, pathNode);
if (failure == null) {
ModelNode relNode = operation.get(RELATIVE_TO);
failure = relativeToValidator.validateParameter(RELATIVE_TO, relNode);
if (failure == null) {
model.get(PATH).set(pathNode);
model.get(RELATIVE_TO).set(relNode);
ModelNode compensating = PathRemoveHandler.getRemovePathOperation(operation.get(OP_ADDR));
String path = pathNode.isDefined() ? pathNode.asString() : null;
String relativeTo = relNode.isDefined() ? relNode.asString() : null;
installPath(name, path, relativeTo, context, resultHandler, compensating);
}
}
if (failure != null) {
resultHandler.handleFailed(new ModelNode().set(failure));
}
}
catch (Exception e) {
resultHandler.handleFailed(new ModelNode().set(e.getLocalizedMessage()));
}
return Cancellable.NULL;
}
@Override
public ModelNode getModelDescription(Locale locale) {
return specified ? PathDescription.getSpecifiedPathAddOperation(locale) : PathDescription.getNamedPathAddOperation(locale);
}
protected void installPath(String name, String path, String relativeTo, NewOperationContext context, ResultHandler resultHandler, ModelNode compensatingOp) {
resultHandler.handleResultComplete(compensatingOp);
}
}
| controller/src/main/java/org/jboss/as/controller/operations/common/PathAddHandler.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.controller.operations.common;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH;
import static org.jboss.as.controller.descriptions.common.PathDescription.RELATIVE_TO;
import java.util.Locale;
import org.jboss.as.controller.Cancellable;
import org.jboss.as.controller.ModelAddOperationHandler;
import org.jboss.as.controller.NewOperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ResultHandler;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.common.PathDescription;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Handler for the path resource add operation.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class PathAddHandler implements ModelAddOperationHandler, DescriptionProvider {
public static final String OPERATION_NAME = ADD;
public static ModelNode getAddPathOperation(ModelNode address, ModelNode path, ModelNode relativeTo) {
ModelNode op = new ModelNode();
op.get(OP).set(OPERATION_NAME);
op.get(OP_ADDR).set(address);
if (path.isDefined()) {
op.get(PATH).set(path);
}
if (relativeTo.isDefined()) {
op.get(RELATIVE_TO).set(relativeTo);
}
return op;
}
public static final PathAddHandler NAMED_INSTANCE = new PathAddHandler(false);
public static final PathAddHandler SPECIFIED_INSTANCE = new PathAddHandler(true);
private final boolean specified;
private final StringLengthValidator pathValidator;
private final ModelTypeValidator relativeToValidator = new ModelTypeValidator(ModelType.STRING, true);
/**
* Create the PathAddHandler
*/
protected PathAddHandler(boolean specified) {
this.specified = specified;
this.pathValidator = new StringLengthValidator(1, !specified);
}
/**
* {@inheritDoc}
*/
@Override
public Cancellable execute(NewOperationContext context, ModelNode operation, ResultHandler resultHandler) {
try {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
String name = address.getLastElement().getValue();
ModelNode model = context.getSubModel();
model.get(NAME).set(name);
ModelNode pathNode = model.get(PATH);
String failure = pathValidator.validateParameter(PATH, pathNode);
if (failure == null) {
String path = pathNode.isDefined() ? pathNode.asString() : null;
ModelNode relNode = model.get(RELATIVE_TO);
failure = relativeToValidator.validateParameter(RELATIVE_TO, relNode);
if (failure == null) {
String relativeTo = relNode.isDefined() ? pathNode.asString() : null;
ModelNode compensating = PathRemoveHandler.getRemovePathOperation(operation.get(OP_ADDR));
installPath(name, path, relativeTo, context, resultHandler, compensating);
}
}
if (failure != null) {
resultHandler.handleFailed(new ModelNode().set(failure));
}
}
catch (Exception e) {
resultHandler.handleFailed(new ModelNode().set(e.getLocalizedMessage()));
}
return Cancellable.NULL;
}
@Override
public ModelNode getModelDescription(Locale locale) {
return specified ? PathDescription.getSpecifiedPathAddOperation(locale) : PathDescription.getNamedPathAddOperation(locale);
}
protected void installPath(String name, String path, String relativeTo, NewOperationContext context, ResultHandler resultHandler, ModelNode compensatingOp) {
resultHandler.handleResultComplete(compensatingOp);
}
}
| Fix path add handling
was: 540fa958f597d68b11be8c62842b9bf5b8506436
| controller/src/main/java/org/jboss/as/controller/operations/common/PathAddHandler.java | Fix path add handling | <ide><path>ontroller/src/main/java/org/jboss/as/controller/operations/common/PathAddHandler.java
<ide> ModelNode model = context.getSubModel();
<ide> model.get(NAME).set(name);
<ide>
<del> ModelNode pathNode = model.get(PATH);
<add> ModelNode pathNode = operation.get(PATH);
<ide> String failure = pathValidator.validateParameter(PATH, pathNode);
<ide> if (failure == null) {
<del> String path = pathNode.isDefined() ? pathNode.asString() : null;
<del> ModelNode relNode = model.get(RELATIVE_TO);
<add> ModelNode relNode = operation.get(RELATIVE_TO);
<ide> failure = relativeToValidator.validateParameter(RELATIVE_TO, relNode);
<ide> if (failure == null) {
<del> String relativeTo = relNode.isDefined() ? pathNode.asString() : null;
<add> model.get(PATH).set(pathNode);
<add> model.get(RELATIVE_TO).set(relNode);
<add>
<ide> ModelNode compensating = PathRemoveHandler.getRemovePathOperation(operation.get(OP_ADDR));
<add> String path = pathNode.isDefined() ? pathNode.asString() : null;
<add> String relativeTo = relNode.isDefined() ? relNode.asString() : null;
<ide> installPath(name, path, relativeTo, context, resultHandler, compensating);
<ide> }
<ide> } |
|
JavaScript | mit | b1dfe738e535d62f3776c35ee7a8ee3927876994 | 0 | AlekseyLeshko/configuration-manager | (function() {
'use strict';
function getDefaultConfig() {
var config = {
version: '0.0.0',
a: 1,
b: 2,
c: 3
};
return config;
}
module.exports = getDefaultConfig();
})();
| src/defaultConfig.js | (function() {
'use strict';
function getDefaultConfig() {
var config = {
a: 1,
b: 2,
c: 3
};
return config;
}
module.exports = getDefaultConfig();
})();
| Update
| src/defaultConfig.js | Update | <ide><path>rc/defaultConfig.js
<ide>
<ide> function getDefaultConfig() {
<ide> var config = {
<add> version: '0.0.0',
<ide> a: 1,
<ide> b: 2,
<ide> c: 3 |
|
JavaScript | mit | e38efc04f1f291b0f32f7442c3449fc6063fa733 | 0 | jammus/lastfm-node,jammus/lastfm-node | require("./common.js");
var _ = require("underscore")
, RecentTracksStream = require("lastfm/recenttracks-stream")
, LastFmRequest = require("lastfm/lastfm-request")
, fakes = require("./fakes");
(function() {
var gently, lastfm, trackStream;
describe("a new stream instance");
before(function() {
gently = new Gently();
lastfm = new LastFmNode();
trackStream = new RecentTracksStream(lastfm, "username");
});
it("accepts listeners", function() {
trackStream.addListener("event", function() {});
});
it("is not streaming", function() {
assert.ok(!trackStream.isStreaming());
});
it("event handlers can be specified in options (deprecated)", function() {
var handlers = {};
gently.expect(handlers, "error");
gently.expect(handlers, "lastPlayed");
gently.expect(handlers, "nowPlaying");
gently.expect(handlers, "stoppedPlaying");
gently.expect(handlers, "scrobbled");
var trackStream = new RecentTracksStream(lastfm, "username", {
error: handlers.error,
lastPlayed: handlers.lastPlayed,
nowPlaying: handlers.nowPlaying,
stoppedPlaying: handlers.stoppedPlaying,
scrobbled: handlers.scrobbled
});
trackStream.emit("error");
trackStream.emit("lastPlayed");
trackStream.emit("nowPlaying");
trackStream.emit("stoppedPlaying");
trackStream.emit("scrobbled");
});
it("event handlers can be specified in options", function() {
var handlers = {};
gently.expect(handlers, "error");
gently.expect(handlers, "lastPlayed");
gently.expect(handlers, "nowPlaying");
gently.expect(handlers, "stoppedPlaying");
gently.expect(handlers, "scrobbled");
var trackStream = new RecentTracksStream(lastfm, "username", {
handlers: {
error: handlers.error,
lastPlayed: handlers.lastPlayed,
nowPlaying: handlers.nowPlaying,
stoppedPlaying: handlers.stoppedPlaying,
scrobbled: handlers.scrobbled
}
});
trackStream.emit("error");
trackStream.emit("lastPlayed");
trackStream.emit("nowPlaying");
trackStream.emit("stoppedPlaying");
trackStream.emit("scrobbled");
});
})();
(function() {
var requestEmits = [],
previousEmits = [];
function ifRequestHasPreviouslyEmit(emits) {
previousEmits = emits;
}
function whenRequestEmits(count, event, object) {
if (typeof count !== "number") {
object = event;
event = count;
count = 1;
}
if (typeof event !== "string") {
object = event;
event = "success";
}
requestEmits = [event, object, count];
}
function expectStreamToEmit(count, expectation) {
if (typeof count === "function") {
expectation = count;
count = 1;
}
var lastfm = new LastFmNode(),
connection = new fakes.Client(80, lastfm.host),
request = new fakes.LastFmRequest(),
gently = new Gently();
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username");
trackStream.start();
trackStream.stop();
for(var index = 0; index < previousEmits.length; index++) {
request.emit("success", previousEmits[index]);
}
gently.expect(trackStream, "emit", count, expectation);
for(var times = 0; times < requestEmits[2]; times++) {
request.emit(requestEmits[0], requestEmits[1]);
}
}
describe("An active stream");
before(function() {
previousEmits = [];
requestEmits = [];
});
it("bubbles errors", function() {
whenRequestEmits("error", { error: 1, message: "An error" });
expectStreamToEmit(function(event, error) {
assert.equal("error", event);
assert.equal("An error", error.message);
});
});
it("emits last played when track received", function() {
whenRequestEmits({ recenttracks: { track:
FakeTracks.LambAndTheLion
} });
expectStreamToEmit(function(event, track) {
assert.equal("lastPlayed", event);
assert.equal("Lamb and the Lion", track.name);
});
});
it("emits now playing if track flagged now playing", function() {
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits now playing and last played if both received", function() {
var count = 0;
whenRequestEmits({
recenttracks: { track: FakeTracks.NowPlayingAndScrobbled }
});
expectStreamToEmit(2, function(event, track) {
if (count == 0) {
assert.equal("nowPlaying", event);
assert.equal("Theme Song", track.name);
}
else {
assert.equal("lastPlayed", event);
assert.equal("Over The Moon", track.name);
}
count++;
});
});
it("does not re-emit lastPlayed on receipt of same track", function() {
whenRequestEmits(2, {
recenttracks: { track: FakeTracks.LambAndTheLion }
});
expectStreamToEmit(1, function(event, track) {
assert.equal("lastPlayed", event);
assert.equal("Lamb and the Lion", track.name);
});
});
it("does not re-emit nowPlaying on receipt of same track", function() {
whenRequestEmits(2, {
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(1, function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits stoppedPlaying track when now playing stops", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.RunToYourGrave } },
{ recenttracks: { track: FakeTracks.RunToYourGrave_NP } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave }
});
expectStreamToEmit(function(event, track) {
assert.equal("stoppedPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits scrobbled when last play changes", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.LambAndTheLion } },
{ recenttracks: { track: FakeTracks.RunToYourGrave_NP } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave }
});
expectStreamToEmit(function(event, track) {
assert.equal("scrobbled", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits nowPlaying when track same as lastPlayed", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.RunToYourGrave } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits error when unexpected item is received", function() {
whenRequestEmits({
something: "we've never seen before"
});
expectStreamToEmit(function(event, error) {
assert.equal("error", event);
assert.equal("Unexpected response", error.message);
});
});
})();
(function() {
var lastfm, gently, request;
describe("Streaming")
before(function() {
lastfm = new LastFmNode();
gently = new Gently();
request = new fakes.LastFmRequest();
});
it("starts and stops streaming when requested", function() {
gently.expect(lastfm, "request", 1, function(method, params) {
return request;
});
var trackStream = new RecentTracksStream(lastfm);
trackStream.start();
trackStream.stop();
assert.ok(!trackStream.isStreaming());
});
it("starts automatically when autostart set to true", function() {
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
assert.ok(trackStream.isStreaming());
trackStream.stop();
});
it("calls user.getrecenttracks method for user", function() {
gently.expect(lastfm, "request", function(method, params) {
assert.equal("user.getrecenttracks", method);
assert.equal("username", params.user);
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
trackStream.stop();
});
it("only fetches most recent track", function() {
gently.expect(lastfm, "request", function(method, params) {
assert.equal(1, params.limit);
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
trackStream.stop();
});
it("bubbles up errors", function() {
var errorMessage = "Bubbled error";
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart:true });
gently.expect(trackStream, "emit", function(event, error) {
assert.equal(errorMessage, error.message);
});
request.emit("error", new Error(errorMessage));
trackStream.stop();
});
})();
(function() {
var lastfm, gently;
describe("Streaming")
var tmpScheduleFn;
before(function() {
tmpScheduleFn = RecentTracksStream.prototype.scheduleCallback;
lastfm = new LastFmNode();
gently = new Gently();
});
after(function() {
RecentTracksStream.prototype.scheduleCallback = tmpScheduleFn;
});
it("queries API every 10 seconds", function() {
var trackStream = new RecentTracksStream(lastfm, "username");
var count = 0;
RecentTracksStream.prototype.scheduleCallback = function(callback, delay) {
count++;
if (count === 10) {
trackStream.stop();
}
assert.ok(delay, 10000);
gently.expect(lastfm, "request", function(method, params) {
return new fakes.LastFmRequest();
});
callback();
};
gently.expect(lastfm, "request", function(method, params) {
return new fakes.LastFmRequest();
});
trackStream.start();
});
})();
| tests/lastfm-recenttracks-stream-test.js | require("./common.js");
var _ = require("underscore")
, RecentTracksStream = require("lastfm/recenttracks-stream")
, LastFmRequest = require("lastfm/lastfm-request")
, fakes = require("./fakes");
(function() {
var gently, lastfm, trackStream;
describe("a new stream instance");
before(function() {
gently = new Gently();
lastfm = new LastFmNode();
trackStream = new RecentTracksStream(lastfm, "username");
});
it("accepts listeners", function() {
trackStream.addListener("event", function() {});
});
it("is not streaming", function() {
assert.ok(!trackStream.isStreaming());
});
it("event handlers can be specified in options (deprecated)", function() {
var handlers = {};
gently.expect(handlers, "error");
gently.expect(handlers, "lastPlayed");
gently.expect(handlers, "nowPlaying");
gently.expect(handlers, "stoppedPlaying");
gently.expect(handlers, "scrobbled");
var trackStream = new RecentTracksStream(lastfm, "username", {
error: handlers.error,
lastPlayed: handlers.lastPlayed,
nowPlaying: handlers.nowPlaying,
stoppedPlaying: handlers.stoppedPlaying,
scrobbled: handlers.scrobbled
});
trackStream.emit("error");
trackStream.emit("lastPlayed");
trackStream.emit("nowPlaying");
trackStream.emit("stoppedPlaying");
trackStream.emit("scrobbled");
});
it("event handlers can be specified in options", function() {
var handlers = {};
gently.expect(handlers, "error");
gently.expect(handlers, "lastPlayed");
gently.expect(handlers, "nowPlaying");
gently.expect(handlers, "stoppedPlaying");
gently.expect(handlers, "scrobbled");
var trackStream = new RecentTracksStream(lastfm, "username", {
handlers: {
error: handlers.error,
lastPlayed: handlers.lastPlayed,
nowPlaying: handlers.nowPlaying,
stoppedPlaying: handlers.stoppedPlaying,
scrobbled: handlers.scrobbled
}
});
trackStream.emit("error");
trackStream.emit("lastPlayed");
trackStream.emit("nowPlaying");
trackStream.emit("stoppedPlaying");
trackStream.emit("scrobbled");
});
})();
(function() {
var requestEmits = [],
previousEmits = [];
function ifRequestHasPreviouslyEmit(emits) {
previousEmits = emits;
}
function whenRequestEmits(count, event, object) {
if (typeof count !== "number") {
object = event;
event = count;
count = 1;
}
if (typeof event !== "string") {
object = event;
event = "success";
}
requestEmits = [event, object, count];
}
function expectStreamToEmit(count, expectation) {
if (typeof count === "function") {
expectation = count;
count = 1;
}
var lastfm = new LastFmNode(),
connection = new fakes.Client(80, lastfm.host),
request = new fakes.LastFmRequest(),
gently = new Gently();
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username");
trackStream.start();
trackStream.stop();
for(var index = 0; index < previousEmits.length; index++) {
request.emit("success", previousEmits[index]);
}
gently.expect(trackStream, "emit", count, expectation);
for(var times = 0; times < requestEmits[2]; times++) {
request.emit(requestEmits[0], requestEmits[1]);
}
}
describe("An active stream");
before(function() {
previousEmits = [];
requestEmits = [];
});
it("bubbles errors", function() {
whenRequestEmits("error", { error: 1, message: "An error" });
expectStreamToEmit(function(event, error) {
assert.equal("error", event);
assert.equal("An error", error.message);
});
});
it("emits last played when track received", function() {
whenRequestEmits({ recenttracks: { track:
FakeTracks.LambAndTheLion
} });
expectStreamToEmit(function(event, track) {
assert.equal("lastPlayed", event);
assert.equal("Lamb and the Lion", track.name);
});
});
it("emits now playing if track flagged now playing", function() {
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits now playing and last played if both received", function() {
var count = 0;
whenRequestEmits({
recenttracks: { track: FakeTracks.NowPlayingAndScrobbled }
});
expectStreamToEmit(2, function(event, track) {
if (count == 0) {
assert.equal("nowPlaying", event);
assert.equal("Theme Song", track.name);
}
else {
assert.equal("lastPlayed", event);
assert.equal("Over The Moon", track.name);
}
count++;
});
});
it("does not re-emit lastPlayed on receipt of same track", function() {
whenRequestEmits(2, {
recenttracks: { track: FakeTracks.LambAndTheLion }
});
expectStreamToEmit(1, function(event, track) {
assert.equal("lastPlayed", event);
assert.equal("Lamb and the Lion", track.name);
});
});
it("does not re-emit nowPlaying on receipt of same track", function() {
whenRequestEmits(2, {
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(1, function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits stoppedPlaying track when now playing stops", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.RunToYourGrave } },
{ recenttracks: { track: FakeTracks.RunToYourGrave_NP } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave }
});
expectStreamToEmit(function(event, track) {
assert.equal("stoppedPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits scrobbled when last play changes", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.LambAndTheLion } },
{ recenttracks: { track: FakeTracks.RunToYourGrave_NP } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave }
});
expectStreamToEmit(function(event, track) {
assert.equal("scrobbled", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits nowPlaying when track same as lastPlayed", function() {
ifRequestHasPreviouslyEmit([
{ recenttracks: { track: FakeTracks.RunToYourGrave } }
]);
whenRequestEmits({
recenttracks: { track: FakeTracks.RunToYourGrave_NP }
});
expectStreamToEmit(function(event, track) {
assert.equal("nowPlaying", event);
assert.equal("Run To Your Grave", track.name);
});
});
it("emits error when unexpected item is received", function() {
whenRequestEmits({
something: "we've never seen before"
});
expectStreamToEmit(function(event, error) {
assert.equal("error", event);
assert.equal("Unexpected response", error.message);
});
});
})();
(function() {
var lastfm, gently, request;
describe("Streaming")
before(function() {
lastfm = new LastFmNode();
gently = new Gently();
request = new fakes.LastFmRequest();
});
it("starts and stops streaming when requested", function() {
gently.expect(lastfm, "request", 1, function(method, params) {
return request;
});
var trackStream = new RecentTracksStream(lastfm);
trackStream.start();
trackStream.stop();
assert.ok(!trackStream.isStreaming());
});
it("starts automatically when autostart set to true", function() {
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
assert.ok(trackStream.isStreaming());
trackStream.stop();
});
it("calls user.getrecenttracks method for user", function() {
gently.expect(lastfm, "request", function(method, params) {
assert.equal("user.getrecenttracks", method);
assert.equal("username", params.user);
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
trackStream.stop();
});
it("only fetches most recent track", function() {
gently.expect(lastfm, "request", function(method, params) {
assert.equal(1, params.limit);
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart: true} );
trackStream.stop();
});
it("bubbles up errors", function() {
var errorMessage = "Bubbled error";
gently.expect(lastfm, "request", function() {
return request;
});
var trackStream = new RecentTracksStream(lastfm, "username", { autostart:true });
gently.expect(trackStream, "emit", function(event, error) {
assert.equal(errorMessage, error.message);
});
request.emit("error", new Error(errorMessage));
trackStream.stop();
});
})();
(function() {
var lastfm, gently, request;
describe("Streaming")
var tmpScheduleFn;
before(function() {
tmpScheduleFn = RecentTracksStream.prototype.scheduleCallback;
lastfm = new LastFmNode();
gently = new Gently();
request = new fakes.LastFmRequest();
});
after(function() {
RecentTracksStream.prototype.scheduleCallback = tmpScheduleFn;
});
it("queries API every 10 seconds", function() {
var trackStream = new RecentTracksStream(lastfm, "username");
var count = 0;
RecentTracksStream.prototype.scheduleCallback = function(callback, delay) {
count++;
if (count === 10) {
trackStream.stop();
}
assert.ok(delay, 10000);
gently.expect(lastfm, "request", function(method, params) {
return request;
});
callback();
};
gently.expect(lastfm, "request", function(method, params) {
return request;
});
trackStream.start();
});
})();
| Fix memory leak warning.
| tests/lastfm-recenttracks-stream-test.js | Fix memory leak warning. | <ide><path>ests/lastfm-recenttracks-stream-test.js
<ide> })();
<ide>
<ide> (function() {
<del> var lastfm, gently, request;
<add> var lastfm, gently;
<ide>
<ide> describe("Streaming")
<ide>
<ide> tmpScheduleFn = RecentTracksStream.prototype.scheduleCallback;
<ide> lastfm = new LastFmNode();
<ide> gently = new Gently();
<del> request = new fakes.LastFmRequest();
<ide> });
<ide>
<ide> after(function() {
<ide> }
<ide> assert.ok(delay, 10000);
<ide> gently.expect(lastfm, "request", function(method, params) {
<del> return request;
<add> return new fakes.LastFmRequest();
<ide> });
<ide> callback();
<ide> };
<ide> gently.expect(lastfm, "request", function(method, params) {
<del> return request;
<add> return new fakes.LastFmRequest();
<ide> });
<ide> trackStream.start();
<ide> }); |
|
Java | apache-2.0 | b778e102b8ab4d23af34ad50924b1dfaf831718f | 0 | mittop/vaadin,bmitc/vaadin,sitexa/vaadin,Scarlethue/vaadin,Peppe/vaadin,cbmeeks/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,Flamenco/vaadin,peterl1084/framework,Legioth/vaadin,jdahlstrom/vaadin.react,cbmeeks/vaadin,shahrzadmn/vaadin,travisfw/vaadin,mittop/vaadin,asashour/framework,peterl1084/framework,sitexa/vaadin,mstahv/framework,magi42/vaadin,synes/vaadin,Darsstar/framework,cbmeeks/vaadin,travisfw/vaadin,Flamenco/vaadin,jdahlstrom/vaadin.react,bmitc/vaadin,fireflyc/vaadin,sitexa/vaadin,oalles/vaadin,shahrzadmn/vaadin,peterl1084/framework,carrchang/vaadin,oalles/vaadin,Peppe/vaadin,kironapublic/vaadin,cbmeeks/vaadin,sitexa/vaadin,mstahv/framework,asashour/framework,Darsstar/framework,mittop/vaadin,Flamenco/vaadin,mstahv/framework,kironapublic/vaadin,Legioth/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,oalles/vaadin,synes/vaadin,Darsstar/framework,Flamenco/vaadin,asashour/framework,oalles/vaadin,travisfw/vaadin,magi42/vaadin,Scarlethue/vaadin,mstahv/framework,synes/vaadin,jdahlstrom/vaadin.react,Legioth/vaadin,udayinfy/vaadin,magi42/vaadin,Scarlethue/vaadin,oalles/vaadin,Legioth/vaadin,carrchang/vaadin,synes/vaadin,synes/vaadin,carrchang/vaadin,Peppe/vaadin,Peppe/vaadin,magi42/vaadin,mstahv/framework,kironapublic/vaadin,asashour/framework,travisfw/vaadin,fireflyc/vaadin,peterl1084/framework,magi42/vaadin,udayinfy/vaadin,travisfw/vaadin,Peppe/vaadin,Darsstar/framework,shahrzadmn/vaadin,Darsstar/framework,fireflyc/vaadin,carrchang/vaadin,bmitc/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,fireflyc/vaadin,bmitc/vaadin,peterl1084/framework,kironapublic/vaadin,mittop/vaadin,kironapublic/vaadin,asashour/framework,udayinfy/vaadin,Legioth/vaadin,sitexa/vaadin,udayinfy/vaadin,Scarlethue/vaadin | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.ui;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import com.itmill.toolkit.data.Buffered;
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.Property;
import com.itmill.toolkit.data.Validatable;
import com.itmill.toolkit.data.Validator;
import com.itmill.toolkit.data.Validator.InvalidValueException;
import com.itmill.toolkit.data.util.BeanItem;
import com.itmill.toolkit.terminal.CompositeErrorMessage;
import com.itmill.toolkit.terminal.ErrorMessage;
import com.itmill.toolkit.terminal.PaintException;
import com.itmill.toolkit.terminal.PaintTarget;
/**
* Form component provides easy way of creating and managing sets fields.
*
* <p>
* <code>Form</code> is a container for fields implementing {@link Field}
* interface. It provides support for any layouts and provides buffering
* interface for easy connection of commit and discard buttons. All the form
* fields can be customized by adding validators, setting captions and icons,
* setting immediateness, etc. Also direct mechanism for replacing existing
* fields with selections is given.
* </p>
*
* <p>
* <code>Form</code> provides customizable editor for classes implementing
* {@link com.itmill.toolkit.data.Item} interface. Also the form itself
* implements this interface for easier connectivity to other items. To use the
* form as editor for an item, just connect the item to form with
* {@link Form#setItemDataSource(Item)}. If only a part of the item needs to be
* edited, {@link Form#setItemDataSource(Item,Collection)} can be used instead.
* After the item has been connected to the form, the automatically created
* fields can be customized and new fields can be added. If you need to connect
* a class that does not implement {@link com.itmill.toolkit.data.Item}
* interface, most properties of any class following bean pattern, can be
* accessed trough {@link com.itmill.toolkit.data.util.BeanItem}.
* </p>
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 3.0
*/
public class Form extends AbstractField implements Item.Editor, Buffered, Item,
Validatable {
private Object propertyValue;
/**
* Layout of the form.
*/
private Layout layout;
/**
* Item connected to this form as datasource.
*/
private Item itemDatasource;
/**
* Ordered list of property ids in this editor.
*/
private final LinkedList propertyIds = new LinkedList();
/**
* Current buffered source exception.
*/
private Buffered.SourceException currentBufferedSourceException = null;
/**
* Is the form in write trough mode.
*/
private boolean writeThrough = true;
/**
* Is the form in read trough mode.
*/
private boolean readThrough = true;
/**
* Mapping from propertyName to corresponding field.
*/
private final HashMap fields = new HashMap();
/**
* Field factory for this form.
*/
private FieldFactory fieldFactory;
/**
* Visible item properties.
*/
private Collection visibleItemProperties;
/**
* Form needs to repaint itself if child fields value changes due possible
* change in form validity.
*/
private final ValueChangeListener fieldValueChangeListener = new ValueChangeListener() {
public void valueChange(
com.itmill.toolkit.data.Property.ValueChangeEvent event) {
requestRepaint();
}
};
private Layout formFooter;
/**
* Contructs a new form with default layout.
*
* <p>
* By default the form uses <code>OrderedLayout</code> with
* <code>form</code>-style.
* </p>
*
* @param formLayout
* the layout of the form.
*/
public Form() {
this(null);
setValidationVisible(false);
}
/**
* Contructs a new form with given layout.
*
* @param formLayout
* the layout of the form.
*/
public Form(Layout formLayout) {
this(formLayout, new BaseFieldFactory());
}
/**
* Contructs a new form with given layout and FieldFactory.
*
* @param formLayout
* the layout of the form.
* @param fieldFactory
* the FieldFactory of the form.
*/
public Form(Layout formLayout, FieldFactory fieldFactory) {
super();
setLayout(formLayout);
setFieldFactory(fieldFactory);
setValidationVisible(false);
}
/* Documented in interface */
public String getTag() {
return "form";
}
/* Documented in interface */
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
layout.paint(target);
if (formFooter != null) {
formFooter.paint(target);
}
}
/**
* The error message of a Form is the error of the first field with a
* non-empty error.
*
* Empty error messages of the contained fields are skipped, because an
* empty error indicator would be confusing to the user, especially if there
* are errors that have something to display. This is also the reason why
* the calculation of the error message is separate from validation, because
* validation fails also on empty errors.
*/
public ErrorMessage getErrorMessage() {
// Reimplement the checking of validation error by using
// getErrorMessage() recursively instead of validate().
ErrorMessage validationError = null;
if (isValidationVisible()) {
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
AbstractComponent field = (AbstractComponent) fields.get(i
.next());
validationError = field.getErrorMessage();
if (validationError != null) {
// Skip empty errors
if ("".equals(validationError.toString())) {
continue;
}
break;
}
} catch (ClassCastException ignored) {
}
}
}
// Return if there are no errors at all
if (getComponentError() == null && validationError == null
&& currentBufferedSourceException == null) {
return null;
}
// Throw combination of the error types
return new CompositeErrorMessage(new ErrorMessage[] {
getComponentError(), validationError,
currentBufferedSourceException });
}
/*
* Commit changes to the data source Don't add a JavaDoc comment here, we
* use the default one from the interface.
*/
public void commit() throws Buffered.SourceException {
LinkedList problems = null;
// Only commit on valid state if so requested
if (!isInvalidCommitted() && !isValid()) {
return;
}
// Try to commit all
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
final Field f = ((Field) fields.get(i.next()));
// Commit only non-readonly fields.
if (!f.isReadOnly()) {
f.commit();
}
} catch (final Buffered.SourceException e) {
if (problems == null) {
problems = new LinkedList();
}
problems.add(e);
}
}
// No problems occurred
if (problems == null) {
if (currentBufferedSourceException != null) {
currentBufferedSourceException = null;
requestRepaint();
}
return;
}
// Commit problems
final Throwable[] causes = new Throwable[problems.size()];
int index = 0;
for (final Iterator i = problems.iterator(); i.hasNext();) {
causes[index++] = (Throwable) i.next();
}
final Buffered.SourceException e = new Buffered.SourceException(this,
causes);
currentBufferedSourceException = e;
requestRepaint();
throw e;
}
/*
* Discards local changes and refresh values from the data source Don't add
* a JavaDoc comment here, we use the default one from the interface.
*/
public void discard() throws Buffered.SourceException {
LinkedList problems = null;
// Try to discard all changes
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
((Field) fields.get(i.next())).discard();
} catch (final Buffered.SourceException e) {
if (problems == null) {
problems = new LinkedList();
}
problems.add(e);
}
}
// No problems occurred
if (problems == null) {
if (currentBufferedSourceException != null) {
currentBufferedSourceException = null;
requestRepaint();
}
return;
}
// Discards problems occurred
final Throwable[] causes = new Throwable[problems.size()];
int index = 0;
for (final Iterator i = problems.iterator(); i.hasNext();) {
causes[index++] = (Throwable) i.next();
}
final Buffered.SourceException e = new Buffered.SourceException(this,
causes);
currentBufferedSourceException = e;
requestRepaint();
throw e;
}
/*
* Is the object modified but not committed? Don't add a JavaDoc comment
* here, we use the default one from the interface.
*/
public boolean isModified() {
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
final Field f = (Field) fields.get(i.next());
if (f != null && f.isModified()) {
return true;
}
}
return false;
}
/*
* Is the editor in a read-through mode? Don't add a JavaDoc comment here,
* we use the default one from the interface.
*/
public boolean isReadThrough() {
return readThrough;
}
/*
* Is the editor in a write-through mode? Don't add a JavaDoc comment here,
* we use the default one from the interface.
*/
public boolean isWriteThrough() {
return writeThrough;
}
/*
* Sets the editor's read-through mode to the specified status. Don't add a
* JavaDoc comment here, we use the default one from the interface.
*/
public void setReadThrough(boolean readThrough) {
if (readThrough != this.readThrough) {
this.readThrough = readThrough;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setReadThrough(readThrough);
}
}
}
/*
* Sets the editor's read-through mode to the specified status. Don't add a
* JavaDoc comment here, we use the default one from the interface.
*/
public void setWriteThrough(boolean writeThrough) {
if (writeThrough != this.writeThrough) {
this.writeThrough = writeThrough;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setWriteThrough(writeThrough);
}
}
}
/**
* Adds a new property to form and create corresponding field.
*
* @see com.itmill.toolkit.data.Item#addItemProperty(Object, Property)
*/
public boolean addItemProperty(Object id, Property property) {
// Checks inputs
if (id == null || property == null) {
throw new NullPointerException("Id and property must be non-null");
}
// Checks that the property id is not reserved
if (propertyIds.contains(id)) {
return false;
}
// Gets suitable field
final Field field = fieldFactory.createField(property, this);
if (field == null) {
return false;
}
// Configures the field
try {
field.setPropertyDataSource(property);
String caption = id.toString();
if (caption.length() > 50) {
caption = caption.substring(0, 47) + "...";
}
if (caption.length() > 0) {
caption = "" + Character.toUpperCase(caption.charAt(0))
+ caption.substring(1, caption.length());
}
field.setCaption(caption);
} catch (final Throwable ignored) {
return false;
}
addField(id, field);
return true;
}
/**
* Adds the field to form.
*
* <p>
* The property id must not be already used in the form.
* </p>
*
* <p>
* This field is added to the form layout in the default position (the
* position used by {@link Layout#addComponent(Component)} method. In the
* special case that the underlying layout is a custom layout, string
* representation of the property id is used instead of the default
* location.
* </p>
*
* @param propertyId
* the Property id the the field.
* @param field
* the New field added to the form.
*/
public void addField(Object propertyId, Field field) {
if (propertyId != null && field != null) {
fields.put(propertyId, field);
field.addListener(fieldValueChangeListener);
propertyIds.addLast(propertyId);
field.setReadThrough(readThrough);
field.setWriteThrough(writeThrough);
if (isImmediate() && field instanceof AbstractComponent) {
((AbstractComponent) field).setImmediate(true);
}
if (layout instanceof CustomLayout) {
((CustomLayout) layout).addComponent(field, propertyId
.toString());
} else {
layout.addComponent(field);
}
requestRepaint();
}
}
/**
* The property identified by the property id.
*
* <p>
* The property data source of the field specified with property id is
* returned. If there is a (with specified property id) having no data
* source, the field is returned instead of the data source.
* </p>
*
* @see com.itmill.toolkit.data.Item#getItemProperty(Object)
*/
public Property getItemProperty(Object id) {
final Field field = (Field) fields.get(id);
if (field == null) {
return null;
}
final Property property = field.getPropertyDataSource();
if (property != null) {
return property;
} else {
return field;
}
}
/**
* Gets the field identified by the propertyid.
*
* @param propertyId
* the id of the property.
*/
public Field getField(Object propertyId) {
return (Field) fields.get(propertyId);
}
/* Documented in interface */
public Collection getItemPropertyIds() {
return Collections.unmodifiableCollection(propertyIds);
}
/**
* Removes the property and corresponding field from the form.
*
* @see com.itmill.toolkit.data.Item#removeItemProperty(Object)
*/
public boolean removeItemProperty(Object id) {
final Field field = (Field) fields.get(id);
if (field != null) {
propertyIds.remove(id);
fields.remove(id);
layout.removeComponent(field);
field.removeListener(fieldValueChangeListener);
return true;
}
return false;
}
/**
* Removes all properties and fields from the form.
*
* @return the Success of the operation. Removal of all fields succeeded if
* (and only if) the return value is <code>true</code>.
*/
public boolean removeAllProperties() {
final Object[] properties = propertyIds.toArray();
boolean success = true;
for (int i = 0; i < properties.length; i++) {
if (!removeItemProperty(properties[i])) {
success = false;
}
}
return success;
}
/* Documented in the interface */
public Item getItemDataSource() {
return itemDatasource;
}
/**
* Sets the item datasource for the form.
*
* <p>
* Setting item datasource clears any fields, the form might contain and
* adds all the properties as fields to the form.
* </p>
*
* @see com.itmill.toolkit.data.Item.Viewer#setItemDataSource(Item)
*/
public void setItemDataSource(Item newDataSource) {
setItemDataSource(newDataSource, newDataSource != null ? newDataSource
.getItemPropertyIds() : null);
}
/**
* Set the item datasource for the form, but limit the form contents to
* specified properties of the item.
*
* <p>
* Setting item datasource clears any fields, the form might contain and
* adds the specified the properties as fields to the form, in the specified
* order.
* </p>
*
* @see com.itmill.toolkit.data.Item.Viewer#setItemDataSource(Item)
*/
public void setItemDataSource(Item newDataSource, Collection propertyIds) {
// Removes all fields first from the form
removeAllProperties();
// Sets the datasource
itemDatasource = newDataSource;
// If the new datasource is null, just set null datasource
if (itemDatasource == null) {
return;
}
// Adds all the properties to this form
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
final Object id = i.next();
final Property property = itemDatasource.getItemProperty(id);
if (id != null && property != null) {
final Field f = fieldFactory.createField(itemDatasource, id,
this);
if (f != null) {
f.setPropertyDataSource(property);
addField(id, f);
}
}
}
}
/**
* Gets the layout of the form.
*
* <p>
* By default form uses <code>OrderedLayout</code> with <code>form</code>-style.
* </p>
*
* @return the Layout of the form.
*/
public Layout getLayout() {
return layout;
}
/**
* Sets the layout of the form.
*
* <p>
* By default form uses <code>OrderedLayout</code> with <code>form</code>-style.
* </p>
*
* @param newLayout
* the Layout of the form.
*/
public void setLayout(Layout newLayout) {
// Use orderedlayout by default
if (newLayout == null) {
newLayout = new FormLayout();
}
// Move components from previous layout
if (layout != null) {
newLayout.moveComponentsFrom(layout);
layout.setParent(null);
}
// Replace the previous layout
newLayout.setParent(this);
layout = newLayout;
}
/**
* Sets the form field to be selectable from static list of changes.
*
* <p>
* The list values and descriptions are given as array. The value-array must
* contain the current value of the field and the lengths of the arrays must
* match. Null values are not supported.
* </p>
*
* @param propertyId
* the id of the property.
* @param values
* @param descriptions
* @return the select property generated
*/
public Select replaceWithSelect(Object propertyId, Object[] values,
Object[] descriptions) {
// Checks the parameters
if (propertyId == null || values == null || descriptions == null) {
throw new NullPointerException("All parameters must be non-null");
}
if (values.length != descriptions.length) {
throw new IllegalArgumentException(
"Value and description list are of different size");
}
// Gets the old field
final Field oldField = (Field) fields.get(propertyId);
if (oldField == null) {
throw new IllegalArgumentException("Field with given propertyid '"
+ propertyId.toString() + "' can not be found.");
}
final Object value = oldField.getValue();
// Checks that the value exists and check if the select should
// be forced in multiselect mode
boolean found = false;
boolean isMultiselect = false;
for (int i = 0; i < values.length && !found; i++) {
if (values[i] == value
|| (value != null && value.equals(values[i]))) {
found = true;
}
}
if (value != null && !found) {
if (value instanceof Collection) {
for (final Iterator it = ((Collection) value).iterator(); it
.hasNext();) {
final Object val = it.next();
found = false;
for (int i = 0; i < values.length && !found; i++) {
if (values[i] == val
|| (val != null && val.equals(values[i]))) {
found = true;
}
}
if (!found) {
throw new IllegalArgumentException(
"Currently selected value '" + val
+ "' of property '"
+ propertyId.toString()
+ "' was not found");
}
}
isMultiselect = true;
} else {
throw new IllegalArgumentException("Current value '" + value
+ "' of property '" + propertyId.toString()
+ "' was not found");
}
}
// Creates the new field matching to old field parameters
final Select newField = new Select();
if (isMultiselect) {
newField.setMultiSelect(true);
}
newField.setCaption(oldField.getCaption());
newField.setReadOnly(oldField.isReadOnly());
newField.setReadThrough(oldField.isReadThrough());
newField.setWriteThrough(oldField.isWriteThrough());
// Creates the options list
newField.addContainerProperty("desc", String.class, "");
newField.setItemCaptionPropertyId("desc");
for (int i = 0; i < values.length; i++) {
Object id = values[i];
if (id == null) {
id = new Object();
newField.setNullSelectionItemId(id);
}
final Item item = newField.addItem(id);
if (item != null) {
item.getItemProperty("desc").setValue(
descriptions[i].toString());
}
}
// Sets the property data source
final Property property = oldField.getPropertyDataSource();
oldField.setPropertyDataSource(null);
newField.setPropertyDataSource(property);
// Replaces the old field with new one
layout.replaceComponent(oldField, newField);
fields.put(propertyId, newField);
newField.addListener(fieldValueChangeListener);
oldField.removeListener(fieldValueChangeListener);
return newField;
}
/**
* Notifies the component that it is connected to an application
*
* @see com.itmill.toolkit.ui.Component#attach()
*/
public void attach() {
super.attach();
layout.attach();
}
/**
* Notifies the component that it is detached from the application.
*
* @see com.itmill.toolkit.ui.Component#detach()
*/
public void detach() {
super.detach();
layout.detach();
}
/**
* Tests the current value of the object against all registered validators
*
* @see com.itmill.toolkit.data.Validatable#isValid()
*/
public boolean isValid() {
boolean valid = true;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
valid &= ((Field) fields.get(i.next())).isValid();
}
return valid && super.isValid();
}
/**
* Checks the validity of the validatable.
*
* @see com.itmill.toolkit.data.Validatable#validate()
*/
public void validate() throws InvalidValueException {
super.validate();
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).validate();
}
}
/**
* Checks the validabtable object accept invalid values.
*
* @see com.itmill.toolkit.data.Validatable#isInvalidAllowed()
*/
public boolean isInvalidAllowed() {
return true;
}
/**
* Should the validabtable object accept invalid values.
*
* @see com.itmill.toolkit.data.Validatable#setInvalidAllowed(boolean)
*/
public void setInvalidAllowed(boolean invalidValueAllowed)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Sets the component's to read-only mode to the specified state.
*
* @see com.itmill.toolkit.ui.Component#setReadOnly(boolean)
*/
public void setReadOnly(boolean readOnly) {
super.setReadOnly(readOnly);
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setReadOnly(readOnly);
}
}
/**
* Sets the field factory of Form.
*
* <code>FieldFactory</code> is used to create fields for form properties.
* By default the form uses BaseFieldFactory to create Field instances.
*
* @param fieldFactory
* the New factory used to create the fields.
* @see Field
* @see FieldFactory
*/
public void setFieldFactory(FieldFactory fieldFactory) {
this.fieldFactory = fieldFactory;
}
/**
* Get the field factory of the form.
*
* @return the FieldFactory Factory used to create the fields.
*/
public FieldFactory getFieldFactory() {
return fieldFactory;
}
/**
* Gets the field type.
*
* @see com.itmill.toolkit.ui.AbstractField#getType()
*/
public Class getType() {
if (getPropertyDataSource() != null) {
return getPropertyDataSource().getType();
}
return Object.class;
}
/**
* Sets the internal value.
*
* This is relevant when the Form is used as Field.
*
* @see com.itmill.toolkit.ui.AbstractField#setInternalValue(java.lang.Object)
*/
protected void setInternalValue(Object newValue) {
// Stores the old value
final Object oldValue = propertyValue;
// Sets the current Value
super.setInternalValue(newValue);
propertyValue = newValue;
// Ignores form updating if data object has not changed.
if (oldValue != newValue) {
setFormDataSource(newValue, getVisibleItemProperties());
}
}
/**
* Gets the first field in form.
*
* @return the Field.
*/
private Field getFirstField() {
Object id = null;
if (getItemPropertyIds() != null) {
id = getItemPropertyIds().iterator().next();
}
if (id != null) {
return getField(id);
}
return null;
}
/**
* Updates the internal form datasource.
*
* Method setFormDataSource.
*
* @param data
* @param properties
*/
protected void setFormDataSource(Object data, Collection properties) {
// If data is an item use it.
Item item = null;
if (data instanceof Item) {
item = (Item) data;
} else if (data != null) {
item = new BeanItem(data);
}
// Sets the datasource to form
if (item != null && properties != null) {
// Shows only given properties
this.setItemDataSource(item, properties);
} else {
// Shows all properties
this.setItemDataSource(item);
}
}
/**
* Returns the visibleProperties.
*
* @return the Collection of visible Item properites.
*/
public Collection getVisibleItemProperties() {
return visibleItemProperties;
}
/**
* Sets the visibleProperties.
*
* @param visibleProperties
* the visibleProperties to set.
*/
public void setVisibleItemProperties(Collection visibleProperties) {
visibleItemProperties = visibleProperties;
Object value = getValue();
if (value == null) {
value = itemDatasource;
}
setFormDataSource(value, getVisibleItemProperties());
}
/**
* Focuses the first field in the form.
*
* @see com.itmill.toolkit.ui.Component.Focusable#focus()
*/
public void focus() {
final Field f = getFirstField();
if (f != null) {
f.focus();
}
}
/**
* Sets the Tabulator index of this Focusable component.
*
* @see com.itmill.toolkit.ui.Component.Focusable#setTabIndex(int)
*/
public void setTabIndex(int tabIndex) {
super.setTabIndex(tabIndex);
for (final Iterator i = getItemPropertyIds().iterator(); i.hasNext();) {
(getField(i.next())).setTabIndex(tabIndex);
}
}
/**
* Setting the form to be immediate also sets all the fields of the form to
* the same state.
*/
public void setImmediate(boolean immediate) {
super.setImmediate(immediate);
for (Iterator i = fields.values().iterator(); i.hasNext();) {
Field f = (Field) i.next();
if (f instanceof AbstractComponent) {
((AbstractComponent) f).setImmediate(immediate);
}
}
}
/** Form is empty if all of its fields are empty. */
protected boolean isEmpty() {
for (Iterator i = fields.values().iterator(); i.hasNext();) {
Field f = (Field) i.next();
if (f instanceof AbstractField) {
if (!((AbstractField) f).isEmpty()) {
return false;
}
}
}
return true;
}
/**
* Adding validators directly to form is not supported.
*
* Add the validators to form fields instead.
*/
public void addValidator(Validator validator) {
throw new UnsupportedOperationException();
}
/**
* Returns a layout that is rendered below normal form contents. This area
* can be used for example to include buttons related to form contents.
*
* @return layout rendered below normal form contents.
*/
public Layout getFooter() {
if (formFooter == null) {
formFooter = new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL);
formFooter.setParent(this);
}
return formFooter;
}
/**
* Sets the layout that is rendered below normal form contens.
*
* @param newFormFooter
* the new Layout
*/
public void setFooter(Layout newFormFooter) {
if (formFooter != null) {
formFooter.setParent(null);
}
formFooter = newFormFooter;
formFooter.setParent(this);
}
}
| src/com/itmill/toolkit/ui/Form.java | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.ui;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import com.itmill.toolkit.data.Buffered;
import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.Property;
import com.itmill.toolkit.data.Validatable;
import com.itmill.toolkit.data.Validator;
import com.itmill.toolkit.data.Validator.InvalidValueException;
import com.itmill.toolkit.data.util.BeanItem;
import com.itmill.toolkit.terminal.CompositeErrorMessage;
import com.itmill.toolkit.terminal.ErrorMessage;
import com.itmill.toolkit.terminal.PaintException;
import com.itmill.toolkit.terminal.PaintTarget;
/**
* Form component provides easy way of creating and managing sets fields.
*
* <p>
* <code>Form</code> is a container for fields implementing {@link Field}
* interface. It provides support for any layouts and provides buffering
* interface for easy connection of commit and discard buttons. All the form
* fields can be customized by adding validators, setting captions and icons,
* setting immediateness, etc. Also direct mechanism for replacing existing
* fields with selections is given.
* </p>
*
* <p>
* <code>Form</code> provides customizable editor for classes implementing
* {@link com.itmill.toolkit.data.Item} interface. Also the form itself
* implements this interface for easier connectivity to other items. To use the
* form as editor for an item, just connect the item to form with
* {@link Form#setItemDataSource(Item)}. If only a part of the item needs to be
* edited, {@link Form#setItemDataSource(Item,Collection)} can be used instead.
* After the item has been connected to the form, the automatically created
* fields can be customized and new fields can be added. If you need to connect
* a class that does not implement {@link com.itmill.toolkit.data.Item}
* interface, most properties of any class following bean pattern, can be
* accessed trough {@link com.itmill.toolkit.data.util.BeanItem}.
* </p>
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 3.0
*/
public class Form extends AbstractField implements Item.Editor, Buffered, Item,
Validatable {
private Object propertyValue;
/**
* Layout of the form.
*/
private Layout layout;
/**
* Item connected to this form as datasource.
*/
private Item itemDatasource;
/**
* Ordered list of property ids in this editor.
*/
private final LinkedList propertyIds = new LinkedList();
/**
* Current buffered source exception.
*/
private Buffered.SourceException currentBufferedSourceException = null;
/**
* Is the form in write trough mode.
*/
private boolean writeThrough = true;
/**
* Is the form in read trough mode.
*/
private boolean readThrough = true;
/**
* Mapping from propertyName to corresponding field.
*/
private final HashMap fields = new HashMap();
/**
* Field factory for this form.
*/
private FieldFactory fieldFactory;
/**
* Visible item properties.
*/
private Collection visibleItemProperties;
/**
* Form needs to repaint itself if child fields value changes due possible
* change in form validity.
*/
private final ValueChangeListener fieldValueChangeListener = new ValueChangeListener() {
public void valueChange(
com.itmill.toolkit.data.Property.ValueChangeEvent event) {
requestRepaint();
}
};
private Layout formFooter;
/**
* Contructs a new form with default layout.
*
* <p>
* By default the form uses <code>OrderedLayout</code> with
* <code>form</code>-style.
* </p>
*
* @param formLayout
* the layout of the form.
*/
public Form() {
this(null);
setValidationVisible(false);
}
/**
* Contructs a new form with given layout.
*
* @param formLayout
* the layout of the form.
*/
public Form(Layout formLayout) {
this(formLayout, new BaseFieldFactory());
}
/**
* Contructs a new form with given layout and FieldFactory.
*
* @param formLayout
* the layout of the form.
* @param fieldFactory
* the FieldFactory of the form.
*/
public Form(Layout formLayout, FieldFactory fieldFactory) {
super();
setLayout(formLayout);
setFieldFactory(fieldFactory);
setValidationVisible(false);
}
/* Documented in interface */
public String getTag() {
return "form";
}
/* Documented in interface */
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
layout.paint(target);
if (formFooter != null) {
formFooter.paint(target);
}
}
/**
* The error message of a Form is the error of the first field with a
* non-empty error.
*
* Empty error messages of the contained fields are skipped, because an
* empty error indicator would be confusing to the user, especially if there
* are errors that have something to display. This is also the reason why
* the calculation of the error message is separate from validation, because
* validation fails also on empty errors.
*/
public ErrorMessage getErrorMessage() {
// Reimplement the checking of validation error by using
// getErrorMessage() recursively instead of validate().
ErrorMessage validationError = null;
if (isValidationVisible()) {
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
AbstractComponent field = (AbstractComponent) fields.get(i
.next());
validationError = field.getErrorMessage();
if (validationError != null) {
// Skip empty errors
if ("".equals(validationError.toString())) {
continue;
}
break;
}
} catch (ClassCastException ignored) {
}
}
}
// Check if there are any systems errors
final ErrorMessage superError = super.getErrorMessage();
// Return if there are no errors at all
if (superError == null && validationError == null
&& currentBufferedSourceException == null) {
return null;
}
// Throw combination of the error types
return new CompositeErrorMessage(new ErrorMessage[] { superError,
validationError, currentBufferedSourceException });
}
/*
* Commit changes to the data source Don't add a JavaDoc comment here, we
* use the default one from the interface.
*/
public void commit() throws Buffered.SourceException {
LinkedList problems = null;
// Only commit on valid state if so requested
if (!isInvalidCommitted() && !isValid()) {
return;
}
// Try to commit all
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
final Field f = ((Field) fields.get(i.next()));
// Commit only non-readonly fields.
if (!f.isReadOnly()) {
f.commit();
}
} catch (final Buffered.SourceException e) {
if (problems == null) {
problems = new LinkedList();
}
problems.add(e);
}
}
// No problems occurred
if (problems == null) {
if (currentBufferedSourceException != null) {
currentBufferedSourceException = null;
requestRepaint();
}
return;
}
// Commit problems
final Throwable[] causes = new Throwable[problems.size()];
int index = 0;
for (final Iterator i = problems.iterator(); i.hasNext();) {
causes[index++] = (Throwable) i.next();
}
final Buffered.SourceException e = new Buffered.SourceException(this,
causes);
currentBufferedSourceException = e;
requestRepaint();
throw e;
}
/*
* Discards local changes and refresh values from the data source Don't add
* a JavaDoc comment here, we use the default one from the interface.
*/
public void discard() throws Buffered.SourceException {
LinkedList problems = null;
// Try to discard all changes
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
try {
((Field) fields.get(i.next())).discard();
} catch (final Buffered.SourceException e) {
if (problems == null) {
problems = new LinkedList();
}
problems.add(e);
}
}
// No problems occurred
if (problems == null) {
if (currentBufferedSourceException != null) {
currentBufferedSourceException = null;
requestRepaint();
}
return;
}
// Discards problems occurred
final Throwable[] causes = new Throwable[problems.size()];
int index = 0;
for (final Iterator i = problems.iterator(); i.hasNext();) {
causes[index++] = (Throwable) i.next();
}
final Buffered.SourceException e = new Buffered.SourceException(this,
causes);
currentBufferedSourceException = e;
requestRepaint();
throw e;
}
/*
* Is the object modified but not committed? Don't add a JavaDoc comment
* here, we use the default one from the interface.
*/
public boolean isModified() {
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
final Field f = (Field) fields.get(i.next());
if (f != null && f.isModified()) {
return true;
}
}
return false;
}
/*
* Is the editor in a read-through mode? Don't add a JavaDoc comment here,
* we use the default one from the interface.
*/
public boolean isReadThrough() {
return readThrough;
}
/*
* Is the editor in a write-through mode? Don't add a JavaDoc comment here,
* we use the default one from the interface.
*/
public boolean isWriteThrough() {
return writeThrough;
}
/*
* Sets the editor's read-through mode to the specified status. Don't add a
* JavaDoc comment here, we use the default one from the interface.
*/
public void setReadThrough(boolean readThrough) {
if (readThrough != this.readThrough) {
this.readThrough = readThrough;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setReadThrough(readThrough);
}
}
}
/*
* Sets the editor's read-through mode to the specified status. Don't add a
* JavaDoc comment here, we use the default one from the interface.
*/
public void setWriteThrough(boolean writeThrough) {
if (writeThrough != this.writeThrough) {
this.writeThrough = writeThrough;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setWriteThrough(writeThrough);
}
}
}
/**
* Adds a new property to form and create corresponding field.
*
* @see com.itmill.toolkit.data.Item#addItemProperty(Object, Property)
*/
public boolean addItemProperty(Object id, Property property) {
// Checks inputs
if (id == null || property == null) {
throw new NullPointerException("Id and property must be non-null");
}
// Checks that the property id is not reserved
if (propertyIds.contains(id)) {
return false;
}
// Gets suitable field
final Field field = fieldFactory.createField(property, this);
if (field == null) {
return false;
}
// Configures the field
try {
field.setPropertyDataSource(property);
String caption = id.toString();
if (caption.length() > 50) {
caption = caption.substring(0, 47) + "...";
}
if (caption.length() > 0) {
caption = "" + Character.toUpperCase(caption.charAt(0))
+ caption.substring(1, caption.length());
}
field.setCaption(caption);
} catch (final Throwable ignored) {
return false;
}
addField(id, field);
return true;
}
/**
* Adds the field to form.
*
* <p>
* The property id must not be already used in the form.
* </p>
*
* <p>
* This field is added to the form layout in the default position (the
* position used by {@link Layout#addComponent(Component)} method. In the
* special case that the underlying layout is a custom layout, string
* representation of the property id is used instead of the default
* location.
* </p>
*
* @param propertyId
* the Property id the the field.
* @param field
* the New field added to the form.
*/
public void addField(Object propertyId, Field field) {
if (propertyId != null && field != null) {
fields.put(propertyId, field);
field.addListener(fieldValueChangeListener);
propertyIds.addLast(propertyId);
field.setReadThrough(readThrough);
field.setWriteThrough(writeThrough);
if (isImmediate() && field instanceof AbstractComponent) {
((AbstractComponent) field).setImmediate(true);
}
if (layout instanceof CustomLayout) {
((CustomLayout) layout).addComponent(field, propertyId
.toString());
} else {
layout.addComponent(field);
}
requestRepaint();
}
}
/**
* The property identified by the property id.
*
* <p>
* The property data source of the field specified with property id is
* returned. If there is a (with specified property id) having no data
* source, the field is returned instead of the data source.
* </p>
*
* @see com.itmill.toolkit.data.Item#getItemProperty(Object)
*/
public Property getItemProperty(Object id) {
final Field field = (Field) fields.get(id);
if (field == null) {
return null;
}
final Property property = field.getPropertyDataSource();
if (property != null) {
return property;
} else {
return field;
}
}
/**
* Gets the field identified by the propertyid.
*
* @param propertyId
* the id of the property.
*/
public Field getField(Object propertyId) {
return (Field) fields.get(propertyId);
}
/* Documented in interface */
public Collection getItemPropertyIds() {
return Collections.unmodifiableCollection(propertyIds);
}
/**
* Removes the property and corresponding field from the form.
*
* @see com.itmill.toolkit.data.Item#removeItemProperty(Object)
*/
public boolean removeItemProperty(Object id) {
final Field field = (Field) fields.get(id);
if (field != null) {
propertyIds.remove(id);
fields.remove(id);
layout.removeComponent(field);
field.removeListener(fieldValueChangeListener);
return true;
}
return false;
}
/**
* Removes all properties and fields from the form.
*
* @return the Success of the operation. Removal of all fields succeeded if
* (and only if) the return value is <code>true</code>.
*/
public boolean removeAllProperties() {
final Object[] properties = propertyIds.toArray();
boolean success = true;
for (int i = 0; i < properties.length; i++) {
if (!removeItemProperty(properties[i])) {
success = false;
}
}
return success;
}
/* Documented in the interface */
public Item getItemDataSource() {
return itemDatasource;
}
/**
* Sets the item datasource for the form.
*
* <p>
* Setting item datasource clears any fields, the form might contain and
* adds all the properties as fields to the form.
* </p>
*
* @see com.itmill.toolkit.data.Item.Viewer#setItemDataSource(Item)
*/
public void setItemDataSource(Item newDataSource) {
setItemDataSource(newDataSource, newDataSource != null ? newDataSource
.getItemPropertyIds() : null);
}
/**
* Set the item datasource for the form, but limit the form contents to
* specified properties of the item.
*
* <p>
* Setting item datasource clears any fields, the form might contain and
* adds the specified the properties as fields to the form, in the specified
* order.
* </p>
*
* @see com.itmill.toolkit.data.Item.Viewer#setItemDataSource(Item)
*/
public void setItemDataSource(Item newDataSource, Collection propertyIds) {
// Removes all fields first from the form
removeAllProperties();
// Sets the datasource
itemDatasource = newDataSource;
// If the new datasource is null, just set null datasource
if (itemDatasource == null) {
return;
}
// Adds all the properties to this form
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
final Object id = i.next();
final Property property = itemDatasource.getItemProperty(id);
if (id != null && property != null) {
final Field f = fieldFactory.createField(itemDatasource, id,
this);
if (f != null) {
f.setPropertyDataSource(property);
addField(id, f);
}
}
}
}
/**
* Gets the layout of the form.
*
* <p>
* By default form uses <code>OrderedLayout</code> with <code>form</code>-style.
* </p>
*
* @return the Layout of the form.
*/
public Layout getLayout() {
return layout;
}
/**
* Sets the layout of the form.
*
* <p>
* By default form uses <code>OrderedLayout</code> with <code>form</code>-style.
* </p>
*
* @param newLayout
* the Layout of the form.
*/
public void setLayout(Layout newLayout) {
// Use orderedlayout by default
if (newLayout == null) {
newLayout = new FormLayout();
}
// Move components from previous layout
if (layout != null) {
newLayout.moveComponentsFrom(layout);
layout.setParent(null);
}
// Replace the previous layout
newLayout.setParent(this);
layout = newLayout;
}
/**
* Sets the form field to be selectable from static list of changes.
*
* <p>
* The list values and descriptions are given as array. The value-array must
* contain the current value of the field and the lengths of the arrays must
* match. Null values are not supported.
* </p>
*
* @param propertyId
* the id of the property.
* @param values
* @param descriptions
* @return the select property generated
*/
public Select replaceWithSelect(Object propertyId, Object[] values,
Object[] descriptions) {
// Checks the parameters
if (propertyId == null || values == null || descriptions == null) {
throw new NullPointerException("All parameters must be non-null");
}
if (values.length != descriptions.length) {
throw new IllegalArgumentException(
"Value and description list are of different size");
}
// Gets the old field
final Field oldField = (Field) fields.get(propertyId);
if (oldField == null) {
throw new IllegalArgumentException("Field with given propertyid '"
+ propertyId.toString() + "' can not be found.");
}
final Object value = oldField.getValue();
// Checks that the value exists and check if the select should
// be forced in multiselect mode
boolean found = false;
boolean isMultiselect = false;
for (int i = 0; i < values.length && !found; i++) {
if (values[i] == value
|| (value != null && value.equals(values[i]))) {
found = true;
}
}
if (value != null && !found) {
if (value instanceof Collection) {
for (final Iterator it = ((Collection) value).iterator(); it
.hasNext();) {
final Object val = it.next();
found = false;
for (int i = 0; i < values.length && !found; i++) {
if (values[i] == val
|| (val != null && val.equals(values[i]))) {
found = true;
}
}
if (!found) {
throw new IllegalArgumentException(
"Currently selected value '" + val
+ "' of property '"
+ propertyId.toString()
+ "' was not found");
}
}
isMultiselect = true;
} else {
throw new IllegalArgumentException("Current value '" + value
+ "' of property '" + propertyId.toString()
+ "' was not found");
}
}
// Creates the new field matching to old field parameters
final Select newField = new Select();
if (isMultiselect) {
newField.setMultiSelect(true);
}
newField.setCaption(oldField.getCaption());
newField.setReadOnly(oldField.isReadOnly());
newField.setReadThrough(oldField.isReadThrough());
newField.setWriteThrough(oldField.isWriteThrough());
// Creates the options list
newField.addContainerProperty("desc", String.class, "");
newField.setItemCaptionPropertyId("desc");
for (int i = 0; i < values.length; i++) {
Object id = values[i];
if (id == null) {
id = new Object();
newField.setNullSelectionItemId(id);
}
final Item item = newField.addItem(id);
if (item != null) {
item.getItemProperty("desc").setValue(
descriptions[i].toString());
}
}
// Sets the property data source
final Property property = oldField.getPropertyDataSource();
oldField.setPropertyDataSource(null);
newField.setPropertyDataSource(property);
// Replaces the old field with new one
layout.replaceComponent(oldField, newField);
fields.put(propertyId, newField);
newField.addListener(fieldValueChangeListener);
oldField.removeListener(fieldValueChangeListener);
return newField;
}
/**
* Notifies the component that it is connected to an application
*
* @see com.itmill.toolkit.ui.Component#attach()
*/
public void attach() {
super.attach();
layout.attach();
}
/**
* Notifies the component that it is detached from the application.
*
* @see com.itmill.toolkit.ui.Component#detach()
*/
public void detach() {
super.detach();
layout.detach();
}
/**
* Tests the current value of the object against all registered validators
*
* @see com.itmill.toolkit.data.Validatable#isValid()
*/
public boolean isValid() {
boolean valid = true;
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
valid &= ((Field) fields.get(i.next())).isValid();
}
return valid && super.isValid();
}
/**
* Checks the validity of the validatable.
*
* @see com.itmill.toolkit.data.Validatable#validate()
*/
public void validate() throws InvalidValueException {
super.validate();
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).validate();
}
}
/**
* Checks the validabtable object accept invalid values.
*
* @see com.itmill.toolkit.data.Validatable#isInvalidAllowed()
*/
public boolean isInvalidAllowed() {
return true;
}
/**
* Should the validabtable object accept invalid values.
*
* @see com.itmill.toolkit.data.Validatable#setInvalidAllowed(boolean)
*/
public void setInvalidAllowed(boolean invalidValueAllowed)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Sets the component's to read-only mode to the specified state.
*
* @see com.itmill.toolkit.ui.Component#setReadOnly(boolean)
*/
public void setReadOnly(boolean readOnly) {
super.setReadOnly(readOnly);
for (final Iterator i = propertyIds.iterator(); i.hasNext();) {
((Field) fields.get(i.next())).setReadOnly(readOnly);
}
}
/**
* Sets the field factory of Form.
*
* <code>FieldFactory</code> is used to create fields for form properties.
* By default the form uses BaseFieldFactory to create Field instances.
*
* @param fieldFactory
* the New factory used to create the fields.
* @see Field
* @see FieldFactory
*/
public void setFieldFactory(FieldFactory fieldFactory) {
this.fieldFactory = fieldFactory;
}
/**
* Get the field factory of the form.
*
* @return the FieldFactory Factory used to create the fields.
*/
public FieldFactory getFieldFactory() {
return fieldFactory;
}
/**
* Gets the field type.
*
* @see com.itmill.toolkit.ui.AbstractField#getType()
*/
public Class getType() {
if (getPropertyDataSource() != null) {
return getPropertyDataSource().getType();
}
return Object.class;
}
/**
* Sets the internal value.
*
* This is relevant when the Form is used as Field.
*
* @see com.itmill.toolkit.ui.AbstractField#setInternalValue(java.lang.Object)
*/
protected void setInternalValue(Object newValue) {
// Stores the old value
final Object oldValue = propertyValue;
// Sets the current Value
super.setInternalValue(newValue);
propertyValue = newValue;
// Ignores form updating if data object has not changed.
if (oldValue != newValue) {
setFormDataSource(newValue, getVisibleItemProperties());
}
}
/**
* Gets the first field in form.
*
* @return the Field.
*/
private Field getFirstField() {
Object id = null;
if (getItemPropertyIds() != null) {
id = getItemPropertyIds().iterator().next();
}
if (id != null) {
return getField(id);
}
return null;
}
/**
* Updates the internal form datasource.
*
* Method setFormDataSource.
*
* @param data
* @param properties
*/
protected void setFormDataSource(Object data, Collection properties) {
// If data is an item use it.
Item item = null;
if (data instanceof Item) {
item = (Item) data;
} else if (data != null) {
item = new BeanItem(data);
}
// Sets the datasource to form
if (item != null && properties != null) {
// Shows only given properties
this.setItemDataSource(item, properties);
} else {
// Shows all properties
this.setItemDataSource(item);
}
}
/**
* Returns the visibleProperties.
*
* @return the Collection of visible Item properites.
*/
public Collection getVisibleItemProperties() {
return visibleItemProperties;
}
/**
* Sets the visibleProperties.
*
* @param visibleProperties
* the visibleProperties to set.
*/
public void setVisibleItemProperties(Collection visibleProperties) {
visibleItemProperties = visibleProperties;
Object value = getValue();
if (value == null) {
value = itemDatasource;
}
setFormDataSource(value, getVisibleItemProperties());
}
/**
* Focuses the first field in the form.
*
* @see com.itmill.toolkit.ui.Component.Focusable#focus()
*/
public void focus() {
final Field f = getFirstField();
if (f != null) {
f.focus();
}
}
/**
* Sets the Tabulator index of this Focusable component.
*
* @see com.itmill.toolkit.ui.Component.Focusable#setTabIndex(int)
*/
public void setTabIndex(int tabIndex) {
super.setTabIndex(tabIndex);
for (final Iterator i = getItemPropertyIds().iterator(); i.hasNext();) {
(getField(i.next())).setTabIndex(tabIndex);
}
}
/**
* Setting the form to be immediate also sets all the fields of the form to
* the same state.
*/
public void setImmediate(boolean immediate) {
super.setImmediate(immediate);
for (Iterator i = fields.values().iterator(); i.hasNext();) {
Field f = (Field) i.next();
if (f instanceof AbstractComponent) {
((AbstractComponent) f).setImmediate(immediate);
}
}
}
/** Form is empty if all of its fields are empty. */
protected boolean isEmpty() {
for (Iterator i = fields.values().iterator(); i.hasNext();) {
Field f = (Field) i.next();
if (f instanceof AbstractField) {
if (!((AbstractField) f).isEmpty()) {
return false;
}
}
}
return true;
}
/**
* Adding validators directly to form is not supported.
*
* Add the validators to form fields instead.
*/
public void addValidator(Validator validator) {
throw new UnsupportedOperationException();
}
/**
* Returns a layout that is rendered below normal form contents. This area
* can be used for example to include buttons related to form contents.
*
* @return layout rendered below normal form contents.
*/
public Layout getFooter() {
if (formFooter == null) {
formFooter = new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL);
formFooter.setParent(this);
}
return formFooter;
}
/**
* Sets the layout that is rendered below normal form contens.
*
* @param newFormFooter
* the new Layout
*/
public void setFooter(Layout newFormFooter) {
if (formFooter != null) {
formFooter.setParent(null);
}
formFooter = newFormFooter;
formFooter.setParent(this);
}
}
| "Final" Fix for #1867
svn changeset:5036/svn branch:trunk
| src/com/itmill/toolkit/ui/Form.java | "Final" Fix for #1867 | <ide><path>rc/com/itmill/toolkit/ui/Form.java
<ide> }
<ide> }
<ide>
<del> // Check if there are any systems errors
<del> final ErrorMessage superError = super.getErrorMessage();
<del>
<ide> // Return if there are no errors at all
<del> if (superError == null && validationError == null
<add> if (getComponentError() == null && validationError == null
<ide> && currentBufferedSourceException == null) {
<ide> return null;
<ide> }
<ide>
<ide> // Throw combination of the error types
<del> return new CompositeErrorMessage(new ErrorMessage[] { superError,
<del> validationError, currentBufferedSourceException });
<add> return new CompositeErrorMessage(new ErrorMessage[] {
<add> getComponentError(), validationError,
<add> currentBufferedSourceException });
<ide> }
<ide>
<ide> /* |
|
Java | apache-2.0 | 87881a6bebe9fe55c81daec8f5cc7c6c0c56f532 | 0 | lovemomia/momia,lovemomia/momia,lovemomia/service,lovemomia/service | package cn.momia.service.course.web.ctrl;
import cn.momia.api.course.dto.course.Course;
import cn.momia.api.course.dto.subject.SubjectOrder;
import cn.momia.api.course.dto.subject.SubjectPackage;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.dto.PagedList;
import cn.momia.common.core.exception.MomiaErrorException;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.common.deal.gateway.PayType;
import cn.momia.common.deal.gateway.PaymentGateway;
import cn.momia.common.deal.gateway.RefundParam;
import cn.momia.common.deal.gateway.RefundQueryParam;
import cn.momia.common.deal.gateway.factory.PaymentGatewayFactory;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.common.webapp.ctrl.BaseController;
import cn.momia.service.course.base.CourseService;
import cn.momia.api.course.dto.coupon.UserCoupon;
import cn.momia.api.course.dto.subject.Subject;
import cn.momia.api.course.dto.coupon.CouponCode;
import cn.momia.service.course.order.Payment;
import cn.momia.service.course.order.Refund;
import cn.momia.service.course.subject.SubjectService;
import cn.momia.api.course.dto.subject.SubjectSku;
import cn.momia.service.course.coupon.CouponService;
import cn.momia.service.course.order.Order;
import cn.momia.service.course.order.OrderService;
import cn.momia.service.course.order.OrderPackage;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping(value = "/order")
public class OrderController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
@Autowired private CourseService courseService;
@Autowired private SubjectService subjectService;
@Autowired private OrderService orderService;
@Autowired private CouponService couponService;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public MomiaHttpResponse placeOrder(@RequestBody Order order) {
List<OrderPackage> orderPackages = order.getPackages();
Set<Long> skuIds = new HashSet<Long>();
for (OrderPackage orderPackage : orderPackages) {
skuIds.add(orderPackage.getSkuId());
}
List<SubjectSku> skus = subjectService.listSkus(skuIds);
if (!checkAndCompleteOrder(order, skus)) return MomiaHttpResponse.FAILED("无效的订单数据");
boolean isTrial = subjectService.isTrial(order.getSubjectId());
if (isTrial && !subjectService.decreaseStock(order.getSubjectId(), order.getCount())) return MomiaHttpResponse.FAILED("下单失败,库存不足或已售完");
long orderId = 0;
try {
orderId = orderService.add(order);
order.setId(orderId);
return MomiaHttpResponse.SUCCESS(buildMiniSubjectOrder(order));
} catch (Exception e) {
return MomiaHttpResponse.FAILED("下单失败");
} finally {
if (orderId <= 0 && isTrial) subjectService.increaseStock(order.getSubjectId(), order.getCount());
}
}
private boolean checkAndCompleteOrder(Order order, List<SubjectSku> skus) {
if (order.isInvalid()) return false;
User user = userServiceApi.get(order.getUserId());
if (!user.exists()) throw new MomiaErrorException("用户不存在");
if (subjectService.isTrial(order.getSubjectId()) && (user.isPayed() || orderService.hasTrialOrder(user.getId()))) throw new MomiaErrorException("本课程包只供新用户专享");
Map<Long, SubjectSku> skusMap = new HashMap<Long, SubjectSku>();
for (SubjectSku sku : skus) {
if (sku.getSubjectId() != order.getSubjectId()) return false;
skusMap.put(sku.getId(), sku);
}
String code = order.getCouponCode();
order.setCouponCode("");
CouponCode couponCode = couponService.getCouponCode(code);
boolean couponCodeUsed = !couponCode.exists();
List<OrderPackage> orderPackages = order.getPackages();
for (OrderPackage orderPackage : orderPackages) {
SubjectSku sku = skusMap.get(orderPackage.getSkuId());
if (sku == null) return false;
if (sku.getLimit() > 0) checkLimit(order.getUserId(), sku.getId(), sku.getLimit());
BigDecimal skuPrice = sku.getPrice();
if (!couponCodeUsed && skuPrice.compareTo(couponCode.getConsumption()) >= 0) {
couponCodeUsed = true;
order.setCouponCode(code);
skuPrice = skuPrice.subtract(couponCode.getDiscount());
}
orderPackage.setPrice(skuPrice);
orderPackage.setBookableCount(sku.getCourseCount());
orderPackage.setTime(sku.getTime());
orderPackage.setTimeUnit(sku.getTimeUnit());
}
return true;
}
private void checkLimit(long userId, long skuId, int limit) {
int boughtCount = orderService.getBoughtCount(userId, skuId);
if (boughtCount > limit) throw new MomiaErrorException("超出购买限额");
}
private SubjectOrder buildMiniSubjectOrder(Order order) {
SubjectOrder subjectOrder = new SubjectOrder();
subjectOrder.setId(order.getId());
subjectOrder.setSubjectId(order.getSubjectId());
subjectOrder.setCount(order.getCount());
subjectOrder.setTotalFee(order.getTotalFee());
subjectOrder.setStatus(order.getStatus() <= Order.Status.PRE_PAYED ? Order.Status.PRE_PAYED : order.getStatus());
subjectOrder.setAddTime(order.getAddTime());
return subjectOrder;
}
@RequestMapping(method = RequestMethod.DELETE)
public MomiaHttpResponse delete(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) {
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(orderService.delete(user.getId(), orderId));
}
@RequestMapping(value = "/{oid}/refund", method = RequestMethod.POST)
public MomiaHttpResponse refund(@RequestParam String utoken,
@PathVariable(value = "oid") long orderId,
@RequestParam BigDecimal fee,
@RequestParam String message) {
if (courseService.queryBookedCourseCounts(Sets.newHashSet(orderId)).get(orderId) > 0) return MomiaHttpResponse.FAILED("已经选过课的订单不能申请退款");
Payment payment = orderService.getPayment(orderId);
if (!payment.exists()) return MomiaHttpResponse.FAILED("未付款的订单不能退款");
if (payment.getFee().compareTo(fee) < 0) return MomiaHttpResponse.FAILED("退款金额超过了付款金额");
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(orderService.applyRefund(user.getId(), fee, message, payment));
}
@RequestMapping(value = "/{oid}/refund/check", method = RequestMethod.POST)
public MomiaHttpResponse refundCheck(@PathVariable(value = "oid") long orderId) {
Order order = orderService.get(orderId);
if (order.getStatus() != Order.Status.TO_REFUND) return MomiaHttpResponse.FAILED("该订单并未申请退款");
Payment payment = orderService.getPayment(orderId);
if (!payment.exists()) return MomiaHttpResponse.FAILED("未付款的订单不能退款");
Refund refund = orderService.queryRefund(orderId, payment.getId());
if (!refund.exists()) return MomiaHttpResponse.FAILED("无效的退款申请");
if (courseService.queryBookedCourseCounts(Sets.newHashSet(orderId)).get(orderId) > 0) return MomiaHttpResponse.FAILED("已经选过课的订单不能退款");
RefundParam refundParam = new RefundParam();
refundParam.setRefundId(refund.getId());
refundParam.setRefundTime(new Date());
refundParam.setTradeNo(payment.getTradeNo());
refundParam.setTotalFee(payment.getFee());
refundParam.setRefundFee(refund.getRefundFee());
refundParam.setRefundMessage(order.getRefundMessage());
PaymentGateway gateway = PaymentGatewayFactory.create(payment.getPayType());
if (gateway.refund(refundParam)) orderService.refundChecked(orderId);
return MomiaHttpResponse.SUCCESS(true);
}
@RequestMapping(value = "/{oid}", method = RequestMethod.GET)
public MomiaHttpResponse get(@RequestParam String utoken, @PathVariable(value = "oid") long orderId) {
User user = userServiceApi.get(utoken);
Order order = orderService.get(orderId);
if (!user.exists() || !order.exists() || order.getUserId() != user.getId()) return MomiaHttpResponse.FAILED("无效的订单");
String title;
String cover;
List<Long> courseIds = order.getCourseIds();
if (courseIds.size() >= 1) {
Course course = courseService.get(courseIds.get(0));
title = course.getTitle();
cover = course.getCover();
} else {
List<OrderPackage> orderPackages = order.getPackages();
if (orderPackages.isEmpty()) throw new MomiaErrorException("无效的订单");
if (orderPackages.size() == 1) {
OrderPackage orderPackage = orderPackages.get(0);
title = orderPackage.getTitle();
cover = orderPackage.getCover();
} else {
title = Configuration.getString("Package.MultiTitle");
cover = Configuration.getString("Package.MultiCover");
}
}
Map<Long, Integer> finishedCourceCounts = courseService.queryFinishedCourseCounts(Sets.newHashSet(orderId));
SubjectOrder detailOrder = buildFullSubjectOrder(order, title, cover, finishedCourceCounts.get(orderId), courseIds);
if (order.getStatus() == Order.Status.REFUND_CHECKED) {
Payment payment = orderService.getPayment(orderId);
Refund refund = orderService.queryRefund(orderId, payment.getId());
if (payment.exists() && PayType.isWeixinPay(payment.getPayType()) && refund.exists()) queryRefund(detailOrder, payment, refund);
}
return MomiaHttpResponse.SUCCESS(detailOrder);
}
private SubjectOrder buildFullSubjectOrder(Order order, String title, String cover, int finishedCourseCount, List<Long> courseIds) {
SubjectOrder subjectOrder = buildBaseSubjectOrder(order, title, cover, finishedCourseCount);
if (courseIds.size() >= 1) subjectOrder.setCourseId(courseIds.get(0));
if (order.isPayed()) {
UserCoupon userCoupon = couponService.queryUsedByOrder(order.getId());
if (userCoupon.exists()) {
subjectOrder.setUserCouponId(userCoupon.getId());
subjectOrder.setCouponId(userCoupon.getCouponId());
subjectOrder.setCouponType(userCoupon.getType());
subjectOrder.setDiscount(userCoupon.getDiscount());
subjectOrder.setCouponDesc(userCoupon.getDiscount() + "元红包"); // TODO 更多类型
}
Payment payment = orderService.getPayment(order.getId());
if (!payment.exists()) throw new MomiaErrorException("无效的订单");
subjectOrder.setPayedFee(payment.getFee());
int payType = payment.getPayType();
payType = (payType == PayType.WEIXIN_APP || payType == PayType.WEIXIN_JSAPI) ? PayType.WEIXIN : payType;
subjectOrder.setPayType(payType);
}
return subjectOrder;
}
private SubjectOrder buildBaseSubjectOrder(Order order, String title, String cover, int finishedCourseCount) {
SubjectOrder subjectOrder = buildMiniSubjectOrder(order);
int bookableCourseCount = order.getBookableCourseCount();
if (bookableCourseCount > 0) {
subjectOrder.setBookingStatus(1);
} else {
int totalCourseCount = order.getTotalCourseCount();
if (finishedCourseCount < totalCourseCount) subjectOrder.setBookingStatus(2);
else subjectOrder.setBookingStatus(3);
}
subjectOrder.setTitle(title);
subjectOrder.setCover(cover);
subjectOrder.setCanRefund(!order.isCanceled() && courseService.queryBookedCourseCounts(Sets.newHashSet(order.getId())).get(order.getId()) <= 0);
return subjectOrder;
}
private void queryRefund(SubjectOrder subjectOrder, Payment payment, Refund refund) {
try {
RefundQueryParam refundQueryParam = new RefundQueryParam();
refundQueryParam.setTradeNo(payment.getTradeNo());
PaymentGateway gateway = PaymentGatewayFactory.create(payment.getPayType());
if (gateway.refundQuery(refundQueryParam)) {
orderService.finishRefund(refund);
subjectOrder.setStatus(Order.Status.REFUNDED);
}
} catch (Exception e) {
LOGGER.error("fail to query refund for order: {}", subjectOrder.getId(), e);
}
}
@RequestMapping(value = "/bookable", method = RequestMethod.GET)
public MomiaHttpResponse listBookableOrders(@RequestParam String utoken,
@RequestParam(value = "oid") long orderId,
@RequestParam int start,
@RequestParam int count) {
if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY);
User user = userServiceApi.get(utoken);
long totalCount = orderId > 0 ? orderService.queryBookableCountByUserAndOrder(user.getId(), orderId) : orderService.queryBookableCountByUser(user.getId());
List<OrderPackage> orderPackages = orderId > 0 ? orderService.queryBookableByUserAndOrder(user.getId(), orderId, start, count) : orderService.queryBookableByUser(user.getId(), start, count);
PagedList<SubjectPackage> pagedSubjectPackages = buildPagedSubjectPackages(orderPackages, totalCount, start, count);
return MomiaHttpResponse.SUCCESS(pagedSubjectPackages);
}
private PagedList<SubjectPackage> buildPagedSubjectPackages(List<OrderPackage> orderPackages, long totalCount, int start, int count) {
Set<Long> packageIds = new HashSet<Long>();
Set<Long> orderIds = new HashSet<Long>();
Set<Long> courseIds = new HashSet<Long>();
for (OrderPackage orderPackage : orderPackages) {
packageIds.add(orderPackage.getId());
orderIds.add(orderPackage.getOrderId());
if (orderPackage.getCourseId() > 0) courseIds.add(orderPackage.getCourseId());
}
List<Course> courses = courseService.list(courseIds);
Map<Long, Course> coursesMap = new HashMap<Long, Course>();
for (Course course : courses) {
coursesMap.put(course.getId(), course);
}
List<Order> orders = orderService.list(orderIds);
Set<Long> subjectIds = new HashSet<Long>();
Map<Long, Order> ordersMap = new HashMap<Long, Order>();
for (Order order : orders) {
subjectIds.add(order.getSubjectId());
ordersMap.put(order.getId(), order);
}
List<Subject> subjects = subjectService.list(subjectIds);
Map<Long, Subject> subjectsMap = new HashMap<Long, Subject>();
for (Subject subject : subjects) {
subjectsMap.put(subject.getId(), subject);
}
List<SubjectPackage> subjectPackages = new ArrayList<SubjectPackage>();
for (OrderPackage orderPackage : orderPackages) {
Order order = ordersMap.get(orderPackage.getOrderId());
if (order == null) continue;
Subject subject = subjectsMap.get(order.getSubjectId());
if (subject == null) continue;
SubjectSku sku = subject.getSku(orderPackage.getSkuId());
if (!sku.exists()) continue;
SubjectPackage subjectPackage = new SubjectPackage();
subjectPackage.setPackageId(orderPackage.getId());
subjectPackage.setSubjectId(order.getSubjectId());
subjectPackage.setTitle(orderPackage.getTitle());
subjectPackage.setCover(orderPackage.getCover());
subjectPackage.setBookableCourseCount(orderPackage.getBookableCount());
subjectPackage.setExpireTime("购买日期: " + TimeUtil.SHORT_DATE_FORMAT.format(order.getAddTime()));
subjectPackage.setCourseId(orderPackage.getCourseId());
Course course = coursesMap.get(orderPackage.getCourseId());
if (course != null) {
subjectPackage.setCover(course.getCover());
subjectPackage.setTitle(course.getTitle());
}
subjectPackages.add(subjectPackage);
}
PagedList<SubjectPackage> pagedSubjectPackages = new PagedList<SubjectPackage>(totalCount, start, count);
pagedSubjectPackages.setList(subjectPackages);
return pagedSubjectPackages;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public MomiaHttpResponse listOrders(@RequestParam String utoken,
@RequestParam int status,
@RequestParam int start,
@RequestParam int count) {
if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY);
User user = userServiceApi.get(utoken);
long totalCount = orderService.queryCountByUser(user.getId(), status);
List<Order> orders = orderService.queryByUser(user.getId(), status, start, count);
PagedList<SubjectOrder> pagedSubjectOrders = buildPagedSubjectOrders(orders, totalCount, start, count);
return MomiaHttpResponse.SUCCESS(pagedSubjectOrders);
}
private PagedList<SubjectOrder> buildPagedSubjectOrders(List<Order> orders, long totalCount, int start, int count) {
Set<Long> orderIds = new HashSet<Long>();
Set<Long> subjectIds = new HashSet<Long>();
Map<Long, Long> orderCourse = new HashMap<Long, Long>();
Set<Long> courseIds = new HashSet<Long>();
for (Order order : orders) {
orderIds.add(order.getId());
subjectIds.add(order.getSubjectId());
List<Long> orderCourseIds = order.getCourseIds();
if (orderCourseIds.size() >= 1) {
long courseId = orderCourseIds.get(0);
orderCourse.put(order.getId(), courseId);
courseIds.add(courseId);
}
}
Map<Long, Integer> finishedCourceCounts = courseService.queryFinishedCourseCounts(orderIds);
List<Subject> subjects = subjectService.list(subjectIds);
Map<Long, Subject> subjectsMap = new HashMap<Long, Subject>();
for (Subject subject : subjects) {
subjectsMap.put(subject.getId(), subject);
}
List<Course> courses = courseService.list(courseIds);
Map<Long, Course> coursesMap = new HashMap<Long, Course>();
for (Course course : courses) {
coursesMap.put(course.getId(), course);
}
List<SubjectOrder> subjectOrders = new ArrayList<SubjectOrder>();
for (Order order : orders) {
String title;
String cover;
Long courseId = orderCourse.get(order.getId());
if (courseId == null) {
Subject subject = subjectsMap.get(order.getSubjectId());
if (subject == null) continue;
List<OrderPackage> orderPackages = order.getPackages();
if (orderPackages.isEmpty()) continue;
if (orderPackages.size() == 1) {
OrderPackage orderPackage = orderPackages.get(0);
title = orderPackage.getTitle();
cover = orderPackage.getCover();
} else {
title = Configuration.getString("Package.MultiTitle");
cover = Configuration.getString("Package.MultiCover");
}
} else {
Course course = coursesMap.get(courseId);
if (course == null) continue;
title = course.getTitle();
cover = course.getCover();
}
SubjectOrder subjectOrder = buildBaseSubjectOrder(order, title, cover, finishedCourceCounts.get(order.getId()));
if (courseId != null) subjectOrder.setCourseId(courseId);
subjectOrders.add(subjectOrder);
}
PagedList<SubjectOrder> pagedSubjectOrders = new PagedList<SubjectOrder>(totalCount, start, count);
pagedSubjectOrders.setList(subjectOrders);
return pagedSubjectOrders;
}
@RequestMapping(value = "/bookable/package", method = RequestMethod.GET)
public MomiaHttpResponse bookable(@RequestParam String utoken, @RequestParam(value = "coid") long courseId) {
// try {
// User user = userServiceApi.get(utoken);
//
// if (courseService.hasNoAvaliableSkus(courseId)) return MomiaHttpResponse.SUCCESS(0);
//
// List<Long> trialCourseIds = courseService.queryTrialCourseIds(courseId);
// List<Long> trialSubjectIds = courseService.queryTrialSubjectIds(courseId);
// Map<Long, List<SubjectSku>> trialSubjectSkusMap = subjectService.querySkus(trialSubjectIds);
// Set<Long> trialSubjectSkuIds = new HashSet<Long>();
// for (List<SubjectSku> trialSubjectSkus : trialSubjectSkusMap.values()) {
// for (SubjectSku subjectSku : trialSubjectSkus) {
// if (subjectSku.getCourseId() == courseId || ) trialSubjectSkuIds.add(subjectSku.getId());
// }
// }
// long subjectId = courseService.querySubjectId(courseId);
// List<SubjectSku> normalSubjectSkus = subjectService.querySkus(subjectId);
// Set<Long> normalSubjectSkuIds = new HashSet<Long>();
// for (SubjectSku subjectSku : normalSubjectSkus) {
// normalSubjectSkuIds.add(subjectSku.getId());
// }
//
// List<Long> excludedPackageIds = courseService.queryBookedPackageIds(user.getId(), courseId);
// List<OrderPackage> packages = orderService.queryAllBookableByUser(user.getId());
// Set<Long> packageIds = new HashSet<Long>();
// for (OrderPackage orderPackage : packages) {
// if (excludedPackageIds.contains(orderPackage.getId()) ||
// (!trialSubjectSkuIds.contains(orderPackage.getSkuId()) && !normalSubjectSkuIds.contains(orderPackage.getSkuId()))) continue;
// packageIds.add(orderPackage.getId());
// }
//
// Map<Long, Date> startTimes = orderService.queryStartTimesOfPackages(packageIds);
//
// List<PackageTime> trialPackageTimes = new ArrayList<PackageTime>();
// List<PackageTime> normalPackageTimes = new ArrayList<PackageTime>();
// for (OrderPackage orderPackage : packages) {
// if (excludedPackageIds.contains(orderPackage.getId())) continue;
//
// PackageTime packageTime = new PackageTime();
// packageTime.setId(orderPackage.getId());
// Date startTime = startTimes.get(orderPackage.getId());
// if (startTime == null) packageTime.setExpireTime(null);
// else packageTime.setExpireTime(TimeUtil.add(startTime, orderPackage.getTime(), orderPackage.getTimeUnit()));
//
// if (trialSubjectSkuIds.contains(orderPackage.getSkuId())) trialPackageTimes.add(packageTime);
// else normalPackageTimes.add(packageTime);
// }
//
// if (!trialPackageTimes.isEmpty()) {
// Collections.sort(trialPackageTimes);
// return MomiaHttpResponse.SUCCESS(trialPackageTimes.get(0).getId());
// } else {
// Collections.sort(normalPackageTimes);
// return MomiaHttpResponse.SUCCESS(normalPackageTimes.get(0).getId());
// }
// } catch (Exception e) {
// return MomiaHttpResponse.SUCCESS(0L);
// }
return MomiaHttpResponse.SUCCESS(0L);
}
// private static class PackageTime implements Comparable {
// private long id;
// private Date expireTime;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// @Override
// public int compareTo(Object o) {
// if (this == o) return 0;
// if (!(o instanceof PackageTime)) return -1;
//
// PackageTime that = (PackageTime) o;
// Date thisTime = expireTime;
// Date thatTime = that.getExpireTime();
//
// if (thatTime == null) return -1;
// if (thisTime == null) return 1;
//
// return thisTime.after(thatTime) ? 1 : -1;
// }
// }
@RequestMapping(value = "/package/time/extend", method = RequestMethod.POST)
public MomiaHttpResponse extendPackageTime(@RequestParam(value = "pid") long packageId, @RequestParam int time) {
OrderPackage orderPackage = orderService.getOrderPackage(packageId);
int originTime = orderPackage.getTime();
int originTimeUnit = orderPackage.getTimeUnit();
int newTime;
int newTimeUnit = TimeUtil.TimeUnit.MONTH;
switch (originTimeUnit) {
case TimeUtil.TimeUnit.MONTH:
newTime = originTime + time;
break;
case TimeUtil.TimeUnit.QUARTER:
newTime = originTime * 3 + time;
break;
case TimeUtil.TimeUnit.YEAR:
newTime = originTime * 12 + time;
break;
case TimeUtil.TimeUnit.HALF_YEAR:
newTime = originTime * 6 + time;
break;
default: throw new MomiaErrorException("无效的课程包");
}
return MomiaHttpResponse.SUCCESS(orderService.extendPackageTime(packageId, newTime, newTimeUnit));
}
@RequestMapping(value = "/bookable/user", method = RequestMethod.GET)
public MomiaHttpResponse queryBookableUserIds() {
return MomiaHttpResponse.SUCCESS(orderService.queryBookableUserIds());
}
@RequestMapping(value = "/package/expired/user", method = RequestMethod.GET)
public MomiaHttpResponse queryUserIdsOfPackagesToExpired(@RequestParam int days) {
return MomiaHttpResponse.SUCCESS(orderService.queryUserIdsOfPackagesToExpired(days));
}
}
| course/service-course/src/main/java/cn/momia/service/course/web/ctrl/OrderController.java | package cn.momia.service.course.web.ctrl;
import cn.momia.api.course.dto.course.Course;
import cn.momia.api.course.dto.subject.SubjectOrder;
import cn.momia.api.course.dto.subject.SubjectPackage;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.dto.PagedList;
import cn.momia.common.core.exception.MomiaErrorException;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.common.deal.gateway.PayType;
import cn.momia.common.deal.gateway.PaymentGateway;
import cn.momia.common.deal.gateway.RefundParam;
import cn.momia.common.deal.gateway.RefundQueryParam;
import cn.momia.common.deal.gateway.factory.PaymentGatewayFactory;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.common.webapp.ctrl.BaseController;
import cn.momia.service.course.base.CourseService;
import cn.momia.api.course.dto.coupon.UserCoupon;
import cn.momia.api.course.dto.subject.Subject;
import cn.momia.api.course.dto.coupon.CouponCode;
import cn.momia.service.course.order.Payment;
import cn.momia.service.course.order.Refund;
import cn.momia.service.course.subject.SubjectService;
import cn.momia.api.course.dto.subject.SubjectSku;
import cn.momia.service.course.coupon.CouponService;
import cn.momia.service.course.order.Order;
import cn.momia.service.course.order.OrderService;
import cn.momia.service.course.order.OrderPackage;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping(value = "/order")
public class OrderController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
@Autowired private CourseService courseService;
@Autowired private SubjectService subjectService;
@Autowired private OrderService orderService;
@Autowired private CouponService couponService;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public MomiaHttpResponse placeOrder(@RequestBody Order order) {
List<OrderPackage> orderPackages = order.getPackages();
Set<Long> skuIds = new HashSet<Long>();
for (OrderPackage orderPackage : orderPackages) {
skuIds.add(orderPackage.getSkuId());
}
List<SubjectSku> skus = subjectService.listSkus(skuIds);
if (!checkAndCompleteOrder(order, skus)) return MomiaHttpResponse.FAILED("无效的订单数据");
boolean isTrial = subjectService.isTrial(order.getSubjectId());
if (isTrial && !subjectService.decreaseStock(order.getSubjectId(), order.getCount())) return MomiaHttpResponse.FAILED("下单失败,库存不足或已售完");
long orderId = 0;
try {
orderId = orderService.add(order);
order.setId(orderId);
return MomiaHttpResponse.SUCCESS(buildMiniSubjectOrder(order));
} catch (Exception e) {
return MomiaHttpResponse.FAILED("下单失败");
} finally {
if (orderId <= 0 && isTrial) subjectService.increaseStock(order.getSubjectId(), order.getCount());
}
}
private boolean checkAndCompleteOrder(Order order, List<SubjectSku> skus) {
if (order.isInvalid()) return false;
User user = userServiceApi.get(order.getUserId());
if (!user.exists()) throw new MomiaErrorException("用户不存在");
if (subjectService.isTrial(order.getSubjectId()) && (user.isPayed() || orderService.hasTrialOrder(user.getId()))) throw new MomiaErrorException("本课程包只供新用户专享");
Map<Long, SubjectSku> skusMap = new HashMap<Long, SubjectSku>();
for (SubjectSku sku : skus) {
if (sku.getSubjectId() != order.getSubjectId()) return false;
skusMap.put(sku.getId(), sku);
}
String code = order.getCouponCode();
order.setCouponCode("");
CouponCode couponCode = couponService.getCouponCode(code);
boolean couponCodeUsed = !couponCode.exists();
List<OrderPackage> orderPackages = order.getPackages();
for (OrderPackage orderPackage : orderPackages) {
SubjectSku sku = skusMap.get(orderPackage.getSkuId());
if (sku == null) return false;
if (sku.getLimit() > 0) checkLimit(order.getUserId(), sku.getId(), sku.getLimit());
BigDecimal skuPrice = sku.getPrice();
if (!couponCodeUsed && skuPrice.compareTo(couponCode.getConsumption()) >= 0) {
couponCodeUsed = true;
order.setCouponCode(code);
skuPrice = skuPrice.subtract(couponCode.getDiscount());
}
orderPackage.setPrice(skuPrice);
orderPackage.setBookableCount(sku.getCourseCount());
orderPackage.setTime(sku.getTime());
orderPackage.setTimeUnit(sku.getTimeUnit());
}
return true;
}
private void checkLimit(long userId, long skuId, int limit) {
int boughtCount = orderService.getBoughtCount(userId, skuId);
if (boughtCount > limit) throw new MomiaErrorException("超出购买限额");
}
private SubjectOrder buildMiniSubjectOrder(Order order) {
SubjectOrder subjectOrder = new SubjectOrder();
subjectOrder.setId(order.getId());
subjectOrder.setSubjectId(order.getSubjectId());
subjectOrder.setCount(order.getCount());
subjectOrder.setTotalFee(order.getTotalFee());
subjectOrder.setStatus(order.getStatus() <= Order.Status.PRE_PAYED ? Order.Status.PRE_PAYED : order.getStatus());
subjectOrder.setAddTime(order.getAddTime());
return subjectOrder;
}
@RequestMapping(method = RequestMethod.DELETE)
public MomiaHttpResponse delete(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) {
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(orderService.delete(user.getId(), orderId));
}
@RequestMapping(value = "/{oid}/refund", method = RequestMethod.POST)
public MomiaHttpResponse refund(@RequestParam String utoken,
@PathVariable(value = "oid") long orderId,
@RequestParam BigDecimal fee,
@RequestParam String message) {
if (courseService.queryBookedCourseCounts(Sets.newHashSet(orderId)).get(orderId) > 0) return MomiaHttpResponse.FAILED("已经选过课的订单不能申请退款");
Payment payment = orderService.getPayment(orderId);
if (!payment.exists()) return MomiaHttpResponse.FAILED("未付款的订单不能退款");
if (payment.getFee().compareTo(fee) < 0) return MomiaHttpResponse.FAILED("退款金额超过了付款金额");
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(orderService.applyRefund(user.getId(), fee, message, payment));
}
@RequestMapping(value = "/{oid}/refund/check", method = RequestMethod.POST)
public MomiaHttpResponse refundCheck(@PathVariable(value = "oid") long orderId) {
Order order = orderService.get(orderId);
if (order.getStatus() != Order.Status.TO_REFUND) return MomiaHttpResponse.FAILED("该订单并未申请退款");
Payment payment = orderService.getPayment(orderId);
if (!payment.exists()) return MomiaHttpResponse.FAILED("未付款的订单不能退款");
Refund refund = orderService.queryRefund(orderId, payment.getId());
if (!refund.exists()) return MomiaHttpResponse.FAILED("无效的退款申请");
if (courseService.queryBookedCourseCounts(Sets.newHashSet(orderId)).get(orderId) > 0) return MomiaHttpResponse.FAILED("已经选过课的订单不能退款");
RefundParam refundParam = new RefundParam();
refundParam.setRefundId(refund.getId());
refundParam.setRefundTime(new Date());
refundParam.setTradeNo(payment.getTradeNo());
refundParam.setTotalFee(payment.getFee());
refundParam.setRefundFee(refund.getRefundFee());
refundParam.setRefundMessage(order.getRefundMessage());
PaymentGateway gateway = PaymentGatewayFactory.create(payment.getPayType());
if (gateway.refund(refundParam)) orderService.refundChecked(orderId);
return MomiaHttpResponse.SUCCESS(true);
}
@RequestMapping(value = "/{oid}", method = RequestMethod.GET)
public MomiaHttpResponse get(@RequestParam String utoken, @PathVariable(value = "oid") long orderId) {
User user = userServiceApi.get(utoken);
Order order = orderService.get(orderId);
if (!user.exists() || !order.exists() || order.getUserId() != user.getId()) return MomiaHttpResponse.FAILED("无效的订单");
String title;
String cover;
List<Long> courseIds = order.getCourseIds();
if (courseIds.size() >= 1) {
Course course = courseService.get(courseIds.get(0));
title = course.getTitle();
cover = course.getCover();
} else {
List<OrderPackage> orderPackages = order.getPackages();
if (orderPackages.isEmpty()) throw new MomiaErrorException("无效的订单");
if (orderPackages.size() == 1) {
OrderPackage orderPackage = orderPackages.get(0);
title = orderPackage.getTitle();
cover = orderPackage.getCover();
} else {
title = Configuration.getString("Package.MultiTitle");
cover = Configuration.getString("Package.MultiCover");
}
}
Map<Long, Integer> finishedCourceCounts = courseService.queryFinishedCourseCounts(Sets.newHashSet(orderId));
SubjectOrder detailOrder = buildFullSubjectOrder(order, title, cover, finishedCourceCounts.get(orderId), courseIds);
if (order.getStatus() == Order.Status.REFUND_CHECKED) {
Payment payment = orderService.getPayment(orderId);
Refund refund = orderService.queryRefund(orderId, payment.getId());
if (payment.exists() && PayType.isWeixinPay(payment.getPayType()) && refund.exists()) queryRefund(detailOrder, payment, refund);
}
return MomiaHttpResponse.SUCCESS(detailOrder);
}
private SubjectOrder buildFullSubjectOrder(Order order, String title, String cover, int finishedCourseCount, List<Long> courseIds) {
SubjectOrder subjectOrder = buildBaseSubjectOrder(order, title, cover, finishedCourseCount);
if (courseIds.size() >= 1) subjectOrder.setCourseId(courseIds.get(0));
if (order.isPayed()) {
UserCoupon userCoupon = couponService.queryUsedByOrder(order.getId());
if (userCoupon.exists()) {
subjectOrder.setUserCouponId(userCoupon.getId());
subjectOrder.setCouponId(userCoupon.getCouponId());
subjectOrder.setCouponType(userCoupon.getType());
subjectOrder.setDiscount(userCoupon.getDiscount());
subjectOrder.setCouponDesc(userCoupon.getDiscount() + "元红包"); // TODO 更多类型
}
Payment payment = orderService.getPayment(order.getId());
if (!payment.exists()) throw new MomiaErrorException("无效的订单");
subjectOrder.setPayedFee(payment.getFee());
int payType = payment.getPayType();
payType = (payType == PayType.WEIXIN_APP || payType == PayType.WEIXIN_JSAPI) ? PayType.WEIXIN : payType;
subjectOrder.setPayType(payType);
}
return subjectOrder;
}
private SubjectOrder buildBaseSubjectOrder(Order order, String title, String cover, int finishedCourseCount) {
SubjectOrder subjectOrder = buildMiniSubjectOrder(order);
int bookableCourseCount = order.getBookableCourseCount();
if (bookableCourseCount > 0) {
subjectOrder.setBookingStatus(1);
} else {
int totalCourseCount = order.getTotalCourseCount();
if (finishedCourseCount < totalCourseCount) subjectOrder.setBookingStatus(2);
else subjectOrder.setBookingStatus(3);
}
subjectOrder.setTitle(title);
subjectOrder.setCover(cover);
subjectOrder.setCanRefund(!order.isCanceled() && courseService.queryBookedCourseCounts(Sets.newHashSet(order.getId())).get(order.getId()) <= 0);
return subjectOrder;
}
private void queryRefund(SubjectOrder subjectOrder, Payment payment, Refund refund) {
try {
RefundQueryParam refundQueryParam = new RefundQueryParam();
refundQueryParam.setTradeNo(payment.getTradeNo());
PaymentGateway gateway = PaymentGatewayFactory.create(payment.getPayType());
if (gateway.refundQuery(refundQueryParam)) {
orderService.finishRefund(refund);
subjectOrder.setStatus(Order.Status.REFUNDED);
}
} catch (Exception e) {
LOGGER.error("fail to query refund for order: {}", subjectOrder.getId(), e);
}
}
@RequestMapping(value = "/bookable", method = RequestMethod.GET)
public MomiaHttpResponse listBookableOrders(@RequestParam String utoken,
@RequestParam(value = "oid") long orderId,
@RequestParam int start,
@RequestParam int count) {
if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY);
User user = userServiceApi.get(utoken);
long totalCount = orderId > 0 ? orderService.queryBookableCountByUserAndOrder(user.getId(), orderId) : orderService.queryBookableCountByUser(user.getId());
List<OrderPackage> orderPackages = orderId > 0 ? orderService.queryBookableByUserAndOrder(user.getId(), orderId, start, count) : orderService.queryBookableByUser(user.getId(), start, count);
PagedList<SubjectPackage> pagedSubjectPackages = buildPagedSubjectPackages(orderPackages, totalCount, start, count);
return MomiaHttpResponse.SUCCESS(pagedSubjectPackages);
}
private PagedList<SubjectPackage> buildPagedSubjectPackages(List<OrderPackage> orderPackages, long totalCount, int start, int count) {
Set<Long> packageIds = new HashSet<Long>();
Set<Long> orderIds = new HashSet<Long>();
Set<Long> courseIds = new HashSet<Long>();
for (OrderPackage orderPackage : orderPackages) {
packageIds.add(orderPackage.getId());
orderIds.add(orderPackage.getOrderId());
if (orderPackage.getCourseId() > 0) courseIds.add(orderPackage.getCourseId());
}
List<Course> courses = courseService.list(courseIds);
Map<Long, Course> coursesMap = new HashMap<Long, Course>();
for (Course course : courses) {
coursesMap.put(course.getId(), course);
}
List<Order> orders = orderService.list(orderIds);
Set<Long> subjectIds = new HashSet<Long>();
Map<Long, Order> ordersMap = new HashMap<Long, Order>();
for (Order order : orders) {
subjectIds.add(order.getSubjectId());
ordersMap.put(order.getId(), order);
}
List<Subject> subjects = subjectService.list(subjectIds);
Map<Long, Subject> subjectsMap = new HashMap<Long, Subject>();
for (Subject subject : subjects) {
subjectsMap.put(subject.getId(), subject);
}
List<SubjectPackage> subjectPackages = new ArrayList<SubjectPackage>();
for (OrderPackage orderPackage : orderPackages) {
Order order = ordersMap.get(orderPackage.getOrderId());
if (order == null) continue;
Subject subject = subjectsMap.get(order.getSubjectId());
if (subject == null) continue;
SubjectSku sku = subject.getSku(orderPackage.getSkuId());
if (!sku.exists()) continue;
SubjectPackage subjectPackage = new SubjectPackage();
subjectPackage.setPackageId(orderPackage.getId());
subjectPackage.setSubjectId(order.getSubjectId());
subjectPackage.setTitle(subject.getTitle());
List<Long> orderCourseIds = order.getCourseIds();
if (orderCourseIds.size() >= 1) {
Course course = courseService.get(orderCourseIds.get(0));
subjectPackage.setCover(course.getCover());
} else {
subjectPackage.setCover(subject.getCover());
}
subjectPackage.setBookableCourseCount(orderPackage.getBookableCount());
subjectPackage.setExpireTime("购买日期: " + TimeUtil.SHORT_DATE_FORMAT.format(order.getAddTime()));
subjectPackage.setCourseId(orderPackage.getCourseId());
Course course = coursesMap.get(orderPackage.getCourseId());
if (course != null) {
subjectPackage.setCover(course.getCover());
subjectPackage.setTitle(course.getTitle());
}
subjectPackages.add(subjectPackage);
}
PagedList<SubjectPackage> pagedSubjectPackages = new PagedList<SubjectPackage>(totalCount, start, count);
pagedSubjectPackages.setList(subjectPackages);
return pagedSubjectPackages;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public MomiaHttpResponse listOrders(@RequestParam String utoken,
@RequestParam int status,
@RequestParam int start,
@RequestParam int count) {
if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY);
User user = userServiceApi.get(utoken);
long totalCount = orderService.queryCountByUser(user.getId(), status);
List<Order> orders = orderService.queryByUser(user.getId(), status, start, count);
PagedList<SubjectOrder> pagedSubjectOrders = buildPagedSubjectOrders(orders, totalCount, start, count);
return MomiaHttpResponse.SUCCESS(pagedSubjectOrders);
}
private PagedList<SubjectOrder> buildPagedSubjectOrders(List<Order> orders, long totalCount, int start, int count) {
Set<Long> orderIds = new HashSet<Long>();
Set<Long> subjectIds = new HashSet<Long>();
Map<Long, Long> orderCourse = new HashMap<Long, Long>();
Set<Long> courseIds = new HashSet<Long>();
for (Order order : orders) {
orderIds.add(order.getId());
subjectIds.add(order.getSubjectId());
List<Long> orderCourseIds = order.getCourseIds();
if (orderCourseIds.size() >= 1) {
long courseId = orderCourseIds.get(0);
orderCourse.put(order.getId(), courseId);
courseIds.add(courseId);
}
}
Map<Long, Integer> finishedCourceCounts = courseService.queryFinishedCourseCounts(orderIds);
List<Subject> subjects = subjectService.list(subjectIds);
Map<Long, Subject> subjectsMap = new HashMap<Long, Subject>();
for (Subject subject : subjects) {
subjectsMap.put(subject.getId(), subject);
}
List<Course> courses = courseService.list(courseIds);
Map<Long, Course> coursesMap = new HashMap<Long, Course>();
for (Course course : courses) {
coursesMap.put(course.getId(), course);
}
List<SubjectOrder> subjectOrders = new ArrayList<SubjectOrder>();
for (Order order : orders) {
String title;
String cover;
Long courseId = orderCourse.get(order.getId());
if (courseId == null) {
Subject subject = subjectsMap.get(order.getSubjectId());
if (subject == null) continue;
List<OrderPackage> orderPackages = order.getPackages();
if (orderPackages.isEmpty()) continue;
if (orderPackages.size() == 1) {
OrderPackage orderPackage = orderPackages.get(0);
title = orderPackage.getTitle();
cover = orderPackage.getCover();
} else {
title = Configuration.getString("Package.MultiTitle");
cover = Configuration.getString("Package.MultiCover");
}
} else {
Course course = coursesMap.get(courseId);
if (course == null) continue;
title = course.getTitle();
cover = course.getCover();
}
SubjectOrder subjectOrder = buildBaseSubjectOrder(order, title, cover, finishedCourceCounts.get(order.getId()));
if (courseId != null) subjectOrder.setCourseId(courseId);
subjectOrders.add(subjectOrder);
}
PagedList<SubjectOrder> pagedSubjectOrders = new PagedList<SubjectOrder>(totalCount, start, count);
pagedSubjectOrders.setList(subjectOrders);
return pagedSubjectOrders;
}
@RequestMapping(value = "/bookable/package", method = RequestMethod.GET)
public MomiaHttpResponse bookable(@RequestParam String utoken, @RequestParam(value = "coid") long courseId) {
// try {
// User user = userServiceApi.get(utoken);
//
// if (courseService.hasNoAvaliableSkus(courseId)) return MomiaHttpResponse.SUCCESS(0);
//
// List<Long> trialCourseIds = courseService.queryTrialCourseIds(courseId);
// List<Long> trialSubjectIds = courseService.queryTrialSubjectIds(courseId);
// Map<Long, List<SubjectSku>> trialSubjectSkusMap = subjectService.querySkus(trialSubjectIds);
// Set<Long> trialSubjectSkuIds = new HashSet<Long>();
// for (List<SubjectSku> trialSubjectSkus : trialSubjectSkusMap.values()) {
// for (SubjectSku subjectSku : trialSubjectSkus) {
// if (subjectSku.getCourseId() == courseId || ) trialSubjectSkuIds.add(subjectSku.getId());
// }
// }
// long subjectId = courseService.querySubjectId(courseId);
// List<SubjectSku> normalSubjectSkus = subjectService.querySkus(subjectId);
// Set<Long> normalSubjectSkuIds = new HashSet<Long>();
// for (SubjectSku subjectSku : normalSubjectSkus) {
// normalSubjectSkuIds.add(subjectSku.getId());
// }
//
// List<Long> excludedPackageIds = courseService.queryBookedPackageIds(user.getId(), courseId);
// List<OrderPackage> packages = orderService.queryAllBookableByUser(user.getId());
// Set<Long> packageIds = new HashSet<Long>();
// for (OrderPackage orderPackage : packages) {
// if (excludedPackageIds.contains(orderPackage.getId()) ||
// (!trialSubjectSkuIds.contains(orderPackage.getSkuId()) && !normalSubjectSkuIds.contains(orderPackage.getSkuId()))) continue;
// packageIds.add(orderPackage.getId());
// }
//
// Map<Long, Date> startTimes = orderService.queryStartTimesOfPackages(packageIds);
//
// List<PackageTime> trialPackageTimes = new ArrayList<PackageTime>();
// List<PackageTime> normalPackageTimes = new ArrayList<PackageTime>();
// for (OrderPackage orderPackage : packages) {
// if (excludedPackageIds.contains(orderPackage.getId())) continue;
//
// PackageTime packageTime = new PackageTime();
// packageTime.setId(orderPackage.getId());
// Date startTime = startTimes.get(orderPackage.getId());
// if (startTime == null) packageTime.setExpireTime(null);
// else packageTime.setExpireTime(TimeUtil.add(startTime, orderPackage.getTime(), orderPackage.getTimeUnit()));
//
// if (trialSubjectSkuIds.contains(orderPackage.getSkuId())) trialPackageTimes.add(packageTime);
// else normalPackageTimes.add(packageTime);
// }
//
// if (!trialPackageTimes.isEmpty()) {
// Collections.sort(trialPackageTimes);
// return MomiaHttpResponse.SUCCESS(trialPackageTimes.get(0).getId());
// } else {
// Collections.sort(normalPackageTimes);
// return MomiaHttpResponse.SUCCESS(normalPackageTimes.get(0).getId());
// }
// } catch (Exception e) {
// return MomiaHttpResponse.SUCCESS(0L);
// }
return MomiaHttpResponse.SUCCESS(0L);
}
// private static class PackageTime implements Comparable {
// private long id;
// private Date expireTime;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// @Override
// public int compareTo(Object o) {
// if (this == o) return 0;
// if (!(o instanceof PackageTime)) return -1;
//
// PackageTime that = (PackageTime) o;
// Date thisTime = expireTime;
// Date thatTime = that.getExpireTime();
//
// if (thatTime == null) return -1;
// if (thisTime == null) return 1;
//
// return thisTime.after(thatTime) ? 1 : -1;
// }
// }
@RequestMapping(value = "/package/time/extend", method = RequestMethod.POST)
public MomiaHttpResponse extendPackageTime(@RequestParam(value = "pid") long packageId, @RequestParam int time) {
OrderPackage orderPackage = orderService.getOrderPackage(packageId);
int originTime = orderPackage.getTime();
int originTimeUnit = orderPackage.getTimeUnit();
int newTime;
int newTimeUnit = TimeUtil.TimeUnit.MONTH;
switch (originTimeUnit) {
case TimeUtil.TimeUnit.MONTH:
newTime = originTime + time;
break;
case TimeUtil.TimeUnit.QUARTER:
newTime = originTime * 3 + time;
break;
case TimeUtil.TimeUnit.YEAR:
newTime = originTime * 12 + time;
break;
case TimeUtil.TimeUnit.HALF_YEAR:
newTime = originTime * 6 + time;
break;
default: throw new MomiaErrorException("无效的课程包");
}
return MomiaHttpResponse.SUCCESS(orderService.extendPackageTime(packageId, newTime, newTimeUnit));
}
@RequestMapping(value = "/bookable/user", method = RequestMethod.GET)
public MomiaHttpResponse queryBookableUserIds() {
return MomiaHttpResponse.SUCCESS(orderService.queryBookableUserIds());
}
@RequestMapping(value = "/package/expired/user", method = RequestMethod.GET)
public MomiaHttpResponse queryUserIdsOfPackagesToExpired(@RequestParam int days) {
return MomiaHttpResponse.SUCCESS(orderService.queryUserIdsOfPackagesToExpired(days));
}
}
| bookable cover & title
| course/service-course/src/main/java/cn/momia/service/course/web/ctrl/OrderController.java | bookable cover & title | <ide><path>ourse/service-course/src/main/java/cn/momia/service/course/web/ctrl/OrderController.java
<ide> SubjectPackage subjectPackage = new SubjectPackage();
<ide> subjectPackage.setPackageId(orderPackage.getId());
<ide> subjectPackage.setSubjectId(order.getSubjectId());
<del> subjectPackage.setTitle(subject.getTitle());
<del> List<Long> orderCourseIds = order.getCourseIds();
<del> if (orderCourseIds.size() >= 1) {
<del> Course course = courseService.get(orderCourseIds.get(0));
<del> subjectPackage.setCover(course.getCover());
<del> } else {
<del> subjectPackage.setCover(subject.getCover());
<del> }
<add> subjectPackage.setTitle(orderPackage.getTitle());
<add> subjectPackage.setCover(orderPackage.getCover());
<ide> subjectPackage.setBookableCourseCount(orderPackage.getBookableCount());
<ide>
<ide> subjectPackage.setExpireTime("购买日期: " + TimeUtil.SHORT_DATE_FORMAT.format(order.getAddTime())); |
|
Java | apache-2.0 | b7bb75586225e2d5e0f35da53cea17e8efcd71f6 | 0 | LApptelier/SmartRecyclerView | package com.lapptelier.smartrecyclerview;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* com.lapptelier.smartrecyclerview.smart_recycler_view.SmartRecyclerView
* <p/>
* Generic implementation of a {@see RecyclerView} intagrated in {@SwipeRefreshLayout} layout.
* <p/>
* Feature placeholder for empty list and loading progress bar both during reloading and loading more items.
* <p/>
* Sub class of {@link LinearLayout}.
*
* @author L'Apptelier SARL
* @date 14/09/2017
*/
public class SmartRecyclerView extends LinearLayout {
protected int ITEM_LEFT_TO_LOAD_MORE = 10; // count of item to display before firing the loadmore action
@BindView(R2.id.smart_list_recycler)
public RecyclerView mRecyclerView;
@BindView(R2.id.smart_list_swipe_layout)
protected SwipeRefreshLayout mSwipeLayout;
@BindView(R2.id.smart_list_loading_stub)
protected ViewStub mLoadingViewStub;
@BindView(R2.id.smart_list_empty_stub)
protected ViewStub mEmptyViewStub;
protected View mLoadingView;
protected View mEmptyView;
protected boolean isLoadingMore; // flag used when the loadmore progress is displayed
protected boolean shouldLoadMore; // flag used to display or not the loadmore progress
private static PlaceHolderCell placeHolderCell = new PlaceHolderCell(); // placeholder cell used to display load more progress
// recycler view listener
protected RecyclerView.OnScrollListener mInternalOnScrollListener;
protected List<RecyclerView.OnScrollListener> mExternalOnScrollListeners;
protected OnMoreListener mOnMoreListener;
// generic adapter
protected AbstractGenericAdapter mAdapter;
// id of the load more layout
protected int loadMoreLayout;
/**
* Simple Constructor
*
* @param context the current context
*/
public SmartRecyclerView(Context context) {
super(context);
}
/**
* Constructor with attributeSet
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
*/
public SmartRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Constructor with attributeSet and style
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
* @param defStyle style of the RecyclerView
*/
public SmartRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/**
* Initialize the view
*/
private void init() {
//bypass for Layout display in UIBuilder
if (isInEditMode()) {
return;
}
mExternalOnScrollListeners = new ArrayList<>();
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.layout_smart_recycler_view, this);
ButterKnife.bind(this, view);
initRecyclerView();
}
/**
* Initialize the inner RecyclerView
*/
protected void initRecyclerView() {
if (mRecyclerView != null) {
mInternalOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (recyclerView.getLayoutManager().getClass().equals(LinearLayoutManager.class)) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager.findLastVisibleItemPosition() >= layoutManager.getItemCount() - ITEM_LEFT_TO_LOAD_MORE
&& !isLoadingMore && shouldLoadMore) {
isLoadingMore = true;
if (mOnMoreListener != null) {
mOnMoreListener.onMoreAsked(mRecyclerView.getAdapter().getItemCount(), ITEM_LEFT_TO_LOAD_MORE, layoutManager.findLastVisibleItemPosition());
}
}
}
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListeners)
listener.onScrolled(recyclerView, dx, dy);
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListeners)
listener.onScrollStateChanged(recyclerView, newState);
}
};
mRecyclerView.addOnScrollListener(mInternalOnScrollListener);
}
//by default, empty screen is hidden and loading screen is displayed
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
if (mLoadingView != null)
mLoadingView.setVisibility(View.VISIBLE);
}
/**
* Set inner RecyclerView' LayoutManager
*
* @param layoutManager inner RecyclerView' LayoutManager
*/
public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
if (mRecyclerView != null)
mRecyclerView.setLayoutManager(layoutManager);
}
/**
* Set inner RecyclerView' adapter
*
* @param adapter inner RecyclerView' adapter
*/
public void setAdapter(final AbstractGenericAdapter adapter) {
mAdapter = adapter;
if (mRecyclerView != null) {
mRecyclerView.setAdapter(mAdapter);
this.updateAccessoryViews();
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount);
updateAccessoryViews();
}
@Override
public void onChanged() {
super.onChanged();
updateAccessoryViews();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
super.onItemRangeChanged(positionStart, itemCount, payload);
updateAccessoryViews();
}
});
}
}
/**
* Update the view to display loading if needed
*/
private void updateAccessoryViews() {
// hiddig the loading view first
if (mLoadingView != null)
mLoadingView.setVisibility(View.GONE);
//flag indicating that the data loading is complete
isLoadingMore = false;
//hidding swipe to refresh too
mSwipeLayout.setRefreshing(false);
if (mAdapter.isEmpty()) {
if (mEmptyView != null)
mEmptyView.setVisibility(View.VISIBLE);
} else {
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
//if there is more item to load, adding a placeholder cell at the end to display the load more
if (shouldLoadMore) {
if (!mAdapter.contains(placeHolderCell) && loadMoreLayout > -1) {
//adding directly to the adapter list to avoid firing callbacks
mAdapter.items.add(placeHolderCell);
//adding the viewHolder (this is safe to add without prior check, as the adapter is smart enought to not add it twice)
if (mAdapter instanceof GenericViewHolderAdapter)
((MultiGenericAdapter) mAdapter).addViewHolderType(PlaceHolderCell.class, PlaceHolderViewHolder.class, loadMoreLayout);
}
}
}
}
/**
* Set the RecyclerView' SwipeRefreshListener
*
* @param listener the RecyclerView' SwipeRefreshListener
*/
public void setRefreshListener(SwipeRefreshLayout.OnRefreshListener listener) {
if (mSwipeLayout != null) {
mSwipeLayout.setEnabled(true);
mSwipeLayout.setOnRefreshListener(listener);
}
}
/**
* Add a the RecyclerView' OnItemTouchListener
*
* @param listener a RecyclerView' OnItemTouchListener
*/
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
if (mRecyclerView != null)
mRecyclerView.addOnItemTouchListener(listener);
}
/**
* set the LoadMore Listener
*
* @param onMoreListener the LoadMore Listener
* @param max count of items left before firing the LoadMore
*/
public void setupMoreListener(OnMoreListener onMoreListener, int max) {
mOnMoreListener = onMoreListener;
ITEM_LEFT_TO_LOAD_MORE = max;
shouldLoadMore = true;
}
/**
* Set the recyclerView' OnTouchListener
*
* @param listener OnTouchListener
*/
public void setOnTouchListener(OnTouchListener listener) {
if (mRecyclerView != null)
mRecyclerView.setOnTouchListener(listener);
}
/**
* Display the pull-to-refresh of the SwipeLayout
*
* @param display true to display the pull-to-refresh, false otherwise
*/
public void displaySwipeToRefresh(boolean display) {
if (mSwipeLayout != null)
mSwipeLayout.setEnabled(display);
}
/**
* Tell the recyclerView that new item can be loaded after the end of the current list (load more)
*
* @param shouldLoadMore true to enable the LoadMore process, false otherwise
*/
public void shouldLoadMore(boolean shouldLoadMore) {
this.shouldLoadMore = shouldLoadMore;
}
/**
* Set the view displayed when no items are in the list. Should have a frame layout at its root.
*
* @param viewLayout the view layout to inflate
*/
public void setEmptyLayout(int viewLayout) {
mEmptyViewStub.setLayoutResource(viewLayout);
mEmptyView = mEmptyViewStub.inflate();
}
/**
* Set the view displayed during loadings. Should have a frame layout at its root.
*
* @param viewLayout the view layout to inflate
*/
public void setLoadingLayout(int viewLayout) {
mLoadingViewStub.setLayoutResource(viewLayout);
mLoadingView = mLoadingViewStub.inflate();
}
/**
* Display the loading placeholder ontop of the list
*/
public void displayLoadingView() {
//si on a un PTR de setté, on l'affiche, sinon on affiche le message de chargement
if (mAdapter != null && mAdapter.getItemCount() > 0) {
if (mSwipeLayout != null && !mSwipeLayout.isRefreshing()) {
// on affiche le PTR
TypedValue typed_value = new TypedValue();
getContext().getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, typed_value, true);
mSwipeLayout.setProgressViewOffset(false, 0, getResources().getDimensionPixelSize(typed_value.resourceId));
mSwipeLayout.setRefreshing(true);
}
} else {
if (mLoadingView != null)
this.mLoadingView.setVisibility(VISIBLE);
}
}
/**
* Clear all elements in the RecyclerView' Adapter list
*/
public void clear() {
if (mAdapter != null)
mAdapter.clear();
}
/**
* Add all given items in the RecyclerView' Adapter list
*
* @param items item to add
*/
public void addAll(List<?> items) {
if (mAdapter != null) {
this.deletePlaceholder();
mAdapter.addAll(items);
}
}
/**
* Insert all given items in the RecyclerView' Adapter list
*
* @param items items to add
* @param position position unto add items
*/
public void insertAll(List<?> items, int position) {
if (mAdapter != null) {
this.deletePlaceholder();
this.mAdapter.insertAll(items, position);
}
}
/**
* Delete all placeholders
*/
private void deletePlaceholder() {
if (mAdapter != null && mAdapter.contains(placeHolderCell)) {
KLog.d("deletePlaceholder", "done");
//removing directly to the adapter list to avoid firing callbacks
mAdapter.items.remove(mAdapter.getItemCount() - 1);
}
}
/**
* Append an item to the RecyclerView' Adapter list
*
* @param item item to append
*/
public void add(Object item) {
if (mAdapter != null) {
this.deletePlaceholder();
mAdapter.add(item);
}
}
/**
* Insert a given item at a given position in the RecyclerView' Adapter list
*
* @param item item to insert
* @param position position to insert to
*/
public void insertAt(int position, Object item) {
if (mAdapter != null)
mAdapter.insertAt(position, item);
}
/**
* Delete an item from the RecyclerView' Adapter list
*
* @param position position of the item to delete
*/
public void removeAt(int position) {
if (mAdapter != null)
mAdapter.removeAt(position);
}
/**
* Replace an item at a given position by another given item of the RecyclerView' Adapter list
*
* @param position position of the item to replace
* @param item new item
*/
public void replaceAt(int position, Object item) {
if (mAdapter != null)
mAdapter.replaceAt(position, item);
}
/**
* Return true if the RecyclerView' Adapter list is empty
*
* @return true if the list is empty, false otherwise
*/
public boolean isEmpty() {
if (mAdapter != null)
return mAdapter.isEmpty();
else
return true;
}
/**
* Return the RecyclerView' Adapter item at the given position
*
* @param position position of the item
* @return the item at the given position, null otherwise
*/
public Object getItemAt(int position) {
if (mAdapter != null)
return mAdapter.getItemAt(position);
else
return null;
}
/**
* Return the position in the RecyclerView' Adapter list of the given item
*
* @param object item to search in the list
* @return item's position if found, -1 otherwise
*/
public int getObjectIndex(Object object) {
if (mAdapter != null)
return mAdapter.getObjectIndex(object);
else
return -1;
}
/**
* Return the item's count of the RecyclerView' Adapter list
*
* @return the item's count of the list
*/
public int getItemCount() {
if (mAdapter != null)
return mAdapter.getItemCount();
else
return -1;
}
/**
* Scroll smoothly to an item position in the RecyclerView
*
* @param position position to scroll to
*/
public void smoothScrollTo(int position) {
if (mRecyclerView != null)
this.mRecyclerView.smoothScrollToPosition(position);
}
/**
* Tell the recycler view that its data has been changed
*/
public void notifyDataSetChanged() {
if (mAdapter != null)
this.mAdapter.notifyDataSetChanged();
}
/**
* Add a custom cell divider to the recycler view
*
* @param dividerItemDecoration custom cell divider
*/
public void addItemDecoration(RecyclerView.ItemDecoration dividerItemDecoration) {
if (mRecyclerView != null)
mRecyclerView.addItemDecoration(dividerItemDecoration);
}
/**
* Change view background color
*
* @param color view background color
*/
@Override
public void setBackgroundColor(int color) {
if (mRecyclerView != null)
mRecyclerView.setBackgroundColor(color);
}
/**
* Set the color scheme of the loading and loadmore circular progress bar
*
* @param color1 color used on the circular progress bar
* @param color2 color used on the circular progress bar
* @param color3 color used on the circular progress bar
* @param color4 color used on the circular progress bar
*/
public void setProgressColorScheme(int color1, int color2, int color3, int color4) {
if (mSwipeLayout != null)
mSwipeLayout.setColorSchemeResources(color1, color2, color3, color4);
}
/**
* Set the layout used to populate the loadmore placeholder cell
*
* @param loadMoreLayout the layout to inflate
*/
public void setLoadMoreLayout(int loadMoreLayout) {
this.loadMoreLayout = loadMoreLayout;
}
/**
* Scroll the recycler view to its top
*/
public void scrollToTop() {
if (!mRecyclerView.isAnimating() && !mRecyclerView.isComputingLayout())
mRecyclerView.scrollToPosition(0);
}
/**
* Smooth scroll the recycler view to its top
*/
public void smoothScrollToTop() {
if (!mRecyclerView.isAnimating() && !mRecyclerView.isComputingLayout())
mRecyclerView.smoothScrollToPosition(0);
}
/**
* Return the inflated view layout placed when the list is empty
*
* @return the 'empty' view
*/
public View getEmptyView() {
return mEmptyView;
}
/**
* Return the inflated view layout placed when the list is loading elements
*
* @return the 'loading' view
*/
public View getLoadingView() {
return mLoadingView;
}
/**
* @return the scroll listeners of the recyclerView
*/
public List<RecyclerView.OnScrollListener> getmExternalOnScrollListeners() {
return mExternalOnScrollListeners;
}
/**
* Add a scroll listener to the recyclerView
*
* @param externalOnScrollListener
*/
public void addExternalOnScrollListener(RecyclerView.OnScrollListener externalOnScrollListener) {
this.mExternalOnScrollListeners.add(externalOnScrollListener);
}
/**
* Clear all scroll listeners of the recycler view
*/
public void clearExternalOnScrollListeners() {
mExternalOnScrollListeners.clear();
}
/**
* Scroll to the bottom of the list
*/
public void scrollToBottom() {
if (mRecyclerView != null && mAdapter != null && mAdapter.getItemCount() > 0)
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
| smartrecyclerview/src/main/java/com/lapptelier/smartrecyclerview/SmartRecyclerView.java | package com.lapptelier.smartrecyclerview;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* com.lapptelier.smartrecyclerview.smart_recycler_view.SmartRecyclerView
* <p/>
* Generic implementation of a {@see RecyclerView} intagrated in {@SwipeRefreshLayout} layout.
* <p/>
* Feature placeholder for empty list and loading progress bar both during reloading and loading more items.
* <p/>
* Sub class of {@link LinearLayout}.
*
* @author L'Apptelier SARL
* @date 14/09/2017
*/
public class SmartRecyclerView extends LinearLayout {
protected int ITEM_LEFT_TO_LOAD_MORE = 10; // count of item to display before firing the loadmore action
@BindView(R2.id.smart_list_recycler)
public RecyclerView mRecyclerView;
@BindView(R2.id.smart_list_swipe_layout)
protected SwipeRefreshLayout mSwipeLayout;
@BindView(R2.id.smart_list_loading_stub)
protected ViewStub mLoadingViewStub;
@BindView(R2.id.smart_list_empty_stub)
protected ViewStub mEmptyViewStub;
protected View mLoadingView;
protected View mEmptyView;
protected boolean isLoadingMore; // flag used when the loadmore progress is displayed
protected boolean shouldLoadMore; // flag used to display or not the loadmore progress
private static PlaceHolderCell placeHolderCell = new PlaceHolderCell(); // placeholder cell used to display load more progress
// recycler view listener
protected RecyclerView.OnScrollListener mInternalOnScrollListener;
protected List<RecyclerView.OnScrollListener> mExternalOnScrollListeners;
protected OnMoreListener mOnMoreListener;
// generic adapter
protected AbstractGenericAdapter mAdapter;
// id of the load more layout
protected int loadMoreLayout;
/**
* Simple Constructor
*
* @param context the current context
*/
public SmartRecyclerView(Context context) {
super(context);
}
/**
* Constructor with attributeSet
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
*/
public SmartRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Constructor with attributeSet and style
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
* @param defStyle style of the RecyclerView
*/
public SmartRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/**
* Initialize the view
*/
private void init() {
//bypass for Layout display in UIBuilder
if (isInEditMode()) {
return;
}
mExternalOnScrollListeners = new ArrayList<>();
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.layout_smart_recycler_view, this);
ButterKnife.bind(this, view);
initRecyclerView();
}
/**
* Initialize the inner RecyclerView
*/
protected void initRecyclerView() {
if (mRecyclerView != null) {
mInternalOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (recyclerView.getLayoutManager().getClass().equals(LinearLayoutManager.class)) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (((!layoutManager.getReverseLayout() && (layoutManager.findLastVisibleItemPosition() >= (layoutManager.getItemCount() - ITEM_LEFT_TO_LOAD_MORE))) ||
(layoutManager.getReverseLayout() && (layoutManager.findLastVisibleItemPosition() <= ITEM_LEFT_TO_LOAD_MORE)))
&& !isLoadingMore && shouldLoadMore) {
isLoadingMore = true;
if (mOnMoreListener != null) {
mOnMoreListener.onMoreAsked(mRecyclerView.getAdapter().getItemCount(), ITEM_LEFT_TO_LOAD_MORE, layoutManager.findLastVisibleItemPosition());
}
}
}
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListeners)
listener.onScrolled(recyclerView, dx, dy);
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListeners)
listener.onScrollStateChanged(recyclerView, newState);
}
};
mRecyclerView.addOnScrollListener(mInternalOnScrollListener);
}
//by default, empty screen is hidden and loading screen is displayed
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
if (mLoadingView != null)
mLoadingView.setVisibility(View.VISIBLE);
}
/**
* Set inner RecyclerView' LayoutManager
*
* @param layoutManager inner RecyclerView' LayoutManager
*/
public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
if (mRecyclerView != null)
mRecyclerView.setLayoutManager(layoutManager);
}
/**
* Set inner RecyclerView' adapter
*
* @param adapter inner RecyclerView' adapter
*/
public void setAdapter(final AbstractGenericAdapter adapter) {
mAdapter = adapter;
if (mRecyclerView != null) {
mRecyclerView.setAdapter(mAdapter);
this.updateAccessoryViews();
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
updateAccessoryViews();
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount);
updateAccessoryViews();
}
@Override
public void onChanged() {
super.onChanged();
updateAccessoryViews();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
super.onItemRangeChanged(positionStart, itemCount, payload);
updateAccessoryViews();
}
});
}
}
/**
* Update the view to display loading if needed
*/
private void updateAccessoryViews() {
// hiddig the loading view first
if (mLoadingView != null)
mLoadingView.setVisibility(View.GONE);
//flag indicating that the data loading is complete
isLoadingMore = false;
//hidding swipe to refresh too
mSwipeLayout.setRefreshing(false);
if (mAdapter.isEmpty()) {
if (mEmptyView != null)
mEmptyView.setVisibility(View.VISIBLE);
} else {
if (mEmptyView != null)
mEmptyView.setVisibility(View.GONE);
//if there is more item to load, adding a placeholder cell at the end to display the load more
if (shouldLoadMore) {
if (!mAdapter.contains(placeHolderCell) && loadMoreLayout > -1) {
//adding directly to the adapter list to avoid firing callbacks
mAdapter.items.add(placeHolderCell);
//adding the viewHolder (this is safe to add without prior check, as the adapter is smart enought to not add it twice)
if (mAdapter instanceof GenericViewHolderAdapter)
((MultiGenericAdapter) mAdapter).addViewHolderType(PlaceHolderCell.class, PlaceHolderViewHolder.class, loadMoreLayout);
}
}
}
}
/**
* Set the RecyclerView' SwipeRefreshListener
*
* @param listener the RecyclerView' SwipeRefreshListener
*/
public void setRefreshListener(SwipeRefreshLayout.OnRefreshListener listener) {
if (mSwipeLayout != null) {
mSwipeLayout.setEnabled(true);
mSwipeLayout.setOnRefreshListener(listener);
}
}
/**
* Add a the RecyclerView' OnItemTouchListener
*
* @param listener a RecyclerView' OnItemTouchListener
*/
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
if (mRecyclerView != null)
mRecyclerView.addOnItemTouchListener(listener);
}
/**
* set the LoadMore Listener
*
* @param onMoreListener the LoadMore Listener
* @param max count of items left before firing the LoadMore
*/
public void setupMoreListener(OnMoreListener onMoreListener, int max) {
mOnMoreListener = onMoreListener;
ITEM_LEFT_TO_LOAD_MORE = max;
shouldLoadMore = true;
}
/**
* Set the recyclerView' OnTouchListener
*
* @param listener OnTouchListener
*/
public void setOnTouchListener(OnTouchListener listener) {
if (mRecyclerView != null)
mRecyclerView.setOnTouchListener(listener);
}
/**
* Display the pull-to-refresh of the SwipeLayout
*
* @param display true to display the pull-to-refresh, false otherwise
*/
public void displaySwipeToRefresh(boolean display) {
if (mSwipeLayout != null)
mSwipeLayout.setEnabled(display);
}
/**
* Tell the recyclerView that new item can be loaded after the end of the current list (load more)
*
* @param shouldLoadMore true to enable the LoadMore process, false otherwise
*/
public void shouldLoadMore(boolean shouldLoadMore) {
this.shouldLoadMore = shouldLoadMore;
}
/**
* Set the view displayed when no items are in the list. Should have a frame layout at its root.
*
* @param viewLayout the view layout to inflate
*/
public void setEmptyLayout(int viewLayout) {
mEmptyViewStub.setLayoutResource(viewLayout);
mEmptyView = mEmptyViewStub.inflate();
}
/**
* Set the view displayed during loadings. Should have a frame layout at its root.
*
* @param viewLayout the view layout to inflate
*/
public void setLoadingLayout(int viewLayout) {
mLoadingViewStub.setLayoutResource(viewLayout);
mLoadingView = mLoadingViewStub.inflate();
}
/**
* Display the loading placeholder ontop of the list
*/
public void displayLoadingView() {
//si on a un PTR de setté, on l'affiche, sinon on affiche le message de chargement
if (mAdapter != null && mAdapter.getItemCount() > 0) {
if (mSwipeLayout != null && !mSwipeLayout.isRefreshing()) {
// on affiche le PTR
TypedValue typed_value = new TypedValue();
getContext().getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, typed_value, true);
mSwipeLayout.setProgressViewOffset(false, 0, getResources().getDimensionPixelSize(typed_value.resourceId));
mSwipeLayout.setRefreshing(true);
}
} else {
if (mLoadingView != null)
this.mLoadingView.setVisibility(VISIBLE);
}
}
/**
* Clear all elements in the RecyclerView' Adapter list
*/
public void clear() {
if (mAdapter != null)
mAdapter.clear();
}
/**
* Add all given items in the RecyclerView' Adapter list
*
* @param items item to add
*/
public void addAll(List<?> items) {
if (mAdapter != null) {
this.deletePlaceholder();
mAdapter.addAll(items);
}
}
/**
* Insert all given items in the RecyclerView' Adapter list
*
* @param items items to add
* @param position position unto add items
*/
public void insertAll(List<?> items, int position) {
if (mAdapter != null) {
this.deletePlaceholder();
this.mAdapter.insertAll(items, position);
}
}
/**
* Delete all placeholders
*/
private void deletePlaceholder() {
if (mAdapter != null && mAdapter.contains(placeHolderCell)) {
KLog.d("deletePlaceholder", "done");
//removing directly to the adapter list to avoid firing callbacks
mAdapter.items.remove(mAdapter.getItemCount() - 1);
}
}
/**
* Append an item to the RecyclerView' Adapter list
*
* @param item item to append
*/
public void add(Object item) {
if (mAdapter != null) {
this.deletePlaceholder();
mAdapter.add(item);
}
}
/**
* Insert a given item at a given position in the RecyclerView' Adapter list
*
* @param item item to insert
* @param position position to insert to
*/
public void insertAt(int position, Object item) {
if (mAdapter != null)
mAdapter.insertAt(position, item);
}
/**
* Delete an item from the RecyclerView' Adapter list
*
* @param position position of the item to delete
*/
public void removeAt(int position) {
if (mAdapter != null)
mAdapter.removeAt(position);
}
/**
* Replace an item at a given position by another given item of the RecyclerView' Adapter list
*
* @param position position of the item to replace
* @param item new item
*/
public void replaceAt(int position, Object item) {
if (mAdapter != null)
mAdapter.replaceAt(position, item);
}
/**
* Return true if the RecyclerView' Adapter list is empty
*
* @return true if the list is empty, false otherwise
*/
public boolean isEmpty() {
if (mAdapter != null)
return mAdapter.isEmpty();
else
return true;
}
/**
* Return the RecyclerView' Adapter item at the given position
*
* @param position position of the item
* @return the item at the given position, null otherwise
*/
public Object getItemAt(int position) {
if (mAdapter != null)
return mAdapter.getItemAt(position);
else
return null;
}
/**
* Return the position in the RecyclerView' Adapter list of the given item
*
* @param object item to search in the list
* @return item's position if found, -1 otherwise
*/
public int getObjectIndex(Object object) {
if (mAdapter != null)
return mAdapter.getObjectIndex(object);
else
return -1;
}
/**
* Return the item's count of the RecyclerView' Adapter list
*
* @return the item's count of the list
*/
public int getItemCount() {
if (mAdapter != null)
return mAdapter.getItemCount();
else
return -1;
}
/**
* Scroll smoothly to an item position in the RecyclerView
*
* @param position position to scroll to
*/
public void smoothScrollTo(int position) {
if (mRecyclerView != null)
this.mRecyclerView.smoothScrollToPosition(position);
}
/**
* Tell the recycler view that its data has been changed
*/
public void notifyDataSetChanged() {
if (mAdapter != null)
this.mAdapter.notifyDataSetChanged();
}
/**
* Add a custom cell divider to the recycler view
*
* @param dividerItemDecoration custom cell divider
*/
public void addItemDecoration(RecyclerView.ItemDecoration dividerItemDecoration) {
if (mRecyclerView != null)
mRecyclerView.addItemDecoration(dividerItemDecoration);
}
/**
* Change view background color
*
* @param color view background color
*/
@Override
public void setBackgroundColor(int color) {
if (mRecyclerView != null)
mRecyclerView.setBackgroundColor(color);
}
/**
* Set the color scheme of the loading and loadmore circular progress bar
*
* @param color1 color used on the circular progress bar
* @param color2 color used on the circular progress bar
* @param color3 color used on the circular progress bar
* @param color4 color used on the circular progress bar
*/
public void setProgressColorScheme(int color1, int color2, int color3, int color4) {
if (mSwipeLayout != null)
mSwipeLayout.setColorSchemeResources(color1, color2, color3, color4);
}
/**
* Set the layout used to populate the loadmore placeholder cell
*
* @param loadMoreLayout the layout to inflate
*/
public void setLoadMoreLayout(int loadMoreLayout) {
this.loadMoreLayout = loadMoreLayout;
}
/**
* Scroll the recycler view to its top
*/
public void scrollToTop() {
if (!mRecyclerView.isAnimating() && !mRecyclerView.isComputingLayout())
mRecyclerView.scrollToPosition(0);
}
/**
* Smooth scroll the recycler view to its top
*/
public void smoothScrollToTop() {
if (!mRecyclerView.isAnimating() && !mRecyclerView.isComputingLayout())
mRecyclerView.smoothScrollToPosition(0);
}
/**
* Return the inflated view layout placed when the list is empty
*
* @return the 'empty' view
*/
public View getEmptyView() {
return mEmptyView;
}
/**
* Return the inflated view layout placed when the list is loading elements
*
* @return the 'loading' view
*/
public View getLoadingView() {
return mLoadingView;
}
/**
* @return the scroll listeners of the recyclerView
*/
public List<RecyclerView.OnScrollListener> getmExternalOnScrollListeners() {
return mExternalOnScrollListeners;
}
/**
* Add a scroll listener to the recyclerView
*
* @param externalOnScrollListener
*/
public void addExternalOnScrollListener(RecyclerView.OnScrollListener externalOnScrollListener) {
this.mExternalOnScrollListeners.add(externalOnScrollListener);
}
/**
* Clear all scroll listeners of the recycler view
*/
public void clearExternalOnScrollListeners() {
mExternalOnScrollListeners.clear();
}
/**
* Scroll to the bottom of the list
*/
public void scrollToBottom() {
if (mRecyclerView != null && mAdapter != null && mAdapter.getItemCount() > 0)
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
| Simplify loadmore
| smartrecyclerview/src/main/java/com/lapptelier/smartrecyclerview/SmartRecyclerView.java | Simplify loadmore | <ide><path>martrecyclerview/src/main/java/com/lapptelier/smartrecyclerview/SmartRecyclerView.java
<ide> if (recyclerView.getLayoutManager().getClass().equals(LinearLayoutManager.class)) {
<ide> LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
<ide>
<del> if (((!layoutManager.getReverseLayout() && (layoutManager.findLastVisibleItemPosition() >= (layoutManager.getItemCount() - ITEM_LEFT_TO_LOAD_MORE))) ||
<del> (layoutManager.getReverseLayout() && (layoutManager.findLastVisibleItemPosition() <= ITEM_LEFT_TO_LOAD_MORE)))
<add> if (layoutManager.findLastVisibleItemPosition() >= layoutManager.getItemCount() - ITEM_LEFT_TO_LOAD_MORE
<ide> && !isLoadingMore && shouldLoadMore) {
<ide>
<ide> isLoadingMore = true; |
|
Java | bsd-2-clause | 78e0d502dcdd6884e44f649dd9579b0cbc9fee1e | 0 | scijava/scijava-common | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2014 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.test;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;
import org.scijava.test.TestUtils;
/**
* Tests the {@link TestUtils}.
*
* @author Johannes Schindelin
*/
public class TestUtilsTest {
@Test
public void testCreateTemporaryDirectory() throws IOException {
final File tmp1 = TestUtils.createTemporaryDirectory("test-utils-test-");
assertTrue("Not in target/: " + tmp1.getAbsolutePath(), tmp1
.getAbsolutePath().replace('\\', '/').contains("/target/"));
final File tmp2 = TestUtils.createTemporaryDirectory("test-utils-test-");
assertTrue(!tmp1.getAbsolutePath().equals(tmp2.getAbsolutePath()));
final File tmp3 =
TestUtils.createTemporaryDirectory("test-utils-test-", getClass());
assertTrue("Not in target/: " + tmp3.getAbsolutePath(), tmp3
.getAbsolutePath().replace('\\', '/').contains("/target/"));
final File tmp4 =
TestUtils.createTemporaryDirectory("test-utils-test-", getClass());
assertTrue(!tmp3.getAbsolutePath().equals(tmp4.getAbsolutePath()));
}
@Test
public void sameDirectoryTwice() throws IOException {
final FileOutputStream[] out = new FileOutputStream[2];
for (int i = 0; i < 2; i++) {
final File tmp = TestUtils.createTemporaryDirectory("same-");
assertTrue(tmp != null);
final String[] list = tmp.list();
assertTrue("Not null: " + Arrays.toString(list), list == null || list.length == 0);
out[i] = new FileOutputStream(new File(tmp, "hello" + i + ".txt"));
}
for (final FileOutputStream stream : out) {
if (stream != null) stream.close();
}
}
}
| src/test/java/org/scijava/test/TestUtilsTest.java | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2014 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.test;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;
import org.scijava.test.TestUtils;
/**
* Tests the {@link TestUtilsTest}.
*
* @author Johannes Schindelin
*/
public class TestUtilsTest {
@Test
public void testCreateTemporaryDirectory() throws IOException {
final File tmp1 = TestUtils.createTemporaryDirectory("test-utils-test-");
assertTrue("Not in target/: " + tmp1.getAbsolutePath(), tmp1
.getAbsolutePath().replace('\\', '/').contains("/target/"));
final File tmp2 = TestUtils.createTemporaryDirectory("test-utils-test-");
assertTrue(!tmp1.getAbsolutePath().equals(tmp2.getAbsolutePath()));
final File tmp3 =
TestUtils.createTemporaryDirectory("test-utils-test-", getClass());
assertTrue("Not in target/: " + tmp3.getAbsolutePath(), tmp3
.getAbsolutePath().replace('\\', '/').contains("/target/"));
final File tmp4 =
TestUtils.createTemporaryDirectory("test-utils-test-", getClass());
assertTrue(!tmp3.getAbsolutePath().equals(tmp4.getAbsolutePath()));
}
@Test
public void sameDirectoryTwice() throws IOException {
final FileOutputStream[] out = new FileOutputStream[2];
for (int i = 0; i < 2; i++) {
final File tmp = TestUtils.createTemporaryDirectory("same-");
assertTrue(tmp != null);
final String[] list = tmp.list();
assertTrue("Not null: " + Arrays.toString(list), list == null || list.length == 0);
out[i] = new FileOutputStream(new File(tmp, "hello" + i + ".txt"));
}
for (final FileOutputStream stream : out) {
if (stream != null) stream.close();
}
}
}
| TestUtilsTest: fix javadoc link
| src/test/java/org/scijava/test/TestUtilsTest.java | TestUtilsTest: fix javadoc link | <ide><path>rc/test/java/org/scijava/test/TestUtilsTest.java
<ide> import org.scijava.test.TestUtils;
<ide>
<ide> /**
<del> * Tests the {@link TestUtilsTest}.
<add> * Tests the {@link TestUtils}.
<ide> *
<ide> * @author Johannes Schindelin
<ide> */ |
|
Java | apache-2.0 | 87de8d16d9eba99fa796c356a06cfba76e609318 | 0 | manstis/drools,lanceleverich/drools,jomarko/drools,manstis/drools,lanceleverich/drools,winklerm/drools,jomarko/drools,manstis/drools,jomarko/drools,lanceleverich/drools,droolsjbpm/drools,jomarko/drools,manstis/drools,lanceleverich/drools,lanceleverich/drools,manstis/drools,droolsjbpm/drools,droolsjbpm/drools,droolsjbpm/drools,droolsjbpm/drools,winklerm/drools,jomarko/drools,winklerm/drools,winklerm/drools,winklerm/drools | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.reteoo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.MemoryFactory;
import org.drools.core.rule.ContextEntry;
import org.drools.core.spi.PropagationContext;
import org.drools.core.util.FastIterator;
public class NotNodeLeftTuple extends BaseLeftTuple {
private static final long serialVersionUID = 540l;
private RightTuple blocker;
private LeftTuple blockedPrevious;
private LeftTuple blockedNext;
public NotNodeLeftTuple() {
// constructor needed for serialisation
}
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
public NotNodeLeftTuple(final InternalFactHandle factHandle,
Sink sink,
boolean leftTupleMemoryEnabled) {
super(factHandle,
sink,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final InternalFactHandle factHandle,
final LeftTuple leftTuple,
final Sink sink) {
super( factHandle, leftTuple, sink );
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final Sink sink,
final PropagationContext pctx,
final boolean leftTupleMemoryEnabled) {
super(leftTuple,
sink,
pctx,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
RightTuple rightTuple,
Sink sink) {
super(leftTuple,
rightTuple,
sink);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final Sink sink,
final boolean leftTupleMemoryEnabled) {
this(leftTuple,
rightTuple,
null,
null,
sink,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final LeftTuple currentLeftChild,
final LeftTuple currentRightChild,
final Sink sink,
final boolean leftTupleMemoryEnabled) {
super(leftTuple,
rightTuple,
currentLeftChild,
currentRightChild,
sink,
leftTupleMemoryEnabled);
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#unlinkFromLeftParent()
*/
public void unlinkFromLeftParent() {
super.unlinkFromLeftParent();
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#unlinkFromRightParent()
*/
public void unlinkFromRightParent() {
super.unlinkFromRightParent();
}
public void clearBlocker() {
this.blockedPrevious = null;
this.blockedNext = null;
this.blocker = null;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlocker(org.kie.reteoo.RightTuple)
*/
public void setBlocker(RightTuple blocker) {
this.blocker = blocker;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlocker()
*/
public RightTuple getBlocker() {
return this.blocker;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlockedPrevious()
*/
public LeftTuple getBlockedPrevious() {
return this.blockedPrevious;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlockedPrevious(org.kie.reteoo.LeftTuple)
*/
public void setBlockedPrevious(LeftTuple blockerPrevious) {
this.blockedPrevious = blockerPrevious;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlockedNext()
*/
public LeftTuple getBlockedNext() {
return this.blockedNext;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlockedNext(org.kie.reteoo.LeftTuple)
*/
public void setBlockedNext(LeftTuple blockerNext) {
this.blockedNext = blockerNext;
}
@Override
public Collection<Object> getAccumulatedObjects() {
if (NodeTypeEnums.ExistsNode != getTupleSink().getType()) {
return Collections.emptyList();
}
BetaNode betaNode = ( (BetaNode) getTupleSink() );
BetaConstraints constraints = betaNode.getRawConstraints();
InternalWorkingMemory wm = getFactHandle().getWorkingMemory();
BetaMemory bm = (BetaMemory) wm.getNodeMemory( (MemoryFactory) getTupleSink() );
TupleMemory rtm = bm.getRightTupleMemory();
FastIterator it = betaNode.getRightIterator( rtm );
ContextEntry[] contextEntry = bm.getContext();
constraints.updateFromTuple( contextEntry, wm, this );
Collection<Object> result = new ArrayList<>();
for (RightTuple rightTuple = betaNode.getFirstRightTuple(this, rtm, null, it); rightTuple != null; ) {
RightTuple nextRight = (RightTuple) it.next(rightTuple);
if ( !(rightTuple instanceof SubnetworkTuple) ) {
InternalFactHandle fh = rightTuple.getFactHandleForEvaluation();
if ( constraints.isAllowedCachedLeft( contextEntry, fh ) ) {
result.add( fh.getObject() );
}
}
rightTuple = nextRight;
}
return result;
}
}
| drools-core/src/main/java/org/drools/core/reteoo/NotNodeLeftTuple.java | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.reteoo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.MemoryFactory;
import org.drools.core.rule.ContextEntry;
import org.drools.core.spi.PropagationContext;
import org.drools.core.util.FastIterator;
public class NotNodeLeftTuple extends BaseLeftTuple {
private static final long serialVersionUID = 540l;
private RightTuple blocker;
private LeftTuple blockedPrevious;
private LeftTuple blockedNext;
public NotNodeLeftTuple() {
// constructor needed for serialisation
}
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
public NotNodeLeftTuple(final InternalFactHandle factHandle,
Sink sink,
boolean leftTupleMemoryEnabled) {
super(factHandle,
sink,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final InternalFactHandle factHandle,
final LeftTuple leftTuple,
final Sink sink) {
super( factHandle, leftTuple, sink );
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final Sink sink,
final PropagationContext pctx,
final boolean leftTupleMemoryEnabled) {
super(leftTuple,
sink,
pctx,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
RightTuple rightTuple,
Sink sink) {
super(leftTuple,
rightTuple,
sink);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final Sink sink,
final boolean leftTupleMemoryEnabled) {
this(leftTuple,
rightTuple,
null,
null,
sink,
leftTupleMemoryEnabled);
}
public NotNodeLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final LeftTuple currentLeftChild,
final LeftTuple currentRightChild,
final Sink sink,
final boolean leftTupleMemoryEnabled) {
super(leftTuple,
rightTuple,
currentLeftChild,
currentRightChild,
sink,
leftTupleMemoryEnabled);
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#unlinkFromLeftParent()
*/
public void unlinkFromLeftParent() {
super.unlinkFromLeftParent();
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#unlinkFromRightParent()
*/
public void unlinkFromRightParent() {
super.unlinkFromRightParent();
}
public void clearBlocker() {
this.blockedPrevious = null;
this.blockedNext = null;
this.blocker = null;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlocker(org.kie.reteoo.RightTuple)
*/
public void setBlocker(RightTuple blocker) {
this.blocker = blocker;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlocker()
*/
public RightTuple getBlocker() {
return this.blocker;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlockedPrevious()
*/
public LeftTuple getBlockedPrevious() {
return this.blockedPrevious;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlockedPrevious(org.kie.reteoo.LeftTuple)
*/
public void setBlockedPrevious(LeftTuple blockerPrevious) {
this.blockedPrevious = blockerPrevious;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#getBlockedNext()
*/
public LeftTuple getBlockedNext() {
return this.blockedNext;
}
/* (non-Javadoc)
* @see org.kie.reteoo.LeftTuple#setBlockedNext(org.kie.reteoo.LeftTuple)
*/
public void setBlockedNext(LeftTuple blockerNext) {
this.blockedNext = blockerNext;
}
@Override
public Collection<Object> getAccumulatedObjects() {
if (NodeTypeEnums.ExistsNode != getTupleSink().getType()) {
return Collections.emptyList();
}
BetaNode betaNode = ( (BetaNode) getTupleSink() );
BetaConstraints constraints = betaNode.getRawConstraints();
InternalWorkingMemory wm = getFactHandle().getWorkingMemory();
BetaMemory bm = (BetaMemory) wm.getNodeMemory( (MemoryFactory) getTupleSink() );
TupleMemory rtm = bm.getRightTupleMemory();
FastIterator it = betaNode.getRightIterator( rtm );
ContextEntry[] contextEntry = bm.getContext();
constraints.updateFromTuple( contextEntry, wm, this );
Collection<Object> result = new ArrayList<>();
for (RightTuple rightTuple = betaNode.getFirstRightTuple(this, rtm, null, it); rightTuple != null; ) {
RightTuple nextRight = (RightTuple) it.next(rightTuple);
InternalFactHandle fh = rightTuple.getFactHandleForEvaluation();
if (constraints.isAllowedCachedLeft(contextEntry, fh)) {
result.add(fh.getObject());
}
rightTuple = nextRight;
}
return result;
}
}
| [DROOLS-4423] avoid returning SubnetworkTuples among objects returned by getObjectsDeep
| drools-core/src/main/java/org/drools/core/reteoo/NotNodeLeftTuple.java | [DROOLS-4423] avoid returning SubnetworkTuples among objects returned by getObjectsDeep | <ide><path>rools-core/src/main/java/org/drools/core/reteoo/NotNodeLeftTuple.java
<ide> Collection<Object> result = new ArrayList<>();
<ide> for (RightTuple rightTuple = betaNode.getFirstRightTuple(this, rtm, null, it); rightTuple != null; ) {
<ide> RightTuple nextRight = (RightTuple) it.next(rightTuple);
<del> InternalFactHandle fh = rightTuple.getFactHandleForEvaluation();
<del> if (constraints.isAllowedCachedLeft(contextEntry, fh)) {
<del> result.add(fh.getObject());
<add> if ( !(rightTuple instanceof SubnetworkTuple) ) {
<add> InternalFactHandle fh = rightTuple.getFactHandleForEvaluation();
<add> if ( constraints.isAllowedCachedLeft( contextEntry, fh ) ) {
<add> result.add( fh.getObject() );
<add> }
<ide> }
<ide> rightTuple = nextRight;
<ide> } |
|
Java | apache-2.0 | fbb7224d8e03e32d7ede13063879b0dc9a998768 | 0 | 52North/javaPS,52North/javaPS,52North/javaPS | /*
* Copyright (C) 2020 by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.n52.javaps.rest.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* LiteralDataType
*/
@Validated
public class LiteralDataType {
@JsonProperty("literalDataDomains")
@Valid
private List<LiteralDataDomain> literalDataDomains = new ArrayList<LiteralDataDomain>();;
public LiteralDataType literalDataDomains(List<LiteralDataDomain> literalDataDomains) {
this.literalDataDomains = literalDataDomains;
return this;
}
public LiteralDataType addLiteralDataDomainsItem(LiteralDataDomain literalDataDomainsItem) {
this.literalDataDomains.add(literalDataDomainsItem);
return this;
}
/**
* Get literalDataDomains
*
* @return literalDataDomains
**/
@ApiModelProperty(required = true, value = "")
@NotNull
@Valid
public List<LiteralDataDomain> getLiteralDataDomains() {
return literalDataDomains;
}
public void setLiteralDataDomains(List<LiteralDataDomain> literalDataDomains) {
this.literalDataDomains = literalDataDomains;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LiteralDataType literalDataType = (LiteralDataType) o;
return Objects.equals(this.literalDataDomains, literalDataType.literalDataDomains);
}
@Override
public int hashCode() {
return Objects.hash(literalDataDomains);
}
@Override
public String toString() {
return String.format("LiteralDataType{literalDataDomains: %s}", literalDataDomains);
}
}
| src/main/java/org/n52/javaps/rest/model/LiteralDataType.java | /*
* Copyright (C) 2020 by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.n52.javaps.rest.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* LiteralDataType
*/
@Validated
public class LiteralDataType {
@JsonProperty("literalDataDomains")
@Valid
private List<LiteralDataDomain> literalDataDomains;
public LiteralDataType literalDataDomains(List<LiteralDataDomain> literalDataDomains) {
this.literalDataDomains = literalDataDomains;
return this;
}
public LiteralDataType addLiteralDataDomainsItem(LiteralDataDomain literalDataDomainsItem) {
if (this.literalDataDomains == null) {
this.literalDataDomains = new ArrayList<LiteralDataDomain>();
}
this.literalDataDomains.add(literalDataDomainsItem);
return this;
}
/**
* Get literalDataDomains
*
* @return literalDataDomains
**/
@Valid
public List<LiteralDataDomain> getLiteralDataDomains() {
return literalDataDomains;
}
public void setLiteralDataDomains(List<LiteralDataDomain> literalDataDomains) {
this.literalDataDomains = literalDataDomains;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LiteralDataType literalDataType = (LiteralDataType) o;
return Objects.equals(this.literalDataDomains, literalDataType.literalDataDomains);
}
@Override
public int hashCode() {
return Objects.hash(literalDataDomains);
}
@Override
public String toString() {
return String.format("LiteralDataType{literalDataDomains: %s}", literalDataDomains);
}
}
| Small update of LiteralDataType
| src/main/java/org/n52/javaps/rest/model/LiteralDataType.java | Small update of LiteralDataType | <ide><path>rc/main/java/org/n52/javaps/rest/model/LiteralDataType.java
<ide>
<ide> import com.fasterxml.jackson.annotation.JsonProperty;
<ide> import org.springframework.validation.annotation.Validated;
<add>import io.swagger.annotations.ApiModelProperty;
<ide>
<add>import javax.validation.constraints.NotNull;
<ide> import javax.validation.Valid;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> public class LiteralDataType {
<ide> @JsonProperty("literalDataDomains")
<ide> @Valid
<del> private List<LiteralDataDomain> literalDataDomains;
<add> private List<LiteralDataDomain> literalDataDomains = new ArrayList<LiteralDataDomain>();;
<ide>
<ide> public LiteralDataType literalDataDomains(List<LiteralDataDomain> literalDataDomains) {
<ide> this.literalDataDomains = literalDataDomains;
<ide> }
<ide>
<ide> public LiteralDataType addLiteralDataDomainsItem(LiteralDataDomain literalDataDomainsItem) {
<del> if (this.literalDataDomains == null) {
<del> this.literalDataDomains = new ArrayList<LiteralDataDomain>();
<del> }
<ide> this.literalDataDomains.add(literalDataDomainsItem);
<ide> return this;
<ide> }
<ide> *
<ide> * @return literalDataDomains
<ide> **/
<add> @ApiModelProperty(required = true, value = "")
<add> @NotNull
<ide> @Valid
<ide> public List<LiteralDataDomain> getLiteralDataDomains() {
<ide> return literalDataDomains; |
|
Java | apache-2.0 | 63e8d11ed8473cd892b14553984844db136f0f9a | 0 | pires/obd-java-api | package com.github.pires.obd.commands.control;
import com.github.pires.obd.commands.ObdCommand;
import com.github.pires.obd.enums.AvailableCommandNames;
import java.io.IOException;
import java.io.InputStream;
/**
* It is not needed no know how many DTC are stored.
* Because when no DTC are stored response will be NO DATA
* And where are more messages it will be stored in frames that have 7 bytes.
* In one frame are stored 3 DTC.
* If we find out DTC P0000 that mean no message are we can end.
*
* @author pires
* @version $Id: $Id
*/
public class TroubleCodesCommand extends ObdCommand {
/** Constant <code>dtcLetters={'P', 'C', 'B', 'U'}</code> */
protected final static char[] dtcLetters = {'P', 'C', 'B', 'U'};
/** Constant <code>hexArray="0123456789ABCDEF".toCharArray()</code> */
protected final static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected StringBuilder codes = null;
/**
* <p>Constructor for TroubleCodesCommand.</p>
*/
public TroubleCodesCommand() {
super("03");
codes = new StringBuilder();
}
/**
* Copy ctor.
*
* @param other a {@link com.github.pires.obd.commands.control.TroubleCodesCommand} object.
*/
public TroubleCodesCommand(TroubleCodesCommand other) {
super(other);
codes = new StringBuilder();
}
/** {@inheritDoc} */
@Override
protected void fillBuffer() {
}
/** {@inheritDoc} */
@Override
protected void performCalculations() {
final String result = getResult();
String workingData;
int startIndex = 0;//Header size.
String canOneFrame = result.replaceAll("[\r\n]", "");
int canOneFrameLength = canOneFrame.length();
if (canOneFrameLength <= 16 && canOneFrameLength % 4 == 0) {//CAN(ISO-15765) protocol one frame.
workingData = canOneFrame;//43yy{codes}
startIndex = 4;//Header is 43yy, yy showing the number of data items.
} else if (result.contains(":")) {//CAN(ISO-15765) protocol two and more frames.
workingData = result.replaceAll("[\r\n].:", "");//xxx43yy{codes}
startIndex = 7;//Header is xxx43yy, xxx is bytes of information to follow, yy showing the number of data items.
} else {//ISO9141-2, KWP2000 Fast and KWP2000 5Kbps (ISO15031) protocols.
workingData = result.replaceAll("^43|[\r\n]43|[\r\n]", "");
}
for (int begin = startIndex; begin < workingData.length(); begin += 4) {
String dtc = "";
byte b1 = hexStringToByteArray(workingData.charAt(begin));
int ch1 = ((b1 & 0xC0) >> 6);
int ch2 = ((b1 & 0x30) >> 4);
dtc += dtcLetters[ch1];
dtc += hexArray[ch2];
dtc += workingData.substring(begin+1, begin + 4);
if (dtc.equals("P0000")) {
return;
}
codes.append(dtc);
codes.append('\n');
}
}
private byte hexStringToByteArray(char s) {
return (byte) ((Character.digit(s, 16) << 4));
}
/**
* <p>formatResult.</p>
*
* @return the formatted result of this command in string representation.
* @deprecated use #getCalculatedResult instead
*/
public String formatResult() {
return codes.toString();
}
/** {@inheritDoc} */
@Override
public String getCalculatedResult() {
return String.valueOf(codes);
}
/** {@inheritDoc} */
@Override
protected void readRawData(InputStream in) throws IOException {
byte b;
StringBuilder res = new StringBuilder();
// read until '>' arrives OR end of stream reached (and skip ' ')
char c;
while (true) {
b = (byte) in.read();
if (b == -1) // -1 if the end of the stream is reached
{
break;
}
c = (char) b;
if (c == '>') // read until '>' arrives
{
break;
}
if (c != ' ') // skip ' '
{
res.append(c);
}
}
rawData = res.toString().trim();
}
/** {@inheritDoc} */
@Override
public String getFormattedResult() {
return codes.toString();
}
/** {@inheritDoc} */
@Override
public String getName() {
return AvailableCommandNames.TROUBLE_CODES.getValue();
}
} | src/main/java/com/github/pires/obd/commands/control/TroubleCodesCommand.java | package com.github.pires.obd.commands.control;
import com.github.pires.obd.commands.ObdCommand;
import com.github.pires.obd.enums.AvailableCommandNames;
import java.io.IOException;
import java.io.InputStream;
/**
* It is not needed no know how many DTC are stored.
* Because when no DTC are stored response will be NO DATA
* And where are more messages it will be stored in frames that have 7 bytes.
* In one frame are stored 3 DTC.
* If we find out DTC P0000 that mean no message are we can end.
*
* @author pires
* @version $Id: $Id
*/
public class TroubleCodesCommand extends ObdCommand {
/** Constant <code>dtcLetters={'P', 'C', 'B', 'U'}</code> */
protected final static char[] dtcLetters = {'P', 'C', 'B', 'U'};
/** Constant <code>hexArray="0123456789ABCDEF".toCharArray()</code> */
protected final static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected StringBuilder codes = null;
/**
* <p>Constructor for TroubleCodesCommand.</p>
*/
public TroubleCodesCommand() {
super("03");
codes = new StringBuilder();
}
/**
* Copy ctor.
*
* @param other a {@link com.github.pires.obd.commands.control.TroubleCodesCommand} object.
*/
public TroubleCodesCommand(TroubleCodesCommand other) {
super(other);
codes = new StringBuilder();
}
/** {@inheritDoc} */
@Override
protected void fillBuffer() {
}
/** {@inheritDoc} */
@Override
protected void performCalculations() {
final String result = getResult();
String workingData;
int startIndex = 0;//Header size.
if (result.length() % 4 == 0) {//CAN(ISO-15765) protocol one frame.
workingData = getResult();//43yy{codes}
startIndex = 4;//Header is 43yy, yy showing the number of data items.
} else if (result.contains(":")) {//CAN(ISO-15765) protocol two and more frames.
workingData = getResult().replaceAll("[\r\n].:", "");//xxx43yy{codes}
startIndex = 7;//Header is xxx43yy, xxx is bytes of information to follow, yy showing the number of data items.
} else {//ISO9141-2, KWP2000 Fast and KWP2000 5Kbps (ISO15031) protocols.
workingData = result.replaceAll("[\r\n]?43", "");
}
for (int begin = startIndex; begin < workingData.length(); begin += 4) {
String dtc = "";
byte b1 = hexStringToByteArray(workingData.charAt(begin));
int ch1 = ((b1 & 0xC0) >> 6);
int ch2 = ((b1 & 0x30) >> 4);
dtc += dtcLetters[ch1];
dtc += hexArray[ch2];
dtc += workingData.substring(begin+1, begin + 4);
if (dtc.equals("P0000")) {
return;
}
codes.append(dtc);
codes.append('\n');
}
}
private byte hexStringToByteArray(char s) {
return (byte) ((Character.digit(s, 16) << 4));
}
/**
* <p>formatResult.</p>
*
* @return the formatted result of this command in string representation.
* @deprecated use #getCalculatedResult instead
*/
public String formatResult() {
return codes.toString();
}
/** {@inheritDoc} */
@Override
public String getCalculatedResult() {
return String.valueOf(codes);
}
/** {@inheritDoc} */
@Override
protected void readRawData(InputStream in) throws IOException {
byte b;
StringBuilder res = new StringBuilder();
// read until '>' arrives OR end of stream reached (and skip ' ')
char c;
while (true) {
b = (byte) in.read();
if (b == -1) // -1 if the end of the stream is reached
{
break;
}
c = (char) b;
if (c == '>') // read until '>' arrives
{
break;
}
if (c != ' ') // skip ' '
{
res.append(c);
}
}
rawData = res.toString().trim();
}
/** {@inheritDoc} */
@Override
public String getFormattedResult() {
return codes.toString();
}
/** {@inheritDoc} */
@Override
public String getName() {
return AvailableCommandNames.TROUBLE_CODES.getValue();
}
}
| Fix broken regex in TroubleCodesCommand
| src/main/java/com/github/pires/obd/commands/control/TroubleCodesCommand.java | Fix broken regex in TroubleCodesCommand | <ide><path>rc/main/java/com/github/pires/obd/commands/control/TroubleCodesCommand.java
<ide> final String result = getResult();
<ide> String workingData;
<ide> int startIndex = 0;//Header size.
<del> if (result.length() % 4 == 0) {//CAN(ISO-15765) protocol one frame.
<del> workingData = getResult();//43yy{codes}
<add>
<add> String canOneFrame = result.replaceAll("[\r\n]", "");
<add> int canOneFrameLength = canOneFrame.length();
<add> if (canOneFrameLength <= 16 && canOneFrameLength % 4 == 0) {//CAN(ISO-15765) protocol one frame.
<add> workingData = canOneFrame;//43yy{codes}
<ide> startIndex = 4;//Header is 43yy, yy showing the number of data items.
<ide> } else if (result.contains(":")) {//CAN(ISO-15765) protocol two and more frames.
<del> workingData = getResult().replaceAll("[\r\n].:", "");//xxx43yy{codes}
<add> workingData = result.replaceAll("[\r\n].:", "");//xxx43yy{codes}
<ide> startIndex = 7;//Header is xxx43yy, xxx is bytes of information to follow, yy showing the number of data items.
<ide> } else {//ISO9141-2, KWP2000 Fast and KWP2000 5Kbps (ISO15031) protocols.
<del> workingData = result.replaceAll("[\r\n]?43", "");
<add> workingData = result.replaceAll("^43|[\r\n]43|[\r\n]", "");
<ide> }
<ide> for (int begin = startIndex; begin < workingData.length(); begin += 4) {
<ide> String dtc = ""; |
|
JavaScript | mpl-2.0 | c0016c9a909d8d0c452db99aff5438a131ad4f23 | 0 | dodidoio/testbot | const client = require('dodido-client');
var cid = require('uuid').v4();
const DEFAULT_TIMEOUT = 10000;
var _request = null;
var _question = null;
var _events = [];
var _listeners = [];
var evtId = 1;
var _requestActive = false;
///////////////////////////////////////////////////////////////////////////////
//managing state of requests and questions
///////////////////////////////////////////////////////////////////////////////
function activeRequest(){return _requestActive? _request : null;}
function activeQuestion(){return _question;}
function setRequest(req){
function requestIsNotActive(){_requestActive = false;}
req.then(requestIsNotActive,requestIsNotActive);
_requestActive = true;
_request = req;
_question = null;
_events = [];
_listeners = [];//clear all listeners - we count on them timing-out so no need to reject them
}
function setQuestion(id,expecting){
_question = {id:id,expecting:expecting};
}
function clearQuestion(id){
if(_question.id === id){
_question = null;
}
}
function readEvent(evt,timeout){
evt = Array.isArray(evt)? evt : [evt];
if(!activeRequest()){
//no active request - reject
return Promise.reject('no active request');
}
//go over all cached events until the requested event type found
while(_events.length > 0){
var ret = _events.shift();
for(let i=0;i<evt.length;++i){
if(evt[i] === ret.event){
return Promise.resolve(ret);
}
}
}
//no event in cache - create promise and add it to listeners
return new Promise(function(resolve,reject){
setTimeout(()=>{
reject('timeout');
},timeout || DEFAULT_TIMEOUT);
_listeners.push({evt:evt,func:resolve});
});
}
function writeEvent(evt){
evt.id = evtId++;
if(_listeners.length > 0){
//there are listeners in line - if the first listener can handle the event then hanlde it
let first = _listeners[0];
for(let i=0;i<first.evt.length;++i){
if(evt.event === first.evt[i]){
return _listeners.shift().func(evt);
}
}
}else{
//no listeners waiting - just cache the event
_events.push(evt);
}
}
///////////////////////////////////////////////////////////////////////////////
module.exports = {
connect : function(params){
var server = params.server || 'wss://assist.dodido.io';
var token = params.token || null;
if(!token){
return Promise.reject('connection token was missing');
}
var ret = client.connect(server,token);
ret.on('opened',()=>{
if(params.verbose){
console.info('Connection to server opened');
}
});
ret.on('error',(err)=>{
if(params.verbose){
console.error('Error connecting to server:',err);
}
});
return ret;
},
sendText : function(text,params){
if(activeRequest() && !activeQuestion()){
//there is an active request and we are not waiting for an answer - wait until the request is completed
return activeRequest().then(
module.exports.sendText.bind(this,text,params),
module.exports.sendText.bind(this,text,params));
}
if(params.verbose){
console.info('user: ' + text);
}
//if there is a pending question then just answer it
if(activeQuestion()){
client.answer(activeQuestion().id,text,activeQuestion().expecting);
clearQuestion(activeQuestion().id);
return true;
}
const input = {
input:text,
packages : params.packages? params.packages.split(',') : [],
token : params['request-token'] || null,
userid : params['userid'] || null,
expecting:params.expecting || 'action'
};
newRequest = client.request(input,cid);
setRequest(newRequest);
newRequest.on('error',(err)=>{
writeEvent({event:'error',message:err});
console.error(('Error sendingText - ' + err).red.bold);
console.error(`\ttext is: ${text}`.red.bold);
});
newRequest.on('fail',()=>{
writeEvent({event:'fail',message:{}});
console.error(('Error parsing request: ' + text).red.bold);
});
newRequest.on('show',(entity,type)=>{
if(params['dump-show']){
console.info('show',type,JSON.stringify(entity));
}
writeEvent({event:'show',message:{entity:entity,type:type}});
});
newRequest.on('log',(message)=>{
if(params.log){
console.info('log: ' + message);
}
});
newRequest.on('ask',(message,id,description,expecting)=>{
setQuestion(id,expecting);
if(params.verbose){
console.info('bot asked: ' + text);
}
writeEvent({event:'ask',message:message,id:id,description:description,exepcting:expecting});
});
newRequest.on('say',(message)=>{
if(params.verbose){
console.info('bot: ' + text);
}
writeEvent({event:'say',message:message});
});
newRequest.then(()=>{
//after request is completed remove it
});
return true;
},
receiveText : function(props){
var timeout = props.timeout || DEFAULT_TIMEOUT;
return readEvent(['say','ask'],timeout).then((evt)=>{
return evt.message;
},(err)=>{
return Promise.reject(err);
});
},
receiveEvent : function(eventName,props){
var timeout = props.timeout || DEFAULT_TIMEOUT;
return readEvent(eventName,timeout).then((evt)=>{
return evt.message;
},(err)=>{
return Promise.reject(err);
});
},
command : function(command,argText){
if(command === 'clear'){
//start a new context
cid = require('uuid').v4();
}
}
}; | platforms/dodido.js | const client = require('../../dodido-client');
var cid = require('uuid').v4();
const DEFAULT_TIMEOUT = 10000;
var _request = null;
var _question = null;
var _events = [];
var _listeners = [];
var evtId = 1;
var _requestActive = false;
///////////////////////////////////////////////////////////////////////////////
//managing state of requests and questions
///////////////////////////////////////////////////////////////////////////////
function activeRequest(){return _requestActive? _request : null;}
function activeQuestion(){return _question;}
function setRequest(req){
function requestIsNotActive(){_requestActive = false;}
req.then(requestIsNotActive,requestIsNotActive);
_requestActive = true;
_request = req;
_question = null;
_events = [];
_listeners = [];//clear all listeners - we count on them timing-out so no need to reject them
}
function setQuestion(id,expecting){
_question = {id:id,expecting:expecting};
}
function clearQuestion(id){
if(_question.id === id){
_question = null;
}
}
function readEvent(evt,timeout){
evt = Array.isArray(evt)? evt : [evt];
if(!activeRequest()){
//no active request - reject
return Promise.reject('no active request');
}
//go over all cached events until the requested event type found
while(_events.length > 0){
var ret = _events.shift();
for(let i=0;i<evt.length;++i){
if(evt[i] === ret.event){
return Promise.resolve(ret);
}
}
}
//no event in cache - create promise and add it to listeners
return new Promise(function(resolve,reject){
setTimeout(()=>{
reject('timeout');
},timeout || DEFAULT_TIMEOUT);
_listeners.push({evt:evt,func:resolve});
});
}
function writeEvent(evt){
evt.id = evtId++;
if(_listeners.length > 0){
//there are listeners in line - if the first listener can handle the event then hanlde it
let first = _listeners[0];
for(let i=0;i<first.evt.length;++i){
if(evt.event === first.evt[i]){
return _listeners.shift().func(evt);
}
}
}else{
//no listeners waiting - just cache the event
_events.push(evt);
}
}
///////////////////////////////////////////////////////////////////////////////
module.exports = {
connect : function(params){
var server = params.server || 'wss://assist.dodido.io';
var token = params.token || null;
if(!token){
return Promise.reject('connection token was missing');
}
var ret = client.connect(server,token);
ret.on('opened',()=>{
if(params.verbose){
console.info('Connection to server opened');
}
});
ret.on('error',(err)=>{
if(params.verbose){
console.error('Error connecting to server:',err);
}
});
return ret;
},
sendText : function(text,params){
if(activeRequest() && !activeQuestion()){
//there is an active request and we are not waiting for an answer - wait until the request is completed
return activeRequest().then(
module.exports.sendText.bind(this,text,params),
module.exports.sendText.bind(this,text,params));
}
if(params.verbose){
console.info('user: ' + text);
}
//if there is a pending question then just answer it
if(activeQuestion()){
client.answer(activeQuestion().id,text,activeQuestion().expecting);
clearQuestion(activeQuestion().id);
return true;
}
const input = {
input:text,
packages : params.packages? params.packages.split(',') : [],
token : params['request-token'] || null,
userid : params['userid'] || null,
expecting:params.expecting || 'action'
};
newRequest = client.request(input,cid);
setRequest(newRequest);
newRequest.on('error',(err)=>{
writeEvent({event:'error',message:err});
console.error(('Error sendingText - ' + err).red.bold);
console.error(`\ttext is: ${text}`.red.bold);
});
newRequest.on('fail',()=>{
writeEvent({event:'fail',message:{}});
console.error(('Error parsing request: ' + text).red.bold);
});
newRequest.on('show',(entity,type)=>{
if(params['dump-show']){
console.info('show',type,JSON.stringify(entity));
}
writeEvent({event:'show',message:{entity:entity,type:type}});
});
newRequest.on('log',(message)=>{
if(params.log){
console.info('log: ' + message);
}
});
newRequest.on('ask',(message,id,description,expecting)=>{
setQuestion(id,expecting);
if(params.verbose){
console.info('bot asked: ' + text);
}
writeEvent({event:'ask',message:message,id:id,description:description,exepcting:expecting});
});
newRequest.on('say',(message)=>{
if(params.verbose){
console.info('bot: ' + text);
}
writeEvent({event:'say',message:message});
});
newRequest.then(()=>{
//after request is completed remove it
});
return true;
},
receiveText : function(props){
var timeout = props.timeout || DEFAULT_TIMEOUT;
return readEvent(['say','ask'],timeout).then((evt)=>{
return evt.message;
},(err)=>{
return Promise.reject(err);
});
},
receiveEvent : function(eventName,props){
var timeout = props.timeout || DEFAULT_TIMEOUT;
return readEvent(eventName,timeout).then((evt)=>{
return evt.message;
},(err)=>{
return Promise.reject(err);
});
},
command : function(command,argText){
if(command === 'clear'){
//start a new context
cid = require('uuid').v4();
}
}
}; | update dodido-client module location
| platforms/dodido.js | update dodido-client module location | <ide><path>latforms/dodido.js
<del>const client = require('../../dodido-client');
<add>const client = require('dodido-client');
<ide> var cid = require('uuid').v4();
<ide> const DEFAULT_TIMEOUT = 10000;
<ide> |
|
Java | apache-2.0 | 70114657fb5d6c22dd736f884b3d9b32358299e9 | 0 | glamperi/optaplanner,baldimir/optaplanner,bernardator/optaplanner,droolsjbpm/optaplanner,tkobayas/optaplanner,codeaudit/optaplanner,gsheldon/optaplanner,snurkabill/optaplanner,oskopek/optaplanner,tomasdavidorg/optaplanner,gsheldon/optaplanner,kunallimaye/optaplanner,eshen1991/optaplanner,codeaudit/optaplanner,kunallimaye/optaplanner,droolsjbpm/optaplanner,baldimir/optaplanner,baldimir/optaplanner,tkobayas/optaplanner,snurkabill/optaplanner,oskopek/optaplanner,oskopek/optaplanner,glamperi/optaplanner,glamperi/optaplanner,droolsjbpm/optaplanner,codeaudit/optaplanner,kunallimaye/optaplanner,bernardator/optaplanner,netinept/Court-Scheduler,gsheldon/optaplanner,snurkabill/optaplanner,DieterDePaepe/optaplanner,netinept/Court-Scheduler,gsheldon/optaplanner,eshen1991/optaplanner,baldimir/optaplanner,eshen1991/optaplanner,netinept/Court-Scheduler,tomasdavidorg/optaplanner,oskopek/optaplanner,tomasdavidorg/optaplanner,tkobayas/optaplanner,DieterDePaepe/optaplanner,droolsjbpm/optaplanner,bernardator/optaplanner,tkobayas/optaplanner | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.config.score.director;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.drools.RuleBase;
import org.drools.RuleBaseConfiguration;
import org.drools.RuleBaseFactory;
import org.drools.compiler.compiler.DroolsParserException;
import org.drools.compiler.compiler.PackageBuilder;
import org.optaplanner.config.EnvironmentMode;
import org.optaplanner.config.util.ConfigUtils;
import org.optaplanner.core.domain.solution.SolutionDescriptor;
import org.optaplanner.core.score.buildin.bendable.BendableScoreDefinition;
import org.optaplanner.core.score.buildin.hardmediumsoft.HardMediumSoftScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoft.HardSoftScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftdouble.HardSoftDoubleScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftlong.HardSoftLongScoreDefinition;
import org.optaplanner.core.score.buildin.simple.SimpleScoreDefinition;
import org.optaplanner.core.score.buildin.simplebigdecimal.SimpleBigDecimalScoreDefinition;
import org.optaplanner.core.score.buildin.simpledouble.SimpleDoubleScoreDefinition;
import org.optaplanner.core.score.buildin.simplelong.SimpleLongScoreDefinition;
import org.optaplanner.core.score.definition.ScoreDefinition;
import org.optaplanner.core.score.director.AbstractScoreDirectorFactory;
import org.optaplanner.core.score.director.ScoreDirectorFactory;
import org.optaplanner.core.score.director.drools.DroolsScoreDirectorFactory;
import org.optaplanner.core.score.director.incremental.IncrementalScoreCalculator;
import org.optaplanner.core.score.director.incremental.IncrementalScoreDirectorFactory;
import org.optaplanner.core.score.director.simple.SimpleScoreCalculator;
import org.optaplanner.core.score.director.simple.SimpleScoreDirectorFactory;
@XStreamAlias("scoreDirectorFactory")
public class ScoreDirectorFactoryConfig {
protected Class<? extends ScoreDefinition> scoreDefinitionClass = null;
protected ScoreDefinitionType scoreDefinitionType = null;
protected Integer bendableHardLevelCount = null;
protected Integer bendableSoftLevelCount = null;
protected Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass = null;
protected Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass = null;
@XStreamOmitField
protected RuleBase ruleBase = null;
@XStreamImplicit(itemFieldName = "scoreDrl")
protected List<String> scoreDrlList = null;
@XStreamAlias("assertionScoreDirectorFactory")
protected ScoreDirectorFactoryConfig assertionScoreDirectorFactory = null;
public Class<? extends ScoreDefinition> getScoreDefinitionClass() {
return scoreDefinitionClass;
}
public void setScoreDefinitionClass(Class<? extends ScoreDefinition> scoreDefinitionClass) {
this.scoreDefinitionClass = scoreDefinitionClass;
}
public ScoreDefinitionType getScoreDefinitionType() {
return scoreDefinitionType;
}
public void setScoreDefinitionType(ScoreDefinitionType scoreDefinitionType) {
this.scoreDefinitionType = scoreDefinitionType;
}
public Integer getBendableHardLevelCount() {
return bendableHardLevelCount;
}
public void setBendableHardLevelCount(Integer bendableHardLevelCount) {
this.bendableHardLevelCount = bendableHardLevelCount;
}
public Integer getBendableSoftLevelCount() {
return bendableSoftLevelCount;
}
public void setBendableSoftLevelCount(Integer bendableSoftLevelCount) {
this.bendableSoftLevelCount = bendableSoftLevelCount;
}
public Class<? extends SimpleScoreCalculator> getSimpleScoreCalculatorClass() {
return simpleScoreCalculatorClass;
}
public void setSimpleScoreCalculatorClass(Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass) {
this.simpleScoreCalculatorClass = simpleScoreCalculatorClass;
}
public Class<? extends IncrementalScoreCalculator> getIncrementalScoreCalculatorClass() {
return incrementalScoreCalculatorClass;
}
public void setIncrementalScoreCalculatorClass(Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) {
this.incrementalScoreCalculatorClass = incrementalScoreCalculatorClass;
}
public RuleBase getRuleBase() {
return ruleBase;
}
public void setRuleBase(RuleBase ruleBase) {
this.ruleBase = ruleBase;
}
public List<String> getScoreDrlList() {
return scoreDrlList;
}
public void setScoreDrlList(List<String> scoreDrlList) {
this.scoreDrlList = scoreDrlList;
}
public ScoreDirectorFactoryConfig getAssertionScoreDirectorFactory() {
return assertionScoreDirectorFactory;
}
public void setAssertionScoreDirectorFactory(ScoreDirectorFactoryConfig assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
}
// ************************************************************************
// Builder methods
// ************************************************************************
public ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode,
SolutionDescriptor solutionDescriptor) {
ScoreDefinition scoreDefinition = buildScoreDefinition();
return buildScoreDirectorFactory(environmentMode, solutionDescriptor, scoreDefinition);
}
protected ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode,
SolutionDescriptor solutionDescriptor, ScoreDefinition scoreDefinition) {
AbstractScoreDirectorFactory scoreDirectorFactory;
// TODO this should fail-fast if multiple scoreDirectorFactory's are configured or if non are configured
scoreDirectorFactory = buildSimpleScoreDirectorFactory();
if (scoreDirectorFactory == null) {
scoreDirectorFactory = buildIncrementalScoreDirectorFactory();
}
if (scoreDirectorFactory == null) {
scoreDirectorFactory = buildDroolsScoreDirectorFactory();
}
scoreDirectorFactory.setSolutionDescriptor(solutionDescriptor);
scoreDirectorFactory.setScoreDefinition(scoreDefinition);
if (assertionScoreDirectorFactory != null) {
if (assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() != null) {
throw new IllegalArgumentException("A assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") cannot have a non-null assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() + ").");
}
if (assertionScoreDirectorFactory.getScoreDefinitionClass() != null
|| assertionScoreDirectorFactory.getScoreDefinitionType() != null) {
throw new IllegalArgumentException("A assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") must reuse the scoreDefinition of its parent." +
" It cannot have a non-null scoreDefinition* property.");
}
if (environmentMode.compareTo(EnvironmentMode.FAST_ASSERT) > 0) {
throw new IllegalArgumentException("A non-null assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") requires an environmentMode ("
+ environmentMode + ") of " + EnvironmentMode.FAST_ASSERT + " or lower.");
}
scoreDirectorFactory.setAssertionScoreDirectorFactory(
assertionScoreDirectorFactory.buildScoreDirectorFactory(
EnvironmentMode.PRODUCTION, solutionDescriptor, scoreDefinition));
}
return scoreDirectorFactory;
}
public ScoreDefinition buildScoreDefinition() {
if ((bendableHardLevelCount != null || bendableSoftLevelCount != null)
&& scoreDefinitionType != ScoreDefinitionType.BENDABLE) {
throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType
+ ") there must be no bendableHardLevelCount (" + bendableHardLevelCount
+ ") or bendableSoftLevelCount (" + bendableSoftLevelCount + ").");
}
if (scoreDefinitionClass != null) {
return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass);
} else if (scoreDefinitionType != null) {
switch (scoreDefinitionType) {
case SIMPLE:
return new SimpleScoreDefinition();
case SIMPLE_LONG:
return new SimpleLongScoreDefinition();
case SIMPLE_DOUBLE:
return new SimpleDoubleScoreDefinition();
case SIMPLE_BIG_DECIMAL:
return new SimpleBigDecimalScoreDefinition();
case HARD_SOFT:
return new HardSoftScoreDefinition();
case HARD_SOFT_LONG:
return new HardSoftLongScoreDefinition();
case HARD_SOFT_DOUBLE:
return new HardSoftDoubleScoreDefinition();
case HARD_SOFT_BIG_DECIMAL:
return new HardSoftBigDecimalScoreDefinition();
case HARD_MEDIUM_SOFT:
return new HardMediumSoftScoreDefinition();
case BENDABLE:
if (bendableHardLevelCount == null || bendableSoftLevelCount == null) {
throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType
+ ") there must be a bendableHardLevelCount (" + bendableHardLevelCount
+ ") and a bendableSoftLevelCount (" + bendableSoftLevelCount + ").");
}
return new BendableScoreDefinition(bendableHardLevelCount, bendableSoftLevelCount);
default:
throw new IllegalStateException("The scoreDefinitionType (" + scoreDefinitionType
+ ") is not implemented.");
}
} else {
return new SimpleScoreDefinition();
}
}
private AbstractScoreDirectorFactory buildSimpleScoreDirectorFactory() {
if (simpleScoreCalculatorClass != null) {
SimpleScoreCalculator simpleScoreCalculator = ConfigUtils.newInstance(this,
"simpleScoreCalculatorClass", simpleScoreCalculatorClass);
return new SimpleScoreDirectorFactory(simpleScoreCalculator);
} else {
return null;
}
}
private AbstractScoreDirectorFactory buildIncrementalScoreDirectorFactory() {
if (incrementalScoreCalculatorClass != null) {
return new IncrementalScoreDirectorFactory(incrementalScoreCalculatorClass);
} else {
return null;
}
}
private AbstractScoreDirectorFactory buildDroolsScoreDirectorFactory() {
DroolsScoreDirectorFactory scoreDirectorFactory = new DroolsScoreDirectorFactory();
scoreDirectorFactory.setRuleBase(buildRuleBase());
return scoreDirectorFactory;
}
private RuleBase buildRuleBase() {
if (ruleBase != null) {
if (!CollectionUtils.isEmpty(scoreDrlList)) {
throw new IllegalArgumentException("If ruleBase is not null, the scoreDrlList (" + scoreDrlList
+ ") must be empty.");
}
return ruleBase;
} else {
PackageBuilder packageBuilder = new PackageBuilder();
for (String scoreDrl : scoreDrlList) {
InputStream scoreDrlIn = getClass().getResourceAsStream(scoreDrl);
if (scoreDrlIn == null) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl
+ ") does not exist as a classpath resource.");
}
try {
packageBuilder.addPackageFromDrl(new InputStreamReader(scoreDrlIn, "UTF-8"));
} catch (DroolsParserException e) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") could not be loaded.", e);
} catch (IOException e) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") could not be loaded.", e);
} finally {
IOUtils.closeQuietly(scoreDrlIn);
}
}
RuleBaseConfiguration ruleBaseConfiguration = new RuleBaseConfiguration();
RuleBase ruleBase = RuleBaseFactory.newRuleBase(ruleBaseConfiguration);
if (packageBuilder.hasErrors()) {
throw new IllegalStateException("There are errors in the scoreDrl's:\n"
+ packageBuilder.getErrors().toString());
}
ruleBase.addPackage(packageBuilder.getPackage());
return ruleBase;
}
}
public void inherit(ScoreDirectorFactoryConfig inheritedConfig) {
if (scoreDefinitionClass == null && scoreDefinitionType == null
&& bendableHardLevelCount == null && bendableSoftLevelCount == null) {
scoreDefinitionClass = inheritedConfig.getScoreDefinitionClass();
scoreDefinitionType = inheritedConfig.getScoreDefinitionType();
bendableHardLevelCount = inheritedConfig.getBendableHardLevelCount();
bendableSoftLevelCount = inheritedConfig.getBendableSoftLevelCount();
}
if (simpleScoreCalculatorClass == null) {
simpleScoreCalculatorClass = inheritedConfig.getSimpleScoreCalculatorClass();
}
if (incrementalScoreCalculatorClass == null) {
incrementalScoreCalculatorClass = inheritedConfig.getIncrementalScoreCalculatorClass();
}
if (ruleBase == null) {
ruleBase = inheritedConfig.getRuleBase();
}
scoreDrlList = ConfigUtils.inheritMergeableListProperty(
scoreDrlList, inheritedConfig.getScoreDrlList());
if (assertionScoreDirectorFactory == null) {
assertionScoreDirectorFactory = inheritedConfig.getAssertionScoreDirectorFactory();
}
}
public static enum ScoreDefinitionType {
SIMPLE,
SIMPLE_LONG,
SIMPLE_DOUBLE,
SIMPLE_BIG_DECIMAL,
HARD_SOFT,
HARD_SOFT_LONG,
HARD_SOFT_DOUBLE,
HARD_SOFT_BIG_DECIMAL,
HARD_MEDIUM_SOFT,
BENDABLE,
}
}
| optaplanner-core/src/main/java/org/optaplanner/config/score/director/ScoreDirectorFactoryConfig.java | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.config.score.director;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.drools.RuleBase;
import org.drools.RuleBaseConfiguration;
import org.drools.RuleBaseFactory;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.optaplanner.config.EnvironmentMode;
import org.optaplanner.config.util.ConfigUtils;
import org.optaplanner.core.domain.solution.SolutionDescriptor;
import org.optaplanner.core.score.buildin.bendable.BendableScoreDefinition;
import org.optaplanner.core.score.buildin.hardmediumsoft.HardMediumSoftScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoft.HardSoftScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftdouble.HardSoftDoubleScoreDefinition;
import org.optaplanner.core.score.buildin.hardsoftlong.HardSoftLongScoreDefinition;
import org.optaplanner.core.score.buildin.simple.SimpleScoreDefinition;
import org.optaplanner.core.score.buildin.simplebigdecimal.SimpleBigDecimalScoreDefinition;
import org.optaplanner.core.score.buildin.simpledouble.SimpleDoubleScoreDefinition;
import org.optaplanner.core.score.buildin.simplelong.SimpleLongScoreDefinition;
import org.optaplanner.core.score.definition.ScoreDefinition;
import org.optaplanner.core.score.director.AbstractScoreDirectorFactory;
import org.optaplanner.core.score.director.ScoreDirectorFactory;
import org.optaplanner.core.score.director.drools.DroolsScoreDirectorFactory;
import org.optaplanner.core.score.director.incremental.IncrementalScoreCalculator;
import org.optaplanner.core.score.director.incremental.IncrementalScoreDirectorFactory;
import org.optaplanner.core.score.director.simple.SimpleScoreCalculator;
import org.optaplanner.core.score.director.simple.SimpleScoreDirectorFactory;
@XStreamAlias("scoreDirectorFactory")
public class ScoreDirectorFactoryConfig {
protected Class<? extends ScoreDefinition> scoreDefinitionClass = null;
protected ScoreDefinitionType scoreDefinitionType = null;
protected Integer bendableHardLevelCount = null;
protected Integer bendableSoftLevelCount = null;
protected Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass = null;
protected Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass = null;
@XStreamOmitField
protected RuleBase ruleBase = null;
@XStreamImplicit(itemFieldName = "scoreDrl")
protected List<String> scoreDrlList = null;
@XStreamAlias("assertionScoreDirectorFactory")
protected ScoreDirectorFactoryConfig assertionScoreDirectorFactory = null;
public Class<? extends ScoreDefinition> getScoreDefinitionClass() {
return scoreDefinitionClass;
}
public void setScoreDefinitionClass(Class<? extends ScoreDefinition> scoreDefinitionClass) {
this.scoreDefinitionClass = scoreDefinitionClass;
}
public ScoreDefinitionType getScoreDefinitionType() {
return scoreDefinitionType;
}
public void setScoreDefinitionType(ScoreDefinitionType scoreDefinitionType) {
this.scoreDefinitionType = scoreDefinitionType;
}
public Integer getBendableHardLevelCount() {
return bendableHardLevelCount;
}
public void setBendableHardLevelCount(Integer bendableHardLevelCount) {
this.bendableHardLevelCount = bendableHardLevelCount;
}
public Integer getBendableSoftLevelCount() {
return bendableSoftLevelCount;
}
public void setBendableSoftLevelCount(Integer bendableSoftLevelCount) {
this.bendableSoftLevelCount = bendableSoftLevelCount;
}
public Class<? extends SimpleScoreCalculator> getSimpleScoreCalculatorClass() {
return simpleScoreCalculatorClass;
}
public void setSimpleScoreCalculatorClass(Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass) {
this.simpleScoreCalculatorClass = simpleScoreCalculatorClass;
}
public Class<? extends IncrementalScoreCalculator> getIncrementalScoreCalculatorClass() {
return incrementalScoreCalculatorClass;
}
public void setIncrementalScoreCalculatorClass(Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) {
this.incrementalScoreCalculatorClass = incrementalScoreCalculatorClass;
}
public RuleBase getRuleBase() {
return ruleBase;
}
public void setRuleBase(RuleBase ruleBase) {
this.ruleBase = ruleBase;
}
public List<String> getScoreDrlList() {
return scoreDrlList;
}
public void setScoreDrlList(List<String> scoreDrlList) {
this.scoreDrlList = scoreDrlList;
}
public ScoreDirectorFactoryConfig getAssertionScoreDirectorFactory() {
return assertionScoreDirectorFactory;
}
public void setAssertionScoreDirectorFactory(ScoreDirectorFactoryConfig assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
}
// ************************************************************************
// Builder methods
// ************************************************************************
public ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode,
SolutionDescriptor solutionDescriptor) {
ScoreDefinition scoreDefinition = buildScoreDefinition();
return buildScoreDirectorFactory(environmentMode, solutionDescriptor, scoreDefinition);
}
protected ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode,
SolutionDescriptor solutionDescriptor, ScoreDefinition scoreDefinition) {
AbstractScoreDirectorFactory scoreDirectorFactory;
// TODO this should fail-fast if multiple scoreDirectorFactory's are configured or if non are configured
scoreDirectorFactory = buildSimpleScoreDirectorFactory();
if (scoreDirectorFactory == null) {
scoreDirectorFactory = buildIncrementalScoreDirectorFactory();
}
if (scoreDirectorFactory == null) {
scoreDirectorFactory = buildDroolsScoreDirectorFactory();
}
scoreDirectorFactory.setSolutionDescriptor(solutionDescriptor);
scoreDirectorFactory.setScoreDefinition(scoreDefinition);
if (assertionScoreDirectorFactory != null) {
if (assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() != null) {
throw new IllegalArgumentException("A assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") cannot have a non-null assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() + ").");
}
if (assertionScoreDirectorFactory.getScoreDefinitionClass() != null
|| assertionScoreDirectorFactory.getScoreDefinitionType() != null) {
throw new IllegalArgumentException("A assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") must reuse the scoreDefinition of its parent." +
" It cannot have a non-null scoreDefinition* property.");
}
if (environmentMode.compareTo(EnvironmentMode.FAST_ASSERT) > 0) {
throw new IllegalArgumentException("A non-null assertionScoreDirectorFactory ("
+ assertionScoreDirectorFactory + ") requires an environmentMode ("
+ environmentMode + ") of " + EnvironmentMode.FAST_ASSERT + " or lower.");
}
scoreDirectorFactory.setAssertionScoreDirectorFactory(
assertionScoreDirectorFactory.buildScoreDirectorFactory(
EnvironmentMode.PRODUCTION, solutionDescriptor, scoreDefinition));
}
return scoreDirectorFactory;
}
public ScoreDefinition buildScoreDefinition() {
if ((bendableHardLevelCount != null || bendableSoftLevelCount != null)
&& scoreDefinitionType != ScoreDefinitionType.BENDABLE) {
throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType
+ ") there must be no bendableHardLevelCount (" + bendableHardLevelCount
+ ") or bendableSoftLevelCount (" + bendableSoftLevelCount + ").");
}
if (scoreDefinitionClass != null) {
return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass);
} else if (scoreDefinitionType != null) {
switch (scoreDefinitionType) {
case SIMPLE:
return new SimpleScoreDefinition();
case SIMPLE_LONG:
return new SimpleLongScoreDefinition();
case SIMPLE_DOUBLE:
return new SimpleDoubleScoreDefinition();
case SIMPLE_BIG_DECIMAL:
return new SimpleBigDecimalScoreDefinition();
case HARD_SOFT:
return new HardSoftScoreDefinition();
case HARD_SOFT_LONG:
return new HardSoftLongScoreDefinition();
case HARD_SOFT_DOUBLE:
return new HardSoftDoubleScoreDefinition();
case HARD_SOFT_BIG_DECIMAL:
return new HardSoftBigDecimalScoreDefinition();
case HARD_MEDIUM_SOFT:
return new HardMediumSoftScoreDefinition();
case BENDABLE:
if (bendableHardLevelCount == null || bendableSoftLevelCount == null) {
throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType
+ ") there must be a bendableHardLevelCount (" + bendableHardLevelCount
+ ") and a bendableSoftLevelCount (" + bendableSoftLevelCount + ").");
}
return new BendableScoreDefinition(bendableHardLevelCount, bendableSoftLevelCount);
default:
throw new IllegalStateException("The scoreDefinitionType (" + scoreDefinitionType
+ ") is not implemented.");
}
} else {
return new SimpleScoreDefinition();
}
}
private AbstractScoreDirectorFactory buildSimpleScoreDirectorFactory() {
if (simpleScoreCalculatorClass != null) {
SimpleScoreCalculator simpleScoreCalculator = ConfigUtils.newInstance(this,
"simpleScoreCalculatorClass", simpleScoreCalculatorClass);
return new SimpleScoreDirectorFactory(simpleScoreCalculator);
} else {
return null;
}
}
private AbstractScoreDirectorFactory buildIncrementalScoreDirectorFactory() {
if (incrementalScoreCalculatorClass != null) {
return new IncrementalScoreDirectorFactory(incrementalScoreCalculatorClass);
} else {
return null;
}
}
private AbstractScoreDirectorFactory buildDroolsScoreDirectorFactory() {
DroolsScoreDirectorFactory scoreDirectorFactory = new DroolsScoreDirectorFactory();
scoreDirectorFactory.setRuleBase(buildRuleBase());
return scoreDirectorFactory;
}
private RuleBase buildRuleBase() {
if (ruleBase != null) {
if (!CollectionUtils.isEmpty(scoreDrlList)) {
throw new IllegalArgumentException("If ruleBase is not null, the scoreDrlList (" + scoreDrlList
+ ") must be empty.");
}
return ruleBase;
} else {
PackageBuilder packageBuilder = new PackageBuilder();
for (String scoreDrl : scoreDrlList) {
InputStream scoreDrlIn = getClass().getResourceAsStream(scoreDrl);
if (scoreDrlIn == null) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl
+ ") does not exist as a classpath resource.");
}
try {
packageBuilder.addPackageFromDrl(new InputStreamReader(scoreDrlIn, "UTF-8"));
} catch (DroolsParserException e) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") could not be loaded.", e);
} catch (IOException e) {
throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") could not be loaded.", e);
} finally {
IOUtils.closeQuietly(scoreDrlIn);
}
}
RuleBaseConfiguration ruleBaseConfiguration = new RuleBaseConfiguration();
RuleBase ruleBase = RuleBaseFactory.newRuleBase(ruleBaseConfiguration);
if (packageBuilder.hasErrors()) {
throw new IllegalStateException("There are errors in the scoreDrl's:\n"
+ packageBuilder.getErrors().toString());
}
ruleBase.addPackage(packageBuilder.getPackage());
return ruleBase;
}
}
public void inherit(ScoreDirectorFactoryConfig inheritedConfig) {
if (scoreDefinitionClass == null && scoreDefinitionType == null
&& bendableHardLevelCount == null && bendableSoftLevelCount == null) {
scoreDefinitionClass = inheritedConfig.getScoreDefinitionClass();
scoreDefinitionType = inheritedConfig.getScoreDefinitionType();
bendableHardLevelCount = inheritedConfig.getBendableHardLevelCount();
bendableSoftLevelCount = inheritedConfig.getBendableSoftLevelCount();
}
if (simpleScoreCalculatorClass == null) {
simpleScoreCalculatorClass = inheritedConfig.getSimpleScoreCalculatorClass();
}
if (incrementalScoreCalculatorClass == null) {
incrementalScoreCalculatorClass = inheritedConfig.getIncrementalScoreCalculatorClass();
}
if (ruleBase == null) {
ruleBase = inheritedConfig.getRuleBase();
}
scoreDrlList = ConfigUtils.inheritMergeableListProperty(
scoreDrlList, inheritedConfig.getScoreDrlList());
if (assertionScoreDirectorFactory == null) {
assertionScoreDirectorFactory = inheritedConfig.getAssertionScoreDirectorFactory();
}
}
public static enum ScoreDefinitionType {
SIMPLE,
SIMPLE_LONG,
SIMPLE_DOUBLE,
SIMPLE_BIG_DECIMAL,
HARD_SOFT,
HARD_SOFT_LONG,
HARD_SOFT_DOUBLE,
HARD_SOFT_BIG_DECIMAL,
HARD_MEDIUM_SOFT,
BENDABLE,
}
}
| Resolve split-packages: move everything from drools-compiler under org.drools.compiler: first move org.drools.compiler under org.drools.compiler.compiler to avoid a mess
| optaplanner-core/src/main/java/org/optaplanner/config/score/director/ScoreDirectorFactoryConfig.java | Resolve split-packages: move everything from drools-compiler under org.drools.compiler: first move org.drools.compiler under org.drools.compiler.compiler to avoid a mess | <ide><path>ptaplanner-core/src/main/java/org/optaplanner/config/score/director/ScoreDirectorFactoryConfig.java
<ide> import org.drools.RuleBase;
<ide> import org.drools.RuleBaseConfiguration;
<ide> import org.drools.RuleBaseFactory;
<del>import org.drools.compiler.DroolsParserException;
<del>import org.drools.compiler.PackageBuilder;
<add>import org.drools.compiler.compiler.DroolsParserException;
<add>import org.drools.compiler.compiler.PackageBuilder;
<ide> import org.optaplanner.config.EnvironmentMode;
<ide> import org.optaplanner.config.util.ConfigUtils;
<ide> import org.optaplanner.core.domain.solution.SolutionDescriptor; |
|
Java | agpl-3.0 | 5afa33a5d381b28a6600602367f723ff3f4099f7 | 0 | imujjwal96/Brime,BrimeNotes/android | package com.procleus.brime.login;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.procleus.brime.ui.MainActivity;
import com.procleus.brime.R;
import com.procleus.brime.utils.CustomButton;
import com.procleus.brime.utils.CustomEditText;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.basgeekball.awesomevalidation.ValidationStyle.UNDERLABEL;
public class SigninActivity extends AppCompatActivity {
public static final String PREF = "com.procleus.brime";
public static final String emailpref = "null";
public static final String passwordpref = "nopassKey";
public static final String loggedin = "IsLoggedIn";
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "SignInActivity";
public SharedPreferences session;
private String msg;
Location mLastLocation = null;
String longi, lati;
ProgressDialog progressDialog;
int responseOp;
CustomButton b ;
CustomEditText etun, etpass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
etun = (CustomEditText) findViewById(R.id.editText);
etpass = (CustomEditText) findViewById(R.id.editText2);
CustomButton stl_btn = (CustomButton) findViewById(R.id.stl_btn);
stl_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(SigninActivity.this, MainActivity.class);
startActivity(i);
finish();
}
});
CustomButton btlog = (CustomButton) findViewById(R.id.log_btn);
btlog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!clientValidation(etun.getText().toString(),etpass.getText().toString())){
return ;
}
progressDialog = new ProgressDialog(SigninActivity.this, R.style.Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Login ...");
logIn( etun.getText().toString(),etpass.getText().toString());
}
});
}
/* * Converts Byte to Hexadecimal
* @param data Byte data
* @return hexadecimal data
public static String convertByteToHex(byte data[]) {
StringBuffer hexData = new StringBuffer();
for (int byteIndex = 0; byteIndex < data.length; byteIndex++) {
hexData.append(Integer.toString((data[byteIndex] & 0xff) + 0x100, 16).substring(1));
}
return hexData.toString();
}
*/
/*
* Encrypts a text
* @param textToHash text to be encrypted
* @return encrypted text
public static String hashText(String textToHash) {
try {
final MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
sha512.update(textToHash.getBytes());
return convertByteToHex(sha512.digest());
} catch (Exception e) {
return textToHash;
}
}*/
public void logIn(String user, String pass) {
progressDialog.show();
final String userid=user;
final String password=pass;
String loginurl = "http://brime.ml/user/login";
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(Request.Method.POST, loginurl,
new Response.Listener<String>()
//JsonObjectRequest req = new JsonObjectRequest(loginurl, new JSONObject(params), new Response.Listener<JSONObject>()
{
@Override
public void onResponse(String response) {
try{
JSONObject reader= new JSONObject(response);
msg = reader.get("message").toString();
if (msg.equals("User logged in successfully.")) {
responseOp = 1;
session = getSharedPreferences(PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = session.edit();
//editor.putString(ID, );
editor.putString("emailpref", userid);
editor.putString("passwordpref",password);
editor.putBoolean("loggedin", true);
editor.apply();
onLogInSuccess();
}
Log.i("Message",msg);
}catch (JSONException e){
e.printStackTrace();
}
progressDialog.dismiss();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(getApplicationContext(),"Login Failed !", Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
progressDialog.dismiss();
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("uid", userid);
params.put("password",password);
return params;
}
};
requestQueue.add(req);
}
public boolean clientValidation(String uid,String pass) {
boolean legal = true;
if (uid.isEmpty()) {
legal = false;
etun.setError("Username can not be empty");
} else {
etun.setError(null);
}
if(pass.isEmpty()){
legal=false;
etpass.setError("Password can not be empty");
}else{
etpass.setError(null);
}
return legal;
}
public void onLogInSuccess() {
notif(1);
Toast.makeText(getBaseContext(), "Logged in successfully", Toast.LENGTH_LONG).show();
finish();
Intent i = new Intent(SigninActivity.this, MainActivity.class);
startActivity(i);
}
public void onLogInFailed(String error) {
notif(2);
Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show();
}
/* @Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
longi = String.valueOf(mLastLocation.getLatitude());
lati = String.valueOf(mLastLocation.getLongitude());
}
}
*/
public void notif(int id) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.logo);
if(id==1)
mBuilder.setContentTitle("Log in Successful");
else
mBuilder.setContentTitle("Log in Failed");
mBuilder.setContentText("Logged in from " + longi + " , " + lati);
mBuilder.setSmallIcon(R.drawable.logo);
int mNotificationId = 4848;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
| app/src/main/java/com/procleus/brime/login/SigninActivity.java | package com.procleus.brime.login;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.procleus.brime.ui.MainActivity;
import com.procleus.brime.R;
import com.procleus.brime.utils.CustomButton;
import com.procleus.brime.utils.CustomEditText;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.basgeekball.awesomevalidation.ValidationStyle.UNDERLABEL;
public class SigninActivity extends AppCompatActivity {
public static final String PREF = "com.procleus.brime";
public static final String emailpref = "null";
public static final String passwordpref = "nopassKey";
public static final String loggedin = "IsLoggedIn";
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "SignInActivity";
public SharedPreferences session;
private String msg;
Location mLastLocation = null;
String longi, lati;
ProgressDialog progressDialog;
int responseOp;
CustomButton b ;
CustomEditText etun, etpass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
etun = (CustomEditText) findViewById(R.id.editText);
etpass = (CustomEditText) findViewById(R.id.editText2);
CustomButton stl_btn = (CustomButton) findViewById(R.id.stl_btn);
stl_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(SigninActivity.this, MainActivity.class);
startActivity(i);
finish();
}
});
CustomButton btlog = (CustomButton) findViewById(R.id.log_btn);
btlog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!cvalidate(etun.getText().toString(),etpass.getText().toString())){
return ;
}
progressDialog = new ProgressDialog(SigninActivity.this, R.style.Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Login ...");
logIn( etun.getText().toString(),etpass.getText().toString());
}
});
}
/* * Converts Byte to Hexadecimal
* @param data Byte data
* @return hexadecimal data
public static String convertByteToHex(byte data[]) {
StringBuffer hexData = new StringBuffer();
for (int byteIndex = 0; byteIndex < data.length; byteIndex++) {
hexData.append(Integer.toString((data[byteIndex] & 0xff) + 0x100, 16).substring(1));
}
return hexData.toString();
}
*/
/*
* Encrypts a text
* @param textToHash text to be encrypted
* @return encrypted text
public static String hashText(String textToHash) {
try {
final MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
sha512.update(textToHash.getBytes());
return convertByteToHex(sha512.digest());
} catch (Exception e) {
return textToHash;
}
}*/
public void logIn(String user, String pass) {
progressDialog.show();
final String userid=user;
final String password=pass;
String loginurl = "http://brime.ml/user/login";
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(Request.Method.POST, loginurl,
new Response.Listener<String>()
//JsonObjectRequest req = new JsonObjectRequest(loginurl, new JSONObject(params), new Response.Listener<JSONObject>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response:mba", response);
try{
JSONObject reader= new JSONObject(response);
msg = reader.get("message").toString();
if (msg.equals("User logged in successfully.")) {
responseOp = 1;
session = getSharedPreferences(PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = session.edit();
//editor.putString(ID, );
editor.putString("emailpref", userid);
editor.putString("passwordpref",password);
editor.putBoolean("loggedin", true);
editor.apply();
onLogInSuccess();
}
Log.i("Message",msg);
}catch (JSONException e){
e.printStackTrace();
}
progressDialog.dismiss();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Log.i("fuckoff:",obj.toString());
Toast.makeText(getApplicationContext(),"Login Failed !", Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
progressDialog.dismiss();
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("uid", userid);
params.put("password",password);
return params;
}
};
requestQueue.add(req);
}
public boolean cvalidate(String uid,String pass) {
boolean legal = true;
if (uid.isEmpty()) {
legal = false;
etun.setError("Username can not be empty");
} else {
etun.setError(null);
}
if(pass.isEmpty()){
legal=false;
etpass.setError("Password can not be empty");
}else{
etpass.setError(null);
}
return legal;
}
public void onLogInSuccess() {
notif(1);
Toast.makeText(getBaseContext(), "Logged in successfully", Toast.LENGTH_LONG).show();
finish();
Intent i = new Intent(SigninActivity.this, MainActivity.class);
startActivity(i);
}
public void onLogInFailed(String error) {
notif(2);
Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show();
}
/* @Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
longi = String.valueOf(mLastLocation.getLatitude());
lati = String.valueOf(mLastLocation.getLongitude());
}
}
*/
public void notif(int id) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.logo);
if(id==1)
mBuilder.setContentTitle("Log in Successful");
else
mBuilder.setContentTitle("Log in Failed");
mBuilder.setContentText("Logged in from " + longi + " , " + lati);
mBuilder.setSmallIcon(R.drawable.logo);
int mNotificationId = 4848;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
| Refractor function name
| app/src/main/java/com/procleus/brime/login/SigninActivity.java | Refractor function name | <ide><path>pp/src/main/java/com/procleus/brime/login/SigninActivity.java
<ide> import java.util.Map;
<ide> import static com.basgeekball.awesomevalidation.ValidationStyle.UNDERLABEL;
<ide>
<del>
<ide> public class SigninActivity extends AppCompatActivity {
<ide> public static final String PREF = "com.procleus.brime";
<ide> public static final String emailpref = "null";
<ide> btlog.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View v) {
<del> if(!cvalidate(etun.getText().toString(),etpass.getText().toString())){
<add> if(!clientValidation(etun.getText().toString(),etpass.getText().toString())){
<ide> return ;
<ide> }
<ide> progressDialog = new ProgressDialog(SigninActivity.this, R.style.Dialog);
<ide> {
<ide> @Override
<ide> public void onResponse(String response) {
<del> // response
<del> Log.d("Response:mba", response);
<add>
<ide> try{
<ide> JSONObject reader= new JSONObject(response);
<ide> msg = reader.get("message").toString();
<ide> HttpHeaderParser.parseCharset(response.headers, "utf-8"));
<ide> // Now you can use any deserializer to make sense of data
<ide> JSONObject obj = new JSONObject(res);
<del> Log.i("fuckoff:",obj.toString());
<ide> Toast.makeText(getApplicationContext(),"Login Failed !", Toast.LENGTH_LONG).show();
<ide> } catch (UnsupportedEncodingException e1) {
<ide> // Couldn't properly decode data to string
<ide>
<ide> }
<ide>
<del> public boolean cvalidate(String uid,String pass) {
<add> public boolean clientValidation(String uid,String pass) {
<ide> boolean legal = true;
<ide> if (uid.isEmpty()) {
<ide> legal = false; |
|
Java | lgpl-2.1 | 67402693ed52cb577dd1a0167a12d9ade30ef5f3 | 0 | sbonoc/opencms-core,alkacon/opencms-core,victos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,gallardo/opencms-core,serrapos/opencms-core,alkacon/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,victos/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,victos/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,victos/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsUUID.java,v $
* Date : $Date: 2005/09/06 15:25:20 $
* Version: $Revision: 1.19 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.util;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsInitException;
import org.opencms.main.CmsRuntimeException;
import java.io.Serializable;
import org.doomdark.uuid.EthernetAddress;
import org.doomdark.uuid.UUID;
import org.doomdark.uuid.UUIDGenerator;
/**
* Generates a UUID using spatial and temporal uniqueness.<p>
*
* Spatial uniqueness is derived from
* ethernet address (MAC, 802.1); temporal from system clock.<p>
*
* For more information about the algorithm used, please see
* <a href="http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt">
* draft-leach-uuids-guids-01.txt</a>.<p>
*
* Because Java is unable to read the MAC address of the machine
* (without using JNI), the MAC address has to be provided first
* by using the static {@link #init(String)} method.<p>
*
* This class is just a facade wrapper for the "real" UUID implementation.<p>
*
* @author Alexander Kandzior
*
* @version $Revision: 1.19 $
*
* @since 6.0.0
*/
public final class CmsUUID extends Object implements Serializable, Cloneable, Comparable {
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = 1726324354709298575L;
/** Ethernet addess of the server machine. */
private static EthernetAddress m_ethernetAddress;
/** Flag to indicate if the ethernet address has been initialized. */
private static boolean m_isNotInitialized = true;
/** OpenCms UUID (name based uuid of "www.opencms.org" in the dns name space). */
private static UUID m_opencmsUUID = UUIDGenerator.getInstance().generateNameBasedUUID(
new UUID(UUID.NAMESPACE_DNS),
"www.opencms.org");
/** Constant for the null UUID. */
private static final CmsUUID NULL_UUID = new CmsUUID(UUID.getNullUUID());
/** Internal UUID implementation. */
private UUID m_uuid;
/**
* Creates a new UUID.<p>
*
* Please note that the static init() method has to be called first to initialize the
* enternet address of the machine.<p>
*/
public CmsUUID() {
synchronized (this) {
if (m_isNotInitialized) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_INVALID_ETHERNET_ADDRESS_0));
}
m_uuid = UUIDGenerator.getInstance().generateTimeBasedUUID(m_ethernetAddress);
}
}
/**
* Create a UUID based on a binary data array.<p>
*
* @param data a binary data array representing a UUID
*/
public CmsUUID(byte[] data) {
m_uuid = new UUID(data);
}
/**
* Create a UUID based on a String.<p>
*
* @param uuid a String representing a UUID
* @throws NumberFormatException in case uuid is not a valid UUID
*/
public CmsUUID(String uuid)
throws NumberFormatException {
m_uuid = new UUID(uuid);
}
/**
* Create a new UUID based on another one (used internal for cloning).<p>
*
* @param uuid the UUID to clone
*/
private CmsUUID(UUID uuid) {
m_uuid = uuid;
}
/**
* Check that the given id is not the null id.<p>
*
* @param id the id to check
* @param canBeNull only if flag is set, <code>null</code> is accepted
*
* @see #isNullUUID()
*/
public static void checkId(CmsUUID id, boolean canBeNull) {
if (canBeNull && id == null) {
return;
}
if ((!canBeNull && id == null) || id.isNullUUID()) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_INVALID_UUID_1, id));
}
}
/**
* Returns a constant (name based) UUID,
* based on the given name in the OpenCms name space.
*
* @param name the name to derive the uuid from
* @return name based UUID of the given name
*/
public static CmsUUID getConstantUUID(String name) {
return new CmsUUID(UUIDGenerator.getInstance().generateNameBasedUUID(m_opencmsUUID, name));
}
/**
* Returns a String representing a dummy (random based) ethernet address.<p>
*
* @return a String representing a dummy (random based) ethernet address
*/
public static String getDummyEthernetAddress() {
return UUIDGenerator.getInstance().getDummyAddress().toString();
}
/**
* Returns a null UUID,
* use this null UUID to check if a UUID has been initilized or not.<p>
*
* @return a null UUID
*/
public static CmsUUID getNullUUID() {
return NULL_UUID;
}
/**
* Returns a constant (name based) UUID for OpenCms,
* based on "www.opencms.org" in the dns name space.
*
* @return name based UUID of OpenCms
*/
public static CmsUUID getOpenCmsUUID() {
return new CmsUUID(m_opencmsUUID);
}
/**
* Initialize the UUID generator with the ethernet address of the server machine.<p>
*
* The ethernetAddress parameter must represent a 'standard' ethernet MAC address string
* (e.g. '00:C0:F0:3D:5B:7C').
*
* @param ethernetAddress the ethernet address of the server machine
* @throws CmsInitException in case the ethernetAddress String is not a valid ethernet address
*/
public static void init(String ethernetAddress) throws CmsInitException {
try {
m_ethernetAddress = new EthernetAddress(ethernetAddress);
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(
Messages.ERR_INVALID_ETHERNET_ADDRESS_1,
ethernetAddress));
}
m_isNotInitialized = false;
}
/**
* Creates a clone of this CmsUUID.<p>
*
* @return a clone of this CmsUUID
*/
public Object clone() {
if (this == NULL_UUID) {
return NULL_UUID;
}
return new CmsUUID((UUID)m_uuid.clone());
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object obj) {
if (obj instanceof CmsUUID) {
return m_uuid.compareTo(((CmsUUID)obj).m_uuid);
}
return 0;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof CmsUUID) {
return ((CmsUUID)obj).m_uuid.equals(m_uuid);
}
return false;
}
/**
* Optimized hashCode implementation for UUID's.<p>
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return m_uuid.hashCode();
}
/**
* Returns true if this UUID is equal to the null UUID.<p>
*
* @return true if this UUID is equal to the null UUID
*/
public boolean isNullUUID() {
if (this == NULL_UUID) {
return true;
}
return m_uuid.equals(UUID.getNullUUID());
}
/**
* Returns the UUID as a 16-byte byte array.<p>
*
* @return 16-byte byte array that contains the UUID's bytes in the network byte order
*/
public byte[] toByteArray() {
return m_uuid.toByteArray();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return m_uuid.toString();
}
} | src/org/opencms/util/CmsUUID.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsUUID.java,v $
* Date : $Date: 2005/07/03 09:41:53 $
* Version: $Revision: 1.18 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.util;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsInitException;
import org.opencms.main.CmsRuntimeException;
import java.io.Serializable;
import org.doomdark.uuid.EthernetAddress;
import org.doomdark.uuid.UUID;
import org.doomdark.uuid.UUIDGenerator;
/**
* Generates a UUID using spatial and temporal uniqueness.<p>
*
* Spatial uniqueness is derived from
* ethernet address (MAC, 802.1); temporal from system clock.<p>
*
* For more information about the algorith used, please see
* <a href="http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt">
* draft-leach-uuids-guids-01.txt</a>.<p>
*
* Because Java is unable to read the MAC address of the machine
* (without using JNI), the MAC address has to be provided first
* by using the static {@link #init(String)} method.<p>
*
* This class is just a facade wrapper for the "real" UUID implementation.<p>
*
* @author Alexander Kandzior
*
* @version $Revision: 1.18 $
*
* @since 6.0.0
*/
public final class CmsUUID extends Object implements Serializable, Cloneable, Comparable {
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = 1726324354709298575L;
/** Ethernet addess of the server machine. */
private static EthernetAddress m_ethernetAddress;
/** Flag to indicate if the ethernet address has been initialized. */
private static boolean m_isNotInitialized = true;
/** OpenCms UUID (name based uuid of "www.opencms.org" in the dns name space). */
private static UUID m_opencmsUUID = UUIDGenerator.getInstance().generateNameBasedUUID(
new UUID(UUID.NAMESPACE_DNS),
"www.opencms.org");
/** Constant for the null UUID. */
private static final CmsUUID NULL_UUID = new CmsUUID(UUID.getNullUUID());
/** Internal UUID implementation. */
private UUID m_uuid;
/**
* Creates a new UUID.<p>
*
* Please note that the static init() method has to be called first to initialize the
* enternet address of the machine.<p>
*/
public CmsUUID() {
synchronized (this) {
if (m_isNotInitialized) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_INVALID_ETHERNET_ADDRESS_0));
}
m_uuid = UUIDGenerator.getInstance().generateTimeBasedUUID(m_ethernetAddress);
}
}
/**
* Create a UUID based on a binary data array.<p>
*
* @param data a binary data array representing a UUID
*/
public CmsUUID(byte[] data) {
m_uuid = new UUID(data);
}
/**
* Create a UUID based on a String.<p>
*
* @param uuid a String representing a UUID
* @throws NumberFormatException in case uuid is not a valid UUID
*/
public CmsUUID(String uuid)
throws NumberFormatException {
m_uuid = new UUID(uuid);
}
/**
* Create a new UUID based on another one (used internal for cloning).<p>
*
* @param uuid the UUID to clone
*/
private CmsUUID(UUID uuid) {
m_uuid = uuid;
}
/**
* Check that the given id is not the null id.<p>
*
* @param id the id to check
* @param canBeNull only if flag is set, <code>null</code> is accepted
*
* @see #isNullUUID()
*/
public static void checkId(CmsUUID id, boolean canBeNull) {
if (canBeNull && id == null) {
return;
}
if ((!canBeNull && id == null) || id.isNullUUID()) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_INVALID_UUID_1, id));
}
}
/**
* Returns a constant (name based) UUID,
* based on the given name in the OpenCms name space.
*
* @param name the name to derive the uuid from
* @return name based UUID of the given name
*/
public static CmsUUID getConstantUUID(String name) {
return new CmsUUID(UUIDGenerator.getInstance().generateNameBasedUUID(m_opencmsUUID, name));
}
/**
* Returns a String representing a dummy (random based) ethernet address.<p>
*
* @return a String representing a dummy (random based) ethernet address
*/
public static String getDummyEthernetAddress() {
return UUIDGenerator.getInstance().getDummyAddress().toString();
}
/**
* Returns a null UUID,
* use this null UUID to check if a UUID has been initilized or not.<p>
*
* @return a null UUID
*/
public static CmsUUID getNullUUID() {
return NULL_UUID;
}
/**
* Returns a constant (name based) UUID for OpenCms,
* based on "www.opencms.org" in the dns name space.
*
* @return name based UUID of OpenCms
*/
public static CmsUUID getOpenCmsUUID() {
return new CmsUUID(m_opencmsUUID);
}
/**
* Initialize the UUID generator with the ethernet address of the server machine.<p>
*
* The ethernetAddress parameter must represent a 'standard' ethernet MAC address string
* (e.g. '00:C0:F0:3D:5B:7C').
*
* @param ethernetAddress the ethernet address of the server machine
* @throws CmsInitException in case the ethernetAddress String is not a valid ethernet address
*/
public static void init(String ethernetAddress) throws CmsInitException {
try {
m_ethernetAddress = new EthernetAddress(ethernetAddress);
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(
Messages.ERR_INVALID_ETHERNET_ADDRESS_1,
ethernetAddress));
}
m_isNotInitialized = false;
}
/**
* Creates a clone of this CmsUUID.<p>
*
* @return a clone of this CmsUUID
*/
public Object clone() {
if (this == NULL_UUID) {
return NULL_UUID;
}
return new CmsUUID((UUID)m_uuid.clone());
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object obj) {
if (obj instanceof CmsUUID) {
return m_uuid.compareTo(((CmsUUID)obj).m_uuid);
}
return 0;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof CmsUUID) {
return ((CmsUUID)obj).m_uuid.equals(m_uuid);
}
return false;
}
/**
* Optimized hashCode implementation for UUID's.<p>
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return m_uuid.hashCode();
}
/**
* Returns true if this UUID is equal to the null UUID.<p>
*
* @return true if this UUID is equal to the null UUID
*/
public boolean isNullUUID() {
if (this == NULL_UUID) {
return true;
}
return m_uuid.equals(UUID.getNullUUID());
}
/**
* Returns the UUID as a 16-byte byte array.<p>
*
* @return 16-byte byte array that contains the UUID's bytes in the network byte order
*/
public byte[] toByteArray() {
return m_uuid.toByteArray();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return m_uuid.toString();
}
} | Removed misspelling algorith -> algorithm
| src/org/opencms/util/CmsUUID.java | Removed misspelling algorith -> algorithm | <ide><path>rc/org/opencms/util/CmsUUID.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsUUID.java,v $
<del> * Date : $Date: 2005/07/03 09:41:53 $
<del> * Version: $Revision: 1.18 $
<add> * Date : $Date: 2005/09/06 15:25:20 $
<add> * Version: $Revision: 1.19 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Mananagement System
<ide> * Spatial uniqueness is derived from
<ide> * ethernet address (MAC, 802.1); temporal from system clock.<p>
<ide> *
<del> * For more information about the algorith used, please see
<add> * For more information about the algorithm used, please see
<ide> * <a href="http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt">
<ide> * draft-leach-uuids-guids-01.txt</a>.<p>
<ide> *
<ide> *
<ide> * @author Alexander Kandzior
<ide> *
<del> * @version $Revision: 1.18 $
<add> * @version $Revision: 1.19 $
<ide> *
<ide> * @since 6.0.0
<ide> */ |
|
Java | apache-2.0 | 28233a147a9bce76802b595327f5d7de0288f2d7 | 0 | mathieufortin01/pdfbox,veraPDF/veraPDF-pdfbox,ChunghwaTelecom/pdfbox,ZhenyaM/veraPDF-pdfbox,mathieufortin01/pdfbox,BezrukovM/veraPDF-pdfbox,gavanx/pdflearn,veraPDF/veraPDF-pdfbox,ChunghwaTelecom/pdfbox,mdamt/pdfbox,ZhenyaM/veraPDF-pdfbox,joansmith/pdfbox,gavanx/pdflearn,benmccann/pdfbox,mdamt/pdfbox,joansmith/pdfbox,torakiki/sambox,benmccann/pdfbox,BezrukovM/veraPDF-pdfbox,torakiki/sambox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.text;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Map;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.util.Matrix;
/**
* This represents a string and a position on the screen of those characters.
*
* @author Ben Litchfield
*/
public final class TextPosition
{
private static final Map<Integer, String> DIACRITICS = createDiacritics();
// Adds non-decomposing diacritics to the hash with their related combining character.
// These are values that the unicode spec claims are equivalent but are not mapped in the form
// NFKC normalization method. Determined by going through the Combining Diacritical Marks
// section of the Unicode spec and identifying which characters are not mapped to by the
// normalization.
private static Map<Integer, String> createDiacritics()
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0x0060, "\u0300");
map.put(0x02CB, "\u0300");
map.put(0x0027, "\u0301");
map.put(0x02B9, "\u0301");
map.put(0x02CA, "\u0301");
map.put(0x005e, "\u0302");
map.put(0x02C6, "\u0302");
map.put(0x007E, "\u0303");
map.put(0x02C9, "\u0304");
map.put(0x00B0, "\u030A");
map.put(0x02BA, "\u030B");
map.put(0x02C7, "\u030C");
map.put(0x02C8, "\u030D");
map.put(0x0022, "\u030E");
map.put(0x02BB, "\u0312");
map.put(0x02BC, "\u0313");
map.put(0x0486, "\u0313");
map.put(0x055A, "\u0313");
map.put(0x02BD, "\u0314");
map.put(0x0485, "\u0314");
map.put(0x0559, "\u0314");
map.put(0x02D4, "\u031D");
map.put(0x02D5, "\u031E");
map.put(0x02D6, "\u031F");
map.put(0x02D7, "\u0320");
map.put(0x02B2, "\u0321");
map.put(0x02CC, "\u0329");
map.put(0x02B7, "\u032B");
map.put(0x02CD, "\u0331");
map.put(0x005F, "\u0332");
map.put(0x204E, "\u0359");
return map;
}
// text matrix for the start of the text object, coordinates are in display units
// and have not been adjusted
private final Matrix textMatrix;
// ending X and Y coordinates in display units
private final float endX;
private final float endY;
private final float maxHeight; // maximum height of text, in display units
private final int rotation; // 0, 90, 180, 270 degrees of page rotation
private final float x;
private final float y;
private final float pageHeight;
private final float pageWidth;
private final float widthOfSpace; // width of a space, in display units
private final int[] charCodes; // internal PDF character codes
private final PDFont font;
private final float fontSize;
private final int fontSizePt;
// mutable
private float[] widths;
private String unicode;
/**
* Constructor.
*
* @param pageRotation rotation of the page that the text is located in
* @param pageWidth rotation of the page that the text is located in
* @param pageHeight rotation of the page that the text is located in
* @param textMatrix TextMatrix for start of text (in display units)
* @param endX x coordinate of the end position
* @param endY y coordinate of the end position
* @param maxHeight Maximum height of text (in display units)
* @param individualWidth The width of the given character/string. (in text units)
* @param spaceWidth The width of the space character. (in display units)
* @param unicode The string of Unicode characters to be displayed.
* @param charCodes An array of the internal PDF character codes for the glyphs in this text.
* @param font The current font for this text position.
* @param fontSize The new font size.
* @param fontSizeInPt The font size in pt units.
*/
public TextPosition(int pageRotation, float pageWidth, float pageHeight, Matrix textMatrix,
float endX, float endY, float maxHeight, float individualWidth,
float spaceWidth, String unicode, int[] charCodes, PDFont font,
float fontSize, int fontSizeInPt)
{
this.textMatrix = textMatrix;
this.endX = endX;
this.endY = endY;
int rotationAngle = pageRotation;
this.rotation = rotationAngle;
this.maxHeight = maxHeight;
this.pageHeight = pageHeight;
this.pageWidth = pageWidth;
this.widths = new float[] { individualWidth };
this.widthOfSpace = spaceWidth;
this.unicode = unicode;
this.charCodes = charCodes;
this.font = font;
this.fontSize = fontSize;
this.fontSizePt = fontSizeInPt;
x = getXRot(rotationAngle);
if (rotationAngle == 0 || rotationAngle == 180)
{
y = this.pageHeight - getYLowerLeftRot(rotationAngle);
}
else
{
y = this.pageWidth - getYLowerLeftRot(rotationAngle);
}
}
/**
* Return the string of characters stored in this object.
*
* @return The string on the screen.
*/
public String getUnicode()
{
return unicode;
}
/**
* Return the internal PDF character codes of the glyphs in this text.
*
* @return an array of internal PDF character codes
*/
public int[] getCharacterCodes()
{
return charCodes;
}
/**
* Return the text matrix stored in this object.
*
* @return The Matrix containing the starting text position
*/
public Matrix getTextMatrix()
{
return textMatrix;
}
/**
* Return the direction/orientation of the string in this object based on its text matrix.
* @return The direction of the text (0, 90, 180, or 270)
*/
public float getDir()
{
float a = textMatrix.getValue(0,0);
float b = textMatrix.getValue(0,1);
float c = textMatrix.getValue(1,0);
float d = textMatrix.getValue(1,1);
// 12 0 left to right
// 0 12
if (a > 0 && Math.abs(b) < d && Math.abs(c) < a && d > 0)
{
return 0;
}
// -12 0 right to left (upside down)
// 0 -12
else if (a < 0 && Math.abs(b) < Math.abs(d) && Math.abs(c) < Math.abs(a) && d < 0)
{
return 180;
}
// 0 12 up
// -12 0
else if (Math.abs(a) < Math.abs(c) && b > 0 && c < 0 && Math.abs(d) < b)
{
return 90;
}
// 0 -12 down
// 12 0
else if (Math.abs(a) < c && b < 0 && c > 0 && Math.abs(d) < Math.abs(b))
{
return 270;
}
return 0;
}
/**
* Return the X starting coordinate of the text, adjusted by the given rotation amount.
* The rotation adjusts where the 0,0 location is relative to the text.
*
* @param rotation Rotation to apply (0, 90, 180, or 270). 0 will perform no adjustments.
* @return X coordinate
*/
private float getXRot(float rotation)
{
if (rotation == 0)
{
return textMatrix.getValue(2,0);
}
else if (rotation == 90)
{
return textMatrix.getValue(2,1);
}
else if (rotation == 180)
{
return pageWidth - textMatrix.getValue(2,0);
}
else if (rotation == 270)
{
return pageHeight - textMatrix.getValue(2,1);
}
return 0;
}
/**
* This will get the page rotation adjusted x position of the character.
* This is adjusted based on page rotation so that the upper left is 0,0.
*
* @return The x coordinate of the character.
*/
public float getX()
{
return x;
}
/**
* This will get the text direction adjusted x position of the character.
* This is adjusted based on text direction so that the first character
* in that direction is in the upper left at 0,0.
*
* @return The x coordinate of the text.
*/
public float getXDirAdj()
{
return getXRot(getDir());
}
/**
* This will get the y position of the character with 0,0 in lower left.
* This will be adjusted by the given rotation.
*
* @param rotation Rotation to apply to text to adjust the 0,0 location (0,90,180,270)
* @return The y coordinate of the text
*/
private float getYLowerLeftRot(float rotation)
{
if (rotation == 0)
{
return textMatrix.getValue(2,1);
}
else if (rotation == 90)
{
return pageWidth - textMatrix.getValue(2,0);
}
else if (rotation == 180)
{
return pageHeight - textMatrix.getValue(2,1);
}
else if (rotation == 270)
{
return textMatrix.getValue(2,0);
}
return 0;
}
/**
* This will get the y position of the text, adjusted so that 0,0 is upper left and it is
* adjusted based on the page rotation.
*
* @return The adjusted y coordinate of the character.
*/
public float getY()
{
return y;
}
/**
* This will get the y position of the text, adjusted so that 0,0 is upper left and it is
* adjusted based on the text direction.
*
* @return The adjusted y coordinate of the character.
*/
public float getYDirAdj()
{
float dir = getDir();
// some PDFBox code assumes that the 0,0 point is in upper left, not lower left
if (dir == 0 || dir == 180)
{
return pageHeight - getYLowerLeftRot(dir);
}
else
{
return pageWidth - getYLowerLeftRot(dir);
}
}
/**
* Get the length or width of the text, based on a given rotation.
*
* @param rotation Rotation that was used to determine coordinates (0,90,180,270)
* @return Width of text in display units
*/
private float getWidthRot(float rotation)
{
if (rotation == 90 || rotation == 270)
{
return Math.abs(endY - textMatrix.getTranslateY());
}
else
{
return Math.abs(endX - textMatrix.getTranslateX());
}
}
/**
* This will get the width of the string when page rotation adjusted coordinates are used.
*
* @return The width of the text in display units.
*/
public float getWidth()
{
return getWidthRot(rotation);
}
/**
* This will get the width of the string when text direction adjusted coordinates are used.
*
* @return The width of the text in display units.
*/
public float getWidthDirAdj()
{
return getWidthRot(getDir());
}
/**
* This will get the maximum height of all characters in this string.
*
* @return The maximum height of all characters in this string.
*/
public float getHeight()
{
return maxHeight;
}
/**
* This will get the maximum height of all characters in this string.
*
* @return The maximum height of all characters in this string.
*/
public float getHeightDir()
{
// this is not really a rotation-dependent calculation, but this is defined for symmetry
return maxHeight;
}
/**
* This will get the font size that this object is suppose to be drawn at.
*
* @return The font size.
*/
public float getFontSize()
{
return fontSize;
}
/**
* This will get the font size in pt. To get this size we have to multiply the pdf-fontsize
* and the scaling from the textmatrix
*
* @return The font size in pt.
*/
public float getFontSizeInPt()
{
return fontSizePt;
}
/**
* This will get the font for the text being drawn.
*
* @return The font size.
*/
public PDFont getFont()
{
return font;
}
/**
* This will get the width of a space character. This is useful for some algorithms such as the
* text stripper, that need to know the width of a space character.
*
* @return The width of a space character.
*/
public float getWidthOfSpace()
{
return widthOfSpace;
}
/**
* @return Returns the xScale.
*/
public float getXScale()
{
return textMatrix.getXScale();
}
/**
* @return Returns the yScale.
*/
public float getYScale()
{
return textMatrix.getYScale();
}
/**
* Get the widths of each individual character.
*
* @return An array that is the same length as the length of the string.
*/
public float[] getIndividualWidths()
{
return widths;
}
/**
* Determine if this TextPosition logically contains another (i.e. they overlap and should be
* rendered on top of each other).
*
* @param tp2 The other TestPosition to compare against
* @return True if tp2 is contained in the bounding box of this text.
*/
public boolean contains(TextPosition tp2)
{
double thisXstart = getXDirAdj();
double thisXend = getXDirAdj() + getWidthDirAdj();
double tp2Xstart = tp2.getXDirAdj();
double tp2Xend = tp2.getXDirAdj() + tp2.getWidthDirAdj();
// no X overlap at all so return as soon as possible
if (tp2Xend <= thisXstart || tp2Xstart >= thisXend)
{
return false;
}
// no Y overlap at all so return as soon as possible. Note: 0.0 is in the upper left and
// y-coordinate is top of TextPosition
if (tp2.getYDirAdj() + tp2.getHeightDir() < getYDirAdj() ||
tp2.getYDirAdj() > getYDirAdj() + getHeightDir())
{
return false;
}
// we're going to calculate the percentage of overlap, if its less than a 15% x-coordinate
// overlap then we'll return false because its negligible, .15 was determined by trial and
// error in the regression test files
else if (tp2Xstart > thisXstart && tp2Xend > thisXend)
{
double overlap = thisXend - tp2Xstart;
double overlapPercent = overlap/getWidthDirAdj();
return overlapPercent > .15;
}
else if (tp2Xstart < thisXstart && tp2Xend < thisXend)
{
double overlap = tp2Xend - thisXstart;
double overlapPercent = overlap/getWidthDirAdj();
return overlapPercent > .15;
}
return true;
}
/**
* Merge a single character TextPosition into the current object. This is to be used only for
* cases where we have a diacritic that overlaps an existing TextPosition. In a graphical
* display, we could overlay them, but for text extraction we need to merge them. Use the
* contains() method to test if two objects overlap.
*
* @param diacritic TextPosition to merge into the current TextPosition.
*/
public void mergeDiacritic(TextPosition diacritic)
{
if (diacritic.getUnicode().length() > 1)
{
return;
}
float diacXStart = diacritic.getXDirAdj();
float diacXEnd = diacXStart + diacritic.widths[0];
float currCharXStart = getXDirAdj();
int strLen = unicode.length();
boolean wasAdded = false;
for (int i = 0; i < strLen && !wasAdded; i++)
{
float currCharXEnd = currCharXStart + widths[i];
// this is the case where there is an overlap of the diacritic character with the
// current character and the previous character. If no previous character, just append
// the diacritic after the current one
if (diacXStart < currCharXStart && diacXEnd <= currCharXEnd)
{
if (i == 0)
{
insertDiacritic(i, diacritic);
}
else
{
float distanceOverlapping1 = diacXEnd - currCharXStart;
float percentage1 = distanceOverlapping1/widths[i];
float distanceOverlapping2 = currCharXStart - diacXStart;
float percentage2 = distanceOverlapping2/widths[i - 1];
if (percentage1 >= percentage2)
{
insertDiacritic(i, diacritic);
}
else
{
insertDiacritic(i - 1, diacritic);
}
}
wasAdded = true;
}
// diacritic completely covers this character and therefore we assume that this is the
// character the diacritic belongs to
else if (diacXStart < currCharXStart && diacXEnd > currCharXEnd)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// otherwise, The diacritic modifies this character because its completely
// contained by the character width
else if (diacXStart >= currCharXStart && diacXEnd <= currCharXEnd)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// last character in the TextPosition so we add diacritic to the end
else if (diacXStart >= currCharXStart && diacXEnd > currCharXEnd && i == strLen - 1)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// couldn't find anything useful so we go to the next character in the TextPosition
currCharXStart += widths[i];
}
}
/**
* Inserts the diacritic TextPosition to the str of this TextPosition and updates the widths
* array to include the extra character width.
*
* @param i current character
* @param diacritic The diacritic TextPosition
*/
private void insertDiacritic(int i, TextPosition diacritic)
{
StringBuilder sb = new StringBuilder();
sb.append(unicode.substring(0, i));
float[] widths2 = new float[widths.length + 1];
System.arraycopy(widths, 0, widths2, 0, i);
// Unicode combining diacritics always go after the base character, regardless of whether
// the string is in presentation order or logical order
sb.append(unicode.charAt(i));
widths2[i] = widths[i];
sb.append(combineDiacritic(diacritic.getUnicode()));
widths2[i + 1] = 0;
// get the rest of the string
sb.append(unicode.substring(i + 1, unicode.length()));
System.arraycopy(widths, i + 1, widths2, i + 2, widths.length - i - 1);
unicode = sb.toString();
widths = widths2;
}
/**
* Combine the diacritic, for example, convert non-combining diacritic characters to their
* combining counterparts.
*
* @param str String to normalize
* @return Normalized string
*/
private String combineDiacritic(String str)
{
// Unicode contains special combining forms of the diacritic characters which we want to use
int codePoint = str.codePointAt(0);
// convert the characters not defined in the Unicode spec
if (DIACRITICS.containsKey(codePoint))
{
return DIACRITICS.get(codePoint);
}
else
{
return Normalizer.normalize(str, Normalizer.Form.NFKC).trim();
}
}
/**
* @return True if the current character is a diacritic char.
*/
public boolean isDiacritic()
{
String text = this.getUnicode();
if (text.length() != 1)
{
return false;
}
int type = Character.getType(text.charAt(0));
return type == Character.NON_SPACING_MARK ||
type == Character.MODIFIER_SYMBOL ||
type == Character.MODIFIER_LETTER;
}
/**
* Show the string data for this text position.
*
* @return A human readable form of this object.
*/
@Override
public String toString()
{
return getUnicode();
}
}
| pdfbox/src/main/java/org/apache/pdfbox/text/TextPosition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.text;
import java.text.Normalizer;
import java.util.HashMap;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.util.Matrix;
/**
* This represents a string and a position on the screen of those characters.
*
* @author Ben Litchfield
*/
public final class TextPosition
{
private static final HashMap<Integer, String> DIACRITICS = createDiacritics();
// Adds non-decomposing diacritics to the hash with their related combining character.
// These are values that the unicode spec claims are equivalent but are not mapped in the form
// NFKC normalization method. Determined by going through the Combining Diacritical Marks
// section of the Unicode spec and identifying which characters are not mapped to by the
// normalization.
private static HashMap<Integer, String> createDiacritics()
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0x0060, "\u0300");
map.put(0x02CB, "\u0300");
map.put(0x0027, "\u0301");
map.put(0x02B9, "\u0301");
map.put(0x02CA, "\u0301");
map.put(0x005e, "\u0302");
map.put(0x02C6, "\u0302");
map.put(0x007E, "\u0303");
map.put(0x02C9, "\u0304");
map.put(0x00B0, "\u030A");
map.put(0x02BA, "\u030B");
map.put(0x02C7, "\u030C");
map.put(0x02C8, "\u030D");
map.put(0x0022, "\u030E");
map.put(0x02BB, "\u0312");
map.put(0x02BC, "\u0313");
map.put(0x0486, "\u0313");
map.put(0x055A, "\u0313");
map.put(0x02BD, "\u0314");
map.put(0x0485, "\u0314");
map.put(0x0559, "\u0314");
map.put(0x02D4, "\u031D");
map.put(0x02D5, "\u031E");
map.put(0x02D6, "\u031F");
map.put(0x02D7, "\u0320");
map.put(0x02B2, "\u0321");
map.put(0x02CC, "\u0329");
map.put(0x02B7, "\u032B");
map.put(0x02CD, "\u0331");
map.put(0x005F, "\u0332");
map.put(0x204E, "\u0359");
return map;
}
// text matrix for the start of the text object, coordinates are in display units
// and have not been adjusted
private final Matrix textMatrix;
// ending X and Y coordinates in display units
private final float endX;
private final float endY;
private final float maxHeight; // maximum height of text, in display units
private final int rotation; // 0, 90, 180, 270 degrees of page rotation
private final float x;
private final float y;
private final float pageHeight;
private final float pageWidth;
private final float widthOfSpace; // width of a space, in display units
private final int[] charCodes; // internal PDF character codes
private final PDFont font;
private final float fontSize;
private final int fontSizePt;
// mutable
private float[] widths;
private String unicode;
/**
* Constructor.
*
* @param pageRotation rotation of the page that the text is located in
* @param pageWidth rotation of the page that the text is located in
* @param pageHeight rotation of the page that the text is located in
* @param textMatrix TextMatrix for start of text (in display units)
* @param endX x coordinate of the end position
* @param endY y coordinate of the end position
* @param maxHeight Maximum height of text (in display units)
* @param individualWidth The width of the given character/string. (in text units)
* @param spaceWidth The width of the space character. (in display units)
* @param unicode The string of Unicode characters to be displayed.
* @param charCodes An array of the internal PDF character codes for the glyphs in this text.
* @param font The current font for this text position.
* @param fontSize The new font size.
* @param fontSizeInPt The font size in pt units.
*/
public TextPosition(int pageRotation, float pageWidth, float pageHeight, Matrix textMatrix,
float endX, float endY, float maxHeight, float individualWidth,
float spaceWidth, String unicode, int[] charCodes, PDFont font,
float fontSize, int fontSizeInPt)
{
this.textMatrix = textMatrix;
this.endX = endX;
this.endY = endY;
int rotationAngle = pageRotation;
this.rotation = rotationAngle;
this.maxHeight = maxHeight;
this.pageHeight = pageHeight;
this.pageWidth = pageWidth;
this.widths = new float[] { individualWidth };
this.widthOfSpace = spaceWidth;
this.unicode = unicode;
this.charCodes = charCodes;
this.font = font;
this.fontSize = fontSize;
this.fontSizePt = fontSizeInPt;
x = getXRot(rotationAngle);
if (rotationAngle == 0 || rotationAngle == 180)
{
y = this.pageHeight - getYLowerLeftRot(rotationAngle);
}
else
{
y = this.pageWidth - getYLowerLeftRot(rotationAngle);
}
}
/**
* Return the string of characters stored in this object.
*
* @return The string on the screen.
*/
public String getUnicode()
{
return unicode;
}
/**
* Return the internal PDF character codes of the glyphs in this text.
*
* @return an array of internal PDF character codes
*/
public int[] getCharacterCodes()
{
return charCodes;
}
/**
* Return the text matrix stored in this object.
*
* @return The Matrix containing the starting text position
*/
public Matrix getTextMatrix()
{
return textMatrix;
}
/**
* Return the direction/orientation of the string in this object based on its text matrix.
* @return The direction of the text (0, 90, 180, or 270)
*/
public float getDir()
{
float a = textMatrix.getValue(0,0);
float b = textMatrix.getValue(0,1);
float c = textMatrix.getValue(1,0);
float d = textMatrix.getValue(1,1);
// 12 0 left to right
// 0 12
if (a > 0 && Math.abs(b) < d && Math.abs(c) < a && d > 0)
{
return 0;
}
// -12 0 right to left (upside down)
// 0 -12
else if (a < 0 && Math.abs(b) < Math.abs(d) && Math.abs(c) < Math.abs(a) && d < 0)
{
return 180;
}
// 0 12 up
// -12 0
else if (Math.abs(a) < Math.abs(c) && b > 0 && c < 0 && Math.abs(d) < b)
{
return 90;
}
// 0 -12 down
// 12 0
else if (Math.abs(a) < c && b < 0 && c > 0 && Math.abs(d) < Math.abs(b))
{
return 270;
}
return 0;
}
/**
* Return the X starting coordinate of the text, adjusted by the given rotation amount.
* The rotation adjusts where the 0,0 location is relative to the text.
*
* @param rotation Rotation to apply (0, 90, 180, or 270). 0 will perform no adjustments.
* @return X coordinate
*/
private float getXRot(float rotation)
{
if (rotation == 0)
{
return textMatrix.getValue(2,0);
}
else if (rotation == 90)
{
return textMatrix.getValue(2,1);
}
else if (rotation == 180)
{
return pageWidth - textMatrix.getValue(2,0);
}
else if (rotation == 270)
{
return pageHeight - textMatrix.getValue(2,1);
}
return 0;
}
/**
* This will get the page rotation adjusted x position of the character.
* This is adjusted based on page rotation so that the upper left is 0,0.
*
* @return The x coordinate of the character.
*/
public float getX()
{
return x;
}
/**
* This will get the text direction adjusted x position of the character.
* This is adjusted based on text direction so that the first character
* in that direction is in the upper left at 0,0.
*
* @return The x coordinate of the text.
*/
public float getXDirAdj()
{
return getXRot(getDir());
}
/**
* This will get the y position of the character with 0,0 in lower left.
* This will be adjusted by the given rotation.
*
* @param rotation Rotation to apply to text to adjust the 0,0 location (0,90,180,270)
* @return The y coordinate of the text
*/
private float getYLowerLeftRot(float rotation)
{
if (rotation == 0)
{
return textMatrix.getValue(2,1);
}
else if (rotation == 90)
{
return pageWidth - textMatrix.getValue(2,0);
}
else if (rotation == 180)
{
return pageHeight - textMatrix.getValue(2,1);
}
else if (rotation == 270)
{
return textMatrix.getValue(2,0);
}
return 0;
}
/**
* This will get the y position of the text, adjusted so that 0,0 is upper left and it is
* adjusted based on the page rotation.
*
* @return The adjusted y coordinate of the character.
*/
public float getY()
{
return y;
}
/**
* This will get the y position of the text, adjusted so that 0,0 is upper left and it is
* adjusted based on the text direction.
*
* @return The adjusted y coordinate of the character.
*/
public float getYDirAdj()
{
float dir = getDir();
// some PDFBox code assumes that the 0,0 point is in upper left, not lower left
if (dir == 0 || dir == 180)
{
return pageHeight - getYLowerLeftRot(dir);
}
else
{
return pageWidth - getYLowerLeftRot(dir);
}
}
/**
* Get the length or width of the text, based on a given rotation.
*
* @param rotation Rotation that was used to determine coordinates (0,90,180,270)
* @return Width of text in display units
*/
private float getWidthRot(float rotation)
{
if (rotation == 90 || rotation == 270)
{
return Math.abs(endY - textMatrix.getTranslateY());
}
else
{
return Math.abs(endX - textMatrix.getTranslateX());
}
}
/**
* This will get the width of the string when page rotation adjusted coordinates are used.
*
* @return The width of the text in display units.
*/
public float getWidth()
{
return getWidthRot(rotation);
}
/**
* This will get the width of the string when text direction adjusted coordinates are used.
*
* @return The width of the text in display units.
*/
public float getWidthDirAdj()
{
return getWidthRot(getDir());
}
/**
* This will get the maximum height of all characters in this string.
*
* @return The maximum height of all characters in this string.
*/
public float getHeight()
{
return maxHeight;
}
/**
* This will get the maximum height of all characters in this string.
*
* @return The maximum height of all characters in this string.
*/
public float getHeightDir()
{
// this is not really a rotation-dependent calculation, but this is defined for symmetry
return maxHeight;
}
/**
* This will get the font size that this object is suppose to be drawn at.
*
* @return The font size.
*/
public float getFontSize()
{
return fontSize;
}
/**
* This will get the font size in pt. To get this size we have to multiply the pdf-fontsize
* and the scaling from the textmatrix
*
* @return The font size in pt.
*/
public float getFontSizeInPt()
{
return fontSizePt;
}
/**
* This will get the font for the text being drawn.
*
* @return The font size.
*/
public PDFont getFont()
{
return font;
}
/**
* This will get the width of a space character. This is useful for some algorithms such as the
* text stripper, that need to know the width of a space character.
*
* @return The width of a space character.
*/
public float getWidthOfSpace()
{
return widthOfSpace;
}
/**
* @return Returns the xScale.
*/
public float getXScale()
{
return textMatrix.getXScale();
}
/**
* @return Returns the yScale.
*/
public float getYScale()
{
return textMatrix.getYScale();
}
/**
* Get the widths of each individual character.
*
* @return An array that is the same length as the length of the string.
*/
public float[] getIndividualWidths()
{
return widths;
}
/**
* Determine if this TextPosition logically contains another (i.e. they overlap and should be
* rendered on top of each other).
*
* @param tp2 The other TestPosition to compare against
* @return True if tp2 is contained in the bounding box of this text.
*/
public boolean contains(TextPosition tp2)
{
double thisXstart = getXDirAdj();
double thisXend = getXDirAdj() + getWidthDirAdj();
double tp2Xstart = tp2.getXDirAdj();
double tp2Xend = tp2.getXDirAdj() + tp2.getWidthDirAdj();
// no X overlap at all so return as soon as possible
if (tp2Xend <= thisXstart || tp2Xstart >= thisXend)
{
return false;
}
// no Y overlap at all so return as soon as possible. Note: 0.0 is in the upper left and
// y-coordinate is top of TextPosition
if (tp2.getYDirAdj() + tp2.getHeightDir() < getYDirAdj() ||
tp2.getYDirAdj() > getYDirAdj() + getHeightDir())
{
return false;
}
// we're going to calculate the percentage of overlap, if its less than a 15% x-coordinate
// overlap then we'll return false because its negligible, .15 was determined by trial and
// error in the regression test files
else if (tp2Xstart > thisXstart && tp2Xend > thisXend)
{
double overlap = thisXend - tp2Xstart;
double overlapPercent = overlap/getWidthDirAdj();
return overlapPercent > .15;
}
else if (tp2Xstart < thisXstart && tp2Xend < thisXend)
{
double overlap = tp2Xend - thisXstart;
double overlapPercent = overlap/getWidthDirAdj();
return overlapPercent > .15;
}
return true;
}
/**
* Merge a single character TextPosition into the current object. This is to be used only for
* cases where we have a diacritic that overlaps an existing TextPosition. In a graphical
* display, we could overlay them, but for text extraction we need to merge them. Use the
* contains() method to test if two objects overlap.
*
* @param diacritic TextPosition to merge into the current TextPosition.
*/
public void mergeDiacritic(TextPosition diacritic)
{
if (diacritic.getUnicode().length() > 1)
{
return;
}
float diacXStart = diacritic.getXDirAdj();
float diacXEnd = diacXStart + diacritic.widths[0];
float currCharXStart = getXDirAdj();
int strLen = unicode.length();
boolean wasAdded = false;
for (int i = 0; i < strLen && !wasAdded; i++)
{
float currCharXEnd = currCharXStart + widths[i];
// this is the case where there is an overlap of the diacritic character with the
// current character and the previous character. If no previous character, just append
// the diacritic after the current one
if (diacXStart < currCharXStart && diacXEnd <= currCharXEnd)
{
if (i == 0)
{
insertDiacritic(i, diacritic);
}
else
{
float distanceOverlapping1 = diacXEnd - currCharXStart;
float percentage1 = distanceOverlapping1/widths[i];
float distanceOverlapping2 = currCharXStart - diacXStart;
float percentage2 = distanceOverlapping2/widths[i - 1];
if (percentage1 >= percentage2)
{
insertDiacritic(i, diacritic);
}
else
{
insertDiacritic(i - 1, diacritic);
}
}
wasAdded = true;
}
// diacritic completely covers this character and therefore we assume that this is the
// character the diacritic belongs to
else if (diacXStart < currCharXStart && diacXEnd > currCharXEnd)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// otherwise, The diacritic modifies this character because its completely
// contained by the character width
else if (diacXStart >= currCharXStart && diacXEnd <= currCharXEnd)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// last character in the TextPosition so we add diacritic to the end
else if (diacXStart >= currCharXStart && diacXEnd > currCharXEnd && i == strLen - 1)
{
insertDiacritic(i, diacritic);
wasAdded = true;
}
// couldn't find anything useful so we go to the next character in the TextPosition
currCharXStart += widths[i];
}
}
/**
* Inserts the diacritic TextPosition to the str of this TextPosition and updates the widths
* array to include the extra character width.
*
* @param i current character
* @param diacritic The diacritic TextPosition
*/
private void insertDiacritic(int i, TextPosition diacritic)
{
StringBuilder sb = new StringBuilder();
sb.append(unicode.substring(0, i));
float[] widths2 = new float[widths.length + 1];
System.arraycopy(widths, 0, widths2, 0, i);
// Unicode combining diacritics always go after the base character, regardless of whether
// the string is in presentation order or logical order
sb.append(unicode.charAt(i));
widths2[i] = widths[i];
sb.append(combineDiacritic(diacritic.getUnicode()));
widths2[i + 1] = 0;
// get the rest of the string
sb.append(unicode.substring(i + 1, unicode.length()));
System.arraycopy(widths, i + 1, widths2, i + 2, widths.length - i - 1);
unicode = sb.toString();
widths = widths2;
}
/**
* Combine the diacritic, for example, convert non-combining diacritic characters to their
* combining counterparts.
*
* @param str String to normalize
* @return Normalized string
*/
private String combineDiacritic(String str)
{
// Unicode contains special combining forms of the diacritic characters which we want to use
int codePoint = str.codePointAt(0);
// convert the characters not defined in the Unicode spec
if (DIACRITICS.containsKey(codePoint))
{
return DIACRITICS.get(codePoint);
}
else
{
return Normalizer.normalize(str, Normalizer.Form.NFKC).trim();
}
}
/**
* @return True if the current character is a diacritic char.
*/
public boolean isDiacritic()
{
String text = this.getUnicode();
if (text.length() != 1)
{
return false;
}
int type = Character.getType(text.charAt(0));
return type == Character.NON_SPACING_MARK ||
type == Character.MODIFIER_SYMBOL ||
type == Character.MODIFIER_LETTER;
}
/**
* Show the string data for this text position.
*
* @return A human readable form of this object.
*/
public String toString()
{
return getUnicode();
}
}
| PDFBOX-2576: avoid using implementation types, use the interface instead
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1646664 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/text/TextPosition.java | PDFBOX-2576: avoid using implementation types, use the interface instead | <ide><path>dfbox/src/main/java/org/apache/pdfbox/text/TextPosition.java
<ide>
<ide> import java.text.Normalizer;
<ide> import java.util.HashMap;
<add>import java.util.Map;
<ide> import org.apache.pdfbox.pdmodel.font.PDFont;
<ide> import org.apache.pdfbox.util.Matrix;
<ide>
<ide> */
<ide> public final class TextPosition
<ide> {
<del> private static final HashMap<Integer, String> DIACRITICS = createDiacritics();
<add> private static final Map<Integer, String> DIACRITICS = createDiacritics();
<ide>
<ide> // Adds non-decomposing diacritics to the hash with their related combining character.
<ide> // These are values that the unicode spec claims are equivalent but are not mapped in the form
<ide> // NFKC normalization method. Determined by going through the Combining Diacritical Marks
<ide> // section of the Unicode spec and identifying which characters are not mapped to by the
<ide> // normalization.
<del> private static HashMap<Integer, String> createDiacritics()
<add> private static Map<Integer, String> createDiacritics()
<ide> {
<ide> HashMap<Integer, String> map = new HashMap<Integer, String>();
<ide> map.put(0x0060, "\u0300");
<ide> *
<ide> * @return A human readable form of this object.
<ide> */
<add> @Override
<ide> public String toString()
<ide> {
<ide> return getUnicode(); |
|
Java | bsd-3-clause | e6e8a09d6b6e6e2eb6d03e0ddf92a4c276b50905 | 0 | Beachbot330/Beachbot2014Java | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.Beachbot2014Java.subsystems;
import org.usfirst.frc330.Beachbot2014Java.RobotMap;
import org.usfirst.frc330.Beachbot2014Java.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc330.Beachbot2014Java.Robot;
import org.usfirst.frc330.wpilibj.PrefSendablePIDController;
/**
*
*/
public class Arm extends Subsystem implements PIDSource, PIDOutput{
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
SpeedController arm1 = RobotMap.armArm1;
SpeedController arm2 = RobotMap.armArm2;
AnalogChannel armPotentiometer = RobotMap.armArmPotentiometer;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private PrefSendablePIDController armPID;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
private static final String PREF_Arm_ArmPositionLowerLimit = "ArmPositionLowerLimit";
private static final String PREF_Arm_ArmPositionUpperLimit = "ArmPositionUpperLimit";
private static final String PREF_Arm_ArmPositionDash = "ArmPositionDash";
public Arm() {
armPID = new PrefSendablePIDController(0,0,0,this,this, "armPID");
// armPID = new PIDController(0,0,0,this,this);
armPID.setAbsoluteTolerance(0.1);
Preferences.getInstance().putDouble("ArmAbsoluteTolerance", 0.1);
SmartDashboard.putData("ArmPID", armPID);
}
public double getArmZero()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeArmPositionZero";
else
name = "CompetitionArmPositionZero";
if (!Preferences.getInstance().containsKey(name))
{
Preferences.getInstance().putDouble(name, 0.0);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble(name, 0.0);
}
public void setArmZero()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeArmPositionZero";
else
name = "CompetitionArmPositionZero";
Preferences.getInstance().putDouble(name, armPotentiometer.getAverageVoltage());
Preferences.getInstance().save();
}
public double getArmFrontPickup() {
if (!Preferences.getInstance().containsKey("armSetpointPickup"))
{
Preferences.getInstance().putDouble("armSetpointPickup", 1.7);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointPickup", 1.7);
}
public double getArmBackPickup() {
return -Robot.arm.getArmFrontPickup();
}
public double getArmFrontCheckPickup() {
if (!Preferences.getInstance().containsKey("armSetpointCheckPickup"))
{
Preferences.getInstance().putDouble("armSetpointCheckPickup", 1.6);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointCheckPickup", 1.6);
}
public double getArmBackCheckPickup() {
return -Robot.arm.getArmFrontCheckPickup();
}
public double getArmFrontLoading() {
if (!Preferences.getInstance().containsKey("armSetpointLoading"))
{
Preferences.getInstance().putDouble("armSetpointLoading", 1.0);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointLoading", 1.0);
}
public double getArmBackLoading() {
return -Robot.arm.getArmFrontLoading();
}
public double getArmFrontCatching() {
if (!Preferences.getInstance().containsKey("armSetpointCatching"))
{
Preferences.getInstance().putDouble("armSetpointCatching", .9);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointCatching", .9);
}
public double getArmBackCatching() {
return -Robot.arm.getArmFrontCatching();
}
public void manualArm() {
double armCommand = Robot.oi.operatorJoystick.getY();
/*
if (Math.abs(armCommand) > 0.10 && armPID.isEnable())
{
armPID.disable();
set(armCommand);
}
else if (!armPID.isEnable() && Math.abs(armCommand) > 0.10)
{
set(armCommand);
}
else if (!armPID.isEnable())
{
set(0);
}
*/
set(armCommand);
}
public double getArmPosition()
{
return armPotentiometer.getAverageVoltage()-getArmZero();
}
public void set(double output){
if (output > 0 && getArmPosition() > armUpperLimit())
{
arm1.set(0);
arm2.set(0);
}
else if (output < 0 && getArmPosition() < armLowerLimit())
{
arm1.set(0);
arm2.set(0);
}
else
{
arm1.set(output);
arm2.set(-output);
}
}
public double armUpperLimit() {
double armpositionupperlimit = 2;
if (Preferences.getInstance().containsKey(PREF_Arm_ArmPositionUpperLimit))
{
armpositionupperlimit = Preferences.getInstance().getDouble(
PREF_Arm_ArmPositionUpperLimit,armpositionupperlimit);
} else
{
Preferences.getInstance().putDouble(PREF_Arm_ArmPositionUpperLimit,
armpositionupperlimit);
Preferences.getInstance().save();
}
return armpositionupperlimit;
}
public double armLowerLimit() {
double armpositionlowerlimit = -2;
if (Preferences.getInstance().containsKey(PREF_Arm_ArmPositionLowerLimit))
{
armpositionlowerlimit = Preferences.getInstance().getDouble(
PREF_Arm_ArmPositionLowerLimit,armpositionlowerlimit);
} else
{
Preferences.getInstance().putDouble(PREF_Arm_ArmPositionLowerLimit,
armpositionlowerlimit);
Preferences.getInstance().save();
}
return armpositionlowerlimit;
}
public void armDashPosition() {
SmartDashboard.putNumber("armDashPosition", getArmPosition());
}
public void armSetPoint(double setpoint) {
//armPID.setSetpoint(setpoint);
}
public void armSetPointFrontPickup() {
armSetPoint(getArmFrontPickup());
}
public void armSetPointBackPickup() {
armSetPoint(getArmBackPickup());
}
public void armSetPointFrontCheckPickup() {
armSetPoint(getArmFrontCheckPickup());
}
public void armSetPointBackCheckPickup() {
armSetPoint(getArmBackCheckPickup());
}
public void armSetPointFrontLoading() {
armSetPoint(getArmFrontLoading());
}
public void armSetPointBackLoading() {
armSetPoint(getArmBackLoading());
}
public void armSetpointFrontCatching() {
armSetPoint(getArmFrontCatching());
}
public void armSetpointBackCatching() {
armSetPoint(getArmBackCatching());
}
public double pidGet() {
return getArmPosition();
}
public void pidWrite(double output) {
set(output);
}
}
| src/org/usfirst/frc330/Beachbot2014Java/subsystems/Arm.java | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.Beachbot2014Java.subsystems;
import org.usfirst.frc330.Beachbot2014Java.RobotMap;
import org.usfirst.frc330.Beachbot2014Java.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc330.Beachbot2014Java.Robot;
import org.usfirst.frc330.wpilibj.BeachbotPrefSendablePIDController;
/**
*
*/
public class Arm extends Subsystem implements PIDSource, PIDOutput{
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
SpeedController arm1 = RobotMap.armArm1;
SpeedController arm2 = RobotMap.armArm2;
AnalogChannel armPotentiometer = RobotMap.armArmPotentiometer;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private BeachbotPrefSendablePIDController armPID;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
private static final String PREF_Arm_ArmPositionLowerLimit = "ArmPositionLowerLimit";
private static final String PREF_Arm_ArmPositionUpperLimit = "ArmPositionUpperLimit";
private static final String PREF_Arm_ArmPositionDash = "ArmPositionDash";
public Arm() {
armPID = new BeachbotPrefSendablePIDController(0,0,0,this,this, "armPID");
// armPID = new PIDController(0,0,0,this,this);
armPID.setAbsoluteTolerance(0.1);
Preferences.getInstance().putDouble("ArmAbsoluteTolerance", 0.1);
SmartDashboard.putData("ArmPID", armPID);
}
public double getArmZero()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeArmPositionZero";
else
name = "CompetitionArmPositionZero";
if (!Preferences.getInstance().containsKey(name))
{
Preferences.getInstance().putDouble(name, 0.0);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble(name, 0.0);
}
public void setArmZero()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeArmPositionZero";
else
name = "CompetitionArmPositionZero";
Preferences.getInstance().putDouble(name, armPotentiometer.getAverageVoltage());
Preferences.getInstance().save();
}
public double getArmFrontPickup() {
if (!Preferences.getInstance().containsKey("armSetpointPickup"))
{
Preferences.getInstance().putDouble("armSetpointPickup", 1.7);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointPickup", 1.7);
}
public double getArmBackPickup() {
return -Robot.arm.getArmFrontPickup();
}
public double getArmFrontCheckPickup() {
if (!Preferences.getInstance().containsKey("armSetpointCheckPickup"))
{
Preferences.getInstance().putDouble("armSetpointCheckPickup", 1.6);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointCheckPickup", 1.6);
}
public double getArmBackCheckPickup() {
return -Robot.arm.getArmFrontCheckPickup();
}
public double getArmFrontLoading() {
if (!Preferences.getInstance().containsKey("armSetpointLoading"))
{
Preferences.getInstance().putDouble("armSetpointLoading", 1.0);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointLoading", 1.0);
}
public double getArmBackLoading() {
return -Robot.arm.getArmFrontLoading();
}
public double getArmFrontCatching() {
if (!Preferences.getInstance().containsKey("armSetpointCatching"))
{
Preferences.getInstance().putDouble("armSetpointCatching", .9);
Preferences.getInstance().save();
}
return Preferences.getInstance().getDouble("armSetpointCatching", .9);
}
public double getArmBackCatching() {
return -Robot.arm.getArmFrontCatching();
}
public void manualArm() {
double armCommand = Robot.oi.operatorJoystick.getY();
/*
if (Math.abs(armCommand) > 0.10 && armPID.isEnable())
{
armPID.disable();
set(armCommand);
}
else if (!armPID.isEnable() && Math.abs(armCommand) > 0.10)
{
set(armCommand);
}
else if (!armPID.isEnable())
{
set(0);
}
*/
set(armCommand);
}
public double getArmPosition()
{
return armPotentiometer.getAverageVoltage()-getArmZero();
}
public void set(double output){
if (output > 0 && getArmPosition() > armUpperLimit())
{
arm1.set(0);
arm2.set(0);
}
else if (output < 0 && getArmPosition() < armLowerLimit())
{
arm1.set(0);
arm2.set(0);
}
else
{
arm1.set(output);
arm2.set(-output);
}
}
public double armUpperLimit() {
double armpositionupperlimit = 2;
if (Preferences.getInstance().containsKey(PREF_Arm_ArmPositionUpperLimit))
{
armpositionupperlimit = Preferences.getInstance().getDouble(
PREF_Arm_ArmPositionUpperLimit,armpositionupperlimit);
} else
{
Preferences.getInstance().putDouble(PREF_Arm_ArmPositionUpperLimit,
armpositionupperlimit);
Preferences.getInstance().save();
}
return armpositionupperlimit;
}
public double armLowerLimit() {
double armpositionlowerlimit = -2;
if (Preferences.getInstance().containsKey(PREF_Arm_ArmPositionLowerLimit))
{
armpositionlowerlimit = Preferences.getInstance().getDouble(
PREF_Arm_ArmPositionLowerLimit,armpositionlowerlimit);
} else
{
Preferences.getInstance().putDouble(PREF_Arm_ArmPositionLowerLimit,
armpositionlowerlimit);
Preferences.getInstance().save();
}
return armpositionlowerlimit;
}
public void armDashPosition() {
SmartDashboard.putNumber("armDashPosition", getArmPosition());
}
public void armSetPoint(double setpoint) {
//armPID.setSetpoint(setpoint);
}
public void armSetPointFrontPickup() {
armSetPoint(getArmFrontPickup());
}
public void armSetPointBackPickup() {
armSetPoint(getArmBackPickup());
}
public void armSetPointFrontCheckPickup() {
armSetPoint(getArmFrontCheckPickup());
}
public void armSetPointBackCheckPickup() {
armSetPoint(getArmBackCheckPickup());
}
public void armSetPointFrontLoading() {
armSetPoint(getArmFrontLoading());
}
public void armSetPointBackLoading() {
armSetPoint(getArmBackLoading());
}
public void armSetpointFrontCatching() {
armSetPoint(getArmFrontCatching());
}
public void armSetpointBackCatching() {
armSetPoint(getArmBackCatching());
}
public double pidGet() {
return getArmPosition();
}
public void pidWrite(double output) {
set(output);
}
}
| modify to use safer PID controllers | src/org/usfirst/frc330/Beachbot2014Java/subsystems/Arm.java | modify to use safer PID controllers | <ide><path>rc/org/usfirst/frc330/Beachbot2014Java/subsystems/Arm.java
<ide> import edu.wpi.first.wpilibj.command.Subsystem;
<ide> import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
<ide> import org.usfirst.frc330.Beachbot2014Java.Robot;
<del>import org.usfirst.frc330.wpilibj.BeachbotPrefSendablePIDController;
<add>import org.usfirst.frc330.wpilibj.PrefSendablePIDController;
<ide> /**
<ide> *
<ide> */
<ide> SpeedController arm2 = RobotMap.armArm2;
<ide> AnalogChannel armPotentiometer = RobotMap.armArmPotentiometer;
<ide> // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
<del> private BeachbotPrefSendablePIDController armPID;
<add> private PrefSendablePIDController armPID;
<ide> // Put methods for controlling this subsystem
<ide> // here. Call these from Commands.
<ide> public void initDefaultCommand() {
<ide> private static final String PREF_Arm_ArmPositionDash = "ArmPositionDash";
<ide>
<ide> public Arm() {
<del> armPID = new BeachbotPrefSendablePIDController(0,0,0,this,this, "armPID");
<add> armPID = new PrefSendablePIDController(0,0,0,this,this, "armPID");
<ide> // armPID = new PIDController(0,0,0,this,this);
<ide> armPID.setAbsoluteTolerance(0.1);
<ide> Preferences.getInstance().putDouble("ArmAbsoluteTolerance", 0.1); |
|
Java | apache-2.0 | bd6993c3d737d9318fb826f3bb50a1847b629617 | 0 | rashidaligee/kylo,claudiu-stanciu/kylo,peter-gergely-horvath/kylo,rashidaligee/kylo,Teradata/kylo,rashidaligee/kylo,Teradata/kylo,rashidaligee/kylo,claudiu-stanciu/kylo,peter-gergely-horvath/kylo,Teradata/kylo,claudiu-stanciu/kylo,claudiu-stanciu/kylo,peter-gergely-horvath/kylo,Teradata/kylo,Teradata/kylo,claudiu-stanciu/kylo,peter-gergely-horvath/kylo | package com.thinkbiganalytics.nifi.provenance.v2;
import com.thinkbiganalytics.nifi.provenance.v2.writer.ThinkbigProvenanceEventWriter;
import com.thinkbiganalytics.util.SpringApplicationContext;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.serialization.RecordWriter;
import org.apache.nifi.provenance.toc.TocWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* Used in conjunction with the ThinkbigProvenanceEventRepository to assign the correct Ids to the incoming ProvenanceEventRecord objects
*
* Created by sr186054 on 8/26/16.
*/
public class ThinkbigRecordWriterDelegate implements RecordWriter {
private static final Logger log = LoggerFactory.getLogger(ThinkbigRecordWriterDelegate.class);
private RecordWriter recordWriter;
public ThinkbigRecordWriterDelegate(RecordWriter recordWriter) {
this.recordWriter = recordWriter;
}
@Override
public void writeHeader(long l) throws IOException {
recordWriter.writeHeader(l);
}
@Override
public long writeRecord(ProvenanceEventRecord provenanceEventRecord, long l) throws IOException {
ThinkbigProvenanceEventWriter thinkbigProvenanceEventWriter = (ThinkbigProvenanceEventWriter) SpringApplicationContext.getInstance().getBean("thinkbigProvenanceEventWriter");
if (thinkbigProvenanceEventWriter != null) {
thinkbigProvenanceEventWriter.writeEvent(provenanceEventRecord, l);
}
return recordWriter.writeRecord(provenanceEventRecord, l);
}
@Override
public void flush() throws IOException {
recordWriter.flush();
}
@Override
public int getRecordsWritten() {
return recordWriter.getRecordsWritten();
}
@Override
public File getFile() {
return recordWriter.getFile();
}
@Override
public void lock() {
recordWriter.lock();
}
@Override
public void unlock() {
recordWriter.unlock();
}
@Override
public boolean tryLock() {
return recordWriter.tryLock();
}
@Override
public void markDirty() {
recordWriter.markDirty();
}
@Override
public void sync() throws IOException {
recordWriter.sync();
}
@Override
public TocWriter getTocWriter() {
return recordWriter.getTocWriter();
}
@Override
public boolean isClosed() {
return recordWriter.isClosed();
}
public synchronized void close() throws IOException {
this.recordWriter.close();
}
}
| integrations/nifi/nifi-nar-bundles/nifi-provenance-repo-bundle/nifi-provenance-repo/src/main/java/com/thinkbiganalytics/nifi/provenance/v2/ThinkbigRecordWriterDelegate.java | package com.thinkbiganalytics.nifi.provenance.v2;
import com.thinkbiganalytics.nifi.provenance.v2.writer.ThinkbigProvenanceEventWriter;
import com.thinkbiganalytics.util.SpringApplicationContext;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.serialization.RecordWriter;
import org.apache.nifi.provenance.toc.TocWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* Used in conjunction with the ThinkbigProvenanceEventRepository to assign the correct Ids to the incoming ProvenanceEventRecord objects
*
* Created by sr186054 on 8/26/16.
*/
public class ThinkbigRecordWriterDelegate implements RecordWriter {
private static final Logger log = LoggerFactory.getLogger(ThinkbigRecordWriterDelegate.class);
private RecordWriter recordWriter;
public ThinkbigRecordWriterDelegate(RecordWriter recordWriter) {
this.recordWriter = recordWriter;
}
@Override
public void writeHeader(long l) throws IOException {
recordWriter.writeHeader(l);
}
@Override
public long writeRecord(ProvenanceEventRecord provenanceEventRecord, long l) throws IOException {
ThinkbigProvenanceEventWriter thinkbigProvenanceEventWriter = (ThinkbigProvenanceEventWriter) SpringApplicationContext.getInstance().getBean("thinkbigProvenanceEventWriter");
if (thinkbigProvenanceEventWriter != null) {
thinkbigProvenanceEventWriter.writeEvent(provenanceEventRecord, l);
}
return recordWriter.writeRecord(provenanceEventRecord, l);
}
@Override
public int getRecordsWritten() {
return recordWriter.getRecordsWritten();
}
@Override
public File getFile() {
return recordWriter.getFile();
}
@Override
public void lock() {
recordWriter.lock();
}
@Override
public void unlock() {
recordWriter.unlock();
}
@Override
public boolean tryLock() {
return recordWriter.tryLock();
}
@Override
public void markDirty() {
recordWriter.markDirty();
}
@Override
public void sync() throws IOException {
recordWriter.sync();
}
@Override
public TocWriter getTocWriter() {
return recordWriter.getTocWriter();
}
@Override
public boolean isClosed() {
return recordWriter.isClosed();
}
public synchronized void close() throws IOException {
this.recordWriter.close();
}
}
| PC-918 Implement NiFi v1.1 RecordWriter interface.
| integrations/nifi/nifi-nar-bundles/nifi-provenance-repo-bundle/nifi-provenance-repo/src/main/java/com/thinkbiganalytics/nifi/provenance/v2/ThinkbigRecordWriterDelegate.java | PC-918 Implement NiFi v1.1 RecordWriter interface. | <ide><path>ntegrations/nifi/nifi-nar-bundles/nifi-provenance-repo-bundle/nifi-provenance-repo/src/main/java/com/thinkbiganalytics/nifi/provenance/v2/ThinkbigRecordWriterDelegate.java
<ide> }
<ide> return recordWriter.writeRecord(provenanceEventRecord, l);
<ide>
<add> }
<add>
<add> @Override
<add> public void flush() throws IOException {
<add> recordWriter.flush();
<ide> }
<ide>
<ide> @Override |
|
Java | agpl-3.0 | 4aad8c13102941d6961492491d6fc6480eae58dc | 0 | samihusseingit/AndroidAPS,MilosKozak/AndroidAPS,AdrianLxM/AndroidAPS,samihusseingit/AndroidAPS,LadyViktoria/AndroidAPS,Heiner1/AndroidAPS,RoumenGeorgiev/AndroidAPS,jotomo/AndroidAPS,PoweRGbg/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS,RoumenGeorgiev/AndroidAPS,jotomo/AndroidAPS,PoweRGbg/AndroidAPS,LadyViktoria/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,AdrianLxM/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS | package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResult;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewExtendedBolusDialog;
import info.nightscout.client.data.DbLogger;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderFragment.class);
ListView bgsourceListView;
ListView pumpListView;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
ListView tempsListView;
ListView profileListView;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
ListView generalListView;
TextView nsclientVerView;
TextView nightscoutVerView;
PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null;
PluginCustomAdapter tempsDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null;
BgSourceInterface activeBgSource;
PumpInterface activePump;
ProfileInterface activeProfile;
TreatmentsInterface activeTreatments;
TempBasalsInterface activeTempBasals;
LoopFragment activeLoop;
public String nightscoutVersionName = "";
public Integer nightscoutVersionCode = 0;
public String nsClientVersionName = "";
public Integer nsClientVersionCode = 0;
ArrayList<PluginBase> pluginList;
Date lastDeviceStatusUpload = new Date(0);
// TODO: sorting
// TODO: Toast and sound when command failed
public ConfigBuilderFragment() {
super();
registerBus();
}
public void initialize() {
pluginList = MainApp.getPluginsList();
loadSettings();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
tempsListView = (ListView) view.findViewById(R.id.configbuilder_tempslistview);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
nsclientVerView = (TextView) view.findViewById(R.id.configbuilder_nsclientversion);
nightscoutVerView = (TextView) view.findViewById(R.id.configbuilder_nightscoutversion);
nsclientVerView.setText(nsClientVersionName);
nightscoutVerView.setText(nightscoutVersionName);
if (nsClientVersionCode < 117) nsclientVerView.setTextColor(Color.RED);
if (nightscoutVersionCode < 900) nightscoutVerView.setTextColor(Color.RED);
setViews();
return view;
}
void setViews() {
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
setListViewHeightBasedOnChildren(pumpListView);
loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
if (MainApp.getSpecificPluginsList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
tempsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL), PluginBase.TEMPBASAL);
tempsListView.setAdapter(tempsDataAdapter);
setListViewHeightBasedOnChildren(tempsListView);
profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ProfileInterface.class), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
if (MainApp.getSpecificPluginsList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
}
/*
* PluginBase interface
*/
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.configbuilder);
}
@Override
public boolean isEnabled(int type) {
return true;
}
@Override
public boolean isVisibleInTabs(int type) {
return true;
}
@Override
public boolean canBeHidden(int type) {
return false;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
// Always enabled
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
// Always visible
}
public static ConfigBuilderFragment newInstance() {
ConfigBuilderFragment fragment = new ConfigBuilderFragment();
return fragment;
}
/*
* Pump interface
*
* Config builder return itself as a pump and check constraints before it passes command to pump driver
*/
@Override
public boolean isTempBasalInProgress() {
return activePump.isTempBasalInProgress();
}
@Override
public boolean isExtendedBoluslInProgress() {
return activePump.isExtendedBoluslInProgress();
}
@Override
public void setNewBasalProfile(NSProfile profile) {
activePump.setNewBasalProfile(profile);
}
@Override
public double getBaseBasalRate() {
return activePump.getBaseBasalRate();
}
@Override
public double getTempBasalAbsoluteRate() {
return activePump.getTempBasalAbsoluteRate();
}
@Override
public double getTempBasalRemainingMinutes() {
return activePump.getTempBasalRemainingMinutes();
}
@Override
public TempBasal getTempBasal(Date time) {
return activePump.getTempBasal(time);
}
@Override
public TempBasal getTempBasal() {
return activePump.getTempBasal();
}
@Override
public TempBasal getExtendedBolus() {
return activePump.getExtendedBolus();
}
/*
{
"_id": {
"$oid": "5789fea07ef0c37deb388240"
},
"boluscalc": {
"profile": "Posunuta snidane",
"eventTime": "2016-07-16T09:30:14.139Z",
"targetBGLow": "5.6",
"targetBGHigh": "5.6",
"isf": "17",
"ic": "26",
"iob": "0.89",
"cob": "0",
"insulincob": "0",
"bg": "3.6",
"insulinbg": "-0.12",
"bgdiff": "-2",
"carbs": "42",
"gi": "2",
"insulincarbs": "1.62",
"othercorrection": "0",
"insulin": "0.6000000000000001",
"roundingcorrection": "-0.009999999999999898",
"carbsneeded": "0"
},
"enteredBy": "",
"eventType": "Bolus Wizard",
"glucose": 3.6,
"glucoseType": "Sensor",
"units": "mmol",
"carbs": 42,
"insulin": 0.6,
"created_at": "2016-07-16T09:30:12.783Z"
}
*/
public PumpEnactResult deliverTreatmentFromBolusWizard(Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatmentFromBolusWizard insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
t.sendToNSClient();
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
/**
* apply constraints, set temp based on absolute valus and expecting absolute result
*
* @param absoluteRate
* @param durationInMinutes
* @return
*/
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
if (result.isPercent) {
uploadTempBasalStartPercent(result.percent, result.duration);
} else {
uploadTempBasalStartAbsolute(result.absolute, result.duration);
}
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
/**
* apply constraints, set temp based on percent and expecting result in percent
*
* @param percent 0 ... 100 ...
* @param durationInMinutes
* @return result
*/
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadExtendedBolus(result.bolusDelivered, result.duration);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult cancelTempBasal() {
PumpEnactResult result = activePump.cancelTempBasal();
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = activePump.cancelExtendedBolus();
if (Config.logCongigBuilderActions)
log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted);
return result;
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*
* @param request
* @return
*/
public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - getBaseBasalRate()) < 0.1) {
if (isTempBasalInProgress()) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
result = cancelTempBasal();
} else {
result = new PumpEnactResult();
result.absolute = request.rate;
result.duration = 0;
result.enacted = false;
result.comment = "Basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
}
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.1) {
result = new PumpEnactResult();
result.absolute = getTempBasalAbsoluteRate();
result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
result = setTempBasalAbsolute(request.rate, request.duration);
}
return result;
}
@Nullable
@Override
public JSONObject getJSONStatus() {
if (activePump != null)
return activePump.getJSONStatus();
else return null;
}
@Override
public String deviceID() {
if (activePump != null)
return activePump.deviceID();
else return "Unknown";
}
/*
* ConfigBuilderFragment code
*/
private class PluginCustomAdapter extends ArrayAdapter<PluginBase> {
private ArrayList<PluginBase> pluginList;
final private int type;
public PluginCustomAdapter(Context context, int textViewResourceId,
ArrayList<PluginBase> pluginList, int type) {
super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<PluginBase>();
this.pluginList.addAll(pluginList);
this.type = type;
}
private class PluginViewHolder {
TextView name;
CheckBox checkboxEnabled;
CheckBox checkboxVisible;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PluginViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.configbuilder_simpleitem_name);
holder.checkboxEnabled = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
holder.checkboxVisible = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
convertView.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentEnabled(type, cb.isChecked());
plugin.setFragmentVisible(type, cb.isChecked());
onEnabledCategoryChanged(plugin, type);
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
holder.checkboxVisible.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentVisible(type, cb.isChecked());
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
} else {
holder = (PluginViewHolder) convertView.getTag();
}
PluginBase plugin = pluginList.get(position);
holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin);
if (!plugin.canBeHidden(type)) {
holder.checkboxEnabled.setEnabled(false);
holder.checkboxVisible.setEnabled(false);
}
int type = plugin.getType();
// Force enabled if there is only one plugin
if (type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.TEMPBASAL || type == PluginBase.PROFILE)
if (pluginList.size() < 2)
holder.checkboxEnabled.setEnabled(false);
// Constraints cannot be disabled
if (type == PluginBase.CONSTRAINTS)
holder.checkboxEnabled.setEnabled(false);
// Hide disabled profiles by default
if (type == PluginBase.PROFILE) {
if (!plugin.isEnabled(type)) {
holder.checkboxVisible.setEnabled(false);
holder.checkboxVisible.setChecked(false);
} else {
holder.checkboxVisible.setEnabled(true);
}
}
return convertView;
}
}
public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
public PumpInterface getActivePump() {
return this;
}
@Nullable
public ProfileInterface getActiveProfile() {
return activeProfile;
}
public TreatmentsInterface getActiveTreatments() {
return activeTreatments;
}
public TempBasalsInterface getActiveTempBasals() {
return activeTempBasals;
}
public LoopFragment getActiveLoop() {
return activeLoop;
}
void onEnabledCategoryChanged(PluginBase changedPlugin, int type) {
int category = changedPlugin.getType();
ArrayList<PluginBase> pluginsInCategory = null;
switch (category) {
// Multiple selection allowed
case PluginBase.APS:
case PluginBase.GENERAL:
case PluginBase.CONSTRAINTS:
case PluginBase.LOOP:
break;
// Single selection allowed
case PluginBase.PROFILE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case PluginBase.BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case PluginBase.TEMPBASAL:
case PluginBase.TREATMENT:
case PluginBase.PUMP:
pluginsInCategory = MainApp.getSpecificPluginsList(category);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setFragmentEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setFragmentEnabled(type, true);
}
setViews();
}
}
private void verifySelectionInCategories() {
ArrayList<PluginBase> pluginsInCategory;
// PluginBase.PROFILE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
if (Config.logConfigBuilder)
log.debug("Selected profile interface: " + ((PluginBase) activeProfile).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeProfile).getName())) {
p.setFragmentVisible(PluginBase.PROFILE, false);
}
}
// PluginBase.BGSOURCE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
activeBgSource = (BgSourceInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.BGSOURCE);
if (Config.logConfigBuilder)
log.debug("Selected bgSource interface: " + ((PluginBase) activeBgSource).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeBgSource).getName())) {
p.setFragmentVisible(PluginBase.BGSOURCE, false);
}
}
// PluginBase.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activePump).getName())) {
p.setFragmentVisible(PluginBase.PUMP, false);
}
}
// PluginBase.LOOP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.LOOP);
activeLoop = (LoopFragment) getTheOneEnabledInArray(pluginsInCategory, PluginBase.LOOP);
if (activeLoop != null) {
if (Config.logConfigBuilder)
log.debug("Selected loop interface: " + activeLoop.getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activeLoop.getName())) {
p.setFragmentVisible(PluginBase.LOOP, false);
}
}
}
// PluginBase.TEMPBASAL
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL);
activeTempBasals = (TempBasalsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TEMPBASAL);
if (Config.logConfigBuilder)
log.debug("Selected tempbasal interface: " + ((PluginBase) activeTempBasals).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTempBasals).getName())) {
p.setFragmentVisible(PluginBase.TEMPBASAL, false);
}
}
// PluginBase.TREATMENT
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
if (Config.logConfigBuilder)
log.debug("Selected treatment interface: " + ((PluginBase) activeTreatments).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTreatments).getName())) {
p.setFragmentVisible(PluginBase.TREATMENT, false);
}
}
}
@Nullable
private PluginBase getTheOneEnabledInArray(ArrayList<PluginBase> pluginsInCategory, int type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
continue;
} else if (p.isEnabled(type)) {
// set others disabled
p.setFragmentEnabled(type, false);
}
}
// If none enabled, enable first one
if (found == null && pluginsInCategory.size() > 0)
found = pluginsInCategory.get(0);
return found;
}
private void storeSettings() {
if (pluginList != null) {
if (Config.logPrefsChange)
log.debug("Storing settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
editor.putBoolean(settingEnabled, p.isEnabled(type));
editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
}
}
editor.commit();
verifySelectionInCategories();
}
}
private void loadSettings() {
if (Config.logPrefsChange)
log.debug("Loading stored settings");
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingEnabled))
p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, true));
}
}
verifySelectionInCategories();
}
/****
* Method for Setting the Height of the ListView dynamically.
* *** Hack to fix the issue of not showing all the items of the ListView
* *** when placed inside a ScrollView
****/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* Constraints interface
**/
@Override
public boolean isLoopEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isLoopEnabled();
}
return result;
}
@Override
public boolean isClosedModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isClosedModeEnabled();
}
return result;
}
@Override
public boolean isAutosensModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAutosensModeEnabled();
}
return result;
}
@Override
public boolean isAMAModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAMAModeEnabled();
}
return result;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
Double rateAfterConstrain = absoluteRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
Integer rateAfterConstrain = percentRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Double applyBolusConstraints(Double insulin) {
Double insulinAfterConstrain = insulin;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
}
return insulinAfterConstrain;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
Integer carbsAfterConstrain = carbs;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
}
return carbsAfterConstrain;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
Double maxIobAfterConstrain = maxIob;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
}
return maxIobAfterConstrain;
}
@Subscribe
public void onStatusEvent(final EventNewBG ev) {
// Give some time to Loop
try {
Thread.sleep(120 * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// if status not uploaded, upload pump status only
if (new Date().getTime() - lastDeviceStatusUpload.getTime() > 120 * 1000L) {
uploadDeviceStatus();
}
}
public static void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("absolute", absolute);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
if (useAbsolute) {
double absolute = MainApp.getConfigBuilder().getActivePump().getBaseBasalRate() * percent / 100d;
uploadTempBasalStartAbsolute(absolute, durationInMinutes);
} else {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("percent", percent - 100);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
}
} catch (JSONException e) {
}
}
public static void uploadTempBasalEnd() {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadExtendedBolus(Double insulin, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Combo Bolus");
data.put("duration", durationInMinutes);
data.put("splitNow", 0);
data.put("splitExt", 100);
data.put("enteredinsulin", insulin);
data.put("relative", insulin);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public void uploadDeviceStatus() {
DeviceStatus deviceStatus = new DeviceStatus();
try {
LoopFragment.LastRun lastRun = LoopFragment.lastRun;
if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 60 * 1000L) {
// do not send if result is older than 1 min
APSResult apsResult = lastRun.request;
apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun));
deviceStatus.suggested = apsResult.json();
if (lastRun.request instanceof DetermineBasalResult) {
DetermineBasalResult result = (DetermineBasalResult) lastRun.request;
deviceStatus.iob = result.iob.json();
deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
}
if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted
deviceStatus.enacted = lastRun.request.json();
deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate"));
deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration"));
deviceStatus.enacted.put("recieved", true);
JSONObject requested = new JSONObject();
requested.put("duration", lastRun.request.duration);
requested.put("rate", lastRun.request.rate);
requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested);
}
}
if (getActivePump() != null) {
deviceStatus.device = "openaps://" + getActivePump().deviceID();
deviceStatus.pump = getActivePump().getJSONStatus();
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
lastDeviceStatusUpload = new Date();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
JSONObject data = new JSONObject();
try {
data.put("eventType", "Bolus Wizard");
if (t.insulin != 0d) data.put("insulin", t.insulin);
if (t.carbs != 0d) data.put("carbs", t.carbs.intValue());
data.put("created_at", DateUtil.toISOString(t.created_at));
data.put("timeIndex", t.timeIndex);
if (glucose != 0d) data.put("glucose", glucose);
data.put("glucoseType", glucoseType);
data.put("boluscalc", boluscalc);
if (carbTime != 0) data.put("preBolus", carbTime);
} catch (JSONException e) {
e.printStackTrace();
}
uploadCareportalEntryToNS(data);
}
public static void uploadCareportalEntryToNS(JSONObject data) {
try {
if (data.has("preBolus") && data.has("carbs")) {
JSONObject prebolus = new JSONObject();
prebolus.put("carbs", data.get("carbs"));
data.remove("carbs");
prebolus.put("eventType", data.get("eventType"));
if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy"));
if (data.has("notes")) prebolus.put("notes", data.get("notes"));
long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime();
Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L);
prebolus.put("created_at", DateUtil.toISOString(preBolusDate));
uploadCareportalEntryToNS(prebolus);
}
Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), NewExtendedBolusDialog.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java | package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResult;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewExtendedBolusDialog;
import info.nightscout.client.data.DbLogger;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderFragment.class);
ListView bgsourceListView;
ListView pumpListView;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
ListView tempsListView;
ListView profileListView;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
ListView generalListView;
TextView nsclientVerView;
TextView nightscoutVerView;
PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null;
PluginCustomAdapter tempsDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null;
BgSourceInterface activeBgSource;
PumpInterface activePump;
ProfileInterface activeProfile;
TreatmentsInterface activeTreatments;
TempBasalsInterface activeTempBasals;
LoopFragment activeLoop;
public String nightscoutVersionName = "";
public Integer nightscoutVersionCode = 0;
public String nsClientVersionName = "";
public Integer nsClientVersionCode = 0;
ArrayList<PluginBase> pluginList;
Date lastDeviceStatusUpload = new Date(0);
// TODO: sorting
// TODO: Toast and sound when command failed
public ConfigBuilderFragment() {
super();
registerBus();
}
public void initialize() {
pluginList = MainApp.getPluginsList();
loadSettings();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
tempsListView = (ListView) view.findViewById(R.id.configbuilder_tempslistview);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
nsclientVerView = (TextView) view.findViewById(R.id.configbuilder_nsclientversion);
nightscoutVerView = (TextView) view.findViewById(R.id.configbuilder_nightscoutversion);
nsclientVerView.setText(nsClientVersionName);
nightscoutVerView.setText(nightscoutVersionName);
if (nsClientVersionCode < 117) nsclientVerView.setTextColor(Color.RED);
if (nightscoutVersionCode < 900) nightscoutVerView.setTextColor(Color.RED);
setViews();
return view;
}
void setViews() {
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
setListViewHeightBasedOnChildren(pumpListView);
loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
if (MainApp.getSpecificPluginsList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
tempsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL), PluginBase.TEMPBASAL);
tempsListView.setAdapter(tempsDataAdapter);
setListViewHeightBasedOnChildren(tempsListView);
profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ProfileInterface.class), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
if (MainApp.getSpecificPluginsList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
}
/*
* PluginBase interface
*/
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.configbuilder);
}
@Override
public boolean isEnabled(int type) {
return true;
}
@Override
public boolean isVisibleInTabs(int type) {
return true;
}
@Override
public boolean canBeHidden(int type) {
return false;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
// Always enabled
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
// Always visible
}
public static ConfigBuilderFragment newInstance() {
ConfigBuilderFragment fragment = new ConfigBuilderFragment();
return fragment;
}
/*
* Pump interface
*
* Config builder return itself as a pump and check constraints before it passes command to pump driver
*/
@Override
public boolean isTempBasalInProgress() {
return activePump.isTempBasalInProgress();
}
@Override
public boolean isExtendedBoluslInProgress() {
return activePump.isExtendedBoluslInProgress();
}
@Override
public void setNewBasalProfile(NSProfile profile) {
activePump.setNewBasalProfile(profile);
}
@Override
public double getBaseBasalRate() {
return activePump.getBaseBasalRate();
}
@Override
public double getTempBasalAbsoluteRate() {
return activePump.getTempBasalAbsoluteRate();
}
@Override
public double getTempBasalRemainingMinutes() {
return activePump.getTempBasalRemainingMinutes();
}
@Override
public TempBasal getTempBasal(Date time) {
return activePump.getTempBasal(time);
}
@Override
public TempBasal getTempBasal() {
return activePump.getTempBasal();
}
@Override
public TempBasal getExtendedBolus() {
return activePump.getExtendedBolus();
}
/*
{
"_id": {
"$oid": "5789fea07ef0c37deb388240"
},
"boluscalc": {
"profile": "Posunuta snidane",
"eventTime": "2016-07-16T09:30:14.139Z",
"targetBGLow": "5.6",
"targetBGHigh": "5.6",
"isf": "17",
"ic": "26",
"iob": "0.89",
"cob": "0",
"insulincob": "0",
"bg": "3.6",
"insulinbg": "-0.12",
"bgdiff": "-2",
"carbs": "42",
"gi": "2",
"insulincarbs": "1.62",
"othercorrection": "0",
"insulin": "0.6000000000000001",
"roundingcorrection": "-0.009999999999999898",
"carbsneeded": "0"
},
"enteredBy": "",
"eventType": "Bolus Wizard",
"glucose": 3.6,
"glucoseType": "Sensor",
"units": "mmol",
"carbs": 42,
"insulin": 0.6,
"created_at": "2016-07-16T09:30:12.783Z"
}
*/
public PumpEnactResult deliverTreatmentFromBolusWizard(Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatmentFromBolusWizard insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
t.sendToNSClient();
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
/**
* apply constraints, set temp based on absolute valus and expecting absolute result
*
* @param absoluteRate
* @param durationInMinutes
* @return
*/
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
if (result.isPercent) {
uploadTempBasalStartPercent(result.percent, result.duration);
} else {
uploadTempBasalStartAbsolute(result.absolute, result.duration);
}
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
/**
* apply constraints, set temp based on percent and expecting result in percent
*
* @param percent 0 ... 100 ...
* @param durationInMinutes
* @return result
*/
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadExtendedBolus(result.bolusDelivered, result.duration);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult cancelTempBasal() {
PumpEnactResult result = activePump.cancelTempBasal();
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = activePump.cancelExtendedBolus();
if (Config.logCongigBuilderActions)
log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted);
return result;
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*
* @param request
* @return
*/
public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - getBaseBasalRate()) < 0.1) {
if (isTempBasalInProgress()) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
result = cancelTempBasal();
} else {
result = new PumpEnactResult();
result.absolute = request.rate;
result.duration = 0;
result.enacted = false;
result.comment = "Basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
}
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.1) {
result = new PumpEnactResult();
result.absolute = getTempBasalAbsoluteRate();
result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
result = setTempBasalAbsolute(request.rate, request.duration);
}
return result;
}
@Nullable
@Override
public JSONObject getJSONStatus() {
if (activePump != null)
return activePump.getJSONStatus();
else return null;
}
@Override
public String deviceID() {
if (activePump != null)
return activePump.deviceID();
else return "Unknown";
}
/*
* ConfigBuilderFragment code
*/
private class PluginCustomAdapter extends ArrayAdapter<PluginBase> {
private ArrayList<PluginBase> pluginList;
final private int type;
public PluginCustomAdapter(Context context, int textViewResourceId,
ArrayList<PluginBase> pluginList, int type) {
super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<PluginBase>();
this.pluginList.addAll(pluginList);
this.type = type;
}
private class PluginViewHolder {
TextView name;
CheckBox checkboxEnabled;
CheckBox checkboxVisible;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PluginViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.configbuilder_simpleitem_name);
holder.checkboxEnabled = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
holder.checkboxVisible = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
convertView.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentEnabled(type, cb.isChecked());
plugin.setFragmentVisible(type, cb.isChecked());
onEnabledCategoryChanged(plugin, type);
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
holder.checkboxVisible.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentVisible(type, cb.isChecked());
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
} else {
holder = (PluginViewHolder) convertView.getTag();
}
PluginBase plugin = pluginList.get(position);
holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin);
if (!plugin.canBeHidden(type)) {
holder.checkboxEnabled.setEnabled(false);
holder.checkboxVisible.setEnabled(false);
}
int type = plugin.getType();
// Force enabled if there is only one plugin
if (type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.TEMPBASAL || type == PluginBase.PROFILE)
if (pluginList.size() < 2)
holder.checkboxEnabled.setEnabled(false);
// Constraints cannot be disabled
if (type == PluginBase.CONSTRAINTS)
holder.checkboxEnabled.setEnabled(false);
// Hide disabled profiles by default
if (type == PluginBase.PROFILE) {
if (!plugin.isEnabled(type)) {
holder.checkboxVisible.setEnabled(false);
holder.checkboxVisible.setChecked(false);
} else {
holder.checkboxVisible.setEnabled(true);
}
}
return convertView;
}
}
public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
public PumpInterface getActivePump() {
return this;
}
@Nullable
public ProfileInterface getActiveProfile() {
return activeProfile;
}
public TreatmentsInterface getActiveTreatments() {
return activeTreatments;
}
public TempBasalsInterface getActiveTempBasals() {
return activeTempBasals;
}
public LoopFragment getActiveLoop() {
return activeLoop;
}
void onEnabledCategoryChanged(PluginBase changedPlugin, int type) {
int category = changedPlugin.getType();
ArrayList<PluginBase> pluginsInCategory = null;
switch (category) {
// Multiple selection allowed
case PluginBase.APS:
case PluginBase.GENERAL:
case PluginBase.CONSTRAINTS:
case PluginBase.LOOP:
break;
// Single selection allowed
case PluginBase.PROFILE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case PluginBase.BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case PluginBase.TEMPBASAL:
case PluginBase.TREATMENT:
case PluginBase.PUMP:
pluginsInCategory = MainApp.getSpecificPluginsList(category);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setFragmentEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setFragmentEnabled(type, true);
}
setViews();
}
}
private void verifySelectionInCategories() {
ArrayList<PluginBase> pluginsInCategory;
// PluginBase.PROFILE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
if (Config.logConfigBuilder)
log.debug("Selected profile interface: " + ((PluginBase) activeProfile).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeProfile).getName())) {
p.setFragmentVisible(PluginBase.PROFILE, false);
}
}
// PluginBase.BGSOURCE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
activeBgSource = (BgSourceInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.BGSOURCE);
if (Config.logConfigBuilder)
log.debug("Selected bgSource interface: " + ((PluginBase) activeBgSource).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeBgSource).getName())) {
p.setFragmentVisible(PluginBase.BGSOURCE, false);
}
}
// PluginBase.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activePump).getName())) {
p.setFragmentVisible(PluginBase.PUMP, false);
}
}
// PluginBase.LOOP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.LOOP);
activeLoop = (LoopFragment) getTheOneEnabledInArray(pluginsInCategory, PluginBase.LOOP);
if (activeLoop != null) {
if (Config.logConfigBuilder)
log.debug("Selected loop interface: " + activeLoop.getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activeLoop.getName())) {
p.setFragmentVisible(PluginBase.LOOP, false);
}
}
}
// PluginBase.TEMPBASAL
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL);
activeTempBasals = (TempBasalsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TEMPBASAL);
if (Config.logConfigBuilder)
log.debug("Selected tempbasal interface: " + ((PluginBase) activeTempBasals).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTempBasals).getName())) {
p.setFragmentVisible(PluginBase.TEMPBASAL, false);
}
}
// PluginBase.TREATMENT
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
if (Config.logConfigBuilder)
log.debug("Selected treatment interface: " + ((PluginBase) activeTreatments).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTreatments).getName())) {
p.setFragmentVisible(PluginBase.TREATMENT, false);
}
}
}
@Nullable
private PluginBase getTheOneEnabledInArray(ArrayList<PluginBase> pluginsInCategory, int type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
continue;
} else if (p.isEnabled(type)) {
// set others disabled
p.setFragmentEnabled(type, false);
}
}
// If none enabled, enable first one
if (found == null && pluginsInCategory.size() > 0)
found = pluginsInCategory.get(0);
return found;
}
private void storeSettings() {
if (pluginList != null) {
if (Config.logPrefsChange)
log.debug("Storing settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getName() + "_Visible";
editor.putBoolean(settingEnabled, p.isEnabled(type));
editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
}
}
editor.commit();
verifySelectionInCategories();
}
}
private void loadSettings() {
if (Config.logPrefsChange)
log.debug("Loading stored settings");
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getName() + "_Visible";
if (SP.contains(settingEnabled))
p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, true));
}
}
verifySelectionInCategories();
}
/****
* Method for Setting the Height of the ListView dynamically.
* *** Hack to fix the issue of not showing all the items of the ListView
* *** when placed inside a ScrollView
****/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* Constraints interface
**/
@Override
public boolean isLoopEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isLoopEnabled();
}
return result;
}
@Override
public boolean isClosedModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isClosedModeEnabled();
}
return result;
}
@Override
public boolean isAutosensModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAutosensModeEnabled();
}
return result;
}
@Override
public boolean isAMAModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAMAModeEnabled();
}
return result;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
Double rateAfterConstrain = absoluteRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
Integer rateAfterConstrain = percentRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Double applyBolusConstraints(Double insulin) {
Double insulinAfterConstrain = insulin;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
}
return insulinAfterConstrain;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
Integer carbsAfterConstrain = carbs;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
}
return carbsAfterConstrain;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
Double maxIobAfterConstrain = maxIob;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
}
return maxIobAfterConstrain;
}
@Subscribe
public void onStatusEvent(final EventNewBG ev) {
// Give some time to Loop
try {
Thread.sleep(120 * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// if status not uploaded, upload pump status only
if (new Date().getTime() - lastDeviceStatusUpload.getTime() > 120 * 1000L) {
uploadDeviceStatus();
}
}
public static void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("absolute", absolute);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
if (useAbsolute) {
double absolute = MainApp.getConfigBuilder().getActivePump().getBaseBasalRate() * percent / 100d;
uploadTempBasalStartAbsolute(absolute, durationInMinutes);
} else {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("percent", percent - 100);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
}
} catch (JSONException e) {
}
}
public static void uploadTempBasalEnd() {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadExtendedBolus(Double insulin, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Combo Bolus");
data.put("duration", durationInMinutes);
data.put("splitNow", 0);
data.put("splitExt", 100);
data.put("enteredinsulin", insulin);
data.put("relative", insulin);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public void uploadDeviceStatus() {
DeviceStatus deviceStatus = new DeviceStatus();
try {
LoopFragment.LastRun lastRun = LoopFragment.lastRun;
if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 60 * 1000L) {
// do not send if result is older than 1 min
APSResult apsResult = lastRun.request;
apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun));
deviceStatus.suggested = apsResult.json();
if (lastRun.request instanceof DetermineBasalResult) {
DetermineBasalResult result = (DetermineBasalResult) lastRun.request;
deviceStatus.iob = result.iob.json();
deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
}
if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted
deviceStatus.enacted = lastRun.request.json();
deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate"));
deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration"));
deviceStatus.enacted.put("recieved", true);
JSONObject requested = new JSONObject();
requested.put("duration", lastRun.request.duration);
requested.put("rate", lastRun.request.rate);
requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested);
}
}
if (getActivePump() != null) {
deviceStatus.device = "openaps://" + getActivePump().deviceID();
deviceStatus.pump = getActivePump().getJSONStatus();
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
lastDeviceStatusUpload = new Date();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
JSONObject data = new JSONObject();
try {
data.put("eventType", "Bolus Wizard");
if (t.insulin != 0d) data.put("insulin", t.insulin);
if (t.carbs != 0d) data.put("carbs", t.carbs.intValue());
data.put("created_at", DateUtil.toISOString(t.created_at));
data.put("timeIndex", t.timeIndex);
if (glucose != 0d) data.put("glucose", glucose);
data.put("glucoseType", glucoseType);
data.put("boluscalc", boluscalc);
if (carbTime != 0) data.put("preBolus", carbTime);
} catch (JSONException e) {
e.printStackTrace();
}
uploadCareportalEntryToNS(data);
}
public static void uploadCareportalEntryToNS(JSONObject data) {
try {
if (data.has("preBolus") && data.has("carbs")) {
JSONObject prebolus = new JSONObject();
prebolus.put("carbs", data.get("carbs"));
data.remove("carbs");
prebolus.put("eventType", data.get("eventType"));
if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy"));
if (data.has("notes")) prebolus.put("notes", data.get("notes"));
long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime();
Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L);
prebolus.put("created_at", DateUtil.toISOString(preBolusDate));
uploadCareportalEntryToNS(prebolus);
}
Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), NewExtendedBolusDialog.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| use class name of fragment for saving preferences
| app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java | use class name of fragment for saving preferences | <ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
<ide>
<ide> for (int type = 1; type < PluginBase.LAST; type++) {
<ide> for (PluginBase p : pluginList) {
<del> String settingEnabled = "ConfigBuilder_" + type + "_" + p.getName() + "_Enabled";
<del> String settingVisible = "ConfigBuilder_" + type + "_" + p.getName() + "_Visible";
<add> String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
<add> String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
<ide> editor.putBoolean(settingEnabled, p.isEnabled(type));
<ide> editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
<ide> }
<ide> SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
<ide> for (int type = 1; type < PluginBase.LAST; type++) {
<ide> for (PluginBase p : pluginList) {
<del> String settingEnabled = "ConfigBuilder_" + type + "_" + p.getName() + "_Enabled";
<del> String settingVisible = "ConfigBuilder_" + type + "_" + p.getName() + "_Visible";
<add> String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
<add> String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
<ide> if (SP.contains(settingEnabled))
<ide> p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
<ide> if (SP.contains(settingVisible)) |
|
Java | mit | 49ab39d87cdee3b97a76ae65e39218b09e6e57ee | 0 | digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext | package no.deichman.services.entity.repository;
import no.deichman.services.entity.EntityType;
import no.deichman.services.entity.patch.Patch;
import no.deichman.services.rdf.RDFModelUtil;
import no.deichman.services.uridefaults.BaseURI;
import no.deichman.services.uridefaults.XURI;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.of;
import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.apache.jena.rdf.model.ResourceFactory.createTypedLiteral;
/**
* Responsibility: TODO.
*/
public final class SPARQLQueryBuilder {
public static final String INSERT = "INSERT";
public static final String DELETE = "DELETE";
public static final String NEWLINE = "\n";
private static final String INDENT = " ";
public static final boolean KEEP_BLANK_NODES = true;
public static final boolean SKIP_BLANK_NODES = false;
public SPARQLQueryBuilder() {
}
public Query getGetResourceByIdQuery(String id) {
String queryString = "DESCRIBE <" + id + ">";
return QueryFactory.create(queryString);
}
public Query describeWorkAndLinkedResources(XURI xuri) {
String queryString = "#\n"
+ "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <__WORKURI__> ?publication ?workContributor ?compType ?format ?mediaType ?subject ?genre ?instrument"
+ " ?litform ?hasWorkType ?serial ?nation ?pubContrib ?publicationContributor ?place ?publishedBy ?publicationPartValues\n"
+ "WHERE {\n"
+ " { <__WORKURI__> a deichman:Work }\n"
+ " UNION { <__WORKURI__> deichman:contributor ?workContrib .\n"
+ " ?workContrib a deichman:Contribution ;\n"
+ " deichman:agent ?workContributor . \n"
+ " OPTIONAL { ?workContributor deichman:nationality ?nation }"
+ " }\n"
+ " UNION { ?publication deichman:publicationOf <__WORKURI__> ; \n"
+ " a deichman:Publication . \n"
+ " OPTIONAL { ?publication deichman:format ?format .\n"
+ " ?format rdfs:label ?label . }\n"
+ " OPTIONAL { ?publication deichman:hasMediaType ?mediaType .\n"
+ " ?mediaType rdfs:label ?label . }\n"
+ " OPTIONAL { ?publication deichman:contributor ?pubContrib. \n"
+ " ?pubContrib a deichman:Contribution ;\n"
+ " deichman:agent ?publicationContributor . }\n"
+ " OPTIONAL { ?publication deichman:inSerial ?serialIssue . \n"
+ " ?serialIssue deichman:serial ?serial . }\n"
+ " OPTIONAL { ?publication deichman:hasPlaceOfPublication ?place }\n"
+ " OPTIONAL { ?publication deichman:publishedBy ?publishedBy }\n"
+ " OPTIONAL { ?publication deichman:hasPublicationPart ?hasPublicationPart ."
+ " ?hasPublicationPart a deichman:PublicationPart;"
+ " ?publicationPartProperties ?publicationPartValues ."
+ " }\n"
+ " }\n"
+ " UNION { <__WORKURI__> deichman:subject ?subject }\n"
+ " UNION { <__WORKURI__> deichman:hasInstrumentation ?instrumentation .\n"
+ " ?instrumentation deichman:hasInstrument ?instrument }\n"
+ " UNION { <__WORKURI__> deichman:genre ?genre }\n"
+ " UNION { <__WORKURI__> deichman:literaryForm ?litform }\n"
+ " UNION { <__WORKURI__> deichman:hasWorkType ?hasWorkType }\n"
+ " UNION { <__WORKURI__> deichman:hasCompositionType ?compType }\n"
+ "}";
queryString = queryString.replaceAll("__WORKURI__", xuri.getUri());
return QueryFactory.create(queryString);
}
public Query describePersonAndLinkedResources(String personId) {
String queryString = format("#\n"
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <%2$s> ?name ?birth ?death ?personTitle ?nationality ?nationalityLabel \n"
+ "WHERE {\n"
+ " <%2$s> a deichman:Person .\n"
+ " optional { <%2$s> deichman:name ?name . }\n"
+ " optional { <%2$s> deichman:birthYear ?birth . }\n"
+ " optional { <%2$s> deichman:deathYear ?death . }\n"
+ " optional { <%2$s> deichman:personTitle ?personTitle . }\n"
+ " optional { <%2$s> deichman:nationality ?nationality . \n"
+ " ?nationality rdfs:label ?nationalityLabel .\n"
+ " }\n"
+ "}", BaseURI.ontology(), personId);
return QueryFactory.create(queryString);
}
public Query describeCorporationAndLinkedResources(String corporationId) {
String queryString = format("#\n"
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <%2$s> ?name ?nationality ?nationalityLabel \n"
+ "WHERE {\n"
+ " <%2$s> a deichman:Corporation .\n"
+ " optional { <%2$s> deichman:name ?name . }\n"
+ " optional { <%2$s> deichman:nationality ?nationality . \n"
+ " ?nationality rdfs:label ?nationalityLabel .\n"
+ " }\n"
+ "}", BaseURI.ontology(), corporationId);
return QueryFactory.create(queryString);
}
public String getUpdateWorkQueryString(Model work) {
return getCreateQueryString(work);
}
public String getReplaceSubjectQueryString(String newURI) {
return "DELETE {\n"
+ " ?s ?p ?o .\n"
+ "}\n"
+ "INSERT {\n"
+ " <" + newURI + "> ?p ?o .\n"
+ "}\n"
+ "WHERE {\n"
+ " ?s ?p ?o .\n"
+ " FILTER (!isBlank(?s))\n"
+ "}\n";
}
public String getCreateQueryString(Model work) {
StringWriter sw = new StringWriter();
RDFDataMgr.write(sw, work, Lang.NTRIPLES);
String data = sw.toString();
return "INSERT DATA {\n"
+ "\n"
+ data
+ "\n"
+ "}";
}
public Query getItemsFromModelQuery(String id) {
String q = "PREFIX deichman: <" + BaseURI.ontology() + ">\n"
+ "PREFIX duo: <http://data.deichman.no/utility#>\n"
+ "CONSTRUCT {\n"
+ " ?uri deichman:editionOf <" + id + "> ;"
+ " a deichman:Item ;"
+ " deichman:branch ?branch ;"
+ " deichman:location ?location ;"
+ " deichman:status ?status ;"
+ " deichman:barcode ?barcode ;"
+ " duo:shelfmark ?shelfmark ."
+ "} WHERE { \n"
+ " ?uri a deichman:Item ;\n"
+ " deichman:branch ?branch ;\n"
+ " deichman:status ?status ;"
+ " deichman:barcode ?barcode .\n"
+ " OPTIONAL { ?uri duo:shelfmark ?shelfmark }\n"
+ " OPTIONAL { ?uri deichman:location ?location }\n"
+ "}";
return QueryFactory.create(q);
}
public Query checkIfResourceExists(XURI xuri) {
String q = "ASK {<" + xuri.getUri() + "> ?p ?o}";
return QueryFactory.create(q);
}
public Query checkIfStatementExists(Statement statement) throws UnsupportedEncodingException {
String triple = statementToN3(statement);
String q = "ASK {" + triple + "}";
return QueryFactory.create(q);
}
private String statementToN3(Statement statement) throws UnsupportedEncodingException {
Model tempExists = ModelFactory.createDefaultModel();
tempExists.add(statement);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
RDFDataMgr.write(baos, tempExists, Lang.NTRIPLES);
return baos.toString("UTF-8");
}
public String patch(List<Patch> patches, Resource subject) {
StringBuilder q = new StringBuilder();
if (subject != null) {
q.append(String.format(""
+ "DELETE { <%s> <%smodified> ?modified }"
+ "WHERE { <%s> <%smodified> ?modified };",
subject.getURI(), BaseURI.ontology(), subject.getURI(), BaseURI.ontology()));
}
String del = getStringOfStatments(patches, "DEL", SKIP_BLANK_NODES);
String delSelect = getStringOfStatementsWithVariables(patches, "DEL");
String add = getStringOfStatments(patches, "ADD", KEEP_BLANK_NODES);
if (del.length() > 0) {
q.append("DELETE DATA {" + NEWLINE + del + "};" + NEWLINE);
}
if (delSelect.length() > 0) {
q.append("DELETE {" + NEWLINE + delSelect + "}" + NEWLINE + "WHERE {" + NEWLINE + delSelect + "};" + NEWLINE);
}
if (add.length() > 0) {
q.append(INSERT + " DATA {" + NEWLINE + add + "};" + NEWLINE);
}
return q.toString();
}
private String getStringOfStatementsWithVariables(List<Patch> patches, String operation) {
String retVal = "";
String bnodeSubjectCheck = patches.stream()
.filter(s -> s.getStatement().getSubject().isAnon())
.map(s -> {
return "a";
})
.collect(joining(""));
String bnodeObjectCheck = patches.stream()
.filter(s -> s.getStatement().getObject().isAnon())
.map(s -> {
return "a";
})
.collect(joining());
if (bnodeSubjectCheck.contains("a") && bnodeObjectCheck.contains("a")) {
retVal = patches.stream()
.filter(patch -> patch.getOperation().toUpperCase().equals(operation.toUpperCase())
&& (patch.getStatement().getSubject().isAnon() || patch.getStatement().getObject().isAnon()))
.map(patch2 -> {
Model model = ModelFactory.createDefaultModel();
model.add(patch2.getStatement());
String withoutBnodes = RDFModelUtil.stringFrom(model, Lang.NTRIPLES).replaceAll("_:", "?");
return INDENT + withoutBnodes;
}
).filter(s -> !s.isEmpty()).collect(joining());
}
return retVal;
}
private String getStringOfStatments(List<Patch> patches, String operation, boolean keepBlankNodes) {
return patches.stream()
.filter(patch -> patch.getOperation().toUpperCase().equals(operation.toUpperCase())
&& (keepBlankNodes || !patch.getStatement().getObject().isAnon() && !patch.getStatement().getSubject().isAnon()))
.map(patch2 -> {
Model model = ModelFactory.createDefaultModel();
model.add(patch2.getStatement());
return INDENT + RDFModelUtil.stringFrom(model, Lang.NTRIPLES);
}
).filter(s -> !s.isEmpty()).collect(joining());
}
public Query getImportedResourceById(String id, String type) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofil" + type + "Id> \"" + id + "\" }";
return QueryFactory.create(q);
}
public Query getBibliofilPersonResource(String personId) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofilPersonId> \"" + personId + "\" }";
return QueryFactory.create(q);
}
public Query getBibliofilPlaceResource(String id) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofilPlaceId> \"" + id + "\" }";
return QueryFactory.create(q);
}
public Query describeWorksByCreator(XURI xuri) {
String q = format(""
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
+ "PREFIX dcterms: <http://purl.org/dc/terms/>\n"
+ "DESCRIBE ?work <%2$s>\n"
+ "WHERE {\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:contributor ?contrib .\n"
+ " ?contrib deichman:agent <%2$s> .\n"
+ "}", BaseURI.ontology(), xuri.getUri());
return QueryFactory.create(q);
}
public Query describeLinkedPublications(XURI xuri) {
String q = format(""
+ "PREFIX deichman: <%s>\n"
+ "DESCRIBE ?publication WHERE \n"
+ " {\n"
+ " ?publication deichman:publicationOf <%s>\n"
+ " }", BaseURI.ontology(), xuri.getUri());
return QueryFactory.create(q);
}
public Query selectAllUrisOfType(String type) {
String q = format(""
+ "PREFIX deichman: <%s>\n"
+ "SELECT ?uri WHERE \n"
+ " {\n"
+ " ?uri a deichman:%s .\n"
+ " }", BaseURI.ontology(), capitalize(type));
return QueryFactory.create(q);
}
public String updateHoldingBranches(String recordId, String branches) {
String q = format(""
+ "PREFIX : <%s>\n"
+ "DELETE { ?pub :hasHoldingBranch ?branch }\n"
+ "INSERT { ?pub :hasHoldingBranch \"%s\" . }\n"
+ "WHERE { ?pub :recordId \"%s\" OPTIONAL { ?pub :hasHoldingBranch ?branch } }\n",
BaseURI.ontology(), StringUtils.join(branches.split(","), "\",\""), recordId);
return q;
}
public Query getWorkByRecordId(String recordId) {
String q = format(""
+ "PREFIX : <%s>\n"
+ "SELECT ?work\n"
+ "WHERE { ?pub :recordId \"%s\" .\n"
+ " ?pub :publicationOf ?work }\n",
BaseURI.ontology(), recordId);
return QueryFactory.create(q);
}
public Query selectWorksByAgent(XURI agent) {
String q = format(""
+ "PREFIX deichman: <%1$s>\n"
+ "SELECT ?work\n"
+ "WHERE {\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:contributor ?contrib .\n"
+ " ?contrib deichman:agent <%2$s> .\n"
+ "}", BaseURI.ontology(), agent.getUri());
return QueryFactory.create(q);
}
public Query constructInformationForMARC(XURI publication) {
String q = ""
+ "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "PREFIX raw: <http://data.deichman.no/raw#>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "CONSTRUCT {\n"
+ " <__PUBLICATIONURI__> deichman:mainTitle ?mainTitle ;\n"
+ " deichman:partTitle ?partTitle ;\n"
+ " deichman:subtitle ?subtitle ;\n"
+ " deichman:partNumber ?partNumber ;\n"
+ " deichman:isbn ?isbn ;\n"
+ " deichman:publicationYear ?publicationYear ;\n"
+ " deichman:publicationPlace ?placeLabel ;\n"
+ " deichman:ageLimit ?ageLimit ;\n"
+ " deichman:mainEntryPerson ?mainEntryPersonName ;\n"
+ " deichman:mainEntryCorporation ?mainEntryCorporationName ;\n"
+ " deichman:subject ?subjectLabelAndSpecification ;\n"
+ " deichman:formatLabel ?formatLabel ;\n"
+ " deichman:language ?language ;\n"
+ " deichman:workType ?workType ;\n"
+ " deichman:mediaType ?mediaTypeLabel ;\n"
+ " deichman:literaryForm ?literaryForm ;\n"
+ " deichman:literaryFormLabel ?literaryFormLabel ;\n"
+ " deichman:adaptationLabel ?formatAdaptationLabel ;\n"
+ " deichman:adaptationLabel ?contentAdaptationLabel ;\n"
+ " deichman:genre ?genreLabel ;\n"
+ " deichman:fictionNonfiction ?fictionNonfiction ;\n"
+ " deichman:summary ?summary ;"
+ " deichman:audience ?audienceLabel ;\n"
+ " deichman:locationFormat ?locationFormat ;\n"
+ " deichman:locationDewey ?locationDewey ;\n"
+ " deichman:locationSignature ?locationSignature ."
+ "}\n"
+ "WHERE {\n"
+ " <__PUBLICATIONURI__> deichman:mainTitle ?mainTitleUntranscribed .\n"
+ " OPTIONAL { <__PUBLICATIONURI__> deichman:subtitle ?subtitleUntranscribed }\n"
+ " OPTIONAL { <__PUBLICATIONURI__> raw:transcribedTitle ?mainTitleTranscribed }\n"
+ " OPTIONAL { <__PUBLICATIONURI__> raw:transcribedSubtitle ?subtitleTranscribed }\n"
+ " { <__PUBLICATIONURI__> deichman:partTitle ?partTitle }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasSummary ?summary }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:partNumber ?partNumber }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:isbn ?isbn }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationYear ?publicationYear }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:language ?language }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:ageLimit ?ageLimit }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasPlaceOfPublication ?place . ?place deichman:prefLabel ?placeLabel }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationFormat ?locationFormat }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationClassNumber ?locationDewey }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationSignature ?locationSignature } \n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasMediaType ?mediaType .\n"
+ " ?mediaType rdfs:label ?mediaTypeLabel .\n"
+ " FILTER(lang(?mediaTypeLabel) = \"no\")\n"
+ " }"
+ "\n"
+ " UNION { <__PUBLICATIONURI__> deichman:format ?format .\n"
+ " ?format rdfs:label ?formatLabel .\n"
+ " FILTER(lang(?formatLabel) = \"no\")\n"
+ " }"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationOf ?work ."
+ " ?work deichman:audience ?audience .\n"
+ " ?audience rdfs:label ?audienceLabel .\n"
+ " FILTER(lang(?audienceLabel) = \"no\")\n"
+ " }"
+ " UNION { <__PUBLICATIONURI__> deichman:hasFormatAdaptation ?formatAdaptation .\n"
+ " ?formatAdaptation rdfs:label ?formatAdaptationLabel .\n"
+ " FILTER(lang(?formatAdaptationLabel) = \"no\")\n"
+ " }"
+ "\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:hasContentAdaptation ?contentAdaptation .\n"
+ " ?contentAdaptation rdfs:label ?contentAdaptationLabel .\n"
+ " FILTER(lang(?contentAdaptationLabel) = \"no\")\n"
+ " }\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work a deichman:Work .\n"
+ " OPTIONAL { ?work deichman:hasWorkType ?type .\n"
+ " ?type rdfs:label ?workType .\n"
+ " FILTER(lang(?workType) = \"no\")\n"
+ " }\n"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:contributor ?contrib .\n"
+ " ?contrib a deichman:MainEntry ;\n"
+ " deichman:agent ?agent .\n"
+ " OPTIONAL { ?agent a deichman:Person ; deichman:name ?mainEntryPersonName . }\n"
+ " OPTIONAL { ?agent a deichman:Corporation ; deichman:name ?mainEntryCorporationName . }\n"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:subject ?subject .\n"
+ " ?subject deichman:prefLabel ?subjectLabel .\n"
+ " OPTIONAL { ?subject deichman:specification ?subjectSpecification .} \n"
+ " BIND(IF(BOUND(?subjectSpecification), CONCAT(?subjectLabel, \"__\", ?subjectSpecification), ?subjectLabel) AS ?subjectLabelAndSpecification)"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:subject ?subject .\n"
+ " ?subject deichman:name ?subjectLabel .\n"
+ " OPTIONAL { ?subject deichman:specification ?subjectSpecification .} \n"
+ " BIND(IF(BOUND(?subjectSpecification), CONCAT(?subjectLabel, \"__\", ?subjectSpecification), ?subjectLabel) AS ?subjectLabelAndSpecification)"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:genre ?genre .\n"
+ " ?genre deichman:prefLabel ?genreLabel .\n"
+ " }\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:literaryForm ?literaryForm .\n"
+ " ?literaryForm rdfs:label ?literaryFormLabel .\n"
+ " FILTER(lang(?literaryFormLabel) = \"no\")\n"
+ " }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationOf ?work . ?work deichman:fictionNonfiction ?fictionNonfiction }"
+ " BIND(IF(BOUND(?mainTitleTranscribed), ?mainTitleTranscribed, ?mainTitleUntranscribed) AS ?mainTitle)\n"
+ " BIND(IF(BOUND(?subtitleTranscribed), ?subtitleTranscribed, ?subtitleUntranscribed) AS ?subtitle)\n"
+ "}";
q = q.replaceAll("__PUBLICATIONURI__", publication.getUri());
return QueryFactory.create(q);
}
public Query getRecordIdsByWork(XURI xuri) {
String queryString = "SELECT ?recordId\n"
+ "WHERE {\n"
+ " ?p <http://data.deichman.no/ontology#publicationOf> <" + xuri.getUri() + "> ;\n"
+ " <http://data.deichman.no/ontology#recordId> ?recordId\n"
+ "}\n";
return QueryFactory.create(queryString);
}
public Query constructInversePublicationRelations(XURI workUri) {
String query = "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "CONSTRUCT {<" + workUri.getUri() + "> deichman:hasPublication ?publication} WHERE {?publication deichman:publicationOf <" + workUri.getUri() + ">}";
return QueryFactory.create(query);
}
public Query getNumberOfRelationsForResource(XURI xuri) {
String queryString = format("PREFIX deich: <http://data.deichman.no/ontology#>\n"
+ "SELECT ?type (COUNT(?a) as ?references)\n"
+ "WHERE {\n"
+ " ?a ?b <%s> ;\n"
+ " a ?type .\n"
+ "}\n"
+ "GROUP BY ?type ", xuri.getUri());
return QueryFactory.create(queryString);
}
public Query constructFromQueryAndProjection(EntityType entityType, Map<String, String> queryParameters, Collection<String> projection) {
Stream<String> start = of("prefix deichman:<http://data.deichman.no/ontology#>\n"
+ "construct {"
+ " ?uri a ?type .\n");
Stream<String> conditionals = queryParameters
.entrySet()
.stream()
.map(entry -> format(" ?uri deichman:%s %s .", entry.getKey(), createTypedLiteral(entry.getValue()).asNode().toString()));
Stream<String> type = of(format(" ?uri a deichman:%s .", org.apache.commons.lang3.StringUtils.capitalize(entityType.getPath())));
Stream<String> selects = projection.stream().map(property -> format(" OPTIONAL { ?uri deichman:%s ?%s } ", property, property));
Stream<String> projections = projection.stream().map(property -> format(" ?uri deichman:%s ?%s .", property, property));
Stream<String> where = of("}\n"
+ "where {"
+ " ?uri a ?type .\n ");
Stream<String> end = newArrayList("}\n").stream();
String query = concat(start, concat(projections, concat(where, concat(type, concat(conditionals, concat(selects, end)))))).collect(joining("\n"));
return QueryFactory.create(query);
}
public String patch(List<Patch> deleteModelAsPatches) {
return patch(deleteModelAsPatches, null);
}
}
| redef/services/src/main/java/no/deichman/services/entity/repository/SPARQLQueryBuilder.java | package no.deichman.services.entity.repository;
import no.deichman.services.entity.EntityType;
import no.deichman.services.entity.patch.Patch;
import no.deichman.services.rdf.RDFModelUtil;
import no.deichman.services.uridefaults.BaseURI;
import no.deichman.services.uridefaults.XURI;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.of;
import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.apache.jena.rdf.model.ResourceFactory.createTypedLiteral;
/**
* Responsibility: TODO.
*/
public final class SPARQLQueryBuilder {
public static final String INSERT = "INSERT";
public static final String DELETE = "DELETE";
public static final String NEWLINE = "\n";
private static final String INDENT = " ";
public static final boolean KEEP_BLANK_NODES = true;
public static final boolean SKIP_BLANK_NODES = false;
public SPARQLQueryBuilder() {
}
public Query getGetResourceByIdQuery(String id) {
String queryString = "DESCRIBE <" + id + ">";
return QueryFactory.create(queryString);
}
public Query describeWorkAndLinkedResources(XURI xuri) {
String queryString = "#\n"
+ "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <__WORKURI__> ?publication ?workContributor ?compType ?format ?mediaType ?subject ?genre ?instrument"
+ " ?litform ?hasWorkType ?serial ?nation ?pubContrib ?publicationContributor ?place ?publishedBy\n"
+ "WHERE {\n"
+ " { <__WORKURI__> a deichman:Work }\n"
+ " UNION { <__WORKURI__> deichman:contributor ?workContrib .\n"
+ " ?workContrib a deichman:Contribution ;\n"
+ " deichman:agent ?workContributor . \n"
+ " OPTIONAL { ?workContributor deichman:nationality ?nation }"
+ " }\n"
+ " UNION { ?publication deichman:publicationOf <__WORKURI__> ; \n"
+ " a deichman:Publication . \n"
+ " OPTIONAL { ?publication deichman:format ?format .\n"
+ " ?format rdfs:label ?label . }\n"
+ " OPTIONAL { ?publication deichman:hasMediaType ?mediaType .\n"
+ " ?mediaType rdfs:label ?label . }\n"
+ " OPTIONAL { ?publication deichman:contributor ?pubContrib. \n"
+ " ?pubContrib a deichman:Contribution ;\n"
+ " deichman:agent ?publicationContributor . }\n"
+ " OPTIONAL { ?publication deichman:inSerial ?serialIssue . \n"
+ " ?serialIssue deichman:serial ?serial . }\n"
+ " OPTIONAL { ?publication deichman:hasPlaceOfPublication ?place }\n"
+ " OPTIONAL { ?publication deichman:publishedBy ?publishedBy }\n"
+ " }\n"
+ " UNION { <__WORKURI__> deichman:subject ?subject }\n"
+ " UNION { <__WORKURI__> deichman:hasInstrumentation ?instrumentation .\n"
+ " ?instrumentation deichman:hasInstrument ?instrument }\n"
+ " UNION { <__WORKURI__> deichman:genre ?genre }\n"
+ " UNION { <__WORKURI__> deichman:literaryForm ?litform }\n"
+ " UNION { <__WORKURI__> deichman:hasWorkType ?hasWorkType }\n"
+ " UNION { <__WORKURI__> deichman:hasCompositionType ?compType }\n"
+ "}";
queryString = queryString.replaceAll("__WORKURI__", xuri.getUri());
return QueryFactory.create(queryString);
}
public Query describePersonAndLinkedResources(String personId) {
String queryString = format("#\n"
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <%2$s> ?name ?birth ?death ?personTitle ?nationality ?nationalityLabel \n"
+ "WHERE {\n"
+ " <%2$s> a deichman:Person .\n"
+ " optional { <%2$s> deichman:name ?name . }\n"
+ " optional { <%2$s> deichman:birthYear ?birth . }\n"
+ " optional { <%2$s> deichman:deathYear ?death . }\n"
+ " optional { <%2$s> deichman:personTitle ?personTitle . }\n"
+ " optional { <%2$s> deichman:nationality ?nationality . \n"
+ " ?nationality rdfs:label ?nationalityLabel .\n"
+ " }\n"
+ "}", BaseURI.ontology(), personId);
return QueryFactory.create(queryString);
}
public Query describeCorporationAndLinkedResources(String corporationId) {
String queryString = format("#\n"
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "DESCRIBE <%2$s> ?name ?nationality ?nationalityLabel \n"
+ "WHERE {\n"
+ " <%2$s> a deichman:Corporation .\n"
+ " optional { <%2$s> deichman:name ?name . }\n"
+ " optional { <%2$s> deichman:nationality ?nationality . \n"
+ " ?nationality rdfs:label ?nationalityLabel .\n"
+ " }\n"
+ "}", BaseURI.ontology(), corporationId);
return QueryFactory.create(queryString);
}
public String getUpdateWorkQueryString(Model work) {
return getCreateQueryString(work);
}
public String getReplaceSubjectQueryString(String newURI) {
return "DELETE {\n"
+ " ?s ?p ?o .\n"
+ "}\n"
+ "INSERT {\n"
+ " <" + newURI + "> ?p ?o .\n"
+ "}\n"
+ "WHERE {\n"
+ " ?s ?p ?o .\n"
+ " FILTER (!isBlank(?s))\n"
+ "}\n";
}
public String getCreateQueryString(Model work) {
StringWriter sw = new StringWriter();
RDFDataMgr.write(sw, work, Lang.NTRIPLES);
String data = sw.toString();
return "INSERT DATA {\n"
+ "\n"
+ data
+ "\n"
+ "}";
}
public Query getItemsFromModelQuery(String id) {
String q = "PREFIX deichman: <" + BaseURI.ontology() + ">\n"
+ "PREFIX duo: <http://data.deichman.no/utility#>\n"
+ "CONSTRUCT {\n"
+ " ?uri deichman:editionOf <" + id + "> ;"
+ " a deichman:Item ;"
+ " deichman:branch ?branch ;"
+ " deichman:location ?location ;"
+ " deichman:status ?status ;"
+ " deichman:barcode ?barcode ;"
+ " duo:shelfmark ?shelfmark ."
+ "} WHERE { \n"
+ " ?uri a deichman:Item ;\n"
+ " deichman:branch ?branch ;\n"
+ " deichman:status ?status ;"
+ " deichman:barcode ?barcode .\n"
+ " OPTIONAL { ?uri duo:shelfmark ?shelfmark }\n"
+ " OPTIONAL { ?uri deichman:location ?location }\n"
+ "}";
return QueryFactory.create(q);
}
public Query checkIfResourceExists(XURI xuri) {
String q = "ASK {<" + xuri.getUri() + "> ?p ?o}";
return QueryFactory.create(q);
}
public Query checkIfStatementExists(Statement statement) throws UnsupportedEncodingException {
String triple = statementToN3(statement);
String q = "ASK {" + triple + "}";
return QueryFactory.create(q);
}
private String statementToN3(Statement statement) throws UnsupportedEncodingException {
Model tempExists = ModelFactory.createDefaultModel();
tempExists.add(statement);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
RDFDataMgr.write(baos, tempExists, Lang.NTRIPLES);
return baos.toString("UTF-8");
}
public String patch(List<Patch> patches, Resource subject) {
StringBuilder q = new StringBuilder();
if (subject != null) {
q.append(String.format(""
+ "DELETE { <%s> <%smodified> ?modified }"
+ "WHERE { <%s> <%smodified> ?modified };",
subject.getURI(), BaseURI.ontology(), subject.getURI(), BaseURI.ontology()));
}
String del = getStringOfStatments(patches, "DEL", SKIP_BLANK_NODES);
String delSelect = getStringOfStatementsWithVariables(patches, "DEL");
String add = getStringOfStatments(patches, "ADD", KEEP_BLANK_NODES);
if (del.length() > 0) {
q.append("DELETE DATA {" + NEWLINE + del + "};" + NEWLINE);
}
if (delSelect.length() > 0) {
q.append("DELETE {" + NEWLINE + delSelect + "}" + NEWLINE + "WHERE {" + NEWLINE + delSelect + "};" + NEWLINE);
}
if (add.length() > 0) {
q.append(INSERT + " DATA {" + NEWLINE + add + "};" + NEWLINE);
}
return q.toString();
}
private String getStringOfStatementsWithVariables(List<Patch> patches, String operation) {
String retVal = "";
String bnodeSubjectCheck = patches.stream()
.filter(s -> s.getStatement().getSubject().isAnon())
.map(s -> {
return "a";
})
.collect(joining(""));
String bnodeObjectCheck = patches.stream()
.filter(s -> s.getStatement().getObject().isAnon())
.map(s -> {
return "a";
})
.collect(joining());
if (bnodeSubjectCheck.contains("a") && bnodeObjectCheck.contains("a")) {
retVal = patches.stream()
.filter(patch -> patch.getOperation().toUpperCase().equals(operation.toUpperCase())
&& (patch.getStatement().getSubject().isAnon() || patch.getStatement().getObject().isAnon()))
.map(patch2 -> {
Model model = ModelFactory.createDefaultModel();
model.add(patch2.getStatement());
String withoutBnodes = RDFModelUtil.stringFrom(model, Lang.NTRIPLES).replaceAll("_:", "?");
return INDENT + withoutBnodes;
}
).filter(s -> !s.isEmpty()).collect(joining());
}
return retVal;
}
private String getStringOfStatments(List<Patch> patches, String operation, boolean keepBlankNodes) {
return patches.stream()
.filter(patch -> patch.getOperation().toUpperCase().equals(operation.toUpperCase())
&& (keepBlankNodes || !patch.getStatement().getObject().isAnon() && !patch.getStatement().getSubject().isAnon()))
.map(patch2 -> {
Model model = ModelFactory.createDefaultModel();
model.add(patch2.getStatement());
return INDENT + RDFModelUtil.stringFrom(model, Lang.NTRIPLES);
}
).filter(s -> !s.isEmpty()).collect(joining());
}
public Query getImportedResourceById(String id, String type) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofil" + type + "Id> \"" + id + "\" }";
return QueryFactory.create(q);
}
public Query getBibliofilPersonResource(String personId) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofilPersonId> \"" + personId + "\" }";
return QueryFactory.create(q);
}
public Query getBibliofilPlaceResource(String id) {
String q = "SELECT ?uri "
+ "WHERE "
+ " { ?uri <http://data.deichman.no/duo#bibliofilPlaceId> \"" + id + "\" }";
return QueryFactory.create(q);
}
public Query describeWorksByCreator(XURI xuri) {
String q = format(""
+ "PREFIX deichman: <%1$s>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
+ "PREFIX dcterms: <http://purl.org/dc/terms/>\n"
+ "DESCRIBE ?work <%2$s>\n"
+ "WHERE {\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:contributor ?contrib .\n"
+ " ?contrib deichman:agent <%2$s> .\n"
+ "}", BaseURI.ontology(), xuri.getUri());
return QueryFactory.create(q);
}
public Query describeLinkedPublications(XURI xuri) {
String q = format(""
+ "PREFIX deichman: <%s>\n"
+ "DESCRIBE ?publication WHERE \n"
+ " {\n"
+ " ?publication deichman:publicationOf <%s>\n"
+ " }", BaseURI.ontology(), xuri.getUri());
return QueryFactory.create(q);
}
public Query selectAllUrisOfType(String type) {
String q = format(""
+ "PREFIX deichman: <%s>\n"
+ "SELECT ?uri WHERE \n"
+ " {\n"
+ " ?uri a deichman:%s .\n"
+ " }", BaseURI.ontology(), capitalize(type));
return QueryFactory.create(q);
}
public String updateHoldingBranches(String recordId, String branches) {
String q = format(""
+ "PREFIX : <%s>\n"
+ "DELETE { ?pub :hasHoldingBranch ?branch }\n"
+ "INSERT { ?pub :hasHoldingBranch \"%s\" . }\n"
+ "WHERE { ?pub :recordId \"%s\" OPTIONAL { ?pub :hasHoldingBranch ?branch } }\n",
BaseURI.ontology(), StringUtils.join(branches.split(","), "\",\""), recordId);
return q;
}
public Query getWorkByRecordId(String recordId) {
String q = format(""
+ "PREFIX : <%s>\n"
+ "SELECT ?work\n"
+ "WHERE { ?pub :recordId \"%s\" .\n"
+ " ?pub :publicationOf ?work }\n",
BaseURI.ontology(), recordId);
return QueryFactory.create(q);
}
public Query selectWorksByAgent(XURI agent) {
String q = format(""
+ "PREFIX deichman: <%1$s>\n"
+ "SELECT ?work\n"
+ "WHERE {\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:contributor ?contrib .\n"
+ " ?contrib deichman:agent <%2$s> .\n"
+ "}", BaseURI.ontology(), agent.getUri());
return QueryFactory.create(q);
}
public Query constructInformationForMARC(XURI publication) {
String q = ""
+ "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "PREFIX raw: <http://data.deichman.no/raw#>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "CONSTRUCT {\n"
+ " <__PUBLICATIONURI__> deichman:mainTitle ?mainTitle ;\n"
+ " deichman:partTitle ?partTitle ;\n"
+ " deichman:subtitle ?subtitle ;\n"
+ " deichman:partNumber ?partNumber ;\n"
+ " deichman:isbn ?isbn ;\n"
+ " deichman:publicationYear ?publicationYear ;\n"
+ " deichman:publicationPlace ?placeLabel ;\n"
+ " deichman:ageLimit ?ageLimit ;\n"
+ " deichman:mainEntryPerson ?mainEntryPersonName ;\n"
+ " deichman:mainEntryCorporation ?mainEntryCorporationName ;\n"
+ " deichman:subject ?subjectLabelAndSpecification ;\n"
+ " deichman:formatLabel ?formatLabel ;\n"
+ " deichman:language ?language ;\n"
+ " deichman:workType ?workType ;\n"
+ " deichman:mediaType ?mediaTypeLabel ;\n"
+ " deichman:literaryForm ?literaryForm ;\n"
+ " deichman:literaryFormLabel ?literaryFormLabel ;\n"
+ " deichman:adaptationLabel ?formatAdaptationLabel ;\n"
+ " deichman:adaptationLabel ?contentAdaptationLabel ;\n"
+ " deichman:genre ?genreLabel ;\n"
+ " deichman:fictionNonfiction ?fictionNonfiction ;\n"
+ " deichman:summary ?summary ;"
+ " deichman:audience ?audienceLabel ;\n"
+ " deichman:locationFormat ?locationFormat ;\n"
+ " deichman:locationDewey ?locationDewey ;\n"
+ " deichman:locationSignature ?locationSignature ."
+ "}\n"
+ "WHERE {\n"
+ " <__PUBLICATIONURI__> deichman:mainTitle ?mainTitleUntranscribed .\n"
+ " OPTIONAL { <__PUBLICATIONURI__> deichman:subtitle ?subtitleUntranscribed }\n"
+ " OPTIONAL { <__PUBLICATIONURI__> raw:transcribedTitle ?mainTitleTranscribed }\n"
+ " OPTIONAL { <__PUBLICATIONURI__> raw:transcribedSubtitle ?subtitleTranscribed }\n"
+ " { <__PUBLICATIONURI__> deichman:partTitle ?partTitle }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasSummary ?summary }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:partNumber ?partNumber }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:isbn ?isbn }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationYear ?publicationYear }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:language ?language }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:ageLimit ?ageLimit }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasPlaceOfPublication ?place . ?place deichman:prefLabel ?placeLabel }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationFormat ?locationFormat }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationClassNumber ?locationDewey }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:locationSignature ?locationSignature } \n"
+ " UNION { <__PUBLICATIONURI__> deichman:hasMediaType ?mediaType .\n"
+ " ?mediaType rdfs:label ?mediaTypeLabel .\n"
+ " FILTER(lang(?mediaTypeLabel) = \"no\")\n"
+ " }"
+ "\n"
+ " UNION { <__PUBLICATIONURI__> deichman:format ?format .\n"
+ " ?format rdfs:label ?formatLabel .\n"
+ " FILTER(lang(?formatLabel) = \"no\")\n"
+ " }"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationOf ?work ."
+ " ?work deichman:audience ?audience .\n"
+ " ?audience rdfs:label ?audienceLabel .\n"
+ " FILTER(lang(?audienceLabel) = \"no\")\n"
+ " }"
+ " UNION { <__PUBLICATIONURI__> deichman:hasFormatAdaptation ?formatAdaptation .\n"
+ " ?formatAdaptation rdfs:label ?formatAdaptationLabel .\n"
+ " FILTER(lang(?formatAdaptationLabel) = \"no\")\n"
+ " }"
+ "\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work a deichman:Work ;\n"
+ " deichman:hasContentAdaptation ?contentAdaptation .\n"
+ " ?contentAdaptation rdfs:label ?contentAdaptationLabel .\n"
+ " FILTER(lang(?contentAdaptationLabel) = \"no\")\n"
+ " }\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work a deichman:Work .\n"
+ " OPTIONAL { ?work deichman:hasWorkType ?type .\n"
+ " ?type rdfs:label ?workType .\n"
+ " FILTER(lang(?workType) = \"no\")\n"
+ " }\n"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:contributor ?contrib .\n"
+ " ?contrib a deichman:MainEntry ;\n"
+ " deichman:agent ?agent .\n"
+ " OPTIONAL { ?agent a deichman:Person ; deichman:name ?mainEntryPersonName . }\n"
+ " OPTIONAL { ?agent a deichman:Corporation ; deichman:name ?mainEntryCorporationName . }\n"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:subject ?subject .\n"
+ " ?subject deichman:prefLabel ?subjectLabel .\n"
+ " OPTIONAL { ?subject deichman:specification ?subjectSpecification .} \n"
+ " BIND(IF(BOUND(?subjectSpecification), CONCAT(?subjectLabel, \"__\", ?subjectSpecification), ?subjectLabel) AS ?subjectLabelAndSpecification)"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:subject ?subject .\n"
+ " ?subject deichman:name ?subjectLabel .\n"
+ " OPTIONAL { ?subject deichman:specification ?subjectSpecification .} \n"
+ " BIND(IF(BOUND(?subjectSpecification), CONCAT(?subjectLabel, \"__\", ?subjectSpecification), ?subjectLabel) AS ?subjectLabelAndSpecification)"
+ " }\n"
+ " UNION {\n"
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:genre ?genre .\n"
+ " ?genre deichman:prefLabel ?genreLabel .\n"
+ " }\n"
+ " UNION { "
+ " <__PUBLICATIONURI__> deichman:publicationOf ?work .\n"
+ " ?work deichman:literaryForm ?literaryForm .\n"
+ " ?literaryForm rdfs:label ?literaryFormLabel .\n"
+ " FILTER(lang(?literaryFormLabel) = \"no\")\n"
+ " }\n"
+ " UNION { <__PUBLICATIONURI__> deichman:publicationOf ?work . ?work deichman:fictionNonfiction ?fictionNonfiction }"
+ " BIND(IF(BOUND(?mainTitleTranscribed), ?mainTitleTranscribed, ?mainTitleUntranscribed) AS ?mainTitle)\n"
+ " BIND(IF(BOUND(?subtitleTranscribed), ?subtitleTranscribed, ?subtitleUntranscribed) AS ?subtitle)\n"
+ "}";
q = q.replaceAll("__PUBLICATIONURI__", publication.getUri());
return QueryFactory.create(q);
}
public Query getRecordIdsByWork(XURI xuri) {
String queryString = "SELECT ?recordId\n"
+ "WHERE {\n"
+ " ?p <http://data.deichman.no/ontology#publicationOf> <" + xuri.getUri() + "> ;\n"
+ " <http://data.deichman.no/ontology#recordId> ?recordId\n"
+ "}\n";
return QueryFactory.create(queryString);
}
public Query constructInversePublicationRelations(XURI workUri) {
String query = "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
+ "CONSTRUCT {<" + workUri.getUri() + "> deichman:hasPublication ?publication} WHERE {?publication deichman:publicationOf <" + workUri.getUri() + ">}";
return QueryFactory.create(query);
}
public Query getNumberOfRelationsForResource(XURI xuri) {
String queryString = format("PREFIX deich: <http://data.deichman.no/ontology#>\n"
+ "SELECT ?type (COUNT(?a) as ?references)\n"
+ "WHERE {\n"
+ " ?a ?b <%s> ;\n"
+ " a ?type .\n"
+ "}\n"
+ "GROUP BY ?type ", xuri.getUri());
return QueryFactory.create(queryString);
}
public Query constructFromQueryAndProjection(EntityType entityType, Map<String, String> queryParameters, Collection<String> projection) {
Stream<String> start = of("prefix deichman:<http://data.deichman.no/ontology#>\n"
+ "construct {"
+ " ?uri a ?type .\n");
Stream<String> conditionals = queryParameters
.entrySet()
.stream()
.map(entry -> format(" ?uri deichman:%s %s .", entry.getKey(), createTypedLiteral(entry.getValue()).asNode().toString()));
Stream<String> type = of(format(" ?uri a deichman:%s .", org.apache.commons.lang3.StringUtils.capitalize(entityType.getPath())));
Stream<String> selects = projection.stream().map(property -> format(" OPTIONAL { ?uri deichman:%s ?%s } ", property, property));
Stream<String> projections = projection.stream().map(property -> format(" ?uri deichman:%s ?%s .", property, property));
Stream<String> where = of("}\n"
+ "where {"
+ " ?uri a ?type .\n ");
Stream<String> end = newArrayList("}\n").stream();
String query = concat(start, concat(projections, concat(where, concat(type, concat(conditionals, concat(selects, end)))))).collect(joining("\n"));
return QueryFactory.create(query);
}
public String patch(List<Patch> deleteModelAsPatches) {
return patch(deleteModelAsPatches, null);
}
}
| DEICH-149: Change sparql query to get the linked resources for publication parts
| redef/services/src/main/java/no/deichman/services/entity/repository/SPARQLQueryBuilder.java | DEICH-149: Change sparql query to get the linked resources for publication parts | <ide><path>edef/services/src/main/java/no/deichman/services/entity/repository/SPARQLQueryBuilder.java
<ide> + "PREFIX deichman: <http://data.deichman.no/ontology#>\n"
<ide> + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
<ide> + "DESCRIBE <__WORKURI__> ?publication ?workContributor ?compType ?format ?mediaType ?subject ?genre ?instrument"
<del> + " ?litform ?hasWorkType ?serial ?nation ?pubContrib ?publicationContributor ?place ?publishedBy\n"
<add> + " ?litform ?hasWorkType ?serial ?nation ?pubContrib ?publicationContributor ?place ?publishedBy ?publicationPartValues\n"
<ide> + "WHERE {\n"
<ide> + " { <__WORKURI__> a deichman:Work }\n"
<ide> + " UNION { <__WORKURI__> deichman:contributor ?workContrib .\n"
<ide> + " ?serialIssue deichman:serial ?serial . }\n"
<ide> + " OPTIONAL { ?publication deichman:hasPlaceOfPublication ?place }\n"
<ide> + " OPTIONAL { ?publication deichman:publishedBy ?publishedBy }\n"
<add> + " OPTIONAL { ?publication deichman:hasPublicationPart ?hasPublicationPart ."
<add> + " ?hasPublicationPart a deichman:PublicationPart;"
<add> + " ?publicationPartProperties ?publicationPartValues ."
<add> + " }\n"
<ide> + " }\n"
<ide> + " UNION { <__WORKURI__> deichman:subject ?subject }\n"
<ide> + " UNION { <__WORKURI__> deichman:hasInstrumentation ?instrumentation .\n" |
|
Java | apache-2.0 | 9ae7b5fc8b0c90bb16b5bd50d3338f56770bea35 | 0 | metaborg/nabl,metaborg/nabl,metaborg/nabl | package mb.statix.concurrent;
import static com.google.common.collect.Streams.stream;
import static mb.nabl2.terms.build.TermBuild.B;
import static mb.nabl2.terms.matching.TermMatch.M;
import static mb.statix.constraints.Constraints.disjoin;
import static mb.statix.solver.persistent.Solver.INCREMENTAL_CRITICAL_EDGES;
import static mb.statix.solver.persistent.Solver.RETURN_ON_FIRST_ERROR;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.metaborg.util.collection.CapsuleUtil;
import org.metaborg.util.functions.CheckedAction0;
import org.metaborg.util.functions.Function0;
import org.metaborg.util.future.CompletableFuture;
import org.metaborg.util.future.IFuture;
import org.metaborg.util.log.Level;
import org.metaborg.util.task.ICancel;
import org.metaborg.util.task.IProgress;
import org.metaborg.util.task.NullProgress;
import org.metaborg.util.tuple.Tuple2;
import org.metaborg.util.tuple.Tuple3;
import org.metaborg.util.unit.Unit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Streams;
import io.usethesource.capsule.Set;
import io.usethesource.capsule.util.stream.CapsuleCollectors;
import mb.nabl2.terms.ITerm;
import mb.nabl2.terms.ITermVar;
import mb.nabl2.terms.stratego.TermIndex;
import mb.nabl2.terms.stratego.TermOrigin;
import mb.nabl2.terms.substitution.ISubstitution;
import mb.nabl2.terms.substitution.Renaming;
import mb.nabl2.terms.unification.OccursException;
import mb.nabl2.terms.unification.RigidException;
import mb.nabl2.terms.unification.u.IUnifier;
import mb.nabl2.terms.unification.ud.Diseq;
import mb.nabl2.terms.unification.ud.IUniDisunifier;
import mb.p_raffrayi.DeadlockException;
import mb.p_raffrayi.ITypeCheckerContext;
import mb.p_raffrayi.nameresolution.DataLeq;
import mb.p_raffrayi.nameresolution.DataWf;
import mb.scopegraph.ecoop21.LabelOrder;
import mb.scopegraph.ecoop21.LabelWf;
import mb.scopegraph.ecoop21.RegExpLabelWf;
import mb.scopegraph.ecoop21.RelationLabelOrder;
import mb.scopegraph.oopsla20.path.IResolutionPath;
import mb.scopegraph.oopsla20.reference.EdgeOrData;
import mb.statix.concurrent.util.VarIndexedCollection;
import mb.statix.constraints.CArith;
import mb.statix.constraints.CAstId;
import mb.statix.constraints.CAstProperty;
import mb.statix.constraints.CConj;
import mb.statix.constraints.CEqual;
import mb.statix.constraints.CExists;
import mb.statix.constraints.CFalse;
import mb.statix.constraints.CInequal;
import mb.statix.constraints.CNew;
import mb.statix.constraints.CResolveQuery;
import mb.statix.constraints.CTellEdge;
import mb.statix.constraints.CTrue;
import mb.statix.constraints.CTry;
import mb.statix.constraints.CUser;
import mb.statix.constraints.Constraints;
import mb.statix.constraints.messages.IMessage;
import mb.statix.constraints.messages.MessageUtil;
import mb.statix.scopegraph.AScope;
import mb.statix.scopegraph.Scope;
import mb.statix.solver.CriticalEdge;
import mb.statix.solver.Delay;
import mb.statix.solver.IConstraint;
import mb.statix.solver.IConstraintStore;
import mb.statix.solver.IState;
import mb.statix.solver.ITermProperty;
import mb.statix.solver.ITermProperty.Multiplicity;
import mb.statix.solver.completeness.Completeness;
import mb.statix.solver.completeness.CompletenessUtil;
import mb.statix.solver.completeness.ICompleteness;
import mb.statix.solver.log.IDebugContext;
import mb.statix.solver.log.LazyDebugContext;
import mb.statix.solver.log.NullDebugContext;
import mb.statix.solver.persistent.BagTermProperty;
import mb.statix.solver.persistent.SingletonTermProperty;
import mb.statix.solver.persistent.Solver;
import mb.statix.solver.persistent.Solver.PreSolveResult;
import mb.statix.solver.persistent.SolverResult;
import mb.statix.solver.persistent.State;
import mb.statix.solver.query.QueryFilter;
import mb.statix.solver.query.QueryMin;
import mb.statix.solver.query.ResolutionDelayException;
import mb.statix.solver.store.BaseConstraintStore;
import mb.statix.spec.ApplyMode;
import mb.statix.spec.ApplyMode.Safety;
import mb.statix.spec.ApplyResult;
import mb.statix.spec.Rule;
import mb.statix.spec.RuleUtil;
import mb.statix.spec.Spec;
import mb.statix.spoofax.StatixTerms;
public class StatixSolver {
private enum ShadowOptimization {
NONE, RULE, CONTEXT
}
private static final ShadowOptimization SHADOW_OPTIMIZATION = ShadowOptimization.RULE;
private static final boolean LOCAL_INFERENCE = true;
private static final ImmutableSet<ITermVar> NO_UPDATED_VARS = ImmutableSet.of();
private static final ImmutableList<IConstraint> NO_NEW_CONSTRAINTS = ImmutableList.of();
private static final mb.statix.solver.completeness.Completeness.Immutable NO_NEW_CRITICAL_EDGES =
Completeness.Immutable.of();
private static final ImmutableMap<ITermVar, ITermVar> NO_EXISTENTIALS = ImmutableMap.of();
private static final int MAX_DEPTH = 32;
private final Spec spec;
private final IConstraintStore constraints;
private final IDebugContext debug;
private final IProgress progress;
private final ICancel cancel;
private final ITypeCheckerContext<Scope, ITerm, ITerm> scopeGraph;
private final int flags;
private IState.Immutable state;
private ICompleteness.Immutable completeness;
private Map<ITermVar, ITermVar> existentials = null;
private final List<ITermVar> updatedVars = Lists.newArrayList();
private final Map<IConstraint, IMessage> failed = Maps.newHashMap();
private final AtomicBoolean inFixedPoint = new AtomicBoolean(false);
private final AtomicInteger pendingResults = new AtomicInteger(0);
private final CompletableFuture<SolverResult> result;
public StatixSolver(IConstraint constraint, Spec spec, IState.Immutable state, ICompleteness.Immutable completeness,
IDebugContext debug, IProgress progress, ICancel cancel,
ITypeCheckerContext<Scope, ITerm, ITerm> scopeGraph, int flags) {
if(INCREMENTAL_CRITICAL_EDGES && !spec.hasPrecomputedCriticalEdges()) {
debug.warn("Leaving precomputing critical edges to solver may result in duplicate work.");
this.spec = spec.precomputeCriticalEdges();
} else {
this.spec = spec;
}
this.scopeGraph = scopeGraph;
this.state = state;
this.debug = debug;
this.constraints = new BaseConstraintStore(debug);
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
final Tuple2<IConstraint, ICompleteness.Immutable> initialConstraintAndCriticalEdges =
CompletenessUtil.precomputeCriticalEdges(constraint, spec.scopeExtensions());
this.constraints.add(initialConstraintAndCriticalEdges._1());
_completeness.addAll(initialConstraintAndCriticalEdges._2(), state.unifier());
} else {
constraints.add(constraint);
_completeness.add(constraint, spec, state.unifier());
}
this.completeness = _completeness.freeze();
this.result = new CompletableFuture<>();
this.progress = progress;
this.cancel = cancel;
this.flags = flags;
}
///////////////////////////////////////////////////////////////////////////
// driver
///////////////////////////////////////////////////////////////////////////
public IFuture<SolverResult> solve(Iterable<Scope> roots) {
try {
for(Scope root : CapsuleUtil.toSet(roots)) {
final Set.Immutable<ITerm> openEdges = getOpenEdges(root);
scopeGraph.initScope(root, openEdges, false);
}
fixedpoint();
} catch(Throwable e) {
result.completeExceptionally(e);
}
return result;
}
public IFuture<SolverResult> entail() {
return solve(Collections.emptyList());
}
private <R> void solveK(K<R> k, R r, Throwable ex) {
debug.debug("Solving continuation");
try {
if(!k.k(r, ex, MAX_DEPTH)) {
debug.debug("Finished fast.");
result.complete(finishSolve());
return;
}
fixedpoint();
} catch(Throwable e) {
result.completeExceptionally(e);
}
debug.debug("Solved continuation");
}
// It can happen that fixedpoint is called in the context of a running fixedpoint.
// This can happen when a continuation is not triggered by a remote message, but
// directly completed (e.g., by a try). The solveK invocation will call fixedpoint
// again. We prevent recursive fixed points to ensure the termination conditions are
// correctly checked.
private void fixedpoint() throws InterruptedException {
if(!inFixedPoint.compareAndSet(false, true)) {
return;
}
debug.debug("Solving constraints");
IConstraint constraint;
while((constraint = constraints.remove()) != null) {
if(!k(constraint, MAX_DEPTH)) {
debug.debug("Finished fast.");
result.complete(finishSolve());
return;
}
}
// invariant: there should be no remaining active constraints
if(constraints.activeSize() > 0) {
debug.warn("Fixed point finished with remaining constraints");
throw new IllegalStateException(
"Expected no remaining active constraints, but got " + constraints.activeSize());
}
debug.debug("Has pending: {}, done: {}", pendingResults.get(), result.isDone());
if(pendingResults.get() == 0 && !result.isDone()) {
debug.debug("Finished.");
result.complete(finishSolve());
} else {
debug.debug("Not finished.");
}
if(!inFixedPoint.compareAndSet(true, false)) {
throw new IllegalStateException("Fixed point nesting detection error.");
}
}
private SolverResult finishSolve() throws InterruptedException {
final Map<IConstraint, Delay> delayed = constraints.delayed();
debug.debug("Solved constraints with {} failed and {} remaining constraint(s).", failed.size(),
constraints.delayedSize());
if(debug.isEnabled(Level.Debug)) {
for(Map.Entry<IConstraint, Delay> entry : delayed.entrySet()) {
debug.debug(" * {} on {}", entry.getKey().toString(state.unifier()::toString), entry.getValue());
removeCompleteness(entry.getKey());
}
}
// cleanup open edges
for(IConstraint delay : delayed.keySet()) {
removeCompleteness(delay);
}
final Map<ITermVar, ITermVar> existentials = Optional.ofNullable(this.existentials).orElse(NO_EXISTENTIALS);
final java.util.Set<CriticalEdge> removedEdges = ImmutableSet.of();
final ICompleteness.Immutable completeness = Completeness.Immutable.of();
final SolverResult result =
SolverResult.of(spec, state, failed, delayed, existentials, updatedVars, removedEdges, completeness);
return result;
}
///////////////////////////////////////////////////////////////////////////
// success/failure signals
///////////////////////////////////////////////////////////////////////////
private boolean success(IConstraint constraint, IState.Immutable newState, Collection<ITermVar> updatedVars,
Collection<IConstraint> newConstraints, ICompleteness.Immutable newCriticalEdges,
Map<ITermVar, ITermVar> existentials, int fuel) throws InterruptedException {
state = newState;
final IDebugContext subDebug = debug.subContext();
if(this.existentials == null) {
this.existentials = existentials;
}
final IUniDisunifier.Immutable unifier = state.unifier();
// updates from unified variables
if(!updatedVars.isEmpty()) {
final ICompleteness.Transient _completeness = completeness.melt();
_completeness.updateAll(updatedVars, unifier);
this.completeness = _completeness.freeze();
constraints.activateFromVars(updatedVars, debug);
this.updatedVars.addAll(updatedVars);
}
// add new constraints
if(!newConstraints.isEmpty()) {
// no constraints::addAll, instead recurse in tail position
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
_completeness.addAll(newCriticalEdges, unifier); // must come before ICompleteness::remove
} else {
_completeness.addAll(newConstraints, spec, unifier); // must come before ICompleteness::remove
}
this.completeness = _completeness.freeze();
if(subDebug.isEnabled(Level.Debug) && !newConstraints.isEmpty()) {
subDebug.debug("Simplified to:");
for(IConstraint newConstraint : newConstraints) {
subDebug.debug(" * {}", Solver.toString(newConstraint, unifier));
}
}
}
removeCompleteness(constraint);
// do this after the state has been completely updated
if(!updatedVars.isEmpty()) {
releaseDelayedActions(updatedVars);
}
// continue on new constraints
for(IConstraint newConstraint : newConstraints) {
if(!k(newConstraint, fuel - 1)) {
return false;
}
}
return true;
}
private boolean delay(IConstraint constraint, Delay delay) throws InterruptedException {
if(!delay.criticalEdges().isEmpty()) {
debug.error("FIXME: constraint failed on critical edges {}: {}", delay.criticalEdges(),
constraint.toString(state.unifier()::toString));
return fail(constraint);
}
final Set.Immutable<ITermVar> vars = delay.vars().stream().flatMap(v -> state.unifier().getVars(v).stream())
.collect(CapsuleCollectors.toSet());
if(vars.isEmpty()) {
debug.error("FIXME: constraint delayed on no vars: {}", delay.criticalEdges(),
constraint.toString(state.unifier()::toString));
return fail(constraint);
}
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint delayed on vars {}: {}", vars, constraint.toString(state.unifier()::toString));
}
final IDebugContext subDebug = debug.subContext();
constraints.delay(constraint, delay);
if(subDebug.isEnabled(Level.Debug)) {
subDebug.debug("Delayed: {}", Solver.toString(constraint, state.unifier()));
}
return true;
}
private <R> boolean future(IFuture<R> future, K<? super R> k) throws InterruptedException {
pendingResults.incrementAndGet();
future.handle((r, ex) -> {
pendingResults.decrementAndGet();
if(!result.isDone()) {
solveK(k, r, ex);
}
return Unit.unit;
});
return true;
}
private boolean fail(IConstraint constraint) throws InterruptedException {
failed.put(constraint, MessageUtil.findClosestMessage(constraint));
removeCompleteness(constraint);
return (flags & RETURN_ON_FIRST_ERROR) == 0;
}
private void removeCompleteness(IConstraint constraint) throws InterruptedException {
final Set.Immutable<CriticalEdge> removedEdges;
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
if(!constraint.ownCriticalEdges().isPresent()) {
throw new IllegalArgumentException("Solver only accepts constraints with pre-computed critical edges.");
}
removedEdges = _completeness.removeAll(constraint.ownCriticalEdges().get(), state.unifier());
} else {
removedEdges = _completeness.remove(constraint, spec, state.unifier());
}
for(CriticalEdge criticalEdge : removedEdges) {
closeEdge(criticalEdge);
}
this.completeness = _completeness.freeze();
}
private boolean queue(IConstraint constraint) {
constraints.add(constraint);
return true;
}
///////////////////////////////////////////////////////////////////////////
// k
///////////////////////////////////////////////////////////////////////////
private boolean k(IConstraint constraint, int fuel) throws InterruptedException {
// stop if thread is interrupted
if(cancel.cancelled()) {
throw new InterruptedException();
}
// stop recursion if we run out of fuel
if(fuel <= 0) {
return queue(constraint);
}
if(debug.isEnabled(Level.Debug)) {
debug.debug("Solving {}",
constraint.toString(Solver.shallowTermFormatter(state.unifier(), Solver.TERM_FORMAT_DEPTH)));
}
// solve
return constraint.matchOrThrow(new IConstraint.CheckedCases<Boolean, InterruptedException>() {
@Override public Boolean caseArith(CArith c) throws InterruptedException {
final IUniDisunifier unifier = state.unifier();
final Optional<ITerm> term1 = c.expr1().isTerm();
final Optional<ITerm> term2 = c.expr2().isTerm();
try {
if(c.op().isEquals() && term1.isPresent()) {
int i2 = c.expr2().eval(unifier);
final IConstraint eq = new CEqual(term1.get(), B.newInt(i2), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else if(c.op().isEquals() && term2.isPresent()) {
int i1 = c.expr1().eval(unifier);
final IConstraint eq = new CEqual(B.newInt(i1), term2.get(), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
int i1 = c.expr1().eval(unifier);
int i2 = c.expr2().eval(unifier);
if(c.op().test(i1, i2)) {
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
} catch(Delay d) {
return delay(c, d);
}
}
@Override public Boolean caseConj(CConj c) throws InterruptedException {
return success(c, state, NO_UPDATED_VARS, disjoin(c), NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS, fuel);
}
@Override public Boolean caseEqual(CEqual c) throws InterruptedException {
final ITerm term1 = c.term1();
final ITerm term2 = c.term2();
IUniDisunifier.Immutable unifier = state.unifier();
try {
final IUniDisunifier.Result<IUnifier.Immutable> result;
if((result = unifier.unify(term1, term2, v -> isRigid(v, state)).orElse(null)) != null) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification succeeded: {}", result.result());
}
final IState.Immutable newState = state.withUnifier(result.unifier());
final Set<ITermVar> updatedVars = result.result().domainSet();
return success(c, newState, updatedVars, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification failed: {} != {}", unifier.toString(term1),
unifier.toString(term2));
}
return fail(c);
}
} catch(OccursException e) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification failed: {} != {}", unifier.toString(term1), unifier.toString(term2));
}
return fail(c);
} catch(RigidException e) {
return delay(c, Delay.ofVars(e.vars()));
}
}
@Override public Boolean caseExists(CExists c) throws InterruptedException {
final Renaming.Builder _existentials = Renaming.builder();
IState.Immutable newState = state;
for(ITermVar var : c.vars()) {
final Tuple2<ITermVar, IState.Immutable> varAndState = newState.freshVar(var);
final ITermVar freshVar = varAndState._1();
newState = varAndState._2();
_existentials.put(var, freshVar);
}
final Renaming existentials = _existentials.build();
final ISubstitution.Immutable subst = existentials.asSubstitution();
final IConstraint newConstraint = c.constraint().apply(subst).withCause(c.cause().orElse(null));
if(INCREMENTAL_CRITICAL_EDGES && !c.bodyCriticalEdges().isPresent()) {
throw new IllegalArgumentException(
"Solver only accepts constraints with pre-computed critical edges.");
}
final ICompleteness.Immutable newCriticalEdges =
c.bodyCriticalEdges().orElse(NO_NEW_CRITICAL_EDGES).apply(subst);
return success(c, newState, NO_UPDATED_VARS, disjoin(newConstraint), newCriticalEdges,
existentials.asMap(), fuel);
}
@Override public Boolean caseFalse(CFalse c) throws InterruptedException {
return fail(c);
}
@Override public Boolean caseInequal(CInequal c) throws InterruptedException {
final ITerm term1 = c.term1();
final ITerm term2 = c.term2();
final IUniDisunifier.Immutable unifier = state.unifier();
try {
final IUniDisunifier.Result<Optional<Diseq>> result;
if((result = unifier.disunify(c.universals(), term1, term2, v -> isRigid(v, state))
.orElse(null)) != null) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Disunification succeeded: {}", result);
}
final IState.Immutable newState = state.withUnifier(result.unifier());
final java.util.Set<ITermVar> updatedVars =
result.result().<java.util.Set<ITermVar>>map(Diseq::domainSet).orElse(NO_UPDATED_VARS);
return success(c, newState, updatedVars, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Disunification failed");
}
return fail(c);
}
} catch(RigidException e) {
return delay(c, Delay.ofVars(e.vars()));
}
}
@Override public Boolean caseNew(CNew c) throws InterruptedException {
final ITerm scopeTerm = c.scopeTerm();
final ITerm datumTerm = c.datumTerm();
final String name = M.var(ITermVar::getName).match(scopeTerm).orElse("s");
final Set<ITerm> labels = getOpenEdges(scopeTerm);
final Scope scope = scopeGraph.freshScope(name, labels, true, false);
scopeGraph.setDatum(scope, datumTerm);
final IConstraint eq = new CEqual(scopeTerm, scope, c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseResolveQuery(CResolveQuery c) throws InterruptedException {
final QueryFilter filter = c.filter();
final QueryMin min = c.min();
final ITerm scopeTerm = c.scopeTerm();
final ITerm resultTerm = c.resultTerm();
final IUniDisunifier unifier = state.unifier();
// @formatter:off
final Set.Immutable<ITermVar> freeVars = Streams.concat(
unifier.getVars(scopeTerm).stream(),
filter.getDataWF().freeVars().stream().flatMap(v -> unifier.getVars(v).stream()),
min.getDataEquiv().freeVars().stream().flatMap(v -> unifier.getVars(v).stream())
).collect(CapsuleCollectors.toSet());
// @formatter:on
if(!freeVars.isEmpty()) {
return delay(c, Delay.ofVars(freeVars));
}
final Rule dataWfRule = RuleUtil.instantiateHeadPatterns(
RuleUtil.closeInUnifier(filter.getDataWF(), state.unifier(), Safety.UNSAFE));
final Rule dataLeqRule = RuleUtil.instantiateHeadPatterns(
RuleUtil.closeInUnifier(min.getDataEquiv(), state.unifier(), Safety.UNSAFE));
final Scope scope = AScope.matcher().match(scopeTerm, unifier).orElseThrow(
() -> new IllegalArgumentException("Expected scope, got " + unifier.toString(scopeTerm)));
final LabelWf<ITerm> labelWF = new RegExpLabelWf<>(filter.getLabelWF());
final LabelOrder<ITerm> labelOrder = new RelationLabelOrder<>(min.getLabelOrder());
final DataWf<Scope, ITerm, ITerm> dataWF = new ConstraintDataWF(spec, dataWfRule);
final DataLeq<Scope, ITerm, ITerm> dataEquiv = new ConstraintDataEquiv(spec, dataLeqRule);
final DataWf<Scope, ITerm, ITerm> dataWFInternal =
LOCAL_INFERENCE ? new ConstraintDataWFInternal(dataWfRule) : null;
final DataLeq<Scope, ITerm, ITerm> dataEquivInternal =
LOCAL_INFERENCE ? new ConstraintDataEquivInternal(dataLeqRule) : null;
final IFuture<? extends java.util.Set<IResolutionPath<Scope, ITerm, ITerm>>> future = scopeGraph
.query(scope, labelWF, labelOrder, dataWF, dataEquiv, dataWFInternal, dataEquivInternal);
final K<java.util.Set<IResolutionPath<Scope, ITerm, ITerm>>> k = (paths, ex, fuel) -> {
if(ex != null) {
// pattern matching for the brave and stupid
try {
throw ex;
} catch(ResolutionDelayException rde) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("delayed query (unsupported) {}", rde,
c.toString(state.unifier()::toString));
}
return fail(c);
} catch(DeadlockException dle) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("deadlocked query (spec error) {}", c.toString(state.unifier()::toString));
}
return fail(c);
} catch(InterruptedException t) {
throw t;
} catch(Throwable t) {
debug.error("failed query {}", t, c.toString(state.unifier()::toString));
return fail(c);
}
} else {
final List<ITerm> pathTerms =
paths.stream().map(p -> StatixTerms.pathToTerm(p, spec.dataLabels()))
.collect(ImmutableList.toImmutableList());
final IConstraint C = new CEqual(resultTerm, B.newList(pathTerms), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(C), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
}
};
return future(future, k);
}
@Override public Boolean caseTellEdge(CTellEdge c) throws InterruptedException {
final ITerm sourceTerm = c.sourceTerm();
final ITerm label = c.label();
final ITerm targetTerm = c.targetTerm();
final IUniDisunifier unifier = state.unifier();
if(!unifier.isGround(sourceTerm)) {
return delay(c, Delay.ofVars(unifier.getVars(sourceTerm)));
}
if(!unifier.isGround(targetTerm)) {
return delay(c, Delay.ofVars(unifier.getVars(targetTerm)));
}
final Scope source =
AScope.matcher().match(sourceTerm, unifier).orElseThrow(() -> new IllegalArgumentException(
"Expected source scope, got " + unifier.toString(sourceTerm)));
final Scope target =
AScope.matcher().match(targetTerm, unifier).orElseThrow(() -> new IllegalArgumentException(
"Expected target scope, got " + unifier.toString(targetTerm)));
scopeGraph.addEdge(source, label, target);
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseTermId(CAstId c) throws InterruptedException {
final ITerm term = c.astTerm();
final ITerm idTerm = c.idTerm();
final IUniDisunifier unifier = state.unifier();
if(!(unifier.isGround(term))) {
return delay(c, Delay.ofVars(unifier.getVars(term)));
}
final CEqual eq;
final Optional<Scope> maybeScope = AScope.matcher().match(term, unifier);
if(maybeScope.isPresent()) {
final AScope scope = maybeScope.get();
eq = new CEqual(idTerm, scope);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
final Optional<TermIndex> maybeIndex = TermIndex.get(unifier.findTerm(term));
if(maybeIndex.isPresent()) {
final ITerm indexTerm = TermOrigin.copy(term, maybeIndex.get());
eq = new CEqual(idTerm, indexTerm);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
}
@Override public Boolean caseTermProperty(CAstProperty c) throws InterruptedException {
final ITerm idTerm = c.idTerm();
final ITerm prop = c.property();
final ITerm value = c.value();
final IUniDisunifier unifier = state.unifier();
if(!(unifier.isGround(idTerm))) {
return delay(c, Delay.ofVars(unifier.getVars(idTerm)));
}
final Optional<TermIndex> maybeIndex = TermIndex.matcher().match(idTerm, unifier);
if(maybeIndex.isPresent()) {
final TermIndex index = maybeIndex.get();
final Tuple2<TermIndex, ITerm> key = Tuple2.of(index, prop);
ITermProperty property;
switch(c.op()) {
case ADD: {
property = state.termProperties().getOrDefault(key, BagTermProperty.of());
if(!property.multiplicity().equals(Multiplicity.BAG)) {
return fail(c);
}
property = property.addValue(value);
break;
}
case SET: {
if(state.termProperties().containsKey(key)) {
return fail(c);
}
property = SingletonTermProperty.of(value);
break;
}
default:
throw new IllegalStateException("Unknown op " + c.op());
}
final IState.Immutable newState =
state.withTermProperties(state.termProperties().__put(key, property));
return success(c, newState, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
@Override public Boolean caseTrue(CTrue c) throws InterruptedException {
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseTry(CTry c) throws InterruptedException {
final IDebugContext subDebug = debug.subContext();
final ITypeCheckerContext<Scope, ITerm, ITerm> subContext = scopeGraph.subContext("try");
final IState.Immutable subState = state.subState().withResource(subContext.id());
final StatixSolver subSolver = new StatixSolver(c.constraint(), spec, subState, completeness, subDebug,
progress, cancel, subContext, RETURN_ON_FIRST_ERROR);
final IFuture<SolverResult> subResult = subSolver.entail();
final K<SolverResult> k = (r, ex, fuel) -> {
if(ex != null) {
debug.error("try {} failed", ex, c.toString(state.unifier()::toString));
return fail(c);
} else {
try {
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", c.toString(state.unifier()::toString));
}
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", c.toString(state.unifier()::toString));
}
return fail(c);
}
} catch(Delay delay) {
return delay(c, delay);
}
}
};
return future(subResult, k);
}
@Override public Boolean caseUser(CUser c) throws InterruptedException {
final String name = c.name();
final List<ITerm> args = c.args();
final LazyDebugContext proxyDebug = new LazyDebugContext(debug);
final List<Rule> rules = spec.rules().getRules(name);
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
final Tuple3<Rule, ApplyResult, Boolean> result;
if((result = RuleUtil.applyOrderedOne(state.unifier(), rules, args, c, ApplyMode.RELAXED, Safety.UNSAFE)
.orElse(null)) == null) {
debug.debug("No rule applies");
return fail(c);
}
final ApplyResult applyResult = result._2();
if(!result._3()) {
final Set<ITermVar> stuckVars = Streams.stream(applyResult.guard())
.flatMap(g -> g.domainSet().stream()).collect(CapsuleCollectors.toSet());
proxyDebug.debug("Rule delayed (multiple conditional matches)");
return delay(c, Delay.ofVars(stuckVars));
}
proxyDebug.debug("Rule accepted");
proxyDebug.commit();
if(INCREMENTAL_CRITICAL_EDGES && applyResult.criticalEdges() == null) {
throw new IllegalArgumentException("Solver only accepts specs with pre-computed critical edges.");
}
return success(c, state, NO_UPDATED_VARS, Collections.singletonList(applyResult.body()),
applyResult.criticalEdges(), NO_EXISTENTIALS, fuel);
}
});
}
///////////////////////////////////////////////////////////////////////////
// entailment
///////////////////////////////////////////////////////////////////////////
private static IFuture<Boolean> entails(ITypeCheckerContext<Scope, ITerm, ITerm> context, Spec spec,
IState.Immutable state, IConstraint constraint, ICompleteness.Immutable criticalEdges, IDebugContext debug,
ICancel cancel, IProgress progress) throws Delay {
final IDebugContext subDebug = debug.subContext();
final ITypeCheckerContext<Scope, ITerm, ITerm> subContext = context.subContext("entails");
final IState.Immutable subState = state.subState().withResource(subContext.id());
final PreSolveResult preSolveResult;
if((preSolveResult = Solver.preEntail(subState, criticalEdges, constraint).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
if(preSolveResult.constraints.isEmpty()) {
return CompletableFuture.completedFuture(Solver.entailed(subState, preSolveResult, subDebug));
}
final StatixSolver subSolver =
new StatixSolver(Constraints.conjoin(preSolveResult.constraints), spec, preSolveResult.state,
preSolveResult.criticalEdges, subDebug, progress, cancel, subContext, RETURN_ON_FIRST_ERROR);
return subSolver.entail().thenCompose(r -> {
final boolean result;
try {
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", constraint.toString(state.unifier()::toString));
}
result = true;
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", constraint.toString(state.unifier()::toString));
}
result = false;
}
} catch(Delay delay) {
throw new IllegalStateException("Unexpected delay.", delay);
}
return CompletableFuture.completedFuture(result);
});
}
private IFuture<Boolean> entails(ITypeCheckerContext<Scope, ITerm, ITerm> subContext, IConstraint constraint,
ICompleteness.Immutable criticalEdges, ICancel cancel) {
final IDebugContext subDebug = debug.subContext();
return absorbDelays(() -> {
final IState.Immutable subState = state.subState().withResource(subContext.id());
final PreSolveResult preSolveResult;
try {
if((preSolveResult = Solver.preEntail(subState, criticalEdges, constraint).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
} catch(Delay d) {
return CompletableFuture.completedExceptionally(d);
}
if(preSolveResult.constraints.isEmpty()) {
return CompletableFuture.completedFuture(Solver.entailed(subState, preSolveResult, subDebug));
}
final StatixSolver subSolver = new StatixSolver(Constraints.conjoin(preSolveResult.constraints), spec,
preSolveResult.state, preSolveResult.criticalEdges, subDebug, progress, cancel, subContext,
RETURN_ON_FIRST_ERROR);
return subSolver.entail().thenCompose(r -> {
final boolean result;
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", constraint.toString(state.unifier()::toString));
}
result = true;
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", constraint.toString(state.unifier()::toString));
}
result = false;
}
return CompletableFuture.completedFuture(result);
});
});
}
private <T> IFuture<T> absorbDelays(Function0<IFuture<T>> f) {
return f.apply().compose((r, ex) -> {
if(ex != null) {
try {
throw ex;
} catch(Delay delay) {
if(!delay.criticalEdges().isEmpty()) {
debug.error("unsupported delay with critical edges {}", delay);
throw new IllegalStateException("unsupported delay with critical edges");
}
if(delay.vars().isEmpty()) {
debug.error("unsupported delay without variables {}", delay);
throw new IllegalStateException("unsupported delay without variables");
}
final CompletableFuture<T> result = new CompletableFuture<>();
try {
delayAction(() -> {
absorbDelays(f).whenComplete(result::complete);
}, delay.vars());
} catch(InterruptedException ie) {
result.completeExceptionally(ie);
}
return result;
} catch(Throwable t) {
return CompletableFuture.completedExceptionally(t);
}
} else {
return CompletableFuture.completedFuture(r);
}
});
}
///////////////////////////////////////////////////////////////////////////
// Open edges & delayed closes
///////////////////////////////////////////////////////////////////////////
private Set.Transient<CriticalEdge> delayedCloses = CapsuleUtil.transientSet();
private Set.Immutable<ITerm> getOpenEdges(ITerm varOrScope) {
// we must include queued edge closes here, to ensure we registered the open
// edge when the close is released
final List<EdgeOrData<ITerm>> openEdges =
Streams.stream(completeness.get(varOrScope, state.unifier())).collect(Collectors.toList());
final List<EdgeOrData<ITerm>> queuedEdges = M.var().match(varOrScope)
.map(var -> delayedCloses.stream().filter(e -> state.unifier().equal(var, e.scope()))
.map(e -> e.edgeOrData()))
.orElse(Stream.<EdgeOrData<ITerm>>empty()).collect(Collectors.toList());
return stream(Iterables.concat(openEdges, queuedEdges)).<ITerm>flatMap(eod -> {
return eod.match(() -> Stream.<ITerm>empty(), (l) -> Stream.of(l));
}).collect(CapsuleCollectors.toSet());
}
private void closeEdge(CriticalEdge criticalEdge) throws InterruptedException {
if(debug.isEnabled(Level.Debug)) {
debug.debug("client {} close edge {}/{}", this, state.unifier().toString(criticalEdge.scope()),
criticalEdge.edgeOrData());
}
delayedCloses.__insert(criticalEdge);
delayAction(() -> {
delayedCloses.__remove(criticalEdge);
closeGroundEdge(criticalEdge);
}, state.unifier().getVars(criticalEdge.scope()));
}
private void closeGroundEdge(CriticalEdge criticalEdge) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("client {} close edge {}/{}", this, state.unifier().toString(criticalEdge.scope()),
criticalEdge.edgeOrData());
}
final Scope scope = Scope.matcher().match(criticalEdge.scope(), state.unifier())
.orElseThrow(() -> new IllegalArgumentException(
"Expected scope, got " + state.unifier().toString(criticalEdge.scope())));
// @formatter:off
criticalEdge.edgeOrData().match(
() -> {
// ignore data labels, they are managed separately
return Unit.unit;
},
label -> {
scopeGraph.closeEdge(scope, label);
return Unit.unit;
}
);
// @formatter:on
}
///////////////////////////////////////////////////////////////////////////
// Delayed actions
///////////////////////////////////////////////////////////////////////////
private final VarIndexedCollection<CheckedAction0<InterruptedException>> delayedActions =
new VarIndexedCollection<>();
private void delayAction(CheckedAction0<InterruptedException> action, Iterable<ITermVar> vars)
throws InterruptedException {
final Set.Immutable<ITermVar> foreignVars =
Streams.stream(vars).filter(v -> !state.vars().contains(v)).collect(CapsuleCollectors.toSet());
if(!foreignVars.isEmpty()) {
throw new IllegalStateException("Cannot delay on foreign variables: " + foreignVars);
}
if(!delayedActions.put(action, vars, state.unifier())) {
action.apply();
}
}
private void releaseDelayedActions(Iterable<ITermVar> updatedVars) throws InterruptedException {
for(CheckedAction0<InterruptedException> action : delayedActions.update(updatedVars, state.unifier())) {
action.apply();
}
}
///////////////////////////////////////////////////////////////////////////
// external data
///////////////////////////////////////////////////////////////////////////
public IFuture<ITerm> getExternalRepresentation(ITerm t) {
final CompletableFuture<ITerm> f = new CompletableFuture<>();
try {
delayAction(() -> {
f.complete(state.unifier().findRecursive(t));
}, state.unifier().getVars(t));
} catch(InterruptedException ex) {
f.completeExceptionally(ex);
}
return f;
}
///////////////////////////////////////////////////////////////////////////
// data wf & leq
///////////////////////////////////////////////////////////////////////////
private static class ConstraintDataWF implements DataWf<Scope, ITerm, ITerm> {
private final Spec spec;
private final Rule constraint;
private final IState.Immutable state;
public ConstraintDataWF(Spec spec, Rule constraint) {
// assume constraint.freeVars().isEmpty()
this.spec = spec;
this.constraint = constraint;
this.state = State.of(); // outer solver state unnecessary, because only applied to ground terms
}
@Override public IFuture<Boolean> wf(ITerm datum, ITypeCheckerContext<Scope, ITerm, ITerm> context,
ICancel cancel) throws InterruptedException {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, applyResult.body(), applyResult.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
@Override public String toString() {
return constraint.toString();
}
}
private class ConstraintDataWFInternal implements DataWf<Scope, ITerm, ITerm> {
// Non-static class that is only used on the unit of the type checker
// that started the query, and on data from that unit. Implicitly uses
// solver state from the surrounding object .
private final Rule constraint;
public ConstraintDataWFInternal(Rule constraint) {
this.constraint = constraint;
}
@Override public IFuture<Boolean> wf(ITerm datum, ITypeCheckerContext<Scope, ITerm, ITerm> context,
ICancel cancel) throws InterruptedException {
return absorbDelays(() -> {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, applyResult.body(), applyResult.criticalEdges(), cancel);
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
private static class ConstraintDataEquiv implements DataLeq<Scope, ITerm, ITerm> {
private final Spec spec;
private final Rule constraint;
private final IState.Immutable state;
public ConstraintDataEquiv(Spec spec, Rule constraint) {
// assume constraint.freeVars().isEmpty()
this.spec = spec;
this.constraint = constraint;
this.state = State.of(); // outer solver state unnecessary, because only applied to ground terms
}
@Override public IFuture<Boolean> leq(ITerm datum1, ITerm datum2,
ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) throws InterruptedException {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum1, datum2), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, applyResult.body(), applyResult.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
private @Nullable IFuture<Boolean> alwaysTrue;
@Override public IFuture<Boolean> alwaysTrue(ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) {
if(alwaysTrue == null) {
try {
switch(SHADOW_OPTIMIZATION) {
case CONTEXT:
final Boolean isAlways;
if((isAlways = constraint.isAlways().orElse(null)) != null) {
alwaysTrue = CompletableFuture.completedFuture(isAlways);
} else {
final ApplyResult result;
final Tuple2<ITermVar, IState.Immutable> d1_state =
state.freshVar(B.newVar(state.resource(), "d1"));
final Tuple2<ITermVar, IState.Immutable> d2_state =
d1_state._2().freshVar(B.newVar(state.resource(), "d2"));
try {
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((result = RuleUtil.apply(d2_state._2().unifier(), constraint,
ImmutableList.of(d1_state._1(), d2_state._1()), null, ApplyMode.STRICT,
Safety.UNSAFE).orElse(null)) == null) {
alwaysTrue = CompletableFuture.completedFuture(false);
} else {
alwaysTrue = entails(context, spec, d2_state._2(), result.body(),
result.criticalEdges(), new NullDebugContext(), cancel,
new NullProgress());
}
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
break;
case RULE:
alwaysTrue = CompletableFuture.completedFuture(constraint.isAlways().orElse(false));
break;
case NONE:
default:
alwaysTrue = CompletableFuture.completedFuture(false);
break;
}
} catch(InterruptedException e) {
return CompletableFuture.completedExceptionally(e);
}
}
return alwaysTrue;
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
private class ConstraintDataEquivInternal implements DataLeq<Scope, ITerm, ITerm> {
// Non-static class that is only used on the unit of the type checker
// that started the query, and on data from that unit. Implicitly uses
// solver state from the surrounding object .
private final Rule constraint;
public ConstraintDataEquivInternal(Rule constraint) {
this.constraint = constraint;
}
@Override public IFuture<Boolean> leq(ITerm datum1, ITerm datum2,
ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) throws InterruptedException {
return absorbDelays(() -> {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum1, datum2),
null, ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, applyResult.body(), applyResult.criticalEdges(), cancel);
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
private @Nullable IFuture<Boolean> alwaysTrue;
@Override public IFuture<Boolean> alwaysTrue(ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) {
if(alwaysTrue == null) {
try {
switch(SHADOW_OPTIMIZATION) {
case CONTEXT:
final Boolean isAlways;
if((isAlways = constraint.isAlways().orElse(null)) != null) {
alwaysTrue = CompletableFuture.completedFuture(isAlways);
} else {
alwaysTrue = absorbDelays(() -> {
try {
final ApplyResult result;
final Tuple2<ITermVar, IState.Immutable> d1_state =
state.freshVar(B.newVar(state.resource(), "d1"));
final Tuple2<ITermVar, IState.Immutable> d2_state =
d1_state._2().freshVar(B.newVar(state.resource(), "d2"));
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((result = RuleUtil.apply(d2_state._2().unifier(), constraint,
ImmutableList.of(d1_state._1(), d2_state._1()), null, ApplyMode.STRICT,
Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, result.body(), result.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
break;
case RULE:
alwaysTrue = CompletableFuture.completedFuture(constraint.isAlways().orElse(false));
break;
case NONE:
default:
alwaysTrue = CompletableFuture.completedFuture(false);
break;
}
} catch(InterruptedException e) {
return CompletableFuture.completedExceptionally(e);
}
}
return alwaysTrue;
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
///////////////////////////////////////////////////////////////////////////
// rigidness
///////////////////////////////////////////////////////////////////////////
private boolean isRigid(ITermVar var, IState state) {
return !state.vars().contains(var);
}
///////////////////////////////////////////////////////////////////////////
// toString
///////////////////////////////////////////////////////////////////////////
@Override public String toString() {
return "StatixSolver";
}
///////////////////////////////////////////////////////////////////////////
// K
///////////////////////////////////////////////////////////////////////////
@FunctionalInterface
private interface K<R> {
boolean k(R result, Throwable ex, int fuel) throws InterruptedException;
}
} | statix.solver/src/main/java/mb/statix/concurrent/StatixSolver.java | package mb.statix.concurrent;
import static com.google.common.collect.Streams.stream;
import static mb.nabl2.terms.build.TermBuild.B;
import static mb.nabl2.terms.matching.TermMatch.M;
import static mb.statix.constraints.Constraints.disjoin;
import static mb.statix.solver.persistent.Solver.INCREMENTAL_CRITICAL_EDGES;
import static mb.statix.solver.persistent.Solver.RETURN_ON_FIRST_ERROR;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.metaborg.util.collection.CapsuleUtil;
import org.metaborg.util.functions.CheckedAction0;
import org.metaborg.util.functions.Function0;
import org.metaborg.util.future.CompletableFuture;
import org.metaborg.util.future.IFuture;
import org.metaborg.util.log.Level;
import org.metaborg.util.task.ICancel;
import org.metaborg.util.task.IProgress;
import org.metaborg.util.task.NullProgress;
import org.metaborg.util.tuple.Tuple2;
import org.metaborg.util.tuple.Tuple3;
import org.metaborg.util.unit.Unit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Streams;
import io.usethesource.capsule.Set;
import io.usethesource.capsule.util.stream.CapsuleCollectors;
import mb.nabl2.terms.ITerm;
import mb.nabl2.terms.ITermVar;
import mb.nabl2.terms.stratego.TermIndex;
import mb.nabl2.terms.stratego.TermOrigin;
import mb.nabl2.terms.substitution.ISubstitution;
import mb.nabl2.terms.substitution.Renaming;
import mb.nabl2.terms.unification.OccursException;
import mb.nabl2.terms.unification.RigidException;
import mb.nabl2.terms.unification.u.IUnifier;
import mb.nabl2.terms.unification.ud.Diseq;
import mb.nabl2.terms.unification.ud.IUniDisunifier;
import mb.p_raffrayi.DeadlockException;
import mb.p_raffrayi.ITypeCheckerContext;
import mb.p_raffrayi.nameresolution.DataLeq;
import mb.p_raffrayi.nameresolution.DataWf;
import mb.scopegraph.ecoop21.LabelOrder;
import mb.scopegraph.ecoop21.LabelWf;
import mb.scopegraph.ecoop21.RegExpLabelWf;
import mb.scopegraph.ecoop21.RelationLabelOrder;
import mb.scopegraph.oopsla20.path.IResolutionPath;
import mb.scopegraph.oopsla20.reference.EdgeOrData;
import mb.statix.concurrent.util.VarIndexedCollection;
import mb.statix.constraints.CArith;
import mb.statix.constraints.CAstId;
import mb.statix.constraints.CAstProperty;
import mb.statix.constraints.CConj;
import mb.statix.constraints.CEqual;
import mb.statix.constraints.CExists;
import mb.statix.constraints.CFalse;
import mb.statix.constraints.CInequal;
import mb.statix.constraints.CNew;
import mb.statix.constraints.CResolveQuery;
import mb.statix.constraints.CTellEdge;
import mb.statix.constraints.CTrue;
import mb.statix.constraints.CTry;
import mb.statix.constraints.CUser;
import mb.statix.constraints.Constraints;
import mb.statix.constraints.messages.IMessage;
import mb.statix.constraints.messages.MessageUtil;
import mb.statix.scopegraph.AScope;
import mb.statix.scopegraph.Scope;
import mb.statix.solver.CriticalEdge;
import mb.statix.solver.Delay;
import mb.statix.solver.IConstraint;
import mb.statix.solver.IConstraintStore;
import mb.statix.solver.IState;
import mb.statix.solver.ITermProperty;
import mb.statix.solver.ITermProperty.Multiplicity;
import mb.statix.solver.completeness.Completeness;
import mb.statix.solver.completeness.CompletenessUtil;
import mb.statix.solver.completeness.ICompleteness;
import mb.statix.solver.log.IDebugContext;
import mb.statix.solver.log.LazyDebugContext;
import mb.statix.solver.log.NullDebugContext;
import mb.statix.solver.persistent.BagTermProperty;
import mb.statix.solver.persistent.SingletonTermProperty;
import mb.statix.solver.persistent.Solver;
import mb.statix.solver.persistent.Solver.PreSolveResult;
import mb.statix.solver.persistent.SolverResult;
import mb.statix.solver.persistent.State;
import mb.statix.solver.query.QueryFilter;
import mb.statix.solver.query.QueryMin;
import mb.statix.solver.query.ResolutionDelayException;
import mb.statix.solver.store.BaseConstraintStore;
import mb.statix.spec.ApplyMode;
import mb.statix.spec.ApplyMode.Safety;
import mb.statix.spec.ApplyResult;
import mb.statix.spec.Rule;
import mb.statix.spec.RuleUtil;
import mb.statix.spec.Spec;
import mb.statix.spoofax.StatixTerms;
public class StatixSolver {
private enum ShadowOptimization {
NONE, RULE, CONTEXT
}
private static final ShadowOptimization SHADOW_OPTIMIZATION = ShadowOptimization.RULE;
private static final boolean LOCAL_INFERENCE = true;
private static final ImmutableSet<ITermVar> NO_UPDATED_VARS = ImmutableSet.of();
private static final ImmutableList<IConstraint> NO_NEW_CONSTRAINTS = ImmutableList.of();
private static final mb.statix.solver.completeness.Completeness.Immutable NO_NEW_CRITICAL_EDGES =
Completeness.Immutable.of();
private static final ImmutableMap<ITermVar, ITermVar> NO_EXISTENTIALS = ImmutableMap.of();
private static final int MAX_DEPTH = 32;
private final Spec spec;
private final IConstraintStore constraints;
private final IDebugContext debug;
private final IProgress progress;
private final ICancel cancel;
private final ITypeCheckerContext<Scope, ITerm, ITerm> scopeGraph;
private final int flags;
private IState.Immutable state;
private ICompleteness.Immutable completeness;
private Map<ITermVar, ITermVar> existentials = null;
private final List<ITermVar> updatedVars = Lists.newArrayList();
private final Map<IConstraint, IMessage> failed = Maps.newHashMap();
private final AtomicBoolean inFixedPoint = new AtomicBoolean(false);
private final AtomicInteger pendingResults = new AtomicInteger(0);
private final CompletableFuture<SolverResult> result;
public StatixSolver(IConstraint constraint, Spec spec, IState.Immutable state, ICompleteness.Immutable completeness,
IDebugContext debug, IProgress progress, ICancel cancel,
ITypeCheckerContext<Scope, ITerm, ITerm> scopeGraph, int flags) {
if(INCREMENTAL_CRITICAL_EDGES && !spec.hasPrecomputedCriticalEdges()) {
debug.warn("Leaving precomputing critical edges to solver may result in duplicate work.");
this.spec = spec.precomputeCriticalEdges();
} else {
this.spec = spec;
}
this.scopeGraph = scopeGraph;
this.state = state;
this.debug = debug;
this.constraints = new BaseConstraintStore(debug);
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
final Tuple2<IConstraint, ICompleteness.Immutable> initialConstraintAndCriticalEdges =
CompletenessUtil.precomputeCriticalEdges(constraint, spec.scopeExtensions());
this.constraints.add(initialConstraintAndCriticalEdges._1());
_completeness.addAll(initialConstraintAndCriticalEdges._2(), state.unifier());
} else {
constraints.add(constraint);
_completeness.add(constraint, spec, state.unifier());
}
this.completeness = _completeness.freeze();
this.result = new CompletableFuture<>();
this.progress = progress;
this.cancel = cancel;
this.flags = flags;
}
///////////////////////////////////////////////////////////////////////////
// driver
///////////////////////////////////////////////////////////////////////////
public IFuture<SolverResult> solve(Iterable<Scope> roots) {
try {
for(Scope root : CapsuleUtil.toSet(roots)) {
final Set.Immutable<ITerm> openEdges = getOpenEdges(root);
scopeGraph.initScope(root, openEdges, false);
}
fixedpoint();
} catch(Throwable e) {
result.completeExceptionally(e);
}
return result;
}
public IFuture<SolverResult> entail() {
return solve(Collections.emptyList());
}
private <R> void solveK(K<R> k, R r, Throwable ex) {
debug.debug("Solving continuation");
try {
if(!k.k(r, ex, MAX_DEPTH)) {
debug.debug("Finished fast.");
result.complete(finishSolve());
return;
}
fixedpoint();
} catch(Throwable e) {
result.completeExceptionally(e);
}
debug.debug("Solved continuation");
}
// It can happen that fixedpoint is called in the context of a running fixedpoint.
// This can happen when a continuation is not triggered by a remote message, but
// directly completed (e.g., by a try). The solveK invocation will call fixedpoint
// again. We prevent recursive fixed points to ensure the termination conditions are
// correctly checked.
private void fixedpoint() throws InterruptedException {
if(!inFixedPoint.compareAndSet(false, true)) {
return;
}
debug.debug("Solving constraints");
IConstraint constraint;
while((constraint = constraints.remove()) != null) {
if(!k(constraint, MAX_DEPTH)) {
debug.debug("Finished fast.");
result.complete(finishSolve());
return;
}
}
// invariant: there should be no remaining active constraints
if(constraints.activeSize() > 0) {
debug.warn("Fixed point finished with remaining constraints");
throw new IllegalStateException(
"Expected no remaining active constraints, but got " + constraints.activeSize());
}
debug.debug("Has pending: {}, done: {}", pendingResults.get(), result.isDone());
if(pendingResults.get() == 0 && !result.isDone()) {
debug.debug("Finished.");
result.complete(finishSolve());
} else {
debug.debug("Not finished.");
}
if(!inFixedPoint.compareAndSet(true, false)) {
throw new IllegalStateException("Fixed point nesting detection error.");
}
}
private SolverResult finishSolve() throws InterruptedException {
final Map<IConstraint, Delay> delayed = constraints.delayed();
debug.debug("Solved constraints with {} failed and {} remaining constraint(s).", failed.size(),
constraints.delayedSize());
if(debug.isEnabled(Level.Debug)) {
for(Map.Entry<IConstraint, Delay> entry : delayed.entrySet()) {
debug.debug(" * {} on {}", entry.getKey().toString(state.unifier()::toString), entry.getValue());
removeCompleteness(entry.getKey());
}
}
final Map<ITermVar, ITermVar> existentials = Optional.ofNullable(this.existentials).orElse(NO_EXISTENTIALS);
final java.util.Set<CriticalEdge> removedEdges = ImmutableSet.of();
final ICompleteness.Immutable completeness = Completeness.Immutable.of();
final SolverResult result =
SolverResult.of(spec, state, failed, delayed, existentials, updatedVars, removedEdges, completeness);
return result;
}
///////////////////////////////////////////////////////////////////////////
// success/failure signals
///////////////////////////////////////////////////////////////////////////
private boolean success(IConstraint constraint, IState.Immutable newState, Collection<ITermVar> updatedVars,
Collection<IConstraint> newConstraints, ICompleteness.Immutable newCriticalEdges,
Map<ITermVar, ITermVar> existentials, int fuel) throws InterruptedException {
state = newState;
final IDebugContext subDebug = debug.subContext();
if(this.existentials == null) {
this.existentials = existentials;
}
final IUniDisunifier.Immutable unifier = state.unifier();
// updates from unified variables
if(!updatedVars.isEmpty()) {
final ICompleteness.Transient _completeness = completeness.melt();
_completeness.updateAll(updatedVars, unifier);
this.completeness = _completeness.freeze();
constraints.activateFromVars(updatedVars, debug);
this.updatedVars.addAll(updatedVars);
}
// add new constraints
if(!newConstraints.isEmpty()) {
// no constraints::addAll, instead recurse in tail position
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
_completeness.addAll(newCriticalEdges, unifier); // must come before ICompleteness::remove
} else {
_completeness.addAll(newConstraints, spec, unifier); // must come before ICompleteness::remove
}
this.completeness = _completeness.freeze();
if(subDebug.isEnabled(Level.Debug) && !newConstraints.isEmpty()) {
subDebug.debug("Simplified to:");
for(IConstraint newConstraint : newConstraints) {
subDebug.debug(" * {}", Solver.toString(newConstraint, unifier));
}
}
}
removeCompleteness(constraint);
// do this after the state has been completely updated
if(!updatedVars.isEmpty()) {
releaseDelayedActions(updatedVars);
}
// continue on new constraints
for(IConstraint newConstraint : newConstraints) {
if(!k(newConstraint, fuel - 1)) {
return false;
}
}
return true;
}
private boolean delay(IConstraint constraint, Delay delay) throws InterruptedException {
if(!delay.criticalEdges().isEmpty()) {
debug.error("FIXME: constraint failed on critical edges {}: {}", delay.criticalEdges(),
constraint.toString(state.unifier()::toString));
return fail(constraint);
}
final Set.Immutable<ITermVar> vars = delay.vars().stream().flatMap(v -> state.unifier().getVars(v).stream())
.collect(CapsuleCollectors.toSet());
if(vars.isEmpty()) {
debug.error("FIXME: constraint delayed on no vars: {}", delay.criticalEdges(),
constraint.toString(state.unifier()::toString));
return fail(constraint);
}
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint delayed on vars {}: {}", vars, constraint.toString(state.unifier()::toString));
}
final IDebugContext subDebug = debug.subContext();
constraints.delay(constraint, delay);
if(subDebug.isEnabled(Level.Debug)) {
subDebug.debug("Delayed: {}", Solver.toString(constraint, state.unifier()));
}
return true;
}
private <R> boolean future(IFuture<R> future, K<? super R> k) throws InterruptedException {
pendingResults.incrementAndGet();
future.handle((r, ex) -> {
pendingResults.decrementAndGet();
if(!result.isDone()) {
solveK(k, r, ex);
}
return Unit.unit;
});
return true;
}
private boolean fail(IConstraint constraint) throws InterruptedException {
failed.put(constraint, MessageUtil.findClosestMessage(constraint));
removeCompleteness(constraint);
return (flags & RETURN_ON_FIRST_ERROR) == 0;
}
private void removeCompleteness(IConstraint constraint) throws InterruptedException {
final Set.Immutable<CriticalEdge> removedEdges;
final ICompleteness.Transient _completeness = completeness.melt();
if(INCREMENTAL_CRITICAL_EDGES) {
if(!constraint.ownCriticalEdges().isPresent()) {
throw new IllegalArgumentException("Solver only accepts constraints with pre-computed critical edges.");
}
removedEdges = _completeness.removeAll(constraint.ownCriticalEdges().get(), state.unifier());
} else {
removedEdges = _completeness.remove(constraint, spec, state.unifier());
}
for(CriticalEdge criticalEdge : removedEdges) {
closeEdge(criticalEdge);
}
this.completeness = _completeness.freeze();
}
private boolean queue(IConstraint constraint) {
constraints.add(constraint);
return true;
}
///////////////////////////////////////////////////////////////////////////
// k
///////////////////////////////////////////////////////////////////////////
private boolean k(IConstraint constraint, int fuel) throws InterruptedException {
// stop if thread is interrupted
if(cancel.cancelled()) {
throw new InterruptedException();
}
// stop recursion if we run out of fuel
if(fuel <= 0) {
return queue(constraint);
}
if(debug.isEnabled(Level.Debug)) {
debug.debug("Solving {}",
constraint.toString(Solver.shallowTermFormatter(state.unifier(), Solver.TERM_FORMAT_DEPTH)));
}
// solve
return constraint.matchOrThrow(new IConstraint.CheckedCases<Boolean, InterruptedException>() {
@Override public Boolean caseArith(CArith c) throws InterruptedException {
final IUniDisunifier unifier = state.unifier();
final Optional<ITerm> term1 = c.expr1().isTerm();
final Optional<ITerm> term2 = c.expr2().isTerm();
try {
if(c.op().isEquals() && term1.isPresent()) {
int i2 = c.expr2().eval(unifier);
final IConstraint eq = new CEqual(term1.get(), B.newInt(i2), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else if(c.op().isEquals() && term2.isPresent()) {
int i1 = c.expr1().eval(unifier);
final IConstraint eq = new CEqual(B.newInt(i1), term2.get(), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
int i1 = c.expr1().eval(unifier);
int i2 = c.expr2().eval(unifier);
if(c.op().test(i1, i2)) {
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
} catch(Delay d) {
return delay(c, d);
}
}
@Override public Boolean caseConj(CConj c) throws InterruptedException {
return success(c, state, NO_UPDATED_VARS, disjoin(c), NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS, fuel);
}
@Override public Boolean caseEqual(CEqual c) throws InterruptedException {
final ITerm term1 = c.term1();
final ITerm term2 = c.term2();
IUniDisunifier.Immutable unifier = state.unifier();
try {
final IUniDisunifier.Result<IUnifier.Immutable> result;
if((result = unifier.unify(term1, term2, v -> isRigid(v, state)).orElse(null)) != null) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification succeeded: {}", result.result());
}
final IState.Immutable newState = state.withUnifier(result.unifier());
final Set<ITermVar> updatedVars = result.result().domainSet();
return success(c, newState, updatedVars, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification failed: {} != {}", unifier.toString(term1),
unifier.toString(term2));
}
return fail(c);
}
} catch(OccursException e) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Unification failed: {} != {}", unifier.toString(term1), unifier.toString(term2));
}
return fail(c);
} catch(RigidException e) {
return delay(c, Delay.ofVars(e.vars()));
}
}
@Override public Boolean caseExists(CExists c) throws InterruptedException {
final Renaming.Builder _existentials = Renaming.builder();
IState.Immutable newState = state;
for(ITermVar var : c.vars()) {
final Tuple2<ITermVar, IState.Immutable> varAndState = newState.freshVar(var);
final ITermVar freshVar = varAndState._1();
newState = varAndState._2();
_existentials.put(var, freshVar);
}
final Renaming existentials = _existentials.build();
final ISubstitution.Immutable subst = existentials.asSubstitution();
final IConstraint newConstraint = c.constraint().apply(subst).withCause(c.cause().orElse(null));
if(INCREMENTAL_CRITICAL_EDGES && !c.bodyCriticalEdges().isPresent()) {
throw new IllegalArgumentException(
"Solver only accepts constraints with pre-computed critical edges.");
}
final ICompleteness.Immutable newCriticalEdges =
c.bodyCriticalEdges().orElse(NO_NEW_CRITICAL_EDGES).apply(subst);
return success(c, newState, NO_UPDATED_VARS, disjoin(newConstraint), newCriticalEdges,
existentials.asMap(), fuel);
}
@Override public Boolean caseFalse(CFalse c) throws InterruptedException {
return fail(c);
}
@Override public Boolean caseInequal(CInequal c) throws InterruptedException {
final ITerm term1 = c.term1();
final ITerm term2 = c.term2();
final IUniDisunifier.Immutable unifier = state.unifier();
try {
final IUniDisunifier.Result<Optional<Diseq>> result;
if((result = unifier.disunify(c.universals(), term1, term2, v -> isRigid(v, state))
.orElse(null)) != null) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Disunification succeeded: {}", result);
}
final IState.Immutable newState = state.withUnifier(result.unifier());
final java.util.Set<ITermVar> updatedVars =
result.result().<java.util.Set<ITermVar>>map(Diseq::domainSet).orElse(NO_UPDATED_VARS);
return success(c, newState, updatedVars, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("Disunification failed");
}
return fail(c);
}
} catch(RigidException e) {
return delay(c, Delay.ofVars(e.vars()));
}
}
@Override public Boolean caseNew(CNew c) throws InterruptedException {
final ITerm scopeTerm = c.scopeTerm();
final ITerm datumTerm = c.datumTerm();
final String name = M.var(ITermVar::getName).match(scopeTerm).orElse("s");
final Set<ITerm> labels = getOpenEdges(scopeTerm);
final Scope scope = scopeGraph.freshScope(name, labels, true, false);
scopeGraph.setDatum(scope, datumTerm);
final IConstraint eq = new CEqual(scopeTerm, scope, c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseResolveQuery(CResolveQuery c) throws InterruptedException {
final QueryFilter filter = c.filter();
final QueryMin min = c.min();
final ITerm scopeTerm = c.scopeTerm();
final ITerm resultTerm = c.resultTerm();
final IUniDisunifier unifier = state.unifier();
// @formatter:off
final Set.Immutable<ITermVar> freeVars = Streams.concat(
unifier.getVars(scopeTerm).stream(),
filter.getDataWF().freeVars().stream().flatMap(v -> unifier.getVars(v).stream()),
min.getDataEquiv().freeVars().stream().flatMap(v -> unifier.getVars(v).stream())
).collect(CapsuleCollectors.toSet());
// @formatter:on
if(!freeVars.isEmpty()) {
return delay(c, Delay.ofVars(freeVars));
}
final Rule dataWfRule = RuleUtil.instantiateHeadPatterns(
RuleUtil.closeInUnifier(filter.getDataWF(), state.unifier(), Safety.UNSAFE));
final Rule dataLeqRule = RuleUtil.instantiateHeadPatterns(
RuleUtil.closeInUnifier(min.getDataEquiv(), state.unifier(), Safety.UNSAFE));
final Scope scope = AScope.matcher().match(scopeTerm, unifier).orElseThrow(
() -> new IllegalArgumentException("Expected scope, got " + unifier.toString(scopeTerm)));
final LabelWf<ITerm> labelWF = new RegExpLabelWf<>(filter.getLabelWF());
final LabelOrder<ITerm> labelOrder = new RelationLabelOrder<>(min.getLabelOrder());
final DataWf<Scope, ITerm, ITerm> dataWF = new ConstraintDataWF(spec, dataWfRule);
final DataLeq<Scope, ITerm, ITerm> dataEquiv = new ConstraintDataEquiv(spec, dataLeqRule);
final DataWf<Scope, ITerm, ITerm> dataWFInternal =
LOCAL_INFERENCE ? new ConstraintDataWFInternal(dataWfRule) : null;
final DataLeq<Scope, ITerm, ITerm> dataEquivInternal =
LOCAL_INFERENCE ? new ConstraintDataEquivInternal(dataLeqRule) : null;
final IFuture<? extends java.util.Set<IResolutionPath<Scope, ITerm, ITerm>>> future = scopeGraph
.query(scope, labelWF, labelOrder, dataWF, dataEquiv, dataWFInternal, dataEquivInternal);
final K<java.util.Set<IResolutionPath<Scope, ITerm, ITerm>>> k = (paths, ex, fuel) -> {
if(ex != null) {
// pattern matching for the brave and stupid
try {
throw ex;
} catch(ResolutionDelayException rde) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("delayed query (unsupported) {}", rde,
c.toString(state.unifier()::toString));
}
return fail(c);
} catch(DeadlockException dle) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("deadlocked query (spec error) {}", c.toString(state.unifier()::toString));
}
return fail(c);
} catch(InterruptedException t) {
throw t;
} catch(Throwable t) {
debug.error("failed query {}", t, c.toString(state.unifier()::toString));
return fail(c);
}
} else {
final List<ITerm> pathTerms =
paths.stream().map(p -> StatixTerms.pathToTerm(p, spec.dataLabels()))
.collect(ImmutableList.toImmutableList());
final IConstraint C = new CEqual(resultTerm, B.newList(pathTerms), c);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(C), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
}
};
return future(future, k);
}
@Override public Boolean caseTellEdge(CTellEdge c) throws InterruptedException {
final ITerm sourceTerm = c.sourceTerm();
final ITerm label = c.label();
final ITerm targetTerm = c.targetTerm();
final IUniDisunifier unifier = state.unifier();
if(!unifier.isGround(sourceTerm)) {
return delay(c, Delay.ofVars(unifier.getVars(sourceTerm)));
}
if(!unifier.isGround(targetTerm)) {
return delay(c, Delay.ofVars(unifier.getVars(targetTerm)));
}
final Scope source =
AScope.matcher().match(sourceTerm, unifier).orElseThrow(() -> new IllegalArgumentException(
"Expected source scope, got " + unifier.toString(sourceTerm)));
final Scope target =
AScope.matcher().match(targetTerm, unifier).orElseThrow(() -> new IllegalArgumentException(
"Expected target scope, got " + unifier.toString(targetTerm)));
scopeGraph.addEdge(source, label, target);
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseTermId(CAstId c) throws InterruptedException {
final ITerm term = c.astTerm();
final ITerm idTerm = c.idTerm();
final IUniDisunifier unifier = state.unifier();
if(!(unifier.isGround(term))) {
return delay(c, Delay.ofVars(unifier.getVars(term)));
}
final CEqual eq;
final Optional<Scope> maybeScope = AScope.matcher().match(term, unifier);
if(maybeScope.isPresent()) {
final AScope scope = maybeScope.get();
eq = new CEqual(idTerm, scope);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
final Optional<TermIndex> maybeIndex = TermIndex.get(unifier.findTerm(term));
if(maybeIndex.isPresent()) {
final ITerm indexTerm = TermOrigin.copy(term, maybeIndex.get());
eq = new CEqual(idTerm, indexTerm);
return success(c, state, NO_UPDATED_VARS, ImmutableList.of(eq), NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
}
@Override public Boolean caseTermProperty(CAstProperty c) throws InterruptedException {
final ITerm idTerm = c.idTerm();
final ITerm prop = c.property();
final ITerm value = c.value();
final IUniDisunifier unifier = state.unifier();
if(!(unifier.isGround(idTerm))) {
return delay(c, Delay.ofVars(unifier.getVars(idTerm)));
}
final Optional<TermIndex> maybeIndex = TermIndex.matcher().match(idTerm, unifier);
if(maybeIndex.isPresent()) {
final TermIndex index = maybeIndex.get();
final Tuple2<TermIndex, ITerm> key = Tuple2.of(index, prop);
ITermProperty property;
switch(c.op()) {
case ADD: {
property = state.termProperties().getOrDefault(key, BagTermProperty.of());
if(!property.multiplicity().equals(Multiplicity.BAG)) {
return fail(c);
}
property = property.addValue(value);
break;
}
case SET: {
if(state.termProperties().containsKey(key)) {
return fail(c);
}
property = SingletonTermProperty.of(value);
break;
}
default:
throw new IllegalStateException("Unknown op " + c.op());
}
final IState.Immutable newState =
state.withTermProperties(state.termProperties().__put(key, property));
return success(c, newState, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
return fail(c);
}
}
@Override public Boolean caseTrue(CTrue c) throws InterruptedException {
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES, NO_EXISTENTIALS,
fuel);
}
@Override public Boolean caseTry(CTry c) throws InterruptedException {
final IDebugContext subDebug = debug.subContext();
final ITypeCheckerContext<Scope, ITerm, ITerm> subContext = scopeGraph.subContext("try");
final IState.Immutable subState = state.subState().withResource(subContext.id());
final StatixSolver subSolver = new StatixSolver(c.constraint(), spec, subState, completeness, subDebug,
progress, cancel, subContext, RETURN_ON_FIRST_ERROR);
final IFuture<SolverResult> subResult = subSolver.entail();
final K<SolverResult> k = (r, ex, fuel) -> {
if(ex != null) {
debug.error("try {} failed", ex, c.toString(state.unifier()::toString));
return fail(c);
} else {
try {
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", c.toString(state.unifier()::toString));
}
return success(c, state, NO_UPDATED_VARS, NO_NEW_CONSTRAINTS, NO_NEW_CRITICAL_EDGES,
NO_EXISTENTIALS, fuel);
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", c.toString(state.unifier()::toString));
}
return fail(c);
}
} catch(Delay delay) {
return delay(c, delay);
}
}
};
return future(subResult, k);
}
@Override public Boolean caseUser(CUser c) throws InterruptedException {
final String name = c.name();
final List<ITerm> args = c.args();
final LazyDebugContext proxyDebug = new LazyDebugContext(debug);
final List<Rule> rules = spec.rules().getRules(name);
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
final Tuple3<Rule, ApplyResult, Boolean> result;
if((result = RuleUtil.applyOrderedOne(state.unifier(), rules, args, c, ApplyMode.RELAXED, Safety.UNSAFE)
.orElse(null)) == null) {
debug.debug("No rule applies");
return fail(c);
}
final ApplyResult applyResult = result._2();
if(!result._3()) {
final Set<ITermVar> stuckVars = Streams.stream(applyResult.guard())
.flatMap(g -> g.domainSet().stream()).collect(CapsuleCollectors.toSet());
proxyDebug.debug("Rule delayed (multiple conditional matches)");
return delay(c, Delay.ofVars(stuckVars));
}
proxyDebug.debug("Rule accepted");
proxyDebug.commit();
if(INCREMENTAL_CRITICAL_EDGES && applyResult.criticalEdges() == null) {
throw new IllegalArgumentException("Solver only accepts specs with pre-computed critical edges.");
}
return success(c, state, NO_UPDATED_VARS, Collections.singletonList(applyResult.body()),
applyResult.criticalEdges(), NO_EXISTENTIALS, fuel);
}
});
}
///////////////////////////////////////////////////////////////////////////
// entailment
///////////////////////////////////////////////////////////////////////////
private static IFuture<Boolean> entails(ITypeCheckerContext<Scope, ITerm, ITerm> context, Spec spec,
IState.Immutable state, IConstraint constraint, ICompleteness.Immutable criticalEdges, IDebugContext debug,
ICancel cancel, IProgress progress) throws Delay {
final IDebugContext subDebug = debug.subContext();
final ITypeCheckerContext<Scope, ITerm, ITerm> subContext = context.subContext("entails");
final IState.Immutable subState = state.subState().withResource(subContext.id());
final PreSolveResult preSolveResult;
if((preSolveResult = Solver.preEntail(subState, criticalEdges, constraint).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
if(preSolveResult.constraints.isEmpty()) {
return CompletableFuture.completedFuture(Solver.entailed(subState, preSolveResult, subDebug));
}
final StatixSolver subSolver =
new StatixSolver(Constraints.conjoin(preSolveResult.constraints), spec, preSolveResult.state,
preSolveResult.criticalEdges, subDebug, progress, cancel, subContext, RETURN_ON_FIRST_ERROR);
return subSolver.entail().thenCompose(r -> {
final boolean result;
try {
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", constraint.toString(state.unifier()::toString));
}
result = true;
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", constraint.toString(state.unifier()::toString));
}
result = false;
}
} catch(Delay delay) {
throw new IllegalStateException("Unexpected delay.", delay);
}
return CompletableFuture.completedFuture(result);
});
}
private IFuture<Boolean> entails(ITypeCheckerContext<Scope, ITerm, ITerm> subContext, IConstraint constraint,
ICompleteness.Immutable criticalEdges, ICancel cancel) {
final IDebugContext subDebug = debug.subContext();
return absorbDelays(() -> {
final IState.Immutable subState = state.subState().withResource(subContext.id());
final PreSolveResult preSolveResult;
try {
if((preSolveResult = Solver.preEntail(subState, criticalEdges, constraint).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
} catch(Delay d) {
return CompletableFuture.completedExceptionally(d);
}
if(preSolveResult.constraints.isEmpty()) {
return CompletableFuture.completedFuture(Solver.entailed(subState, preSolveResult, subDebug));
}
final StatixSolver subSolver = new StatixSolver(Constraints.conjoin(preSolveResult.constraints), spec,
preSolveResult.state, preSolveResult.criticalEdges, subDebug, progress, cancel, subContext,
RETURN_ON_FIRST_ERROR);
return subSolver.entail().thenCompose(r -> {
final boolean result;
// check entailment w.r.t. the initial substate, not the current state: otherwise,
// some variables may be treated as external while they are not
if(Solver.entailed(subState, r, subDebug)) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} entailed", constraint.toString(state.unifier()::toString));
}
result = true;
} else {
if(debug.isEnabled(Level.Debug)) {
debug.debug("constraint {} not entailed", constraint.toString(state.unifier()::toString));
}
result = false;
}
return CompletableFuture.completedFuture(result);
});
});
}
private <T> IFuture<T> absorbDelays(Function0<IFuture<T>> f) {
return f.apply().compose((r, ex) -> {
if(ex != null) {
try {
throw ex;
} catch(Delay delay) {
if(!delay.criticalEdges().isEmpty()) {
debug.error("unsupported delay with critical edges {}", delay);
throw new IllegalStateException("unsupported delay with critical edges");
}
if(delay.vars().isEmpty()) {
debug.error("unsupported delay without variables {}", delay);
throw new IllegalStateException("unsupported delay without variables");
}
final CompletableFuture<T> result = new CompletableFuture<>();
try {
delayAction(() -> {
absorbDelays(f).whenComplete(result::complete);
}, delay.vars());
} catch(InterruptedException ie) {
result.completeExceptionally(ie);
}
return result;
} catch(Throwable t) {
return CompletableFuture.completedExceptionally(t);
}
} else {
return CompletableFuture.completedFuture(r);
}
});
}
///////////////////////////////////////////////////////////////////////////
// Open edges & delayed closes
///////////////////////////////////////////////////////////////////////////
private Set.Transient<CriticalEdge> delayedCloses = CapsuleUtil.transientSet();
private Set.Immutable<ITerm> getOpenEdges(ITerm varOrScope) {
// we must include queued edge closes here, to ensure we registered the open
// edge when the close is released
final List<EdgeOrData<ITerm>> openEdges =
Streams.stream(completeness.get(varOrScope, state.unifier())).collect(Collectors.toList());
final List<EdgeOrData<ITerm>> queuedEdges = M.var().match(varOrScope)
.map(var -> delayedCloses.stream().filter(e -> state.unifier().equal(var, e.scope()))
.map(e -> e.edgeOrData()))
.orElse(Stream.<EdgeOrData<ITerm>>empty()).collect(Collectors.toList());
return stream(Iterables.concat(openEdges, queuedEdges)).<ITerm>flatMap(eod -> {
return eod.match(() -> Stream.<ITerm>empty(), (l) -> Stream.of(l));
}).collect(CapsuleCollectors.toSet());
}
private void closeEdge(CriticalEdge criticalEdge) throws InterruptedException {
if(debug.isEnabled(Level.Debug)) {
debug.debug("client {} close edge {}/{}", this, state.unifier().toString(criticalEdge.scope()),
criticalEdge.edgeOrData());
}
delayedCloses.__insert(criticalEdge);
delayAction(() -> {
delayedCloses.__remove(criticalEdge);
closeGroundEdge(criticalEdge);
}, state.unifier().getVars(criticalEdge.scope()));
}
private void closeGroundEdge(CriticalEdge criticalEdge) {
if(debug.isEnabled(Level.Debug)) {
debug.debug("client {} close edge {}/{}", this, state.unifier().toString(criticalEdge.scope()),
criticalEdge.edgeOrData());
}
final Scope scope = Scope.matcher().match(criticalEdge.scope(), state.unifier())
.orElseThrow(() -> new IllegalArgumentException(
"Expected scope, got " + state.unifier().toString(criticalEdge.scope())));
// @formatter:off
criticalEdge.edgeOrData().match(
() -> {
// ignore data labels, they are managed separately
return Unit.unit;
},
label -> {
scopeGraph.closeEdge(scope, label);
return Unit.unit;
}
);
// @formatter:on
}
///////////////////////////////////////////////////////////////////////////
// Delayed actions
///////////////////////////////////////////////////////////////////////////
private final VarIndexedCollection<CheckedAction0<InterruptedException>> delayedActions =
new VarIndexedCollection<>();
private void delayAction(CheckedAction0<InterruptedException> action, Iterable<ITermVar> vars)
throws InterruptedException {
if(!delayedActions.put(action, vars, state.unifier())) {
action.apply();
}
}
private void releaseDelayedActions(Iterable<ITermVar> updatedVars) throws InterruptedException {
for(CheckedAction0<InterruptedException> action : delayedActions.update(updatedVars, state.unifier())) {
action.apply();
}
}
///////////////////////////////////////////////////////////////////////////
// external data
///////////////////////////////////////////////////////////////////////////
public IFuture<ITerm> getExternalRepresentation(ITerm t) {
final CompletableFuture<ITerm> f = new CompletableFuture<>();
try {
delayAction(() -> {
f.complete(state.unifier().findRecursive(t));
}, state.unifier().getVars(t));
} catch(InterruptedException ex) {
f.completeExceptionally(ex);
}
return f;
}
///////////////////////////////////////////////////////////////////////////
// data wf & leq
///////////////////////////////////////////////////////////////////////////
private static class ConstraintDataWF implements DataWf<Scope, ITerm, ITerm> {
private final Spec spec;
private final Rule constraint;
private final IState.Immutable state;
public ConstraintDataWF(Spec spec, Rule constraint) {
// assume constraint.freeVars().isEmpty()
this.spec = spec;
this.constraint = constraint;
this.state = State.of(); // outer solver state unnecessary, because only applied to ground terms
}
@Override public IFuture<Boolean> wf(ITerm datum, ITypeCheckerContext<Scope, ITerm, ITerm> context,
ICancel cancel) throws InterruptedException {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, applyResult.body(), applyResult.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
@Override public String toString() {
return constraint.toString();
}
}
private class ConstraintDataWFInternal implements DataWf<Scope, ITerm, ITerm> {
// Non-static class that is only used on the unit of the type checker
// that started the query, and on data from that unit. Implicitly uses
// solver state from the surrounding object .
private final Rule constraint;
public ConstraintDataWFInternal(Rule constraint) {
this.constraint = constraint;
}
@Override public IFuture<Boolean> wf(ITerm datum, ITypeCheckerContext<Scope, ITerm, ITerm> context,
ICancel cancel) throws InterruptedException {
return absorbDelays(() -> {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, applyResult.body(), applyResult.criticalEdges(), cancel);
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
private static class ConstraintDataEquiv implements DataLeq<Scope, ITerm, ITerm> {
private final Spec spec;
private final Rule constraint;
private final IState.Immutable state;
public ConstraintDataEquiv(Spec spec, Rule constraint) {
// assume constraint.freeVars().isEmpty()
this.spec = spec;
this.constraint = constraint;
this.state = State.of(); // outer solver state unnecessary, because only applied to ground terms
}
@Override public IFuture<Boolean> leq(ITerm datum1, ITerm datum2,
ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) throws InterruptedException {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum1, datum2), null,
ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, applyResult.body(), applyResult.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
private @Nullable IFuture<Boolean> alwaysTrue;
@Override public IFuture<Boolean> alwaysTrue(ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) {
if(alwaysTrue == null) {
try {
switch(SHADOW_OPTIMIZATION) {
case CONTEXT:
final Boolean isAlways;
if((isAlways = constraint.isAlways().orElse(null)) != null) {
alwaysTrue = CompletableFuture.completedFuture(isAlways);
} else {
final ApplyResult result;
final Tuple2<ITermVar, IState.Immutable> d1_state =
state.freshVar(B.newVar(state.resource(), "d1"));
final Tuple2<ITermVar, IState.Immutable> d2_state =
d1_state._2().freshVar(B.newVar(state.resource(), "d2"));
try {
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((result = RuleUtil.apply(d2_state._2().unifier(), constraint,
ImmutableList.of(d1_state._1(), d2_state._1()), null, ApplyMode.STRICT,
Safety.UNSAFE).orElse(null)) == null) {
alwaysTrue = CompletableFuture.completedFuture(false);
} else {
alwaysTrue = entails(context, spec, d2_state._2(), result.body(),
result.criticalEdges(), new NullDebugContext(), cancel,
new NullProgress());
}
} catch(Delay e) {
throw new IllegalStateException("Unexpected delay.", e);
}
}
break;
case RULE:
alwaysTrue = CompletableFuture.completedFuture(constraint.isAlways().orElse(false));
break;
case NONE:
default:
alwaysTrue = CompletableFuture.completedFuture(false);
break;
}
} catch(InterruptedException e) {
return CompletableFuture.completedExceptionally(e);
}
}
return alwaysTrue;
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
private class ConstraintDataEquivInternal implements DataLeq<Scope, ITerm, ITerm> {
// Non-static class that is only used on the unit of the type checker
// that started the query, and on data from that unit. Implicitly uses
// solver state from the surrounding object .
private final Rule constraint;
public ConstraintDataEquivInternal(Rule constraint) {
this.constraint = constraint;
}
@Override public IFuture<Boolean> leq(ITerm datum1, ITerm datum2,
ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) throws InterruptedException {
return absorbDelays(() -> {
try {
final ApplyResult applyResult;
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((applyResult = RuleUtil.apply(state.unifier(), constraint, ImmutableList.of(datum1, datum2),
null, ApplyMode.STRICT, Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, applyResult.body(), applyResult.criticalEdges(), cancel);
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
private @Nullable IFuture<Boolean> alwaysTrue;
@Override public IFuture<Boolean> alwaysTrue(ITypeCheckerContext<Scope, ITerm, ITerm> context, ICancel cancel) {
if(alwaysTrue == null) {
try {
switch(SHADOW_OPTIMIZATION) {
case CONTEXT:
final Boolean isAlways;
if((isAlways = constraint.isAlways().orElse(null)) != null) {
alwaysTrue = CompletableFuture.completedFuture(isAlways);
} else {
alwaysTrue = absorbDelays(() -> {
try {
final ApplyResult result;
final Tuple2<ITermVar, IState.Immutable> d1_state =
state.freshVar(B.newVar(state.resource(), "d1"));
final Tuple2<ITermVar, IState.Immutable> d2_state =
d1_state._2().freshVar(B.newVar(state.resource(), "d2"));
// UNSAFE : we assume the resource of spec variables is empty and of state variables non-empty
if((result = RuleUtil.apply(d2_state._2().unifier(), constraint,
ImmutableList.of(d1_state._1(), d2_state._1()), null, ApplyMode.STRICT,
Safety.UNSAFE).orElse(null)) == null) {
return CompletableFuture.completedFuture(false);
}
return entails(context, spec, state, result.body(), result.criticalEdges(),
new NullDebugContext(), cancel, new NullProgress());
} catch(Delay delay) {
return CompletableFuture.completedExceptionally(delay);
}
});
}
break;
case RULE:
alwaysTrue = CompletableFuture.completedFuture(constraint.isAlways().orElse(false));
break;
case NONE:
default:
alwaysTrue = CompletableFuture.completedFuture(false);
break;
}
} catch(InterruptedException e) {
return CompletableFuture.completedExceptionally(e);
}
}
return alwaysTrue;
}
@Override public String toString() {
return constraint.toString(state.unifier()::toString);
}
}
///////////////////////////////////////////////////////////////////////////
// rigidness
///////////////////////////////////////////////////////////////////////////
private boolean isRigid(ITermVar var, IState state) {
return !state.vars().contains(var);
}
///////////////////////////////////////////////////////////////////////////
// toString
///////////////////////////////////////////////////////////////////////////
@Override public String toString() {
return "StatixSolver";
}
///////////////////////////////////////////////////////////////////////////
// K
///////////////////////////////////////////////////////////////////////////
@FunctionalInterface
private interface K<R> {
boolean k(R result, Throwable ex, int fuel) throws InterruptedException;
}
} | Cleanup open edges, and fail if foreign variables leak into delays.
| statix.solver/src/main/java/mb/statix/concurrent/StatixSolver.java | Cleanup open edges, and fail if foreign variables leak into delays. | <ide><path>tatix.solver/src/main/java/mb/statix/concurrent/StatixSolver.java
<ide> }
<ide> }
<ide>
<add> // cleanup open edges
<add> for(IConstraint delay : delayed.keySet()) {
<add> removeCompleteness(delay);
<add> }
<add>
<ide> final Map<ITermVar, ITermVar> existentials = Optional.ofNullable(this.existentials).orElse(NO_EXISTENTIALS);
<ide> final java.util.Set<CriticalEdge> removedEdges = ImmutableSet.of();
<ide> final ICompleteness.Immutable completeness = Completeness.Immutable.of();
<ide>
<ide> private void delayAction(CheckedAction0<InterruptedException> action, Iterable<ITermVar> vars)
<ide> throws InterruptedException {
<add> final Set.Immutable<ITermVar> foreignVars =
<add> Streams.stream(vars).filter(v -> !state.vars().contains(v)).collect(CapsuleCollectors.toSet());
<add> if(!foreignVars.isEmpty()) {
<add> throw new IllegalStateException("Cannot delay on foreign variables: " + foreignVars);
<add> }
<ide> if(!delayedActions.put(action, vars, state.unifier())) {
<ide> action.apply();
<ide> } |
|
Java | apache-2.0 | 79e1fb95d49ff0a9064077f035d3bf2fec13c49c | 0 | HanSolo/tilesfx,HanSolo/tilesfx,HanSolo/tilesfx | /*
* Copyright (c) 2016 by Gerrit Grunwald
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.hansolo.tilesfx.skins;
import eu.hansolo.tilesfx.Tile;
import eu.hansolo.tilesfx.events.SwitchEvent;
import eu.hansolo.tilesfx.fonts.Fonts;
import eu.hansolo.tilesfx.tools.Helper;
import javafx.animation.FillTransition;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.util.Duration;
/**
* Created by hansolo on 19.12.16.
*/
public class SwitchTileSkin extends TileSkin {
private static final SwitchEvent SWITCH_PRESSED = new SwitchEvent(SwitchEvent.SWITCH_PRESSED);
private static final SwitchEvent SWITCH_RELEASED = new SwitchEvent(SwitchEvent.SWITCH_RELEASED);
private Text titleText;
private Text text;
private Rectangle switchBorder;
private Rectangle switchBackground;
private Circle thumb;
private Timeline timeline;
// ******************** Constructors **************************************
public SwitchTileSkin(final Tile TILE) {
super(TILE);
}
// ******************** Initialization ************************************
@Override protected void initGraphics() {
super.initGraphics();
timeline = new Timeline();
titleText = new Text();
titleText.setFill(getSkinnable().getTitleColor());
Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty());
text = new Text(getSkinnable().getUnit());
text.setFill(getSkinnable().getUnitColor());
Helper.enableNode(text, getSkinnable().isTextVisible());
switchBorder = new Rectangle();
switchBackground = new Rectangle();
switchBackground.setMouseTransparent(true);
switchBackground.setFill(getSkinnable().isSelected() ? getSkinnable().getActiveColor() : getSkinnable().getBackgroundColor());
thumb = new Circle();
thumb.setMouseTransparent(true);
getPane().getChildren().addAll(titleText, text, switchBorder, switchBackground, thumb);
}
@Override protected void registerListeners() {
super.registerListeners();
switchBorder.setOnMousePressed(e -> {
getSkinnable().setSelected(!getSkinnable().isSelected());
getSkinnable().fireEvent(SWITCH_PRESSED);
});
switchBorder.setOnMouseReleased(e -> getSkinnable().fireEvent(SWITCH_RELEASED));
getSkinnable().selectedProperty().addListener(e -> moveThumb());
}
// ******************** Methods *******************************************
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty());
Helper.enableNode(text, getSkinnable().isTextVisible());
}
};
private void moveThumb() {
KeyValue thumbLeftX = new KeyValue(thumb.centerXProperty(), size * 0.3875);
KeyValue thumbRightX = new KeyValue(thumb.centerXProperty(), size * 0.6125);
KeyValue switchBackgroundLeftColor = new KeyValue(switchBackground.fillProperty(), getSkinnable().getBackgroundColor());
KeyValue switchBackgroundRightColor = new KeyValue(switchBackground.fillProperty(), getSkinnable().getActiveColor());
if (getSkinnable().isSelected()) {
// move thumb from left to the right
KeyFrame kf0 = new KeyFrame(Duration.ZERO, thumbLeftX, switchBackgroundLeftColor);
KeyFrame kf1 = new KeyFrame(Duration.millis(200), thumbRightX, switchBackgroundRightColor);
timeline.getKeyFrames().setAll(kf0, kf1);
} else {
// move thumb from right to the left
KeyFrame kf0 = new KeyFrame(Duration.ZERO, thumbRightX, switchBackgroundRightColor);
KeyFrame kf1 = new KeyFrame(Duration.millis(200), thumbLeftX, switchBackgroundLeftColor);
timeline.getKeyFrames().setAll(kf0, kf1);
}
timeline.play();
}
// ******************** Resizing ******************************************
@Override protected void resizeStaticText() {
double maxWidth = size * 0.9;
double fontSize = size * 0.06;
titleText.setFont(Fonts.latoRegular(fontSize));
if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
titleText.relocate(size * 0.05, size * 0.05);
maxWidth = size * 0.9;
fontSize = size * 0.05;
text.setText(getSkinnable().getText());
if (text.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(text, maxWidth, fontSize); }
text.setX(size * 0.05);
text.setY(size * 0.95);
};
@Override protected void resize() {
super.resize();
switchBorder.setWidth(size * 0.445);
switchBorder.setHeight(size * 0.22);
switchBorder.setArcWidth(size * 0.22);
switchBorder.setArcHeight(size * 0.22);
switchBorder.relocate((size - switchBorder.getWidth()) * 0.5, (size - switchBorder.getHeight()) * 0.5);
switchBackground.setWidth(size * 0.425);
switchBackground.setHeight(size * 0.2);
switchBackground.setArcWidth(size * 0.2);
switchBackground.setArcHeight(size * 0.2);
switchBackground.relocate((size - switchBackground.getWidth()) * 0.5, (size - switchBackground.getHeight()) * 0.5);
thumb.setRadius(size * 0.09);
thumb.setCenterX(getSkinnable().isSelected() ? size * 0.6125 : size * 0.3875);
thumb.setCenterY(size * 0.5);
};
@Override protected void redraw() {
super.redraw();
titleText.setText(getSkinnable().getTitle());
text.setText(getSkinnable().getText());
resizeStaticText();
titleText.setFill(getSkinnable().getTitleColor());
text.setFill(getSkinnable().getTextColor());
switchBorder.setFill(getSkinnable().getForegroundColor());
thumb.setFill(getSkinnable().getForegroundColor());
};
}
| src/main/java/eu/hansolo/tilesfx/skins/SwitchTileSkin.java | /*
* Copyright (c) 2016 by Gerrit Grunwald
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.hansolo.tilesfx.skins;
import eu.hansolo.tilesfx.Tile;
import eu.hansolo.tilesfx.events.SwitchEvent;
import eu.hansolo.tilesfx.fonts.Fonts;
import eu.hansolo.tilesfx.tools.Helper;
import javafx.animation.FillTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.TranslateTransition;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.util.Duration;
/**
* Created by hansolo on 19.12.16.
*/
public class SwitchTileSkin extends TileSkin {
private static final SwitchEvent SWITCH_PRESSED = new SwitchEvent(SwitchEvent.SWITCH_PRESSED);
private static final SwitchEvent SWITCH_RELEASED = new SwitchEvent(SwitchEvent.SWITCH_RELEASED);
private Text titleText;
private Text text;
private Rectangle switchBorder;
private Rectangle switchBackground;
private Circle thumb;
// ******************** Constructors **************************************
public SwitchTileSkin(final Tile TILE) {
super(TILE);
}
// ******************** Initialization ************************************
@Override protected void initGraphics() {
super.initGraphics();
titleText = new Text();
titleText.setFill(getSkinnable().getTitleColor());
Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty());
text = new Text(getSkinnable().getUnit());
text.setFill(getSkinnable().getUnitColor());
Helper.enableNode(text, getSkinnable().isTextVisible());
switchBorder = new Rectangle();
switchBackground = new Rectangle();
switchBackground.setMouseTransparent(true);
switchBackground.setFill(getSkinnable().isSelected() ? getSkinnable().getActiveColor() : getSkinnable().getBackgroundColor());
thumb = new Circle();
thumb.setMouseTransparent(true);
getPane().getChildren().addAll(titleText, text, switchBorder, switchBackground, thumb);
}
@Override protected void registerListeners() {
super.registerListeners();
switchBorder.setOnMousePressed(e -> {
getSkinnable().setSelected(!getSkinnable().isSelected());
getSkinnable().fireEvent(SWITCH_PRESSED);
});
switchBorder.setOnMouseReleased(e -> getSkinnable().fireEvent(SWITCH_RELEASED));
getSkinnable().selectedProperty().addListener(e -> moveThumb());
}
// ******************** Methods *******************************************
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty());
Helper.enableNode(text, getSkinnable().isTextVisible());
}
};
private void moveThumb() {
if (getSkinnable().isSelected()) {
// move thumb to the right
TranslateTransition moveThumb = new TranslateTransition(Duration.millis(200), thumb);
moveThumb.setFromX(0);
moveThumb.setToX(size * 0.225);
FillTransition fillSwitch = new FillTransition(Duration.millis(200), switchBackground);
fillSwitch.setFromValue(getSkinnable().getBackgroundColor());
fillSwitch.setToValue(getSkinnable().getActiveColor());
ParallelTransition parallelTransition = new ParallelTransition(moveThumb, fillSwitch);
parallelTransition.play();
} else {
// move thumb to the left
TranslateTransition moveThumb = new TranslateTransition(Duration.millis(200), thumb);
moveThumb.setFromX(size * 0.225);
moveThumb.setToX(0);
FillTransition fillSwitch = new FillTransition(Duration.millis(200), switchBackground);
fillSwitch.setFromValue(getSkinnable().getActiveColor());
fillSwitch.setToValue(getSkinnable().getBackgroundColor());
ParallelTransition parallelTransition = new ParallelTransition(moveThumb, fillSwitch);
parallelTransition.play();
}
}
// ******************** Resizing ******************************************
@Override protected void resizeStaticText() {
double maxWidth = size * 0.9;
double fontSize = size * 0.06;
titleText.setFont(Fonts.latoRegular(fontSize));
if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
titleText.relocate(size * 0.05, size * 0.05);
maxWidth = size * 0.9;
fontSize = size * 0.05;
text.setText(getSkinnable().getText());
if (text.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(text, maxWidth, fontSize); }
text.setX(size * 0.05);
text.setY(size * 0.95);
};
@Override protected void resize() {
super.resize();
switchBorder.setWidth(size * 0.445);
switchBorder.setHeight(size * 0.22);
switchBorder.setArcWidth(size * 0.22);
switchBorder.setArcHeight(size * 0.22);
switchBorder.relocate((size - switchBorder.getWidth()) * 0.5, (size - switchBorder.getHeight()) * 0.5);
switchBackground.setWidth(size * 0.425);
switchBackground.setHeight(size * 0.2);
switchBackground.setArcWidth(size * 0.2);
switchBackground.setArcHeight(size * 0.2);
switchBackground.relocate((size - switchBackground.getWidth()) * 0.5, (size - switchBackground.getHeight()) * 0.5);
thumb.setRadius(size * 0.09);
thumb.setCenterX(size * 0.3875);
thumb.setCenterY(size * 0.5);
thumb.setLayoutX(getSkinnable().isSelected() ? size * 0.225 : 0);
};
@Override protected void redraw() {
super.redraw();
titleText.setText(getSkinnable().getTitle());
text.setText(getSkinnable().getText());
resizeStaticText();
titleText.setFill(getSkinnable().getTitleColor());
text.setFill(getSkinnable().getTextColor());
switchBorder.setFill(getSkinnable().getForegroundColor());
thumb.setFill(getSkinnable().getForegroundColor());
};
}
| Fixed bug in SwitchTileSkin related to thumb position
| src/main/java/eu/hansolo/tilesfx/skins/SwitchTileSkin.java | Fixed bug in SwitchTileSkin related to thumb position | <ide><path>rc/main/java/eu/hansolo/tilesfx/skins/SwitchTileSkin.java
<ide> import eu.hansolo.tilesfx.fonts.Fonts;
<ide> import eu.hansolo.tilesfx.tools.Helper;
<ide> import javafx.animation.FillTransition;
<add>import javafx.animation.KeyFrame;
<add>import javafx.animation.KeyValue;
<ide> import javafx.animation.ParallelTransition;
<add>import javafx.animation.Timeline;
<ide> import javafx.animation.TranslateTransition;
<ide> import javafx.scene.shape.Circle;
<ide> import javafx.scene.shape.Rectangle;
<ide> private Rectangle switchBorder;
<ide> private Rectangle switchBackground;
<ide> private Circle thumb;
<add> private Timeline timeline;
<ide>
<ide>
<ide> // ******************** Constructors **************************************
<ide> // ******************** Initialization ************************************
<ide> @Override protected void initGraphics() {
<ide> super.initGraphics();
<add>
<add> timeline = new Timeline();
<ide>
<ide> titleText = new Text();
<ide> titleText.setFill(getSkinnable().getTitleColor());
<ide> };
<ide>
<ide> private void moveThumb() {
<add> KeyValue thumbLeftX = new KeyValue(thumb.centerXProperty(), size * 0.3875);
<add> KeyValue thumbRightX = new KeyValue(thumb.centerXProperty(), size * 0.6125);
<add> KeyValue switchBackgroundLeftColor = new KeyValue(switchBackground.fillProperty(), getSkinnable().getBackgroundColor());
<add> KeyValue switchBackgroundRightColor = new KeyValue(switchBackground.fillProperty(), getSkinnable().getActiveColor());
<ide> if (getSkinnable().isSelected()) {
<del> // move thumb to the right
<del> TranslateTransition moveThumb = new TranslateTransition(Duration.millis(200), thumb);
<del> moveThumb.setFromX(0);
<del> moveThumb.setToX(size * 0.225);
<del> FillTransition fillSwitch = new FillTransition(Duration.millis(200), switchBackground);
<del> fillSwitch.setFromValue(getSkinnable().getBackgroundColor());
<del> fillSwitch.setToValue(getSkinnable().getActiveColor());
<del> ParallelTransition parallelTransition = new ParallelTransition(moveThumb, fillSwitch);
<del> parallelTransition.play();
<add> // move thumb from left to the right
<add> KeyFrame kf0 = new KeyFrame(Duration.ZERO, thumbLeftX, switchBackgroundLeftColor);
<add> KeyFrame kf1 = new KeyFrame(Duration.millis(200), thumbRightX, switchBackgroundRightColor);
<add> timeline.getKeyFrames().setAll(kf0, kf1);
<ide> } else {
<del> // move thumb to the left
<del> TranslateTransition moveThumb = new TranslateTransition(Duration.millis(200), thumb);
<del> moveThumb.setFromX(size * 0.225);
<del> moveThumb.setToX(0);
<del> FillTransition fillSwitch = new FillTransition(Duration.millis(200), switchBackground);
<del> fillSwitch.setFromValue(getSkinnable().getActiveColor());
<del> fillSwitch.setToValue(getSkinnable().getBackgroundColor());
<del> ParallelTransition parallelTransition = new ParallelTransition(moveThumb, fillSwitch);
<del> parallelTransition.play();
<add> // move thumb from right to the left
<add> KeyFrame kf0 = new KeyFrame(Duration.ZERO, thumbRightX, switchBackgroundRightColor);
<add> KeyFrame kf1 = new KeyFrame(Duration.millis(200), thumbLeftX, switchBackgroundLeftColor);
<add> timeline.getKeyFrames().setAll(kf0, kf1);
<ide> }
<add> timeline.play();
<ide> }
<ide>
<ide>
<ide> switchBackground.relocate((size - switchBackground.getWidth()) * 0.5, (size - switchBackground.getHeight()) * 0.5);
<ide>
<ide> thumb.setRadius(size * 0.09);
<del> thumb.setCenterX(size * 0.3875);
<add> thumb.setCenterX(getSkinnable().isSelected() ? size * 0.6125 : size * 0.3875);
<ide> thumb.setCenterY(size * 0.5);
<del> thumb.setLayoutX(getSkinnable().isSelected() ? size * 0.225 : 0);
<ide> };
<ide>
<ide> @Override protected void redraw() { |
|
Java | bsd-3-clause | abf3af150540807822d01ac46e9b0442819d3f0e | 0 | gooddata/GoodData-CL,dagi/GoodData-CL,dagi/GoodData-CL,gooddata/GoodData-CL,dagi/GoodData-CL,gooddata/GoodData-CL | /*
* Copyright (c) 2009, GoodData Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the GoodData Corporation nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gooddata.util;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.gooddata.util.CSVReader;
import com.gooddata.naming.N;
import com.ibm.icu.text.Transliterator;
/**
* GoodData String utilities
*
* @author zd <[email protected]>
* @version 1.0
*/
public class StringUtil {
/**
* Formats a string as identifier
* Currently only converts to the lowercase and replace spaces
* @param s the string to convert to identifier
* @return converted string
*/
public static String toIdentifier(String s) {
return convertToIdentifier(s);
}
/**
* Formats a string as a fact column name
* @param s the string to convert to identifier
* @return converted string
*/
public static String toFactColumnName(String s) {
return N.FCT_PFX + convertToIdentifier(s);
}
/**
* Formats a string as title
* Currently does nothing TBD
* @param s the string to convert to a title
* @return converted string
*/
public static String toTitle(String s) {
if(s == null)
return s;
//Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
//s = t.transliterate(s);
s = s.replaceAll("\"","");
return s.trim();
}
private static String convertToIdentifier(String s) {
if (s == null)
return s;
Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
s = t.transliterate(s);
s = s.replaceAll("[^a-zA-Z0-9_]", "");
s = s.replaceAll("^[0-9_]*", "");
//s = s.replaceAll("[_]*$", "");
//s = s.replaceAll("[_]+", "_");
return s.toLowerCase().trim();
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string
*
* @param separator
* @param list
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list) {
return join(separator, list, null);
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string.
* If the <tt>replacement</tt> parameter is not null, it is used to populate
* the result string instead of list elements.
*
* @param separator
* @param list
* @param replacement
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list, String replacement) {
StringBuffer sb = new StringBuffer();
boolean first = true;
for (final String s : list) {
if (first)
first = false;
else
sb.append(separator);
sb.append(replacement == null ? s : replacement);
}
return sb.toString();
}
/**
* Parse CSV line
* @param elements CSV line
* @return alements as String[]
*/
public static List<String> parseLine(String elements) throws java.io.IOException {
if (elements == null) {
return new ArrayList<String>();
}
CSVReader cr = new CSVReader(new StringReader(elements));
return Arrays.asList(cr.readNext());
}
/**
* Returns first <tt>limit</tt> characters of the string with last 3 letters replaced with ellipsis
* <p>
* Example: <tt>previewString("potatoe", 6)</tt> returns "pot..."
* @param string
* @param limit
* @return
*/
public static String previewString(String string, int limit) {
return (string.length() > limit)
? string.substring(0, limit - 4) + "..."
: string;
}
}
| common/src/main/java/com/gooddata/util/StringUtil.java | /*
* Copyright (c) 2009, GoodData Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the GoodData Corporation nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gooddata.util;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.gooddata.util.CSVReader;
import com.gooddata.naming.N;
import com.ibm.icu.text.Transliterator;
/**
* GoodData String utilities
*
* @author zd <[email protected]>
* @version 1.0
*/
public class StringUtil {
/**
* Formats a string as identifier
* Currently only converts to the lowercase and replace spaces
* @param s the string to convert to identifier
* @return converted string
*/
public static String toIdentifier(String s) {
return convertToIdentifier(s);
}
/**
* Formats a string as a fact column name
* @param s the string to convert to identifier
* @return converted string
*/
public static String toFactColumnName(String s) {
return N.FCT_PFX + convertToIdentifier(s);
}
/**
* Formats a string as title
* Currently does nothing TBD
* @param s the string to convert to a title
* @return converted string
*/
public static String toTitle(String s) {
if(s == null)
return s;
Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
s = t.transliterate(s);
s = s.replaceAll("\"","");
return s.trim();
}
private static String convertToIdentifier(String s) {
if (s == null)
return s;
Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
s = t.transliterate(s);
s = s.replaceAll("[^a-zA-Z0-9_]", "");
s = s.replaceAll("^[0-9_]*", "");
//s = s.replaceAll("[_]*$", "");
//s = s.replaceAll("[_]+", "_");
return s.toLowerCase().trim();
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string
*
* @param separator
* @param list
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list) {
return join(separator, list, null);
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string.
* If the <tt>replacement</tt> parameter is not null, it is used to populate
* the result string instead of list elements.
*
* @param separator
* @param list
* @param replacement
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list, String replacement) {
StringBuffer sb = new StringBuffer();
boolean first = true;
for (final String s : list) {
if (first)
first = false;
else
sb.append(separator);
sb.append(replacement == null ? s : replacement);
}
return sb.toString();
}
/**
* Parse CSV line
* @param elements CSV line
* @return alements as String[]
*/
public static List<String> parseLine(String elements) throws java.io.IOException {
if (elements == null) {
return new ArrayList<String>();
}
CSVReader cr = new CSVReader(new StringReader(elements));
return Arrays.asList(cr.readNext());
}
/**
* Returns first <tt>limit</tt> characters of the string with last 3 letters replaced with ellipsis
* <p>
* Example: <tt>previewString("potatoe", 6)</tt> returns "pot..."
* @param string
* @param limit
* @return
*/
public static String previewString(String string, int limit) {
return (string.length() > limit)
? string.substring(0, limit - 4) + "..."
: string;
}
}
| Removed the transliteration of the attribute and fact titles.
| common/src/main/java/com/gooddata/util/StringUtil.java | Removed the transliteration of the attribute and fact titles. | <ide><path>ommon/src/main/java/com/gooddata/util/StringUtil.java
<ide> public static String toTitle(String s) {
<ide> if(s == null)
<ide> return s;
<del> Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
<del> s = t.transliterate(s);
<add> //Transliterator t = Transliterator.getInstance("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC");
<add> //s = t.transliterate(s);
<ide> s = s.replaceAll("\"","");
<ide> return s.trim();
<ide> } |
|
Java | mit | 4115d40d209a6010fcbe3e699d6a3d756094d516 | 0 | EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edacc.properties;
import edacc.model.ExperimentResult;
import edacc.model.ExperimentResultDAO;
import edacc.model.NoConnectionToDBException;
import edacc.model.SolverProperty;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* A class to parse the ResultFileProperties from a ResultFile.
*
* @author rretz
*/
public class FilePropertyParser {
public FilePropertyParser(){
}
/**
*
*
* @param solvProp to parse for
* @param expResult on which the parser works (result file oder client output file)
* @return values of all occurences of given SolverProperty in the given ExperimentResult.
* @throws FileNotFoundException
* @throws IOException
* @throws NoAllowedSolverPropertyTypeException
*/
public Vector<String> parse(SolverProperty solvProp, ExperimentResult expResult) throws FileNotFoundException, IOException, NoAllowedSolverPropertyTypeException, NoConnectionToDBException, SQLException{
File file;
if(solvProp.getSolverPropertyType() == SolverPropertyType.ResultFile)
file = ExperimentResultDAO.getResultFile(expResult);
else if(solvProp.getSolverPropertyType() == SolverPropertyType.ClientOutput)
file = ExperimentResultDAO.getClientOutput(expResult);
else
throw new NoAllowedSolverPropertyTypeException();
BufferedReader br = new BufferedReader(new FileReader(file));
Vector<String> res = new Vector<String>();
boolean found = false;
String buffer;
// Parse the complete file, because the Property can have multiple occurences in the file
if(solvProp.isMultiple()){
StringTokenizer t;
while((buffer = br.readLine()) != null){
t = new StringTokenizer(buffer);
while(t.hasMoreTokens()){
String token = t.nextToken();
if(found){
res.add(token);
found = false;
}
else if(token.equals(solvProp.getPrefix()))
found = true;
}
}
// Only parse to the first occurnce of the prefix, because the Property only have one occurence per file
}else {
StringTokenizer t;
while((buffer = br.readLine()) != null){
t = new StringTokenizer(buffer);
while(t.hasMoreTokens()){
String token = t.nextToken();
if(found){
res.add(token);
break;
}
else if(token.equals(solvProp.getPrefix()))
found = true;
}
}
}
return res;
}
}
| src/edacc/properties/FilePropertyParser.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edacc.properties;
import edacc.model.ExperimentResult;
import edacc.model.ExperimentResultDAO;
import edacc.model.SolverProperty;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* A class to parse the ResultFileProperties from a ResultFile.
*
* @author rretz
*/
public class FilePropertyParser {
public FilePropertyParser(){
}
/**
*
*
* @param solvProp to parse for
* @param expResult on which the parser works (result file oder client output file)
* @return values of all occurences of given SolverProperty in the given ExperimentResult.
* @throws FileNotFoundException
* @throws IOException
* @throws NoAllowedSolverPropertyTypeException
*/
public Vector<String> parse(SolverProperty solvProp, ExperimentResult expResult) throws FileNotFoundException, IOException, NoAllowedSolverPropertyTypeException{
File file;
if(solvProp.getSolverPropertyType() == SolverPropertyType.ResultFile)
file = ExperimentResultDAO.getResultFile(expResult.getId());
else if(solvProp.getSolverPropertyType() == SolverPropertyType.ClientOutput)
file = ExperimentResultDAO.getClientOutput(expResult.getId());
else
throw new NoAllowedSolverPropertyTypeException();
BufferedReader br = new BufferedReader(new FileReader(file));
Vector<String> res = new Vector<String>();
boolean found = false;
String buffer;
// Parse the complete file, because the Property can have multiple occurences in the file
if(solvProp.isMultiple()){
StringTokenizer t;
while((buffer = br.readLine()) != null){
t = new StringTokenizer(buffer);
while(t.hasMoreTokens()){
String token = t.nextToken();
if(found){
res.add(token);
found = false;
}
else if(token.equals(solvProp.getPrefix()))
found = true;
}
}
// Only parse to the first occurnce of the prefix, because the Property only have one occurence per file
}else {
StringTokenizer t;
while((buffer = br.readLine()) != null){
t = new StringTokenizer(buffer);
while(t.hasMoreTokens()){
String token = t.nextToken();
if(found){
res.add(token);
break;
}
else if(token.equals(solvProp.getPrefix()))
found = true;
}
}
}
return res;
}
}
| little bugfix
| src/edacc/properties/FilePropertyParser.java | little bugfix | <ide><path>rc/edacc/properties/FilePropertyParser.java
<ide>
<ide> import edacc.model.ExperimentResult;
<ide> import edacc.model.ExperimentResultDAO;
<add>import edacc.model.NoConnectionToDBException;
<ide> import edacc.model.SolverProperty;
<ide> import java.io.BufferedReader;
<ide> import java.io.File;
<ide> import java.io.FileNotFoundException;
<ide> import java.io.FileReader;
<ide> import java.io.IOException;
<add>import java.sql.SQLException;
<ide> import java.util.StringTokenizer;
<ide> import java.util.Vector;
<ide>
<ide> * @throws IOException
<ide> * @throws NoAllowedSolverPropertyTypeException
<ide> */
<del> public Vector<String> parse(SolverProperty solvProp, ExperimentResult expResult) throws FileNotFoundException, IOException, NoAllowedSolverPropertyTypeException{
<add> public Vector<String> parse(SolverProperty solvProp, ExperimentResult expResult) throws FileNotFoundException, IOException, NoAllowedSolverPropertyTypeException, NoConnectionToDBException, SQLException{
<ide> File file;
<ide> if(solvProp.getSolverPropertyType() == SolverPropertyType.ResultFile)
<del> file = ExperimentResultDAO.getResultFile(expResult.getId());
<add> file = ExperimentResultDAO.getResultFile(expResult);
<ide> else if(solvProp.getSolverPropertyType() == SolverPropertyType.ClientOutput)
<del> file = ExperimentResultDAO.getClientOutput(expResult.getId());
<add> file = ExperimentResultDAO.getClientOutput(expResult);
<ide> else
<ide> throw new NoAllowedSolverPropertyTypeException();
<ide> |
|
Java | bsd-3-clause | fc3207ee09b144cce92d00b97568c3850308c650 | 0 | NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox,NordicSemiconductor/Android-nRF-Toolbox | package no.nordicsemi.android.nrftoolbox.battery;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.UUID;
import no.nordicsemi.android.ble.BleManager;
import no.nordicsemi.android.ble.callback.DataReceivedCallback;
import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelDataCallback;
import no.nordicsemi.android.ble.data.Data;
import no.nordicsemi.android.log.LogContract;
/**
* The Ble Manager with Battery Service support.
*
* @param <T> The profile callbacks type.
* @see BleManager
*/
@SuppressWarnings("WeakerAccess")
public abstract class BatteryManager<T extends BatteryManagerCallbacks> extends BleManager<T> {
/** Battery Service UUID. */
private final static UUID BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb");
/** Battery Level characteristic UUID. */
private final static UUID BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb");
private BluetoothGattCharacteristic mBatteryLevelCharacteristic;
/** Last received Battery Level value. */
private Integer mBatteryLevel;
/**
* The manager constructor.
*
* @param context context.
*/
public BatteryManager(final Context context) {
super(context);
}
private DataReceivedCallback mBatteryLevelDataCallback = new BatteryLevelDataCallback() {
@Override
public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) {
log(LogContract.Log.Level.APPLICATION,"Battery Level received: " + batteryLevel + "%");
mBatteryLevel = batteryLevel;
mCallbacks.onBatteryLevelChanged(device, batteryLevel);
}
@Override
public void onInvalidDataReceived(@NonNull final BluetoothDevice device, final @NonNull Data data) {
log(LogContract.Log.Level.WARNING, "Invalid Battery Level data received: " + data);
}
};
public void readBatteryLevelCharacteristic() {
if (isConnected()) {
readCharacteristic(mBatteryLevelCharacteristic)
.with(mBatteryLevelDataCallback)
.fail((device, status) -> log(LogContract.Log.Level.WARNING,"Battery Level characteristic not found"))
.enqueue();
}
}
public void enableBatteryLevelCharacteristicNotifications() {
if (isConnected()) {
// If the Battery Level characteristic is null, the request will be ignored
setNotificationCallback(mBatteryLevelCharacteristic)
.with(mBatteryLevelDataCallback);
enableNotifications(mBatteryLevelCharacteristic)
.done(device -> log(LogContract.Log.Level.INFO, "Battery Level notifications enabled"))
.fail((device, status) -> log(LogContract.Log.Level.WARNING, "Battery Level characteristic not found"))
.enqueue();
}
}
/**
* Disables Battery Level notifications on the Server.
*/
public void disableBatteryLevelCharacteristicNotifications() {
if (isConnected()) {
disableNotifications(mBatteryLevelCharacteristic)
.done(device -> log(LogContract.Log.Level.INFO, "Battery Level notifications disabled"))
.enqueue();
}
}
/**
* Returns the last received Battery Level value.
* The value is set to null when the device disconnects.
* @return Battery Level value, in percent.
*/
public Integer getBatteryLevel() {
return mBatteryLevel;
}
protected abstract class BatteryManagerGattCallback extends BleManagerGattCallback {
@Override
protected void initialize() {
readBatteryLevelCharacteristic();
enableBatteryLevelCharacteristicNotifications();
}
@Override
protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) {
final BluetoothGattService service = gatt.getService(BATTERY_SERVICE_UUID);
if (service != null) {
mBatteryLevelCharacteristic = service.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID);
}
return mBatteryLevelCharacteristic != null;
}
@Override
protected void onDeviceDisconnected() {
mBatteryLevelCharacteristic = null;
mBatteryLevel = null;
}
}
}
| app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java | package no.nordicsemi.android.nrftoolbox.battery;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.UUID;
import no.nordicsemi.android.ble.BleManager;
import no.nordicsemi.android.ble.callback.DataReceivedCallback;
import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelDataCallback;
import no.nordicsemi.android.ble.data.Data;
import no.nordicsemi.android.log.LogContract;
/**
* The Ble Manager with Battery Service support.
*
* @param <T> The profile callbacks type.
* @see BleManager
*/
@SuppressWarnings("WeakerAccess")
public abstract class BatteryManager<T extends BatteryManagerCallbacks> extends BleManager<T> {
/** Battery Service UUID. */
private final static UUID BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb");
/** Battery Level characteristic UUID. */
private final static UUID BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb");
private BluetoothGattCharacteristic mBatteryLevelCharacteristic;
/** Last received Battery Level value. */
private Integer mBatteryLevel;
/**
* The manager constructor.
*
* @param context context.
*/
public BatteryManager(final Context context) {
super(context);
}
@NonNull
@Override
protected abstract BatteryManagerGattCallback getGattCallback();
private DataReceivedCallback mBatteryLevelDataCallback = new BatteryLevelDataCallback() {
@Override
public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) {
log(LogContract.Log.Level.APPLICATION,"Battery Level received: " + batteryLevel + "%");
mBatteryLevel = batteryLevel;
mCallbacks.onBatteryLevelChanged(device, batteryLevel);
}
@Override
public void onInvalidDataReceived(@NonNull final BluetoothDevice device, final @NonNull Data data) {
log(LogContract.Log.Level.WARNING, "Invalid Battery Level data received: " + data);
}
};
public void readBatteryLevelCharacteristic() {
if (isConnected()) {
readCharacteristic(mBatteryLevelCharacteristic)
.with(mBatteryLevelDataCallback)
.fail((device, status) -> log(LogContract.Log.Level.WARNING,"Battery Level characteristic not found"))
.enqueue();
}
}
public void enableBatteryLevelCharacteristicNotifications() {
if (isConnected()) {
// If the Battery Level characteristic is null, the request will be ignored
setNotificationCallback(mBatteryLevelCharacteristic)
.with(mBatteryLevelDataCallback);
enableNotifications(mBatteryLevelCharacteristic)
.done(device -> log(LogContract.Log.Level.INFO, "Battery Level notifications enabled"))
.fail((device, status) -> log(LogContract.Log.Level.WARNING, "Battery Level characteristic not found"))
.enqueue();
}
}
/**
* Disables Battery Level notifications on the Server.
*/
public void disableBatteryLevelCharacteristicNotifications() {
if (isConnected()) {
disableNotifications(mBatteryLevelCharacteristic)
.done(device -> log(LogContract.Log.Level.INFO, "Battery Level notifications disabled"))
.enqueue();
}
}
/**
* Returns the last received Battery Level value.
* The value is set to null when the device disconnects.
* @return Battery Level value, in percent.
*/
public Integer getBatteryLevel() {
return mBatteryLevel;
}
protected abstract class BatteryManagerGattCallback extends BleManagerGattCallback {
@Override
protected void initialize() {
readBatteryLevelCharacteristic();
enableBatteryLevelCharacteristicNotifications();
}
@Override
protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) {
final BluetoothGattService service = gatt.getService(BATTERY_SERVICE_UUID);
if (service != null) {
mBatteryLevelCharacteristic = service.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID);
}
return mBatteryLevelCharacteristic != null;
}
@Override
protected void onDeviceDisconnected() {
mBatteryLevelCharacteristic = null;
mBatteryLevel = null;
}
}
}
| Unnecessary code removed
| app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java | Unnecessary code removed | <ide><path>pp/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java
<ide> public BatteryManager(final Context context) {
<ide> super(context);
<ide> }
<del>
<del> @NonNull
<del> @Override
<del> protected abstract BatteryManagerGattCallback getGattCallback();
<ide>
<ide> private DataReceivedCallback mBatteryLevelDataCallback = new BatteryLevelDataCallback() {
<ide> @Override |
|
Java | apache-2.0 | 27768d30b589f7e2e0ffbc88b190bf325986603c | 0 | indus1/k-9,dgger/k-9,cketti/k-9,vatsalsura/k-9,philipwhiuk/q-mail,rishabhbitsg/k-9,dgger/k-9,vt0r/k-9,G00fY2/k-9_material_design,vasyl-khomko/k-9,mawiegand/k-9,vatsalsura/k-9,k9mail/k-9,k9mail/k-9,ndew623/k-9,indus1/k-9,roscrazy/k-9,G00fY2/k-9_material_design,philipwhiuk/q-mail,cketti/k-9,vt0r/k-9,sedrubal/k-9,GuillaumeSmaha/k-9,cketti/k-9,dgger/k-9,roscrazy/k-9,mawiegand/k-9,philipwhiuk/k-9,ndew623/k-9,mawiegand/k-9,philipwhiuk/q-mail,sedrubal/k-9,rishabhbitsg/k-9,k9mail/k-9,CodingRmy/k-9,jca02266/k-9,jca02266/k-9,gilbertw1/k-9,jca02266/k-9,ndew623/k-9,jberkel/k-9,philipwhiuk/k-9,jberkel/k-9,GuillaumeSmaha/k-9,vasyl-khomko/k-9,cketti/k-9,CodingRmy/k-9,gilbertw1/k-9,GuillaumeSmaha/k-9,gilbertw1/k-9,vasyl-khomko/k-9 | package com.fsck.k9.activity.compose;
import java.util.Arrays;
import java.util.List;
import android.app.PendingIntent;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.fsck.k9.FontSizes;
import com.fsck.k9.R;
import com.fsck.k9.activity.MessageCompose;
import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.view.RecipientSelectView;
import com.fsck.k9.view.RecipientSelectView.Recipient;
import com.fsck.k9.view.RecipientSelectView.TokenListener;
public class RecipientMvpView implements OnFocusChangeListener, OnClickListener {
private static final int VIEW_INDEX_HIDDEN = -1;
private static final int VIEW_INDEX_CRYPTO_STATUS_DISABLED = 0;
private static final int VIEW_INDEX_CRYPTO_STATUS_ERROR = 1;
private static final int VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS = 2;
private static final int VIEW_INDEX_CRYPTO_STATUS_ERROR_NO_KEY = 3;
private static final int VIEW_INDEX_CRYPTO_STATUS_DISABLED_NO_KEY = 4;
private static final int VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED = 5;
private static final int VIEW_INDEX_CRYPTO_STATUS_TRUSTED = 6;
private static final int VIEW_INDEX_CRYPTO_STATUS_SIGN_ONLY = 7;
private static final int VIEW_INDEX_BCC_EXPANDER_VISIBLE = 0;
private static final int VIEW_INDEX_BCC_EXPANDER_HIDDEN = 1;
private final MessageCompose activity;
private final View ccWrapper;
private final View ccDivider;
private final View bccWrapper;
private final View bccDivider;
private final RecipientSelectView toView;
private final RecipientSelectView ccView;
private final RecipientSelectView bccView;
private final ViewAnimator cryptoStatusView;
private final ViewAnimator recipientExpanderContainer;
private RecipientPresenter presenter;
public RecipientMvpView(MessageCompose activity) {
this.activity = activity;
toView = (RecipientSelectView) activity.findViewById(R.id.to);
ccView = (RecipientSelectView) activity.findViewById(R.id.cc);
bccView = (RecipientSelectView) activity.findViewById(R.id.bcc);
ccWrapper = activity.findViewById(R.id.cc_wrapper);
ccDivider = activity.findViewById(R.id.cc_divider);
bccWrapper = activity.findViewById(R.id.bcc_wrapper);
bccDivider = activity.findViewById(R.id.bcc_divider);
recipientExpanderContainer = (ViewAnimator) activity.findViewById(R.id.recipient_expander_container);
cryptoStatusView = (ViewAnimator) activity.findViewById(R.id.crypto_status);
cryptoStatusView.setOnClickListener(this);
toView.setOnFocusChangeListener(this);
ccView.setOnFocusChangeListener(this);
bccView.setOnFocusChangeListener(this);
View recipientExpander = activity.findViewById(R.id.recipient_expander);
recipientExpander.setOnClickListener(this);
View toLabel = activity.findViewById(R.id.to_label);
View ccLabel = activity.findViewById(R.id.cc_label);
View bccLabel = activity.findViewById(R.id.bcc_label);
toLabel.setOnClickListener(this);
ccLabel.setOnClickListener(this);
bccLabel.setOnClickListener(this);
}
public void setPresenter(final RecipientPresenter presenter) {
this.presenter = presenter;
if (presenter == null) {
toView.setTokenListener(null);
ccView.setTokenListener(null);
bccView.setTokenListener(null);
return;
}
toView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onToTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onToTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onToTokenChanged(recipient);
}
});
ccView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onCcTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onCcTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onCcTokenChanged(recipient);
}
});
bccView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onBccTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onBccTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onBccTokenChanged(recipient);
}
});
}
public void addTextChangedListener(TextWatcher textWatcher) {
toView.addTextChangedListener(textWatcher);
ccView.addTextChangedListener(textWatcher);
bccView.addTextChangedListener(textWatcher);
}
public void setCryptoProvider(String openPgpProvider) {
toView.setCryptoProvider(openPgpProvider);
ccView.setCryptoProvider(openPgpProvider);
bccView.setCryptoProvider(openPgpProvider);
}
public void requestFocusOnToField() {
toView.requestFocus();
}
public void requestFocusOnCcField() {
ccView.requestFocus();
}
public void requestFocusOnBccField() {
bccView.requestFocus();
}
public void setFontSizes(FontSizes fontSizes, int fontSize) {
fontSizes.setViewTextSize(toView, fontSize);
fontSizes.setViewTextSize(ccView, fontSize);
fontSizes.setViewTextSize(bccView, fontSize);
}
public void addRecipients(RecipientType recipientType, Recipient... recipients) {
switch (recipientType) {
case TO: {
toView.addRecipients(recipients);
break;
}
case CC: {
ccView.addRecipients(recipients);
break;
}
case BCC: {
bccView.addRecipients(recipients);
break;
}
}
}
public void setCcVisibility(boolean visible) {
ccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE);
ccDivider.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void setBccVisibility(boolean visible) {
bccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE);
bccDivider.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void setRecipientExpanderVisibility(boolean visible) {
int childToDisplay = visible ? VIEW_INDEX_BCC_EXPANDER_VISIBLE : VIEW_INDEX_BCC_EXPANDER_HIDDEN;
if (recipientExpanderContainer.getDisplayedChild() != childToDisplay) {
recipientExpanderContainer.setDisplayedChild(childToDisplay);
}
}
public boolean isCcVisible() {
return ccWrapper.getVisibility() == View.VISIBLE;
}
public boolean isBccVisible() {
return bccWrapper.getVisibility() == View.VISIBLE;
}
public void showNoRecipientsError() {
toView.setError(toView.getContext().getString(R.string.message_compose_error_no_recipients));
}
public List<Address> getToAddresses() {
return Arrays.asList(toView.getAddresses());
}
public List<Address> getCcAddresses() {
return Arrays.asList(ccView.getAddresses());
}
public List<Address> getBccAddresses() {
return Arrays.asList(bccView.getAddresses());
}
public List<Recipient> getToRecipients() {
return toView.getObjects();
}
public List<Recipient> getCcRecipients() {
return ccView.getObjects();
}
public List<Recipient> getBccRecipients() {
return bccView.getObjects();
}
public boolean recipientToHasUncompletedText() {
return toView.hasUncompletedText();
}
public boolean recipientCcHasUncompletedText() {
return ccView.hasUncompletedText();
}
public boolean recipientBccHasUncompletedText() {
return bccView.hasUncompletedText();
}
public void showToUncompletedError() {
toView.setError(toView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showCcUncompletedError() {
ccView.setError(ccView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showBccUncompletedError() {
bccView.setError(bccView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showCryptoStatus(final CryptoStatusDisplayType cryptoStatusDisplayType) {
boolean shouldBeHidden = cryptoStatusDisplayType.childToDisplay == VIEW_INDEX_HIDDEN;
if (shouldBeHidden) {
cryptoStatusView.setVisibility(View.GONE);
return;
}
cryptoStatusView.setVisibility(View.VISIBLE);
int childToDisplay = cryptoStatusDisplayType.childToDisplay;
cryptoStatusView.setDisplayedChild(childToDisplay);
}
public void showContactPicker(int requestCode) {
activity.showContactPicker(requestCode);
}
public void showErrorContactNoAddress() {
Toast.makeText(activity, R.string.error_contact_address_not_found, Toast.LENGTH_LONG).show();
}
public void showErrorOpenPgpConnection() {
Toast.makeText(activity, R.string.error_crypto_provider_connect, Toast.LENGTH_LONG).show();
}
public void showErrorOpenPgpUserInteractionRequired() {
Toast.makeText(activity, R.string.error_crypto_provider_ui_required, Toast.LENGTH_LONG).show();
}
public void showErrorMissingSignKey() {
Toast.makeText(activity, R.string.compose_error_no_signing_key, Toast.LENGTH_LONG).show();
}
public void showErrorPrivateButMissingKeys() {
Toast.makeText(activity, R.string.compose_error_private_missing_keys, Toast.LENGTH_LONG).show();
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
return;
}
switch (view.getId()) {
case R.id.to: {
presenter.onToFocused();
break;
}
case R.id.cc: {
presenter.onCcFocused();
break;
}
case R.id.bcc: {
presenter.onBccFocused();
break;
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.to_label: {
presenter.onClickToLabel();
break;
}
case R.id.cc_label: {
presenter.onClickCcLabel();
break;
}
case R.id.bcc_label: {
presenter.onClickBccLabel();
break;
}
case R.id.recipient_expander: {
presenter.onClickRecipientExpander();
break;
}
case R.id.crypto_status: {
presenter.onClickCryptoStatus();
break;
}
}
}
public void showCryptoDialog(CryptoMode currentCryptoMode) {
CryptoSettingsDialog dialog = CryptoSettingsDialog.newInstance(currentCryptoMode);
dialog.show(activity.getFragmentManager(), "crypto_settings");
}
public void launchUserInteractionPendingIntent(PendingIntent pendingIntent, int requestCode) {
activity.launchUserInteractionPendingIntent(pendingIntent, requestCode);
}
public enum CryptoStatusDisplayType {
UNCONFIGURED(VIEW_INDEX_HIDDEN),
UNINITIALIZED(VIEW_INDEX_HIDDEN),
DISABLED(VIEW_INDEX_CRYPTO_STATUS_DISABLED),
SIGN_ONLY(VIEW_INDEX_CRYPTO_STATUS_SIGN_ONLY),
OPPORTUNISTIC_EMPTY(VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS),
OPPORTUNISTIC_NOKEY(VIEW_INDEX_CRYPTO_STATUS_DISABLED_NO_KEY),
OPPORTUNISTIC_UNTRUSTED(VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED),
OPPORTUNISTIC_TRUSTED(VIEW_INDEX_CRYPTO_STATUS_TRUSTED),
PRIVATE_EMPTY(VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS),
PRIVATE_NOKEY(VIEW_INDEX_CRYPTO_STATUS_ERROR_NO_KEY),
PRIVATE_UNTRUSTED(VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED),
PRIVATE_TRUSTED(VIEW_INDEX_CRYPTO_STATUS_TRUSTED),
ERROR(VIEW_INDEX_CRYPTO_STATUS_ERROR);
final int childToDisplay;
CryptoStatusDisplayType(int childToDisplay) {
this.childToDisplay = childToDisplay;
}
}
}
| k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java | package com.fsck.k9.activity.compose;
import java.util.Arrays;
import java.util.List;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.PendingIntent;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.fsck.k9.FontSizes;
import com.fsck.k9.R;
import com.fsck.k9.activity.MessageCompose;
import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.view.RecipientSelectView;
import com.fsck.k9.view.RecipientSelectView.Recipient;
import com.fsck.k9.view.RecipientSelectView.TokenListener;
public class RecipientMvpView implements OnFocusChangeListener, OnClickListener {
private static final int VIEW_INDEX_HIDDEN = -1;
private static final int VIEW_INDEX_CRYPTO_STATUS_DISABLED = 0;
private static final int VIEW_INDEX_CRYPTO_STATUS_ERROR = 1;
private static final int VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS = 2;
private static final int VIEW_INDEX_CRYPTO_STATUS_ERROR_NO_KEY = 3;
private static final int VIEW_INDEX_CRYPTO_STATUS_DISABLED_NO_KEY = 4;
private static final int VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED = 5;
private static final int VIEW_INDEX_CRYPTO_STATUS_TRUSTED = 6;
private static final int VIEW_INDEX_CRYPTO_STATUS_SIGN_ONLY = 7;
private static final int VIEW_INDEX_BCC_EXPANDER_VISIBLE = 0;
private static final int VIEW_INDEX_BCC_EXPANDER_HIDDEN = 1;
private final MessageCompose activity;
private final View ccWrapper;
private final View ccDivider;
private final View bccWrapper;
private final View bccDivider;
private final RecipientSelectView toView;
private final RecipientSelectView ccView;
private final RecipientSelectView bccView;
private final ViewAnimator cryptoStatusView;
private final ViewAnimator recipientExpanderContainer;
private RecipientPresenter presenter;
public RecipientMvpView(MessageCompose activity) {
this.activity = activity;
toView = (RecipientSelectView) activity.findViewById(R.id.to);
ccView = (RecipientSelectView) activity.findViewById(R.id.cc);
bccView = (RecipientSelectView) activity.findViewById(R.id.bcc);
ccWrapper = activity.findViewById(R.id.cc_wrapper);
ccDivider = activity.findViewById(R.id.cc_divider);
bccWrapper = activity.findViewById(R.id.bcc_wrapper);
bccDivider = activity.findViewById(R.id.bcc_divider);
recipientExpanderContainer = (ViewAnimator) activity.findViewById(R.id.recipient_expander_container);
cryptoStatusView = (ViewAnimator) activity.findViewById(R.id.crypto_status);
cryptoStatusView.setOnClickListener(this);
toView.setOnFocusChangeListener(this);
ccView.setOnFocusChangeListener(this);
bccView.setOnFocusChangeListener(this);
View recipientExpander = activity.findViewById(R.id.recipient_expander);
recipientExpander.setOnClickListener(this);
View toLabel = activity.findViewById(R.id.to_label);
View ccLabel = activity.findViewById(R.id.cc_label);
View bccLabel = activity.findViewById(R.id.bcc_label);
toLabel.setOnClickListener(this);
ccLabel.setOnClickListener(this);
bccLabel.setOnClickListener(this);
}
public void setPresenter(final RecipientPresenter presenter) {
this.presenter = presenter;
if (presenter == null) {
toView.setTokenListener(null);
ccView.setTokenListener(null);
bccView.setTokenListener(null);
return;
}
toView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onToTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onToTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onToTokenChanged(recipient);
}
});
ccView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onCcTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onCcTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onCcTokenChanged(recipient);
}
});
bccView.setTokenListener(new TokenListener<Recipient>() {
@Override
public void onTokenAdded(Recipient recipient) {
presenter.onBccTokenAdded(recipient);
}
@Override
public void onTokenRemoved(Recipient recipient) {
presenter.onBccTokenRemoved(recipient);
}
@Override
public void onTokenChanged(Recipient recipient) {
presenter.onBccTokenChanged(recipient);
}
});
}
public void addTextChangedListener(TextWatcher textWatcher) {
toView.addTextChangedListener(textWatcher);
ccView.addTextChangedListener(textWatcher);
bccView.addTextChangedListener(textWatcher);
}
public void setCryptoProvider(String openPgpProvider) {
toView.setCryptoProvider(openPgpProvider);
ccView.setCryptoProvider(openPgpProvider);
bccView.setCryptoProvider(openPgpProvider);
}
public void requestFocusOnToField() {
toView.requestFocus();
}
public void requestFocusOnCcField() {
ccView.requestFocus();
}
public void requestFocusOnBccField() {
bccView.requestFocus();
}
public void setFontSizes(FontSizes fontSizes, int fontSize) {
fontSizes.setViewTextSize(toView, fontSize);
fontSizes.setViewTextSize(ccView, fontSize);
fontSizes.setViewTextSize(bccView, fontSize);
}
public void addRecipients(RecipientType recipientType, Recipient... recipients) {
switch (recipientType) {
case TO: {
toView.addRecipients(recipients);
break;
}
case CC: {
ccView.addRecipients(recipients);
break;
}
case BCC: {
bccView.addRecipients(recipients);
break;
}
}
}
public void setCcVisibility(boolean visible) {
ccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE);
ccDivider.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void setBccVisibility(boolean visible) {
bccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE);
bccDivider.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void setRecipientExpanderVisibility(boolean visible) {
int childToDisplay = visible ? VIEW_INDEX_BCC_EXPANDER_VISIBLE : VIEW_INDEX_BCC_EXPANDER_HIDDEN;
if (recipientExpanderContainer.getDisplayedChild() != childToDisplay) {
recipientExpanderContainer.setDisplayedChild(childToDisplay);
}
}
public boolean isCcVisible() {
return ccWrapper.getVisibility() == View.VISIBLE;
}
public boolean isBccVisible() {
return bccWrapper.getVisibility() == View.VISIBLE;
}
public void showNoRecipientsError() {
toView.setError(toView.getContext().getString(R.string.message_compose_error_no_recipients));
}
public List<Address> getToAddresses() {
return Arrays.asList(toView.getAddresses());
}
public List<Address> getCcAddresses() {
return Arrays.asList(ccView.getAddresses());
}
public List<Address> getBccAddresses() {
return Arrays.asList(bccView.getAddresses());
}
public List<Recipient> getToRecipients() {
return toView.getObjects();
}
public List<Recipient> getCcRecipients() {
return ccView.getObjects();
}
public List<Recipient> getBccRecipients() {
return bccView.getObjects();
}
public boolean recipientToHasUncompletedText() {
return toView.hasUncompletedText();
}
public boolean recipientCcHasUncompletedText() {
return ccView.hasUncompletedText();
}
public boolean recipientBccHasUncompletedText() {
return bccView.hasUncompletedText();
}
public void showToUncompletedError() {
toView.setError(toView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showCcUncompletedError() {
ccView.setError(ccView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showBccUncompletedError() {
bccView.setError(bccView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
public void showCryptoStatus(final CryptoStatusDisplayType cryptoStatusDisplayType) {
boolean shouldBeHidden = cryptoStatusDisplayType.childToDisplay == VIEW_INDEX_HIDDEN;
if (shouldBeHidden) {
hideCryptoStatus();
return;
}
boolean alreadyVisible = cryptoStatusView.getVisibility() == View.VISIBLE;
if (alreadyVisible) {
switchCryptoStatus(cryptoStatusDisplayType);
return;
}
cryptoStatusView.setTranslationX(100);
cryptoStatusView.setVisibility(View.VISIBLE);
cryptoStatusView.animate().translationX(0).setDuration(300).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
switchCryptoStatus(cryptoStatusDisplayType);
}
}).start();
}
private void hideCryptoStatus() {
if (cryptoStatusView.getVisibility() == View.GONE) {
return;
}
cryptoStatusView.animate().translationX(100).setDuration(300).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
cryptoStatusView.setVisibility(View.GONE);
}
}).start();
}
private void switchCryptoStatus(CryptoStatusDisplayType cryptoStatus) {
int childToDisplay = cryptoStatus.childToDisplay;
if (cryptoStatusView.getDisplayedChild() != childToDisplay) {
cryptoStatusView.setDisplayedChild(childToDisplay);
}
}
public void showContactPicker(int requestCode) {
activity.showContactPicker(requestCode);
}
public void showErrorContactNoAddress() {
Toast.makeText(activity, R.string.error_contact_address_not_found, Toast.LENGTH_LONG).show();
}
public void showErrorOpenPgpConnection() {
Toast.makeText(activity, R.string.error_crypto_provider_connect, Toast.LENGTH_LONG).show();
}
public void showErrorOpenPgpUserInteractionRequired() {
Toast.makeText(activity, R.string.error_crypto_provider_ui_required, Toast.LENGTH_LONG).show();
}
public void showErrorMissingSignKey() {
Toast.makeText(activity, R.string.compose_error_no_signing_key, Toast.LENGTH_LONG).show();
}
public void showErrorPrivateButMissingKeys() {
Toast.makeText(activity, R.string.compose_error_private_missing_keys, Toast.LENGTH_LONG).show();
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
return;
}
switch (view.getId()) {
case R.id.to: {
presenter.onToFocused();
break;
}
case R.id.cc: {
presenter.onCcFocused();
break;
}
case R.id.bcc: {
presenter.onBccFocused();
break;
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.to_label: {
presenter.onClickToLabel();
break;
}
case R.id.cc_label: {
presenter.onClickCcLabel();
break;
}
case R.id.bcc_label: {
presenter.onClickBccLabel();
break;
}
case R.id.recipient_expander: {
presenter.onClickRecipientExpander();
break;
}
case R.id.crypto_status: {
presenter.onClickCryptoStatus();
break;
}
}
}
public void showCryptoDialog(CryptoMode currentCryptoMode) {
CryptoSettingsDialog dialog = CryptoSettingsDialog.newInstance(currentCryptoMode);
dialog.show(activity.getFragmentManager(), "crypto_settings");
}
public void launchUserInteractionPendingIntent(PendingIntent pendingIntent, int requestCode) {
activity.launchUserInteractionPendingIntent(pendingIntent, requestCode);
}
public enum CryptoStatusDisplayType {
UNCONFIGURED(VIEW_INDEX_HIDDEN),
UNINITIALIZED(VIEW_INDEX_HIDDEN),
DISABLED(VIEW_INDEX_CRYPTO_STATUS_DISABLED),
SIGN_ONLY(VIEW_INDEX_CRYPTO_STATUS_SIGN_ONLY),
OPPORTUNISTIC_EMPTY(VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS),
OPPORTUNISTIC_NOKEY(VIEW_INDEX_CRYPTO_STATUS_DISABLED_NO_KEY),
OPPORTUNISTIC_UNTRUSTED(VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED),
OPPORTUNISTIC_TRUSTED(VIEW_INDEX_CRYPTO_STATUS_TRUSTED),
PRIVATE_EMPTY(VIEW_INDEX_CRYPTO_STATUS_NO_RECIPIENTS),
PRIVATE_NOKEY(VIEW_INDEX_CRYPTO_STATUS_ERROR_NO_KEY),
PRIVATE_UNTRUSTED(VIEW_INDEX_CRYPTO_STATUS_UNTRUSTED),
PRIVATE_TRUSTED(VIEW_INDEX_CRYPTO_STATUS_TRUSTED),
ERROR(VIEW_INDEX_CRYPTO_STATUS_ERROR);
final int childToDisplay;
CryptoStatusDisplayType(int childToDisplay) {
this.childToDisplay = childToDisplay;
}
}
}
| compose: ditch crypto status icon animation
| k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java | compose: ditch crypto status icon animation | <ide><path>9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<del>import android.animation.Animator;
<del>import android.animation.AnimatorListenerAdapter;
<ide> import android.app.PendingIntent;
<ide> import android.text.TextWatcher;
<ide> import android.view.View;
<ide> public void showCryptoStatus(final CryptoStatusDisplayType cryptoStatusDisplayType) {
<ide> boolean shouldBeHidden = cryptoStatusDisplayType.childToDisplay == VIEW_INDEX_HIDDEN;
<ide> if (shouldBeHidden) {
<del> hideCryptoStatus();
<add> cryptoStatusView.setVisibility(View.GONE);
<ide> return;
<ide> }
<ide>
<del> boolean alreadyVisible = cryptoStatusView.getVisibility() == View.VISIBLE;
<del> if (alreadyVisible) {
<del> switchCryptoStatus(cryptoStatusDisplayType);
<del> return;
<del> }
<del>
<del> cryptoStatusView.setTranslationX(100);
<ide> cryptoStatusView.setVisibility(View.VISIBLE);
<del> cryptoStatusView.animate().translationX(0).setDuration(300).setListener(new AnimatorListenerAdapter() {
<del> @Override
<del> public void onAnimationEnd(Animator animation) {
<del> switchCryptoStatus(cryptoStatusDisplayType);
<del> }
<del> }).start();
<del> }
<del>
<del>
<del> private void hideCryptoStatus() {
<del> if (cryptoStatusView.getVisibility() == View.GONE) {
<del> return;
<del> }
<del>
<del> cryptoStatusView.animate().translationX(100).setDuration(300).setListener(new AnimatorListenerAdapter() {
<del> @Override
<del> public void onAnimationEnd(Animator animation) {
<del> super.onAnimationEnd(animation);
<del> cryptoStatusView.setVisibility(View.GONE);
<del> }
<del> }).start();
<del> }
<del>
<del> private void switchCryptoStatus(CryptoStatusDisplayType cryptoStatus) {
<del> int childToDisplay = cryptoStatus.childToDisplay;
<del> if (cryptoStatusView.getDisplayedChild() != childToDisplay) {
<del> cryptoStatusView.setDisplayedChild(childToDisplay);
<del> }
<add> int childToDisplay = cryptoStatusDisplayType.childToDisplay;
<add> cryptoStatusView.setDisplayedChild(childToDisplay);
<ide> }
<ide>
<ide> public void showContactPicker(int requestCode) { |
|
JavaScript | mit | 00aaa8fbb30dc6bcb1343ef963b4d918476996b6 | 0 | dotansimha/graphql-code-generator,dotansimha/graphql-code-generator,dotansimha/graphql-code-generator | /* eslint-disable no-console */
const { argv } = require('yargs');
const { writeJSON, readJSON, existsSync } = require('fs-extra');
const { join } = require('path');
const semver = require('semver');
const cp = require('child_process');
const npm = require('npm');
const limit = require('p-limit')(5);
function readWorkspaceInfo() {
const rawOutput = cp.execSync(`yarn workspaces info`).toString();
const lines = rawOutput.split('\n');
lines.shift();
lines.pop();
lines.pop();
return JSON.parse(lines.join('\n'));
}
async function readPackage(path) {
const packagePath = join(path, './package.json');
return readJSON(packagePath);
}
async function writePackage(path, content) {
if (argv.dryrun) {
return;
}
const packagePath = join(path, './package.json');
await writeJSON(packagePath, content, { spaces: 2, replacer: null });
}
async function getNewVersion() {
let version = argv._[0] || process.env.RELEASE_VERSION || await getMostRecentStable();
if (version.startsWith('v')) {
version = version.replace('v', '')
}
if (argv.canary) {
const gitHash = cp.spawnSync('git', ['rev-parse', '--short', 'HEAD']).stdout.toString().trim();
version = semver.inc(version, 'prerelease', true, 'alpha-' + gitHash);
}
return version;
}
async function getMostRecentStable() {
return new Promise((resolve, reject) => {
npm.view(`@graphql-codegen/cli`, 'version', (err, res) => {
if (err) {
return reject(err)
} else {
resolve(Object.keys(res)[0]);
}
})
})
}
async function bumpDependencies(availableSiblings, newVersion, dependencies = {}) {
return Promise.all(Object.keys(dependencies).map(async dependency => {
if (availableSiblings.includes(dependency)) {
dependencies[dependency] = newVersion;
}
}));
}
async function publishDirectory(directory) {
if (argv.dryrun) {
return;
}
return new Promise((resolve, reject) => {
npm.publish(directory, (err, result) => {
if (err) {
if (err.toString().includes('You cannot publish over the previously published versions')) {
resolve({});
} else {
reject(err);
}
} else {
resolve(result);
}
})
});
}
async function release() {
const version = await getNewVersion();
const workspaceInfo = readWorkspaceInfo();
const packages = new Map();
// Get all package.json content from dist/
await Promise.all(
Object.keys(workspaceInfo).map(async packageName => {
const distPath = join(workspaceInfo[packageName].location, `./dist/`);
const packagePath = existsSync(distPath) ? distPath : workspaceInfo[packageName].location;
const packageContent = await readPackage(packagePath);
if (!packageContent.private) {
if (packages.has(packageName)) {
throw new Error(`Package ${packageName} seems to be duplicated! Locations: ${[
packages.get(packageName).path,
packagePath,
].join('\n')}`)
}
packages.set(packageName, {
path: packagePath,
content: packageContent,
});
}
})
);
// Bump all package.json files and publish
const availableSiblings = Array.from(packages.keys());
await Promise.all(
Array.from(packages.entries()).map(([packageName, { path, content }]) => limit(async () => {
console.info(`Updating and publishing package: ${packageName} from package; ${path}`)
content.version = version;
content.publishConfig = { access: 'public', tag: content.version.includes('alpha') ? 'alpha' : 'latest' };
bumpDependencies(availableSiblings, version, content.dependencies);
if (content.devDependencies) {
delete content.devDependencies;
}
await writePackage(path, content);
await publishDirectory(path);
}))
);
return version;
}
const initNpm = new Promise((resolve, reject) => {
npm.load({}, err => {
if (err) {
reject(err);
} else {
resolve();
}
})
});
initNpm.then(() => release()).then(version => {
console.info(`Published => ${version}`)
}).catch(err => {
console.error(err);
process.exit(1);
});
| scripts/release.js | /* eslint-disable no-console */
const { argv } = require('yargs');
const { writeJSON, readJSON, existsSync } = require('fs-extra');
const { join } = require('path');
const semver = require('semver');
const cp = require('child_process');
const npm = require('npm');
function readWorkspaceInfo() {
const rawOutput = cp.execSync(`yarn workspaces info`).toString();
const lines = rawOutput.split('\n');
lines.shift();
lines.pop();
lines.pop();
return JSON.parse(lines.join('\n'));
}
async function readPackage(path) {
const packagePath = join(path, './package.json');
return readJSON(packagePath);
}
async function writePackage(path, content) {
if (argv.dryrun) {
return;
}
const packagePath = join(path, './package.json');
await writeJSON(packagePath, content, { spaces: 2, replacer: null });
}
async function getNewVersion() {
let version = argv._[0] || process.env.RELEASE_VERSION || await getMostRecentStable();
if (version.startsWith('v')) {
version = version.replace('v', '')
}
if (argv.canary) {
const gitHash = cp.spawnSync('git', ['rev-parse', '--short', 'HEAD']).stdout.toString().trim();
version = semver.inc(version, 'prerelease', true, 'alpha-' + gitHash);
}
return version;
}
async function getMostRecentStable() {
return new Promise((resolve, reject) => {
npm.view(`@graphql-codegen/cli`, 'version', (err, res) => {
if (err) {
return reject(err)
} else {
resolve(Object.keys(res)[0]);
}
})
})
}
async function bumpDependencies(availableSiblings, newVersion, dependencies = {}) {
return Promise.all(Object.keys(dependencies).map(async dependency => {
if (availableSiblings.includes(dependency)) {
dependencies[dependency] = newVersion;
}
}));
}
async function publishDirectory(directory, attempt = 0) {
return new Promise((resolve, reject) => {
npm.publish(directory, (err, result) => {
if (err) {
if (err.toString().includes('You cannot publish over the previously published versions')) {
resolve({});
} else {
reject(err);
}
} else {
resolve(result);
}
})
});
}
async function release() {
const version = await getNewVersion();
const workspaceInfo = readWorkspaceInfo();
const packages = new Map();
// Get all package.json content from dist/
await Promise.all(
Object.keys(workspaceInfo).map(async packageName => {
const distPath = join(workspaceInfo[packageName].location, `./dist/`);
const packagePath = existsSync(distPath) ? distPath : workspaceInfo[packageName].location;
const packageContent = await readPackage(packagePath);
if (!packageContent.private) {
if (packages.has(packageName)) {
throw new Error(`Package ${packageName} seems to be duplicated! Locations: ${[
packages.get(packageName).path,
packagePath,
].join('\n')}`)
}
packages.set(packageName, {
path: packagePath,
content: packageContent,
});
}
})
);
// Bump all package.json files and publish
const availableSiblings = Array.from(packages.keys());
await Promise.all(
Array.from(packages.entries()).map(async ([packageName, { path, content }]) => {
console.info(`Updating and publishing package: ${packageName} from package; ${path}`)
content.version = version;
content.publishConfig = { access: 'public', tag: content.version.includes('alpha') ? 'alpha' : 'latest' };
bumpDependencies(availableSiblings, version, content.dependencies);
if (content.devDependencies) {
delete content.devDependencies;
}
await writePackage(path, content);
await publishDirectory(path);
})
);
return version;
}
const initNpm = new Promise((resolve, reject) => {
npm.load({}, err => {
if (err) {
reject(err);
} else {
resolve();
}
})
});
initNpm.then(() => release()).then(version => {
console.info(`Published => ${version}`)
}).catch(err => {
console.error(err);
process.exit(1);
});
| fix for promise limit
| scripts/release.js | fix for promise limit | <ide><path>cripts/release.js
<ide> const semver = require('semver');
<ide> const cp = require('child_process');
<ide> const npm = require('npm');
<add>const limit = require('p-limit')(5);
<ide>
<ide> function readWorkspaceInfo() {
<ide> const rawOutput = cp.execSync(`yarn workspaces info`).toString();
<ide> }
<ide>
<ide> async function getNewVersion() {
<del> let version = argv._[0] || process.env.RELEASE_VERSION || await getMostRecentStable();
<add> let version = argv._[0] || process.env.RELEASE_VERSION || await getMostRecentStable();
<ide>
<ide> if (version.startsWith('v')) {
<ide> version = version.replace('v', '')
<ide> }));
<ide> }
<ide>
<del>async function publishDirectory(directory, attempt = 0) {
<add>async function publishDirectory(directory) {
<add> if (argv.dryrun) {
<add> return;
<add> }
<add>
<ide> return new Promise((resolve, reject) => {
<ide> npm.publish(directory, (err, result) => {
<ide> if (err) {
<ide> // Bump all package.json files and publish
<ide> const availableSiblings = Array.from(packages.keys());
<ide> await Promise.all(
<del> Array.from(packages.entries()).map(async ([packageName, { path, content }]) => {
<add> Array.from(packages.entries()).map(([packageName, { path, content }]) => limit(async () => {
<ide> console.info(`Updating and publishing package: ${packageName} from package; ${path}`)
<ide> content.version = version;
<ide> content.publishConfig = { access: 'public', tag: content.version.includes('alpha') ? 'alpha' : 'latest' };
<ide>
<ide> bumpDependencies(availableSiblings, version, content.dependencies);
<del>
<add>
<ide> if (content.devDependencies) {
<ide> delete content.devDependencies;
<ide> }
<ide>
<ide> await writePackage(path, content);
<ide> await publishDirectory(path);
<del> })
<add> }))
<ide> );
<ide>
<ide> return version; |
|
Java | apache-2.0 | a0d8ac5a0ef4030a8c5e6e6f9a234216cce18337 | 0 | Terradue/dsi-tools | package com.terradue.dsione;
/*
* Copyright 2012 Terradue srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 static com.sun.jersey.api.client.Client.create;
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
final class DsiOneToolsModule
extends AbstractModule
{
@Override
protected void configure()
{
bind( ClientConfig.class ).toProvider( RestClientConfigProvider.class );
bind( Client.class ).toProvider( RestClientProvider.class );
}
public static final class RestClientConfigProvider
implements Provider<ClientConfig>
{
@Override
public ClientConfig get()
{
DefaultAhcConfig config = new DefaultAhcConfig();
return config;
}
}
public static final class RestClientProvider
implements Provider<Client>
{
private final ClientConfig config;
@Inject
public RestClientProvider( ClientConfig config )
{
this.config = config;
}
@Override
public Client get()
{
return create( config );
}
}
}
| src/main/java/com/terradue/dsione/DsiOneToolsModule.java | package com.terradue.dsione;
/*
* Copyright 2012 Terradue srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 com.google.inject.AbstractModule;
import com.sun.jersey.api.client.Client;
final class DsiOneToolsModule
extends AbstractModule
{
@Override
protected void configure()
{
bind( Client.class ).toProvider( RestClientProvider.class );
}
}
| started adding the ClientConfig provider impl | src/main/java/com/terradue/dsione/DsiOneToolsModule.java | started adding the ClientConfig provider impl | <ide><path>rc/main/java/com/terradue/dsione/DsiOneToolsModule.java
<ide> * limitations under the License.
<ide> */
<ide>
<add>import static com.sun.jersey.api.client.Client.create;
<add>
<add>import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig;
<add>
<ide> import com.google.inject.AbstractModule;
<add>import com.google.inject.Inject;
<add>import com.google.inject.Provider;
<ide> import com.sun.jersey.api.client.Client;
<add>import com.sun.jersey.api.client.config.ClientConfig;
<ide>
<ide> final class DsiOneToolsModule
<ide> extends AbstractModule
<ide> @Override
<ide> protected void configure()
<ide> {
<add> bind( ClientConfig.class ).toProvider( RestClientConfigProvider.class );
<ide> bind( Client.class ).toProvider( RestClientProvider.class );
<ide> }
<ide>
<add> public static final class RestClientConfigProvider
<add> implements Provider<ClientConfig>
<add> {
<add>
<add> @Override
<add> public ClientConfig get()
<add> {
<add> DefaultAhcConfig config = new DefaultAhcConfig();
<add> return config;
<add> }
<add>
<add> }
<add>
<add> public static final class RestClientProvider
<add> implements Provider<Client>
<add> {
<add>
<add> private final ClientConfig config;
<add>
<add> @Inject
<add> public RestClientProvider( ClientConfig config )
<add> {
<add> this.config = config;
<add> }
<add>
<add> @Override
<add> public Client get()
<add> {
<add> return create( config );
<add> }
<add>
<add> }
<add>
<ide> } |
|
Java | agpl-3.0 | e377e18043ab1a83ec53fa3c6fdecc7921bfdb06 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 7d13d4fc-2e60-11e5-9284-b827eb9e62be | hello.java | 7d0e6a3a-2e60-11e5-9284-b827eb9e62be | 7d13d4fc-2e60-11e5-9284-b827eb9e62be | hello.java | 7d13d4fc-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>7d0e6a3a-2e60-11e5-9284-b827eb9e62be
<add>7d13d4fc-2e60-11e5-9284-b827eb9e62be |
|
JavaScript | agpl-3.0 | 48d7aa3b19c477663c5ba78352ef80c745a5ff7b | 0 | sergeygaychuk/pcs-web,sergeygaychuk/pcs-web,yanovich/pcs-web,yanovich/pcs-web,yanovich/pcs-web,sergeygaychuk/pcs-web | /* test/app/unit/controllers/page.js -- test Page Angular controller
* Copyright 2014 Sergei Ianovich
*
* Licensed under AGPL-3.0 or later, see LICENSE
* Process Control Service Web Interface
*/
'use strict';
describe("Page Controller", function() {
var httpBackend;
beforeEach(function() {
angular.mock.module('pcs.services');
angular.mock.module('pcs.controllers');
});
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend;
}));
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
});
describe("PageCtrl", function() {
var scope, location, controller;
beforeEach(inject(function($location, $controller) {
location = $location;
controller = $controller;
scope = {};
controller('PageCtrl', { $scope: scope });
}));
it("should define pager", function() {
expect(scope.pager).to.exist();
expect(scope.pager.first).to.equal(0);
expect(scope.pager.last).to.equal(0);
expect(scope.pager.count).to.equal(0);
expect(scope.pager.page).to.equal(1);
expect(scope.pager.show).to.not.be.true;
});
it("should define moment", function() {
expect(scope.moment).to.exist();
});
it("should define operator", function() {
expect(scope.operator).to.eql({});
});
describe("#setNewURL", function() {
it("should update newURL", function() {
expect(scope.newURL).to.be.undefined;
scope.setNewURL("HELLO");
expect(scope.newURL).to.equal("HELLO");
});
});
describe("#page", function() {
it("should update pager count", function() {
scope.page(1, 23, 26);
expect(scope.pager.count).to.equal(26);
});
it("should update count per page", function() {
scope.page(1, 23, 26);
expect(scope.pager.page).to.equal(1);
});
it("should update pager first", function() {
scope.page(1, 23, 26);
expect(scope.pager.first).to.equal(1);
scope.page(2, 23, 26);
expect(scope.pager.first).to.equal(24);
});
it("should update pager last", function() {
scope.page(1, 23, 26);
expect(scope.pager.last).to.equal(23);
scope.page(2, 23, 26);
expect(scope.pager.last).to.equal(26);
});
describe("update show attribute", function() {
it("should show if count is positive", function() {
scope.page(1, 23, 26);
expect(scope.pager.show).to.be.true;
});
it("should show if count is zero", function() {
scope.page(1, 23, 0);
expect(scope.pager.show).to.not.be.true;
});
});
describe("update prev attribute", function() {
it("should set prev if page is more then 1", function() {
location.path("/hello");
scope.page(2, 23, 26);
expect(scope.pager.prev).to.equal('#/hello?page=1');
});
it("should clear prev is page is 1", function() {
scope.page(1, 23, 26);
expect(scope.pager.prev).to.equal('');
});
});
describe("update next attribute", function() {
it("should set next if page is not the last", function() {
location.path("/hello");
scope.page(1, 23, 26);
expect(scope.pager.next).to.equal('#/hello?page=2');
});
it("should clear next if page is the last", function() {
scope.page(2, 23, 26);
expect(scope.pager.next).to.equal('');
});
});
});
});
});
// vim:ts=2 sts=2 sw=2 et:
| test/browser/page_controller_test.js | /* test/app/unit/controllers/page.js -- test Page Angular controller
* Copyright 2014 Sergei Ianovich
*
* Licensed under AGPL-3.0 or later, see LICENSE
* Process Control Service Web Interface
*/
'use strict';
describe("Page Controller", function() {
var httpBackend;
beforeEach(function() {
angular.mock.module('pcs.services');
angular.mock.module('pcs.controllers');
});
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend;
}));
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
});
describe("PageCtrl", function() {
var scope, location, controller;
beforeEach(inject(function($location, $controller) {
location = $location;
controller = $controller;
scope = {};
controller('PageCtrl', { $scope: scope });
}));
it("should define pager", function() {
expect(scope.pager).to.exist();
expect(scope.pager.first).to.equal(0);
expect(scope.pager.last).to.equal(0);
expect(scope.pager.count).to.equal(0);
expect(scope.pager.page).to.equal(1);
expect(scope.pager.show).to.not.be.true;
});
it("should define moment", function() {
expect(scope.moment).to.exist();
});
it("should define operator", function() {
expect(scope.operator).to.eql({});
});
describe("#setNewURL", function() {
it("should update newURL", function() {
expect(scope.newURL).to.be.undefined;
scope.setNewURL("HELLO");
expect(scope.newURL).to.equal("HELLO");
});
});
describe("#page", function() {
it("should update pager count", function() {
scope.page(1, 23, 26);
expect(scope.pager.count).to.equal(26);
});
it("should update count per page", function() {
scope.page(1, 23, 26);
expect(scope.pager.page).to.equal(1);
});
it("should update pager first", function() {
scope.page(1, 23, 26);
expect(scope.pager.first).to.equal(1);
scope.page(2, 23, 26);
expect(scope.pager.first).to.equal(24);
});
it("should update pager last", function() {
scope.page(1, 23, 26);
expect(scope.pager.last).to.equal(23);
scope.page(2, 23, 26);
expect(scope.pager.last).to.equal(26);
});
describe("update show attribute", function() {
it("should show if count is positive", function() {
scope.page(1, 23, 26);
expect(scope.pager.show).to.be.true;
});
it("should show if count is zero", function() {
scope.page(1, 23, 0);
expect(scope.pager.show).to.not.be.true;
});
});
describe("update prev attribute", function() {
it("should set prev if page is more then 1", function() {
location.path("/hello");
scope.page(2, 23, 26);
expect(scope.pager.prev).to.equal('#/hello?page=1');
});
it("should clear prev is page is 1", function() {
scope.page(1, 23, 26);
expect(scope.pager.prev).to.equal('');
});
});
describe("update next attribute", function() {
it("should set next if page is not the last", function() {
location.path("/hello");
scope.page(1, 23, 26);
expect(scope.pager.next).to.equal('#/hello?page=2');
});
it("should clear next is page is the last", function() {
scope.page(2, 23, 26);
expect(scope.pager.next).to.equal('');
});
});
});
});
});
// vim:ts=2 sts=2 sw=2 et:
| tests: fix typo in description
Signed-off-by: Sergei Ianovich <[email protected]>
| test/browser/page_controller_test.js | tests: fix typo in description | <ide><path>est/browser/page_controller_test.js
<ide> expect(scope.pager.next).to.equal('#/hello?page=2');
<ide> });
<ide>
<del> it("should clear next is page is the last", function() {
<add> it("should clear next if page is the last", function() {
<ide> scope.page(2, 23, 26);
<ide> expect(scope.pager.next).to.equal('');
<ide> }); |
|
Java | mit | f2fc260ea15a44b7d5d6ecb726a23c371012a3c8 | 0 | EsfingeFramework/metadata | package net.sf.esfinge.container.processor.Field;
import static org.junit.Assert.*;
import org.junit.Test;
import net.sf.esfinge.metadata.AnnotationReader;
public class ContainerProcessorsTest {
@Test
public void test() throws Exception {
ContainerMapField container = new ContainerMapField();
AnnotationReader a1 = new AnnotationReader();
container = a1.readingAnnotationsTo(Dominio.class, container.getClass());
System.out.println(container);
}
}
| src/test/java/net/sf/esfinge/container/processor/Field/ContainerProcessorsTest.java | package net.sf.esfinge.container.processor.Field;
import static org.junit.Assert.*;
import org.junit.Test;
import net.sf.esfinge.metadata.AnnotationReader;
public class ContainerProcessorsTest {
@Test
public void test() throws Exception {
ContainerMapField container = new ContainerMapField();
AnnotationReader a1 = new AnnotationReader();
container = a1.readingAnnotationsTo(Dominio.class, container.getClass());
System.out.println(container);
//assert();
}
}
| Update testes
| src/test/java/net/sf/esfinge/container/processor/Field/ContainerProcessorsTest.java | Update testes | <ide><path>rc/test/java/net/sf/esfinge/container/processor/Field/ContainerProcessorsTest.java
<ide> AnnotationReader a1 = new AnnotationReader();
<ide> container = a1.readingAnnotationsTo(Dominio.class, container.getClass());
<ide> System.out.println(container);
<del> //assert();
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 0cc39bf0efc524bb11f2eaf98dcf17414d6e57ec | 0 | playn/playn,ruslansennov/playn2,tinkerstudent/playn,rachelharvey/playn,longtaoge/playn,thecocce/playn-1,tinkerstudent/playn,playn/playn,thecocce/playn-1,ruslansennov/playn2,playn/playn,longtaoge/playn,rachelharvey/playn | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package playn.html;
import java.util.Map;
import java.util.HashMap;
import com.google.gwt.canvas.dom.client.CanvasGradient;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.DOM;
import pythagoras.f.Point;
import playn.core.Asserts;
import playn.core.CanvasImage;
import playn.core.Font;
import playn.core.Game;
import playn.core.Gradient;
import playn.core.Graphics;
import playn.core.TextFormat;
import playn.core.TextLayout;
import playn.core.gl.GL20;
import playn.core.gl.Scale;
public abstract class HtmlGraphics implements Graphics {
static String cssColorString(int color) {
double a = ((color >> 24) & 0xff) / 255.0;
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 0) & 0xff;
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
private static native void setLoadHandlers(ImageElement img, EventHandler onload,
EventHandler onerror) /*-{
img.onload = function(e) {
[email protected]::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e);
};
img.onerror = function(e) {
[email protected]::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e);
};
}-*/;
protected final CanvasElement dummyCanvas;
protected Element rootElement;
private final Context2d dummyCtx;
private final Point mousePoint = new Point();
private final Element measureElement;
private final Map<Font,HtmlFontMetrics> fontMetrics = new HashMap<Font,HtmlFontMetrics>();
private static final String HEIGHT_TEXT =
"THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGthequickbrownfoxjumpedoverthelazydog";
private static final String EMWIDTH_TEXT = "m";
/**
* Sizes or resizes the root element that contains the PlayN view.
* @param width the new width, in pixels, of the view.
* @param height the new height, in pixels, of the view.
*/
public void setSize(int width, int height) {
rootElement.getStyle().setWidth(width, Unit.PX);
rootElement.getStyle().setHeight(height, Unit.PX);
}
/**
* Registers metrics for the specified font in the specified style and size. This overrides the
* default font metrics calculation (which is hacky and inaccurate). If you want to ensure
* somewhat consistent font layout across browsers, you should register font metrics for every
* combination of font, style and size that you use in your app.
*
* @param lineHeight the height of a line of text in the specified font (in pixels).
*/
public void registerFontMetrics(String name, Font.Style style, float size, float lineHeight) {
HtmlFont font = new HtmlFont(name, style, size);
HtmlFontMetrics metrics = getFontMetrics(font); // get emwidth via default measurement
fontMetrics.put(font, new HtmlFontMetrics(lineHeight, metrics.emwidth));
}
@Override
public CanvasImage createImage(float width, float height) {
return new HtmlCanvasImage(ctx(), new HtmlCanvas(scale().scaledCeil(width),
scale().scaledCeil(height)));
}
@Override
public Gradient createLinearGradient(float x0, float y0, float x1, float y1,
int[] colors, float[] positions) {
Asserts.checkArgument(colors.length == positions.length);
CanvasGradient gradient = dummyCtx.createLinearGradient(x0, y0, x1, y1);
for (int i = 0; i < colors.length; ++i) {
gradient.addColorStop(positions[i], cssColorString(colors[i]));
}
return new HtmlGradient(gradient);
}
@Override
public Gradient createRadialGradient(float x, float y, float r, int[] colors,
float[] positions) {
Asserts.checkArgument(colors.length == positions.length);
CanvasGradient gradient = dummyCtx.createRadialGradient(x, y, 0, x, y, r);
for (int i = 0; i < colors.length; ++i) {
gradient.addColorStop(positions[i], cssColorString(colors[i]));
}
return new HtmlGradient(gradient);
}
@Override
public Font createFont(String name, Font.Style style, float size) {
return new HtmlFont(name, style, size);
}
@Override
public TextLayout layoutText(String text, TextFormat format) {
return new HtmlTextLayout(dummyCtx, text, format);
}
@Override
public int screenHeight() {
return Document.get().getDocumentElement().getClientHeight();
}
@Override
public int screenWidth() {
return Document.get().getDocumentElement().getClientWidth();
}
@Override
public float scaleFactor() {
return 1;
}
@Override
public GL20 gl20() {
throw new UnsupportedOperationException();
}
@Override
public HtmlGLContext ctx() {
return null;
}
protected HtmlGraphics() {
Document doc = Document.get();
dummyCanvas = doc.createCanvasElement();
dummyCtx = dummyCanvas.getContext2d();
rootElement = doc.getElementById("playn-root");
if (rootElement == null) {
rootElement = doc.createDivElement();
rootElement.setAttribute("style", "width: 640px; height: 480px");
doc.getBody().appendChild(rootElement);
} else {
// clear the contents of the "playn-root" element, if present
rootElement.setInnerHTML("");
}
// create a hidden element used to measure font heights
measureElement = doc.createDivElement();
measureElement.getStyle().setVisibility(Style.Visibility.HIDDEN);
measureElement.getStyle().setPosition(Style.Position.ABSOLUTE);
measureElement.getStyle().setTop(-500, Unit.PX);
measureElement.getStyle().setOverflow(Style.Overflow.VISIBLE);
rootElement.appendChild(measureElement);
}
Scale scale() {
HtmlGLContext ctx = ctx();
return (ctx == null) ? Scale.ONE : ctx.scale;
}
HtmlFontMetrics getFontMetrics(Font font) {
HtmlFontMetrics metrics = fontMetrics.get(font);
if (metrics == null) {
// TODO: when Context2d.measureText some day returns a height, nix this hackery
measureElement.getStyle().setFontSize(font.size(), Unit.PX);
measureElement.getStyle().setFontWeight(Style.FontWeight.NORMAL);
measureElement.getStyle().setFontStyle(Style.FontStyle.NORMAL);
measureElement.setInnerText(HEIGHT_TEXT);
switch (font.style()) {
case BOLD:
measureElement.getStyle().setFontWeight(Style.FontWeight.BOLD);
break;
case ITALIC:
measureElement.getStyle().setFontStyle(Style.FontStyle.ITALIC);
break;
default:
break; // nada
}
float height = measureElement.getOffsetHeight();
measureElement.setInnerText(EMWIDTH_TEXT);
float emwidth = measureElement.getOffsetWidth();
metrics = new HtmlFontMetrics(height, emwidth);
fontMetrics.put(font, metrics);
}
return metrics;
}
Point transformMouse(float x, float y) {
return mousePoint.set(x / scale().factor, y / scale().factor);
}
abstract Element rootElement();
abstract void paint(Game game, float paintAlpha);
}
| html/src/playn/html/HtmlGraphics.java | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package playn.html;
import java.util.Map;
import java.util.HashMap;
import com.google.gwt.canvas.dom.client.CanvasGradient;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.DOM;
import pythagoras.f.Point;
import playn.core.Asserts;
import playn.core.CanvasImage;
import playn.core.Font;
import playn.core.Game;
import playn.core.Gradient;
import playn.core.Graphics;
import playn.core.TextFormat;
import playn.core.TextLayout;
import playn.core.gl.GL20;
import playn.core.gl.Scale;
public abstract class HtmlGraphics implements Graphics {
static String cssColorString(int color) {
double a = ((color >> 24) & 0xff) / 255.0;
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 0) & 0xff;
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
private static native void setLoadHandlers(ImageElement img, EventHandler onload,
EventHandler onerror) /*-{
img.onload = function(e) {
[email protected]::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e);
};
img.onerror = function(e) {
[email protected]::handleEvent(Lcom/google/gwt/dom/client/NativeEvent;)(e);
};
}-*/;
protected final CanvasElement dummyCanvas;
protected Element rootElement;
private final Context2d dummyCtx;
private final Point mousePoint = new Point();
private final Element measureElement;
private final Map<Font,HtmlFontMetrics> fontMetrics = new HashMap<Font,HtmlFontMetrics>();
private static final String HEIGHT_TEXT =
"THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGthequickbrownfoxjumpedoverthelazydog";
private static final String EMWIDTH_TEXT = "m";
protected HtmlGraphics() {
Document doc = Document.get();
dummyCanvas = doc.createCanvasElement();
dummyCtx = dummyCanvas.getContext2d();
rootElement = doc.getElementById("playn-root");
if (rootElement == null) {
rootElement = doc.createDivElement();
rootElement.setAttribute("style", "width: 640px; height: 480px");
doc.getBody().appendChild(rootElement);
} else {
// clear the contents of the "playn-root" element, if present
rootElement.setInnerHTML("");
}
// create a hidden element used to measure font heights
measureElement = doc.createDivElement();
measureElement.getStyle().setVisibility(Style.Visibility.HIDDEN);
measureElement.getStyle().setPosition(Style.Position.ABSOLUTE);
measureElement.getStyle().setTop(-500, Unit.PX);
measureElement.getStyle().setOverflow(Style.Overflow.VISIBLE);
rootElement.appendChild(measureElement);
}
/**
* Sizes or resizes the root element that contains the PlayN view.
* @param width the new width, in pixels, of the view.
* @param height the new height, in pixels, of the view.
*/
public void setSize(int width, int height) {
rootElement.getStyle().setWidth(width, Unit.PX);
rootElement.getStyle().setHeight(height, Unit.PX);
}
@Override
public CanvasImage createImage(float width, float height) {
return new HtmlCanvasImage(ctx(), new HtmlCanvas(scale().scaledCeil(width),
scale().scaledCeil(height)));
}
@Override
public Gradient createLinearGradient(float x0, float y0, float x1, float y1,
int[] colors, float[] positions) {
Asserts.checkArgument(colors.length == positions.length);
CanvasGradient gradient = dummyCtx.createLinearGradient(x0, y0, x1, y1);
for (int i = 0; i < colors.length; ++i) {
gradient.addColorStop(positions[i], cssColorString(colors[i]));
}
return new HtmlGradient(gradient);
}
@Override
public Gradient createRadialGradient(float x, float y, float r, int[] colors,
float[] positions) {
Asserts.checkArgument(colors.length == positions.length);
CanvasGradient gradient = dummyCtx.createRadialGradient(x, y, 0, x, y, r);
for (int i = 0; i < colors.length; ++i) {
gradient.addColorStop(positions[i], cssColorString(colors[i]));
}
return new HtmlGradient(gradient);
}
@Override
public Font createFont(String name, Font.Style style, float size) {
return new HtmlFont(name, style, size);
}
@Override
public TextLayout layoutText(String text, TextFormat format) {
return new HtmlTextLayout(dummyCtx, text, format);
}
@Override
public int screenHeight() {
return Document.get().getDocumentElement().getClientHeight();
}
@Override
public int screenWidth() {
return Document.get().getDocumentElement().getClientWidth();
}
@Override
public float scaleFactor() {
return 1;
}
@Override
public GL20 gl20() {
throw new UnsupportedOperationException();
}
@Override
public HtmlGLContext ctx() {
return null;
}
Scale scale() {
HtmlGLContext ctx = ctx();
return (ctx == null) ? Scale.ONE : ctx.scale;
}
HtmlFontMetrics getFontMetrics(Font font) {
HtmlFontMetrics metrics = fontMetrics.get(font);
if (metrics == null) {
// TODO: when Context2d.measureText some day returns a height, nix this hackery
measureElement.getStyle().setFontSize(font.size(), Unit.PX);
measureElement.getStyle().setFontWeight(Style.FontWeight.NORMAL);
measureElement.getStyle().setFontStyle(Style.FontStyle.NORMAL);
measureElement.setInnerText(HEIGHT_TEXT);
switch (font.style()) {
case BOLD:
measureElement.getStyle().setFontWeight(Style.FontWeight.BOLD);
break;
case ITALIC:
measureElement.getStyle().setFontStyle(Style.FontStyle.ITALIC);
break;
default:
break; // nada
}
float height = measureElement.getOffsetHeight();
measureElement.setInnerText(EMWIDTH_TEXT);
float emwidth = measureElement.getOffsetWidth();
metrics = new HtmlFontMetrics(height, emwidth);
fontMetrics.put(font, metrics);
}
return metrics;
}
Point transformMouse(float x, float y) {
return mousePoint.set(x / scale().factor, y / scale().factor);
}
abstract Element rootElement();
abstract void paint(Game game, float paintAlpha);
}
| Added HtmlGraphics.registerFontMetrics for overriding font line height.
Font measurement in HTML5 is a giant hack, and it's not super surprising that
browsers return wildly different values for the height of a line of text. This
allows a game to override the measured values and just use a value that is
consistent and will actually result in sanely rendered text across browsers.
| html/src/playn/html/HtmlGraphics.java | Added HtmlGraphics.registerFontMetrics for overriding font line height. | <ide><path>tml/src/playn/html/HtmlGraphics.java
<ide> "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGthequickbrownfoxjumpedoverthelazydog";
<ide> private static final String EMWIDTH_TEXT = "m";
<ide>
<add> /**
<add> * Sizes or resizes the root element that contains the PlayN view.
<add> * @param width the new width, in pixels, of the view.
<add> * @param height the new height, in pixels, of the view.
<add> */
<add> public void setSize(int width, int height) {
<add> rootElement.getStyle().setWidth(width, Unit.PX);
<add> rootElement.getStyle().setHeight(height, Unit.PX);
<add> }
<add>
<add> /**
<add> * Registers metrics for the specified font in the specified style and size. This overrides the
<add> * default font metrics calculation (which is hacky and inaccurate). If you want to ensure
<add> * somewhat consistent font layout across browsers, you should register font metrics for every
<add> * combination of font, style and size that you use in your app.
<add> *
<add> * @param lineHeight the height of a line of text in the specified font (in pixels).
<add> */
<add> public void registerFontMetrics(String name, Font.Style style, float size, float lineHeight) {
<add> HtmlFont font = new HtmlFont(name, style, size);
<add> HtmlFontMetrics metrics = getFontMetrics(font); // get emwidth via default measurement
<add> fontMetrics.put(font, new HtmlFontMetrics(lineHeight, metrics.emwidth));
<add> }
<add>
<add> @Override
<add> public CanvasImage createImage(float width, float height) {
<add> return new HtmlCanvasImage(ctx(), new HtmlCanvas(scale().scaledCeil(width),
<add> scale().scaledCeil(height)));
<add> }
<add>
<add> @Override
<add> public Gradient createLinearGradient(float x0, float y0, float x1, float y1,
<add> int[] colors, float[] positions) {
<add> Asserts.checkArgument(colors.length == positions.length);
<add>
<add> CanvasGradient gradient = dummyCtx.createLinearGradient(x0, y0, x1, y1);
<add> for (int i = 0; i < colors.length; ++i) {
<add> gradient.addColorStop(positions[i], cssColorString(colors[i]));
<add> }
<add> return new HtmlGradient(gradient);
<add> }
<add>
<add> @Override
<add> public Gradient createRadialGradient(float x, float y, float r, int[] colors,
<add> float[] positions) {
<add> Asserts.checkArgument(colors.length == positions.length);
<add>
<add> CanvasGradient gradient = dummyCtx.createRadialGradient(x, y, 0, x, y, r);
<add> for (int i = 0; i < colors.length; ++i) {
<add> gradient.addColorStop(positions[i], cssColorString(colors[i]));
<add> }
<add> return new HtmlGradient(gradient);
<add> }
<add>
<add> @Override
<add> public Font createFont(String name, Font.Style style, float size) {
<add> return new HtmlFont(name, style, size);
<add> }
<add>
<add> @Override
<add> public TextLayout layoutText(String text, TextFormat format) {
<add> return new HtmlTextLayout(dummyCtx, text, format);
<add> }
<add>
<add> @Override
<add> public int screenHeight() {
<add> return Document.get().getDocumentElement().getClientHeight();
<add> }
<add>
<add> @Override
<add> public int screenWidth() {
<add> return Document.get().getDocumentElement().getClientWidth();
<add> }
<add>
<add> @Override
<add> public float scaleFactor() {
<add> return 1;
<add> }
<add>
<add> @Override
<add> public GL20 gl20() {
<add> throw new UnsupportedOperationException();
<add> }
<add>
<add> @Override
<add> public HtmlGLContext ctx() {
<add> return null;
<add> }
<add>
<ide> protected HtmlGraphics() {
<ide> Document doc = Document.get();
<ide>
<ide> measureElement.getStyle().setTop(-500, Unit.PX);
<ide> measureElement.getStyle().setOverflow(Style.Overflow.VISIBLE);
<ide> rootElement.appendChild(measureElement);
<del> }
<del>
<del> /**
<del> * Sizes or resizes the root element that contains the PlayN view.
<del> * @param width the new width, in pixels, of the view.
<del> * @param height the new height, in pixels, of the view.
<del> */
<del> public void setSize(int width, int height) {
<del> rootElement.getStyle().setWidth(width, Unit.PX);
<del> rootElement.getStyle().setHeight(height, Unit.PX);
<del> }
<del>
<del> @Override
<del> public CanvasImage createImage(float width, float height) {
<del> return new HtmlCanvasImage(ctx(), new HtmlCanvas(scale().scaledCeil(width),
<del> scale().scaledCeil(height)));
<del> }
<del>
<del> @Override
<del> public Gradient createLinearGradient(float x0, float y0, float x1, float y1,
<del> int[] colors, float[] positions) {
<del> Asserts.checkArgument(colors.length == positions.length);
<del>
<del> CanvasGradient gradient = dummyCtx.createLinearGradient(x0, y0, x1, y1);
<del> for (int i = 0; i < colors.length; ++i) {
<del> gradient.addColorStop(positions[i], cssColorString(colors[i]));
<del> }
<del> return new HtmlGradient(gradient);
<del> }
<del>
<del> @Override
<del> public Gradient createRadialGradient(float x, float y, float r, int[] colors,
<del> float[] positions) {
<del> Asserts.checkArgument(colors.length == positions.length);
<del>
<del> CanvasGradient gradient = dummyCtx.createRadialGradient(x, y, 0, x, y, r);
<del> for (int i = 0; i < colors.length; ++i) {
<del> gradient.addColorStop(positions[i], cssColorString(colors[i]));
<del> }
<del> return new HtmlGradient(gradient);
<del> }
<del>
<del> @Override
<del> public Font createFont(String name, Font.Style style, float size) {
<del> return new HtmlFont(name, style, size);
<del> }
<del>
<del> @Override
<del> public TextLayout layoutText(String text, TextFormat format) {
<del> return new HtmlTextLayout(dummyCtx, text, format);
<del> }
<del>
<del> @Override
<del> public int screenHeight() {
<del> return Document.get().getDocumentElement().getClientHeight();
<del> }
<del>
<del> @Override
<del> public int screenWidth() {
<del> return Document.get().getDocumentElement().getClientWidth();
<del> }
<del>
<del> @Override
<del> public float scaleFactor() {
<del> return 1;
<del> }
<del>
<del> @Override
<del> public GL20 gl20() {
<del> throw new UnsupportedOperationException();
<del> }
<del>
<del> @Override
<del> public HtmlGLContext ctx() {
<del> return null;
<ide> }
<ide>
<ide> Scale scale() { |
|
Java | mit | 4ba93ab673a3446d325d31fcf6048c11669bc9a0 | 0 | arjanvlek/cyanogen-update-tracker-app | package com.arjanvlek.cyngnotainfo;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.arjanvlek.cyngnotainfo.Model.DeviceTypeEntity;
import com.arjanvlek.cyngnotainfo.Support.ServerConnector;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.List;
/**
* Part of Cyanogen Update Tracker.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
extras.putBoolean("Send error", true);
sendNotification(extras);
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
extras.putBoolean("deleted", true);
sendNotification(extras);
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
sendNotification(extras);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(Bundle msg) {
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
String message = null;
if(msg!= null) {
System.out.println(msg.getString("version_number"));
if(msg.getString("version_number") != null) {
String deviceName = getDeviceName(msg.getString("tracking_device_type_id"));
if(deviceName != null) {
message = "Version " + msg.getString("version_number") + " is now available for your " + deviceName + "!";
}
}
else if (msg.getLong("new_device_id", 0) != 0 ) {
String deviceName = getDeviceName(msg.getString("new_device_id"));
if(deviceName != null) {
message = "A new Cyanogen device can now be tracked: the " + deviceName + "!";
}
}
}
long[] vibrationPattern = new long[2];
vibrationPattern[0] = 100L;
vibrationPattern[1] = 100L;
if(message != null) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setVibrate(vibrationPattern)
.setAutoCancel(true)
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
private String getDeviceName(String deviceId) {
Long deviceIdLong;
try {
deviceIdLong = Long.parseLong(deviceId);
}
catch (NumberFormatException ignored) {
return null;
}
String deviceName = null;
ServerConnector serverConnector = new ServerConnector();
List<DeviceTypeEntity> deviceTypeEntityList = serverConnector.getDeviceTypeEntities();
for (DeviceTypeEntity deviceTypeEntity : deviceTypeEntityList) {
if(deviceTypeEntity.getId() == deviceIdLong) {
deviceName = deviceTypeEntity.getDeviceType();
}
}
return deviceName;
}
} | src/main/java/com/arjanvlek/cyngnotainfo/GcmIntentService.java | package com.arjanvlek.cyngnotainfo;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.arjanvlek.cyngnotainfo.Model.DeviceTypeEntity;
import com.arjanvlek.cyngnotainfo.Support.ServerConnector;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.List;
/**
* Part of Cyanogen Update Tracker.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
extras.putBoolean("Send error", true);
sendNotification(extras);
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
extras.putBoolean("deleted", true);
sendNotification(extras);
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
sendNotification(extras);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(Bundle msg) {
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
String message = null;
if(msg!= null) {
System.out.println(msg.getString("version_number"));
if(msg.getString("version_number") != null) {
String deviceName = getDeviceName(msg.getString("tracking_device_type_id"));
if(deviceName != null) {
message = "Version " + msg.getString("version_number") + " is now available for your " + deviceName + "!";
}
}
else if (msg.getLong("new_device_id", 0) != 0 ) {
String deviceName = getDeviceName(msg.getString("new_device_id"));
if(deviceName != null) {
message = "A new Cyanogen device can now be tracked: the " + deviceName + "!";
}
}
}
long[] vibrationPattern = new long[2];
vibrationPattern[0] = 100L;
vibrationPattern[1] = 100L;
if(message != null) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setVibrate(vibrationPattern)
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
private String getDeviceName(String deviceId) {
Long deviceIdLong;
try {
deviceIdLong = Long.parseLong(deviceId);
}
catch (NumberFormatException ignored) {
return null;
}
String deviceName = null;
ServerConnector serverConnector = new ServerConnector();
List<DeviceTypeEntity> deviceTypeEntityList = serverConnector.getDeviceTypeEntities();
for (DeviceTypeEntity deviceTypeEntity : deviceTypeEntityList) {
if(deviceTypeEntity.getId() == deviceIdLong) {
deviceName = deviceTypeEntity.getDeviceType();
}
}
return deviceName;
}
} | notification will now close when clicked
| src/main/java/com/arjanvlek/cyngnotainfo/GcmIntentService.java | notification will now close when clicked | <ide><path>rc/main/java/com/arjanvlek/cyngnotainfo/GcmIntentService.java
<ide> .setStyle(new NotificationCompat.BigTextStyle()
<ide> .bigText(message))
<ide> .setVibrate(vibrationPattern)
<add> .setAutoCancel(true)
<ide> .setContentText(message);
<ide>
<ide> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.