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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript | agpl-3.0 | 54bafd684d538eeb972db0971feb9d09f7daa82d | 0 | mvdstruijk/flamingo,B3Partners/flamingo,B3Partners/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo | /*
* Copyright (C) 2012-2013 B3Partners B.V.
*
* This program 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Edit component
* @author <a href="mailto:[email protected]">Meine Toonen</a>
*/
Ext.define ("viewer.components.Edit",{
extend: "viewer.components.Component",
vectorLayer:null,
inputContainer:null,
showGeomType:null,
newGeomType:null,
mode:null,
layerSelector:null,
toolMapClick:null,
editingLayer: null,
currentFID:null,
geometryEditable:null,
deActivatedTools: [],
config:{
title: "",
iconUrl: "",
tooltip: "",
layers:null,
label: ""
},
constructor: function (conf){
viewer.components.Edit.superclass.constructor.call(this, conf);
this.initConfig(conf);
var me = this;
Ext.util.Observable.capture(this.viewerController.mapComponent.getMap(), function(event) {
if(event == viewer.viewercontroller.controller.Event.ON_GET_FEATURE_INFO
|| event == viewer.viewercontroller.controller.Event.ON_MAPTIP) {
if(me.mode == "new" || me.mode == "edit") {
return false;
}
}
return true;
});
if (this.layers!=null){
this.layers = Ext.Array.filter(this.layers, function(layerId) {
// XXX must check editAuthorized in appLayer
// cannot get that from this layerId
return true;
});
}
this.renderButton({
handler: function(){
me.showWindow();
},
text: me.title,
icon: me.iconUrl,
tooltip: me.tooltip,
label: me.label
});
this.toolMapClick = this.viewerController.mapComponent.createTool({
type: viewer.viewercontroller.controller.Tool.MAP_CLICK,
id: this.name + "toolMapClick",
handler:{
fn: this.mapClicked,
scope:this
},
viewerController: this.viewerController
});
this.loadWindow();
this.viewerController.addListener(viewer.viewercontroller.controller.Event.ON_SELECTEDCONTENT_CHANGE,this.selectedContentChanged,this );
return this;
},
selectedContentChanged : function (){
if(this.vectorLayer == null){
this.createVectorLayer();
}else{
this.viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
}
},
createVectorLayer : function (){
this.vectorLayer=this.viewerController.mapComponent.createVectorLayer({
name: this.name + 'VectorLayer',
geometrytypes:["Circle","Polygon","MultiPolygon","Point", "LineString"],
showmeasures:false,
viewerController : this.viewerController,
style: {
fillcolor: "FF0000",
fillopacity: 50,
strokecolor: "FF0000",
strokeopacity: 50
}
});
this.viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
},
showWindow : function(){
if(this.vectorLayer == null){
this.createVectorLayer();
}
this.layerSelector.initLayers();
this.popup.popupWin.setTitle(this.title);
this.popup.show();
},
loadWindow : function (){
var me =this;
this.maincontainer = Ext.create('Ext.container.Container', {
id: this.name + 'Container',
width: '100%',
height: '100%',
autoScroll: true,
layout: {
type: 'vbox'
},
style: {
backgroundColor: 'White'
},
renderTo: this.getContentDiv(),
items: [{
id: this.name + 'LayerSelectorPanel',
xtype: "container",
padding: "4px",
width: '100%',
height: 36
},
{
id: this.name + 'ButtonPanel',
xtype: "container",
padding: "4px",
width: '280px',
height: MobileManager.isMobile() ? 60 : 36,
items:[
{
xtype: 'button',
id: this.name +"newButton",
disabled: true,
tooltip: "Nieuw",
text: "Nieuw",
componentCls: 'mobileLarge',
listeners: {
click:{
scope: me,
fn: me.createNew
}
}
},
{
xtype: 'button',
id : this.name + "editButton",
tooltip: "Bewerk",
componentCls: 'mobileLarge',
disabled: true,
text: "Bewerk",
listeners: {
click:{
scope: me,
fn: me.edit
}
}
},
{
id : this.name + "geomLabel",
margin: 5,
text: '',
xtype: "label"
}
]
},
{
id: this.name + 'InputPanel',
border: 0,
xtype: "form",
autoScroll: true,
width: '100%',
flex: 1
},{
id: this.name + 'savePanel',
xtype: "container",
width: '100%',
height: MobileManager.isMobile() ? 45 : 30,
layout: {
type: 'hbox',
pack: 'end'
},
defaults: {
xtype: 'button',
componentCls: 'mobileLarge'
},
items:[
{
id : this.name + "cancelButton",
tooltip: "Annuleren",
text: "Annuleren",
listeners: {
click:{
scope: me,
fn: me.cancel
}
}
},
{
id : this.name + "saveButton",
tooltip: "Opslaan",
text: "Opslaan",
listeners: {
click:{
scope: me,
fn: me.save
}
}
}
]
}
]
});
this.inputContainer = Ext.getCmp(this.name + 'InputPanel');
this.createLayerSelector();
},
createLayerSelector: function(){
var config = {
viewerController : this.viewerController,
restriction : "editable",
id : this.name + "layerSelector",
layers: this.layers,
div: this.name + 'LayerSelectorPanel'
};
this.layerSelector = Ext.create("viewer.components.LayerSelector",config);
this.layerSelector.addListener(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE,this.layerChanged,this);
},
layerChanged : function (appLayer,afterLoadAttributes,scope){
if(appLayer != null){
this.vectorLayer.removeAllFeatures();
this.mode=null;
this.viewerController.mapComponent.getMap().removeMarker("edit");
if(appLayer.details && appLayer.details["editfunction.title"]){
this.popup.popupWin.setTitle(appLayer.details["editfunction.title"]);
}
this.inputContainer.setLoading("Laad attributen...");
this.inputContainer.removeAll();
this.loadAttributes(appLayer,afterLoadAttributes,scope);
this.inputContainer.setLoading(false);
}else{
this.cancel();
}
},
loadAttributes: function(appLayer,afterLoadAttributes,scope) {
this.appLayer = appLayer;
var me = this;
if (scope==undefined){
scope=me;
}
if(this.appLayer != null) {
this.featureService = this.viewerController.getAppLayerFeatureService(this.appLayer);
// check if featuretype was loaded
if(this.appLayer.attributes == undefined) {
this.featureService.loadAttributes(me.appLayer, function(attributes) {
me.initAttributeInputs(me.appLayer);
if (afterLoadAttributes){
afterLoadAttributes.call(scope);
}
});
} else {
this.initAttributeInputs(me.appLayer);
if (afterLoadAttributes){
afterLoadAttributes.call(scope);
}
}
}
},
initAttributeInputs : function (appLayer){
var attributes = appLayer.attributes;
var type = "geometry";
if(appLayer.geometryAttributeIndex != undefined || appLayer.geometryAttributeIndex != null ){
var geomAttribute = appLayer.attributes[appLayer.geometryAttributeIndex];
if(geomAttribute.editValues != undefined && geomAttribute.editValues !=null && geomAttribute.editValues.length >= 1){
type = geomAttribute.editValues[0]
}else{
type = geomAttribute.type;
}
this.geometryEditable = appLayer.attributes[appLayer.geometryAttributeIndex].editable;
}else{
this.geometryEditable = false;
}
this.showGeomType = type;
var possible = true;
var tekst = "";
switch(type){
case "multipolygon":
this.showGeomType = "MultiPolygon";
this.newGeomType = "Polygon";
tekst = "vlak";
break;
case "polygon":
this.showGeomType = "Polygon";
this.newGeomType = "Polygon";
tekst = "vlak";
break;
case "multipoint":
case "point":
this.showGeomType = "Point";
this.newGeomType = "Point";
tekst = "punt";
break;
case "multilinestring":
case "linestring":
this.showGeomType = "LineString";
this.newGeomType = "LineString";
tekst = "lijn";
break;
case "geometry":
possible = true;
this.newGeomType = null;
break;
default:
this.newGeomType = null;
possible = false;
break;
}
var gl = Ext.getCmp( this.name +"geomLabel");
if(possible){
if(this.geometryEditable){
Ext.getCmp(this.name +"editButton").setDisabled(false);
if(this.newGeomType == null){
tekst = "Geometrie mag alleen bewerkt worden";
}else{
Ext.getCmp(this.name +"newButton").setDisabled(false);
tekst = 'Bewerk een ' + tekst+ " op de kaart";
}
}else{
tekst = 'Geometrie mag niet bewerkt worden.';
}
gl.setText(tekst);
for(var i= 0 ; i < attributes.length ;i++){
var attribute = attributes[i];
if(attribute.editable){
var allowedEditable = this.allowedEditable(attribute);
var values = Ext.clone(attribute.editValues);
var input = null;
if(i == appLayer.geometryAttributeIndex){
continue;
}
if(values == undefined || values.length == 1){
var fieldText = "";
if(values!= undefined){
fieldText = values[0];
}
var options={
name: attribute.name,
fieldLabel: attribute.editAlias || attribute.name,
renderTo: this.name + 'InputPanel',
value: fieldText,
disabled: !allowedEditable
};
if (attribute.editHeight){
options.rows = attribute.editHeight;
input = Ext.create("Ext.form.field.TextArea",options)
}else{
input = Ext.create("Ext.form.field.Text",options);
}
}else if (values.length > 1){
var allBoolean=true;
for (var v=0; v < values.length; v++){
if (values[v].toLowerCase()!=="true" && values[v].toLowerCase()!=="false"){
allBoolean =false;
break;
}
}
Ext.each(values,function(value,index,original){
if (allBoolean){
value= value.toLowerCase() ==="true";
}
original[index] = {
id: value
};
});
var valueStore = Ext.create('Ext.data.Store', {
fields: ['id'],
data : values
});
input = Ext.create('viewer.components.FlamingoCombobox', {
fieldLabel: attribute.editAlias || attribute.name,
store: valueStore,
queryMode: 'local',
displayField: 'id',
name:attribute.name,
renderTo: this.name + 'InputPanel',
valueField: 'id',
disabled: !allowedEditable
});
}
this.inputContainer.add(input);
}
}
}else{
gl.setText("Geometrietype onbekend. Bewerken niet mogelijk.");
Ext.getCmp(this.name +"editButton").setDisabled(true);
Ext.getCmp(this.name +"newButton").setDisabled(true);
}
},
setInputPanel : function (feature){
this.inputContainer.getForm().setValues(feature);
},
mapClicked : function (toolMapClick,comp){
this.deactivateMapClick();
Ext.get(this.getContentDiv()).mask("Haalt features op...")
var coords = comp.coord;
var x = coords.x;
var y = coords.y;
var layer = this.layerSelector.getValue();
this.viewerController.mapComponent.getMap().setMarker("edit",x,y);
var featureInfo = Ext.create("viewer.FeatureInfo", {
viewerController: this.viewerController
});
var me =this;
featureInfo.editFeatureInfo(x,y,this.viewerController.mapComponent.getMap().getResolution() * 4,layer, function (features){
me.featuresReceived(features);
},function(msg){
me.failed(msg);});
},
featuresReceived : function (features){
if(features.length == 1){
var feat = this.indexFeatureToNamedFeature(features[0]);
this.handleFeature(feat);
}else if(features.length == 0){
this.handleFeature(null);
} else{
// Handel meerdere features af.
this.createFeaturesGrid(features);
}
},
handleFeature : function (feature){
if(feature != null){
this.inputContainer.getForm().setValues(feature);
this.currentFID = feature.__fid;
if(this.geometryEditable){
var wkt = feature[this.appLayer.geometryAttribute];
var feat = Ext.create("viewer.viewercontroller.controller.Feature",{
wktgeom: wkt,
id: "T_0"
});
this.vectorLayer.addFeature(feat);
}
}
Ext.get(this.getContentDiv()).unmask()
},
failed : function (msg){
Ext.Msg.alert('Mislukt',msg);
Ext.get(this.getContentDiv()).unmask()
},
createNew : function(){
this.vectorLayer.removeAllFeatures();
this.inputContainer.getForm().reset()
this.viewerController.mapComponent.getMap().removeMarker("edit");
this.mode = "new";
if(this.newGeomType != null && this.geometryEditable){
this.vectorLayer.drawFeature(this.newGeomType);
}
},
edit : function(){
this.vectorLayer.removeAllFeatures();
this.mode = "edit";
this.activateMapClick();
},
activateMapClick: function(){
this.deActivatedTools = this.viewerController.mapComponent.deactivateTools();
this.toolMapClick.activateTool();
},
deactivateMapClick: function(){
for (var i=0; i < this.deActivatedTools.length; i++){
this.deActivatedTools[i].activate();
}
this.deActivatedTools = [];
this.toolMapClick.deactivateTool();
},
save : function(){
var feature =this.inputContainer.getValues();
if(this.geometryEditable){
var wkt = this.vectorLayer.getActiveFeature().wktgeom;
feature[this.appLayer.geometryAttribute] = wkt;
}
if(this.mode == "edit"){
feature.__fid = this.currentFID;
}
try{
feature = this.changeFeatureBeforeSave(feature);
}catch(e){
this.failed(e);
return;
}
var me = this;
me.editingLayer = this.viewerController.getLayer(this.layerSelector.getValue());
Ext.create("viewer.EditFeature", {
viewerController: this.viewerController
})
.edit(
me.editingLayer,
feature,
function(fid) { me.saveSucces(fid); },
this.failed);
},
/**
* Can be overwritten to add some extra feature attributes before saving the
* feature.
* @return the changed feature
*/
changeFeatureBeforeSave: function(feature){
return feature;
},
/**
* Can be overwritten to disable editing in the component/js
*/
allowedEditable: function (attribute){
return true;
},
saveSucces : function (fid){
this.editingLayer.reload();
this.currentFID = fid;
Ext.Msg.alert('Gelukt',"Het feature is aangepast.");
this.cancel();
},
saveFailed : function (msg){
Ext.Msg.alert('Mislukt',msg);
},
cancel : function (){
this.resetForm();
this.popup.hide();
},
resetForm : function (){
Ext.getCmp(this.name +"editButton").setDisabled(true);
Ext.getCmp(this.name +"newButton").setDisabled(true);
this.mode=null;
this.layerSelector.combobox.select(null);
Ext.getCmp( this.name +"geomLabel").setText("");
this.inputContainer.removeAll();
this.viewerController.mapComponent.getMap().removeMarker("edit");
this.vectorLayer.removeAllFeatures();
},
getExtComponents: function() {
return [ this.maincontainer.getId() ];
},
createFeaturesGrid : function (features){
var appLayer = this.layerSelector.getSelectedAppLayer();
var attributes = appLayer.attributes;
var index = 0;
var attributeList = new Array();
var columns = new Array();
for(var i= 0 ; i < attributes.length ;i++){
var attribute = attributes[i];
if(attribute.editable){
var attIndex = index++;
if(i == appLayer.geometryAttributeIndex){
continue;
}
var colName = attribute.alias != undefined ? attribute.alias : attribute.name;
attributeList.push({
name: "c" + attIndex,
type : 'string'
});
columns.push({
id: "c" +attIndex,
text:colName,
dataIndex: "c" + attIndex,
flex: 1,
filter: {
xtype: 'textfield'
}
});
}
}
Ext.define(this.name + 'Model', {
extend: 'Ext.data.Model',
fields: attributeList
});
var store = Ext.create('Ext.data.Store', {
pageSize: 10,
model: this.name + 'Model',
data:features
});
var me =this;
var grid = Ext.create('Ext.grid.Panel', {
id: this.name + 'GridFeaturesWindow',
store: store,
columns: columns,
listeners:{
itemdblclick:{
scope: me,
fn: me.itemDoubleClick
}
}
});
var container = Ext.create("Ext.container.Container",{
id: this.name + "GridContainerFeaturesWindow",
width: "100%",
height: "100%",
layout: {
type: 'vbox',
align: 'stretch'
},
items:[
{
id: this.name + 'GridPanelFeaturesWindow',
xtype: "container",
autoScroll: true,
width: '100%',
flex: 1,
items:[grid]
},{
id: this.name + 'ButtonPanelFeaturesWindow',
xtype: "container",
width: '100%',
height: 30,
items:[{
xtype: "button",
id: this.name + "SelectFeatureButtonFeaturesWindow",
text: "Bewerk geselecteerd feature",
listeners: {
click:{
scope: me,
fn: me.selectFeature
}
}
},
{
xtype: "button",
id: this.name + "CancelFeatureButtonFeaturesWindow",
text: "Annuleren",
listeners: {
click:{
scope: me,
fn: me.cancelSelectFeature
}
}
}]
}
]
});
var window = Ext.create("Ext.window.Window",{
id: this.name + "FeaturesWindow",
width: 500,
height: 300,
layout: 'fit',
title: "Kies één feature",
items: [container]
});
window.show();
},
itemDoubleClick : function (gridview,row){
this.featuresReceived ([row.data]);
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
selectFeature :function() {
var grid = Ext.getCmp(this.name + 'GridFeaturesWindow');
var selection = grid.getSelectionModel().getSelection()[0];
var feature = selection.data;
this.featuresReceived ([feature]);
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
cancelSelectFeature : function (){
this.resetForm();
Ext.get(this.getContentDiv()).unmask()
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
indexFeatureToNamedFeature : function (feature){
var map = this.makeConversionMap();
var newFeature = {};
for (var key in feature){
var namedIndex = map[key];
var value = feature[key];
if(namedIndex != undefined){
newFeature[namedIndex] = value;
}else{
newFeature[key] = value;
}
}
return newFeature;
},
makeConversionMap : function (){
var appLayer = this.layerSelector.getSelectedAppLayer();
var attributes = appLayer.attributes;
var map = {};
var index = 0;
for (var i = 0 ; i < attributes.length ;i++){
if(attributes[i].editable){
map["c"+index] = attributes[i].name;
index++;
}
}
return map;
}
});
| viewer/src/main/webapp/viewer-html/components/Edit.js | /*
* Copyright (C) 2012-2013 B3Partners B.V.
*
* This program 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Edit component
* @author <a href="mailto:[email protected]">Meine Toonen</a>
*/
Ext.define ("viewer.components.Edit",{
extend: "viewer.components.Component",
vectorLayer:null,
inputContainer:null,
showGeomType:null,
newGeomType:null,
mode:null,
layerSelector:null,
toolMapClick:null,
editingLayer: null,
currentFID:null,
geometryEditable:null,
deActivatedTools: [],
config:{
title: "",
iconUrl: "",
tooltip: "",
layers:null,
label: ""
},
constructor: function (conf){
viewer.components.Edit.superclass.constructor.call(this, conf);
this.initConfig(conf);
var me = this;
Ext.util.Observable.capture(this.viewerController.mapComponent.getMap(), function(event) {
if(event == viewer.viewercontroller.controller.Event.ON_GET_FEATURE_INFO
|| event == viewer.viewercontroller.controller.Event.ON_MAPTIP) {
if(me.mode == "new" || me.mode == "edit") {
return false;
}
}
return true;
});
if (this.layers!=null){
this.layers = Ext.Array.filter(this.layers, function(layerId) {
// XXX must check editAuthorized in appLayer
// cannot get that from this layerId
return true;
});
}
this.renderButton({
handler: function(){
me.showWindow();
},
text: me.title,
icon: me.iconUrl,
tooltip: me.tooltip,
label: me.label
});
this.toolMapClick = this.viewerController.mapComponent.createTool({
type: viewer.viewercontroller.controller.Tool.MAP_CLICK,
id: this.name + "toolMapClick",
handler:{
fn: this.mapClicked,
scope:this
},
viewerController: this.viewerController
});
this.loadWindow();
this.viewerController.addListener(viewer.viewercontroller.controller.Event.ON_SELECTEDCONTENT_CHANGE,this.selectedContentChanged,this );
return this;
},
selectedContentChanged : function (){
if(this.vectorLayer == null){
this.createVectorLayer();
}else{
this.viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
}
},
createVectorLayer : function (){
this.vectorLayer=this.viewerController.mapComponent.createVectorLayer({
name: this.name + 'VectorLayer',
geometrytypes:["Circle","Polygon","MultiPolygon","Point", "LineString"],
showmeasures:false,
viewerController : this.viewerController,
style: {
fillcolor: "FF0000",
fillopacity: 50,
strokecolor: "FF0000",
strokeopacity: 50
}
});
this.viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
},
showWindow : function(){
if(this.vectorLayer == null){
this.createVectorLayer();
}
this.layerSelector.initLayers();
this.popup.popupWin.setTitle(this.title);
this.popup.show();
},
loadWindow : function (){
var me =this;
this.maincontainer = Ext.create('Ext.container.Container', {
id: this.name + 'Container',
width: '100%',
height: '100%',
autoScroll: true,
layout: {
type: 'vbox'
},
style: {
backgroundColor: 'White'
},
renderTo: this.getContentDiv(),
items: [{
id: this.name + 'LayerSelectorPanel',
xtype: "container",
padding: "4px",
width: '100%',
height: 36
},
{
id: this.name + 'ButtonPanel',
xtype: "container",
padding: "4px",
width: '280px',
height: MobileManager.isMobile() ? 60 : 36,
items:[
{
xtype: 'button',
id: this.name +"newButton",
disabled: true,
tooltip: "Nieuw",
text: "Nieuw",
componentCls: 'mobileLarge',
listeners: {
click:{
scope: me,
fn: me.createNew
}
}
},
{
xtype: 'button',
id : this.name + "editButton",
tooltip: "Bewerk",
componentCls: 'mobileLarge',
disabled: true,
text: "Bewerk",
listeners: {
click:{
scope: me,
fn: me.edit
}
}
},
{
id : this.name + "geomLabel",
margin: 5,
text: '',
xtype: "label"
}
]
},
{
id: this.name + 'InputPanel',
border: 0,
xtype: "form",
autoScroll: true,
width: '100%',
flex: 1
},{
id: this.name + 'savePanel',
xtype: "container",
width: '100%',
height: MobileManager.isMobile() ? 45 : 30,
layout: {
type: 'hbox',
pack: 'end'
},
defaults: {
xtype: 'button',
componentCls: 'mobileLarge'
},
items:[
{
id : this.name + "cancelButton",
tooltip: "Annuleren",
text: "Annuleren",
listeners: {
click:{
scope: me,
fn: me.cancel
}
}
},
{
id : this.name + "saveButton",
tooltip: "Opslaan",
text: "Opslaan",
listeners: {
click:{
scope: me,
fn: me.save
}
}
}
]
}
]
});
this.inputContainer = Ext.getCmp(this.name + 'InputPanel');
this.createLayerSelector();
},
createLayerSelector: function(){
var config = {
viewerController : this.viewerController,
restriction : "editable",
id : this.name + "layerSelector",
layers: this.layers,
div: this.name + 'LayerSelectorPanel'
};
this.layerSelector = Ext.create("viewer.components.LayerSelector",config);
this.layerSelector.addListener(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE,this.layerChanged,this);
},
layerChanged : function (appLayer,afterLoadAttributes,scope){
if(appLayer != null){
this.vectorLayer.removeAllFeatures();
this.mode=null;
this.viewerController.mapComponent.getMap().removeMarker("edit");
if(appLayer.details && appLayer.details["editfunction.title"]){
this.popup.popupWin.setTitle(appLayer.details["editfunction.title"]);
}
this.inputContainer.setLoading("Laad attributen...");
this.inputContainer.removeAll();
this.loadAttributes(appLayer,afterLoadAttributes,scope);
this.inputContainer.setLoading(false);
}else{
this.cancel();
}
},
loadAttributes: function(appLayer,afterLoadAttributes,scope) {
this.appLayer = appLayer;
var me = this;
if (scope==undefined){
scope=me;
}
if(this.appLayer != null) {
this.featureService = this.viewerController.getAppLayerFeatureService(this.appLayer);
// check if featuretype was loaded
if(this.appLayer.attributes == undefined) {
this.featureService.loadAttributes(me.appLayer, function(attributes) {
me.initAttributeInputs(me.appLayer);
if (afterLoadAttributes){
afterLoadAttributes.call(scope);
}
});
} else {
this.initAttributeInputs(me.appLayer);
if (afterLoadAttributes){
afterLoadAttributes.call(scope);
}
}
}
},
initAttributeInputs : function (appLayer){
var attributes = appLayer.attributes;
var type = "geometry";
if(appLayer.geometryAttributeIndex != undefined || appLayer.geometryAttributeIndex != null ){
var geomAttribute = appLayer.attributes[appLayer.geometryAttributeIndex];
if(geomAttribute.editValues != undefined && geomAttribute.editValues !=null && geomAttribute.editValues.length >= 1){
type = geomAttribute.editValues[0]
}else{
type = geomAttribute.type;
}
this.geometryEditable = appLayer.attributes[appLayer.geometryAttributeIndex].editable;
}else{
this.geometryEditable = false;
}
this.showGeomType = type;
var possible = true;
var tekst = "";
switch(type){
case "multipolygon":
this.showGeomType = "MultiPolygon";
this.newGeomType = "Polygon";
tekst = "vlak";
break;
case "polygon":
this.showGeomType = "Polygon";
this.newGeomType = "Polygon";
tekst = "vlak";
break;
case "multipoint":
case "point":
this.showGeomType = "Point";
this.newGeomType = "Point";
tekst = "punt";
break;
case "multilinestring":
case "linestring":
this.showGeomType = "LineString";
this.newGeomType = "LineString";
tekst = "lijn";
break;
case "geometry":
possible = true;
this.newGeomType = null;
break;
default:
this.newGeomType = null;
possible = false;
break;
}
var gl = Ext.getCmp( this.name +"geomLabel");
if(possible){
if(this.geometryEditable){
Ext.getCmp(this.name +"editButton").setDisabled(false);
if(this.newGeomType == null){
tekst = "Geometrie mag alleen bewerkt worden";
}else{
Ext.getCmp(this.name +"newButton").setDisabled(false);
tekst = 'Bewerk een ' + tekst+ " op de kaart";
}
}else{
tekst = 'Geometrie mag niet bewerkt worden.';
}
gl.setText(tekst);
for(var i= 0 ; i < attributes.length ;i++){
var attribute = attributes[i];
if(attribute.editable){
var allowedEditable = this.allowedEditable(attribute);
var values = Ext.clone(attribute.editValues);
var input = null;
if(i == appLayer.geometryAttributeIndex){
continue;
}
if(values == undefined || values.length == 1){
var fieldText = "";
if(values!= undefined){
fieldText = values[0];
}
var options={
name: attribute.name,
fieldLabel: attribute.editAlias || attribute.name,
renderTo: this.name + 'InputPanel',
value: fieldText,
disabled: !allowedEditable
};
if (attribute.editHeight){
options.rows = attribute.editHeight;
input = Ext.create("Ext.form.field.TextArea",options)
}else{
input = Ext.create("Ext.form.field.Text",options);
}
}else if (values.length > 1){
Ext.each(values,function(value,index,original){
original[index] = {
id: value
};
});
var valueStore = Ext.create('Ext.data.Store', {
fields: ['id'],
data : values
});
input = Ext.create('viewer.components.FlamingoCombobox', {
fieldLabel: attribute.editAlias || attribute.name,
store: valueStore,
queryMode: 'local',
displayField: 'id',
name:attribute.name,
renderTo: this.name + 'InputPanel',
valueField: 'id',
disabled: !allowedEditable
});
}
this.inputContainer.add(input);
}
}
}else{
gl.setText("Geometrietype onbekend. Bewerken niet mogelijk.");
Ext.getCmp(this.name +"editButton").setDisabled(true);
Ext.getCmp(this.name +"newButton").setDisabled(true);
}
},
setInputPanel : function (feature){
this.inputContainer.getForm().setValues(feature);
},
mapClicked : function (toolMapClick,comp){
this.deactivateMapClick();
Ext.get(this.getContentDiv()).mask("Haalt features op...")
var coords = comp.coord;
var x = coords.x;
var y = coords.y;
var layer = this.layerSelector.getValue();
this.viewerController.mapComponent.getMap().setMarker("edit",x,y);
var featureInfo = Ext.create("viewer.FeatureInfo", {
viewerController: this.viewerController
});
var me =this;
featureInfo.editFeatureInfo(x,y,this.viewerController.mapComponent.getMap().getResolution() * 4,layer, function (features){
me.featuresReceived(features);
},function(msg){
me.failed(msg);});
},
featuresReceived : function (features){
if(features.length == 1){
var feat = this.indexFeatureToNamedFeature(features[0]);
this.handleFeature(feat);
}else if(features.length == 0){
this.handleFeature(null);
} else{
// Handel meerdere features af.
this.createFeaturesGrid(features);
}
},
handleFeature : function (feature){
if(feature != null){
this.inputContainer.getForm().setValues(feature);
this.currentFID = feature.__fid;
if(this.geometryEditable){
var wkt = feature[this.appLayer.geometryAttribute];
var feat = Ext.create("viewer.viewercontroller.controller.Feature",{
wktgeom: wkt,
id: "T_0"
});
this.vectorLayer.addFeature(feat);
}
}
Ext.get(this.getContentDiv()).unmask()
},
failed : function (msg){
Ext.Msg.alert('Mislukt',msg);
Ext.get(this.getContentDiv()).unmask()
},
createNew : function(){
this.vectorLayer.removeAllFeatures();
this.inputContainer.getForm().reset()
this.viewerController.mapComponent.getMap().removeMarker("edit");
this.mode = "new";
if(this.newGeomType != null && this.geometryEditable){
this.vectorLayer.drawFeature(this.newGeomType);
}
},
edit : function(){
this.vectorLayer.removeAllFeatures();
this.mode = "edit";
this.activateMapClick();
},
activateMapClick: function(){
this.deActivatedTools = this.viewerController.mapComponent.deactivateTools();
this.toolMapClick.activateTool();
},
deactivateMapClick: function(){
for (var i=0; i < this.deActivatedTools.length; i++){
this.deActivatedTools[i].activate();
}
this.deActivatedTools = [];
this.toolMapClick.deactivateTool();
},
save : function(){
var feature =this.inputContainer.getValues();
if(this.geometryEditable){
var wkt = this.vectorLayer.getActiveFeature().wktgeom;
feature[this.appLayer.geometryAttribute] = wkt;
}
if(this.mode == "edit"){
feature.__fid = this.currentFID;
}
try{
feature = this.changeFeatureBeforeSave(feature);
}catch(e){
this.failed(e);
return;
}
var me = this;
me.editingLayer = this.viewerController.getLayer(this.layerSelector.getValue());
Ext.create("viewer.EditFeature", {
viewerController: this.viewerController
})
.edit(
me.editingLayer,
feature,
function(fid) { me.saveSucces(fid); },
this.failed);
},
/**
* Can be overwritten to add some extra feature attributes before saving the
* feature.
* @return the changed feature
*/
changeFeatureBeforeSave: function(feature){
return feature;
},
/**
* Can be overwritten to disable editing in the component/js
*/
allowedEditable: function (attribute){
return true;
},
saveSucces : function (fid){
this.editingLayer.reload();
this.currentFID = fid;
Ext.Msg.alert('Gelukt',"Het feature is aangepast.");
this.cancel();
},
saveFailed : function (msg){
Ext.Msg.alert('Mislukt',msg);
},
cancel : function (){
this.resetForm();
this.popup.hide();
},
resetForm : function (){
Ext.getCmp(this.name +"editButton").setDisabled(true);
Ext.getCmp(this.name +"newButton").setDisabled(true);
this.mode=null;
this.layerSelector.combobox.select(null);
Ext.getCmp( this.name +"geomLabel").setText("");
this.inputContainer.removeAll();
this.viewerController.mapComponent.getMap().removeMarker("edit");
this.vectorLayer.removeAllFeatures();
},
getExtComponents: function() {
return [ this.maincontainer.getId() ];
},
createFeaturesGrid : function (features){
var appLayer = this.layerSelector.getSelectedAppLayer();
var attributes = appLayer.attributes;
var index = 0;
var attributeList = new Array();
var columns = new Array();
for(var i= 0 ; i < attributes.length ;i++){
var attribute = attributes[i];
if(attribute.editable){
var attIndex = index++;
if(i == appLayer.geometryAttributeIndex){
continue;
}
var colName = attribute.alias != undefined ? attribute.alias : attribute.name;
attributeList.push({
name: "c" + attIndex,
type : 'string'
});
columns.push({
id: "c" +attIndex,
text:colName,
dataIndex: "c" + attIndex,
flex: 1,
filter: {
xtype: 'textfield'
}
});
}
}
Ext.define(this.name + 'Model', {
extend: 'Ext.data.Model',
fields: attributeList
});
var store = Ext.create('Ext.data.Store', {
pageSize: 10,
model: this.name + 'Model',
data:features
});
var me =this;
var grid = Ext.create('Ext.grid.Panel', {
id: this.name + 'GridFeaturesWindow',
store: store,
columns: columns,
listeners:{
itemdblclick:{
scope: me,
fn: me.itemDoubleClick
}
}
});
var container = Ext.create("Ext.container.Container",{
id: this.name + "GridContainerFeaturesWindow",
width: "100%",
height: "100%",
layout: {
type: 'vbox',
align: 'stretch'
},
items:[
{
id: this.name + 'GridPanelFeaturesWindow',
xtype: "container",
autoScroll: true,
width: '100%',
flex: 1,
items:[grid]
},{
id: this.name + 'ButtonPanelFeaturesWindow',
xtype: "container",
width: '100%',
height: 30,
items:[{
xtype: "button",
id: this.name + "SelectFeatureButtonFeaturesWindow",
text: "Bewerk geselecteerd feature",
listeners: {
click:{
scope: me,
fn: me.selectFeature
}
}
},
{
xtype: "button",
id: this.name + "CancelFeatureButtonFeaturesWindow",
text: "Annuleren",
listeners: {
click:{
scope: me,
fn: me.cancelSelectFeature
}
}
}]
}
]
});
var window = Ext.create("Ext.window.Window",{
id: this.name + "FeaturesWindow",
width: 500,
height: 300,
layout: 'fit',
title: "Kies één feature",
items: [container]
});
window.show();
},
itemDoubleClick : function (gridview,row){
this.featuresReceived ([row.data]);
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
selectFeature :function() {
var grid = Ext.getCmp(this.name + 'GridFeaturesWindow');
var selection = grid.getSelectionModel().getSelection()[0];
var feature = selection.data;
this.featuresReceived ([feature]);
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
cancelSelectFeature : function (){
this.resetForm();
Ext.get(this.getContentDiv()).unmask()
Ext.getCmp(this.name + "FeaturesWindow").destroy();
},
indexFeatureToNamedFeature : function (feature){
var map = this.makeConversionMap();
var newFeature = {};
for (var key in feature){
var namedIndex = map[key];
var value = feature[key];
if(namedIndex != undefined){
newFeature[namedIndex] = value;
}else{
newFeature[key] = value;
}
}
return newFeature;
},
makeConversionMap : function (){
var appLayer = this.layerSelector.getSelectedAppLayer();
var attributes = appLayer.attributes;
var map = {};
var index = 0;
for (var i = 0 ; i < attributes.length ;i++){
if(attributes[i].editable){
map["c"+index] = attributes[i].name;
index++;
}
}
return map;
}
});
| If all listed edit values are boolean, make all boolean
| viewer/src/main/webapp/viewer-html/components/Edit.js | If all listed edit values are boolean, make all boolean | <ide><path>iewer/src/main/webapp/viewer-html/components/Edit.js
<ide> input = Ext.create("Ext.form.field.Text",options);
<ide> }
<ide> }else if (values.length > 1){
<add> var allBoolean=true;
<add> for (var v=0; v < values.length; v++){
<add> if (values[v].toLowerCase()!=="true" && values[v].toLowerCase()!=="false"){
<add> allBoolean =false;
<add> break;
<add> }
<add> }
<add>
<ide> Ext.each(values,function(value,index,original){
<add> if (allBoolean){
<add> value= value.toLowerCase() ==="true";
<add> }
<ide> original[index] = {
<ide> id: value
<ide> }; |
|
JavaScript | mit | df2310cc1ad6dca60479ebf22a48dd884814911b | 0 | ksom/SonataAdminBundle,mgdigital/SonataAdminBundle,gnorby88/SonataAdminBundle,claudusd/SonataAdminBundle,amine2z/SonataAdminBundle,tim96/SonataAdminBundle,jlamur/SonataAdminBundle,mgdigital/SonataAdminBundle,ruscon/SonataAdminBundle,peter-gribanov/SonataAdminBundle,jordisala1991/SonataAdminBundle,cmacetko/SonataAdminBundle,ruscon/SonataAdminBundle,OskarStark/SonataAdminBundle,jordisala1991/SonataAdminBundle,core23/SonataAdminBundle,UnDeleteRU/SonataAdminBundle,jlamur/SonataAdminBundle,robhunt3r/SonataAdminBundle,digitalkaoz/SonataAdminBundle,osavchenko/SonataAdminBundle,Th3Mouk/SonataAdminBundle,ksom/SonataAdminBundle,idchlife/SonataAdminBundle,tim96/SonataAdminBundle,mgdigital/SonataAdminBundle,sonata-project/SonataAdminBundle,dankempster/SonataAdminBundle,mikemeier/SonataAdminBundle,gnorby88/SonataAdminBundle,Armstrong1992/SonataAdminBundle,rschumacher/SonataAdminBundle,lutangar/SonataAdminBundle,lutangar/SonataAdminBundle,jakublech/SonataAdminBundle,greg0ire/SonataAdminBundle,fosvn/SonataAdminBundle,ellementA/SonataAdminBundle,mweimerskirch/SonataAdminBundle,dmarkowicz/SonataAdminBundle,tim96/SonataAdminBundle,ejkun/SonataAdminBundle,Soullivaneuh/SonataAdminBundle,mweimerskirch/SonataAdminBundle,vincenttouzet/SonataAdminBundle,UnDeleteRU/SonataAdminBundle,qsomazzi/SonataAdminBundle,dankempster/SonataAdminBundle,goldbroker/SonataAdminBundle,Soullivaneuh/SonataAdminBundle,morgangiraud/SonataAdminBundle,lightglitch/SonataAdminBundle,tskorupka/SonataAdminBundle,binhle410/SonataAdminBundle,binhle410/SonataAdminBundle,Soullivaneuh/SonataAdminBundle,Storke/SonataAdminBundle,rmzamora/SonataAdminBundle,Denniskevin/SonataAdminBundle,FabienD/SonataAdminBundle,qsomazzi/SonataAdminBundle,claudusd/SonataAdminBundle,ossinkine/SonataAdminBundle,rswork/SonataAdminBundle,jszmidt/SonataAdminBundle,amine2z/SonataAdminBundle,dmarkowicz/SonataAdminBundle,andythorne/SonataAdminBundle,Th3Mouk/SonataAdminBundle,robhunt3r/SonataAdminBundle,edouardkombo/SonataAdminBundle,jordisala1991/SonataAdminBundle,rschumacher/SonataAdminBundle,claudusd/SonataAdminBundle,jakublech/SonataAdminBundle,lutangar/SonataAdminBundle,mikemeier/SonataAdminBundle,nexylan/SonataAdminBundle,ellementA/SonataAdminBundle,UnDeleteRU/SonataAdminBundle,rmzamora/SonataAdminBundle,0mars/SonataAdminBundle,Romashka/SonataAdminBundle,core23/SonataAdminBundle,tunne/SonataAdminBundle,idchlife/SonataAdminBundle,rmzamora/SonataAdminBundle,fosvn/SonataAdminBundle,idchlife/SonataAdminBundle,mgdigital/SonataAdminBundle,Koc/SonataAdminBundle,tskorupka/SonataAdminBundle,jlamur/SonataAdminBundle,FabienD/SonataAdminBundle,news-life-media/SonataAdminBundle,UnDeleteRU/SonataAdminBundle,ejkun/SonataAdminBundle,lightglitch/SonataAdminBundle,arbislimen/SonataAdminBundle,gnorby88/SonataAdminBundle,mohebifar/SonataAdminBundle,Romashka/SonataAdminBundle,lutangar/SonataAdminBundle,ksom/SonataAdminBundle,arbislimen/SonataAdminBundle,arbislimen/SonataAdminBundle,Koc/SonataAdminBundle,mohebifar/SonataAdminBundle,gRoussac/SonataAdminBundle,jszmidt/SonataAdminBundle,ruscon/SonataAdminBundle,jordisala1991/SonataAdminBundle,osavchenko/SonataAdminBundle,ejkun/SonataAdminBundle,peter-gribanov/SonataAdminBundle,peter-gribanov/SonataAdminBundle,ju1ius/SonataAdminBundle,Storke/SonataAdminBundle,ju1ius/SonataAdminBundle,sonata-project/SonataAdminBundle,osavchenko/SonataAdminBundle,arbislimen/SonataAdminBundle,morgangiraud/SonataAdminBundle,dmarkowicz/SonataAdminBundle,rmzamora/SonataAdminBundle,andythorne/SonataAdminBundle,ARTACK/SonataAdminBundle,Denniskevin/SonataAdminBundle,mweimerskirch/SonataAdminBundle,0mars/SonataAdminBundle,j-ledoux/SonataAdminBundle,FabienD/SonataAdminBundle,Romashka/SonataAdminBundle,ARTACK/SonataAdminBundle,j-ledoux/SonataAdminBundle,dankempster/SonataAdminBundle,vincenttouzet/SonataAdminBundle,core23/SonataAdminBundle,ossinkine/SonataAdminBundle,tim96/SonataAdminBundle,ryanhughes/SonataAdminBundle,tunne/SonataAdminBundle,joshlopes/SonataAdminBundle,0mars/SonataAdminBundle,fosvn/SonataAdminBundle,Denniskevin/SonataAdminBundle,Denniskevin/SonataAdminBundle,FabienD/SonataAdminBundle,idchlife/SonataAdminBundle,jszmidt/SonataAdminBundle,ruscon/SonataAdminBundle,rswork/SonataAdminBundle,core23/SonataAdminBundle,Storke/SonataAdminBundle,jlamur/SonataAdminBundle,jakublech/SonataAdminBundle,ejkun/SonataAdminBundle,Soullivaneuh/SonataAdminBundle,greg0ire/SonataAdminBundle,morfin60/SonataAdminBundle,Storke/SonataAdminBundle,edouardkombo/SonataAdminBundle,robhunt3r/SonataAdminBundle,joshlopes/SonataAdminBundle,robhunt3r/SonataAdminBundle,jakublech/SonataAdminBundle,tskorupka/SonataAdminBundle,fosvn/SonataAdminBundle,Armstrong1992/SonataAdminBundle,ryanhughes/SonataAdminBundle,mohebifar/SonataAdminBundle,lightglitch/SonataAdminBundle,ju1ius/SonataAdminBundle,news-life-media/SonataAdminBundle,ARTACK/SonataAdminBundle,j-ledoux/SonataAdminBundle,binhle410/SonataAdminBundle,tskorupka/SonataAdminBundle,news-life-media/SonataAdminBundle,cmacetko/SonataAdminBundle,ryanhughes/SonataAdminBundle,UnDeleteRU/SonataAdminBundle,Th3Mouk/SonataAdminBundle,ellementA/SonataAdminBundle,jszmidt/SonataAdminBundle,ossinkine/SonataAdminBundle,Romashka/SonataAdminBundle,joshlopes/SonataAdminBundle,morgangiraud/SonataAdminBundle,osavchenko/SonataAdminBundle,gnorby88/SonataAdminBundle,ju1ius/SonataAdminBundle,vincenttouzet/SonataAdminBundle,0mars/SonataAdminBundle,andythorne/SonataAdminBundle,j-ledoux/SonataAdminBundle,news-life-media/SonataAdminBundle,Koc/SonataAdminBundle,OskarStark/SonataAdminBundle,vincenttouzet/SonataAdminBundle,gRoussac/SonataAdminBundle,Th3Mouk/SonataAdminBundle,jlamur/SonataAdminBundle,binhle410/SonataAdminBundle,binhle410/SonataAdminBundle,OskarStark/SonataAdminBundle,goldbroker/SonataAdminBundle,mikemeier/SonataAdminBundle,andythorne/SonataAdminBundle,greg0ire/SonataAdminBundle,ksom/SonataAdminBundle,peter-gribanov/SonataAdminBundle,ryanhughes/SonataAdminBundle,amine2z/SonataAdminBundle,nexylan/SonataAdminBundle,digitalkaoz/SonataAdminBundle,ossinkine/SonataAdminBundle,gRoussac/SonataAdminBundle,amine2z/SonataAdminBundle,morfin60/SonataAdminBundle,Romashka/SonataAdminBundle,ellementA/SonataAdminBundle,ejkun/SonataAdminBundle,rschumacher/SonataAdminBundle,greg0ire/SonataAdminBundle,dmarkowicz/SonataAdminBundle,osavchenko/SonataAdminBundle,morfin60/SonataAdminBundle,rschumacher/SonataAdminBundle,digitalkaoz/SonataAdminBundle,dmarkowicz/SonataAdminBundle,cmacetko/SonataAdminBundle,mikemeier/SonataAdminBundle,news-life-media/SonataAdminBundle,claudusd/SonataAdminBundle,nexylan/SonataAdminBundle,edouardkombo/SonataAdminBundle,ARTACK/SonataAdminBundle,Koc/SonataAdminBundle,nexylan/SonataAdminBundle,rswork/SonataAdminBundle,j-ledoux/SonataAdminBundle,cmacetko/SonataAdminBundle,OskarStark/SonataAdminBundle,dankempster/SonataAdminBundle,qsomazzi/SonataAdminBundle,joshlopes/SonataAdminBundle,tunne/SonataAdminBundle,mohebifar/SonataAdminBundle,rswork/SonataAdminBundle,ellementA/SonataAdminBundle,mweimerskirch/SonataAdminBundle,goldbroker/SonataAdminBundle,edouardkombo/SonataAdminBundle,digitalkaoz/SonataAdminBundle,goldbroker/SonataAdminBundle,morfin60/SonataAdminBundle,qsomazzi/SonataAdminBundle,morfin60/SonataAdminBundle,gRoussac/SonataAdminBundle,lightglitch/SonataAdminBundle,tunne/SonataAdminBundle,morgangiraud/SonataAdminBundle | jQuery(document).ready(function() {
jQuery('html').removeClass('no-js');
Admin.add_pretty_errors(document);
Admin.add_collapsed_toggle();
Admin.add_filters(document);
Admin.set_object_field_value(document);
Admin.setup_collection_buttons(document);
});
var Admin = {
/**
* render log message
* @param mixed
*/
log: function() {
var msg = '[Sonata.Admin] ' + Array.prototype.join.call(arguments,', ');
if (window.console && window.console.log) {
window.console.log(msg);
} else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
},
/**
* display related errors messages
*
* @param subject
*/
add_pretty_errors: function(subject) {
jQuery('div.sonata-ba-field-error', subject).each(function(index, element) {
var input = jQuery('input, textarea, select', element);
var message = jQuery('div.sonata-ba-field-error-messages', element).html();
jQuery('div.sonata-ba-field-error-messages', element).html('');
if (!message) {
message = '';
}
if (message.length == 0) {
return;
}
var target;
/* Hack to handle qTip on select */
if(jQuery(input).is("select")) {
jQuery(element).prepend("<span></span>");
target = jQuery('span', element);
jQuery(input).appendTo(target);
}
else {
target = input;
}
target.qtip({
content: message,
show: 'focusin',
hide: 'focusout',
position: {
corner: {
target: 'rightMiddle',
tooltip: 'leftMiddle'
}
},
style: {
name: 'red',
border: {
radius: 2
},
tip: 'leftMiddle'
}
});
});
},
/**
* Add the collapsed toggle option to the admin
*
* @param subject
*/
add_collapsed_toggle: function(subject) {
jQuery('fieldset.sonata-ba-fielset-collapsed').has('.error').addClass('sonata-ba-collapsed-fields-close');
jQuery('fieldset.sonata-ba-fielset-collapsed div.sonata-ba-collapsed-fields').not(':has(.error)').hide();
jQuery('fieldset legend a.sonata-ba-collapsed', subject).live('click', function(event) {
event.preventDefault();
var fieldset = jQuery(this).closest('fieldset');
jQuery('div.sonata-ba-collapsed-fields', fieldset).slideToggle();
fieldset.toggleClass('sonata-ba-collapsed-fields-close');
});
},
stopEvent: function(event) {
// https://github.com/sonata-project/SonataAdminBundle/issues/151
//if it is a standard browser use preventDefault otherwise it is IE then return false
if(event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
//if it is a standard browser get target otherwise it is IE then adapt syntax and get target
if (typeof event.target != 'undefined') {
targetElement = event.target;
} else {
targetElement = event.srcElement;
}
return targetElement;
},
add_filters: function(subject) {
jQuery('div.filter_container.inactive', subject).hide();
jQuery('fieldset.filter_legend', subject).click(function(event) {
jQuery('div.filter_container', jQuery(event.target).parent()).toggle();
});
},
/**
* Change object field value
* @param subject
*/
set_object_field_value: function(subject) {
this.log(jQuery('a.sonata-ba-edit-inline', subject));
jQuery('a.sonata-ba-edit-inline', subject).click(function(event) {
Admin.stopEvent(event);
var subject = jQuery(this);
jQuery.ajax({
url: subject.attr('href'),
type: 'POST',
success: function(json) {
if(json.status === "OK") {
var elm = jQuery(subject).parent();
elm.children().remove();
// fix issue with html comment ...
elm.html(jQuery(json.content.replace(/<!--[\s\S]*?-->/g, "")).html());
elm.effect("highlight", {'color' : '#57A957'}, 2000);
Admin.set_object_field_value(elm);
} else {
jQuery(subject).parent().effect("highlight", {'color' : '#C43C35'}, 2000);
}
}
});
});
},
setup_collection_buttons: function(subject) {
jQuery(subject).on('click', '.sonata-collection-add', function(event) {
Admin.stopEvent(event);
var container = jQuery(this).closest('[data-prototype]');
var proto = container.attr('data-prototype');
// Set field id
var idRegexp = new RegExp(container.attr('id')+'___name__','g');
proto = proto.replace(idRegexp, container.attr('id')+'_'+(container.children().length - 1));
// Set field name
var parts = container.attr('id').split('_');
var nameRegexp = new RegExp(parts[parts.length-1]+'\\]\\[__name__','g');
proto = proto.replace(nameRegexp, parts[parts.length-1]+']['+(container.children().length - 1));
jQuery(proto).insertBefore(jQuery(this).parent());
jQuery(this).trigger('sonata-collection-item-added');
});
jQuery(subject).on('click', '.sonata-collection-delete', function(event) {
Admin.stopEvent(event);
jQuery(this).closest('.sonata-collection-row').remove();
jQuery(this).trigger('sonata-collection-item-deleted');
});
}
}
| Resources/public/base.js | jQuery(document).ready(function() {
jQuery('html').removeClass('no-js');
Admin.add_pretty_errors(document);
Admin.add_collapsed_toggle();
Admin.add_filters(document);
Admin.set_object_field_value(document);
Admin.setup_collection_buttons(document);
});
var Admin = {
/**
* render log message
* @param mixed
*/
log: function() {
var msg = '[Sonata.Admin] ' + Array.prototype.join.call(arguments,', ');
if (window.console && window.console.log) {
window.console.log(msg);
} else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
},
/**
* display related errors messages
*
* @param subject
*/
add_pretty_errors: function(subject) {
jQuery('div.sonata-ba-field-error', subject).each(function(index, element) {
var input = jQuery('input, textarea, select', element);
var message = jQuery('div.sonata-ba-field-error-messages', element).html();
jQuery('div.sonata-ba-field-error-messages', element).html('');
if (!message) {
message = '';
}
if (message.length == 0) {
return;
}
var target;
/* Hack to handle qTip on select */
if(jQuery(input).is("select")) {
jQuery(element).prepend("<span></span>");
target = jQuery('span', element);
jQuery(input).appendTo(target);
}
else {
target = input;
}
target.qtip({
content: message,
show: 'focusin',
hide: 'focusout',
position: {
corner: {
target: 'rightMiddle',
tooltip: 'leftMiddle'
}
},
style: {
name: 'red',
border: {
radius: 2
},
tip: 'leftMiddle'
}
});
});
},
/**
* Add the collapsed toggle option to the admin
*
* @param subject
*/
add_collapsed_toggle: function(subject) {
jQuery('fieldset.sonata-ba-fielset-collapsed').has('.error').addClass('sonata-ba-collapsed-fields-close');
jQuery('fieldset.sonata-ba-fielset-collapsed div.sonata-ba-collapsed-fields').not(':has(.error)').hide();
jQuery('fieldset legend a.sonata-ba-collapsed', subject).live('click', function(event) {
event.preventDefault();
var fieldset = jQuery(this).closest('fieldset');
jQuery('div.sonata-ba-collapsed-fields', fieldset).slideToggle();
fieldset.toggleClass('sonata-ba-collapsed-fields-close');
});
},
stopEvent: function(event) {
// https://github.com/sonata-project/SonataAdminBundle/issues/151
//if it is a standard browser use preventDefault otherwise it is IE then return false
if(event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
//if it is a standard browser get target otherwise it is IE then adapt syntax and get target
if (typeof event.target != 'undefined') {
targetElement = event.target;
} else {
targetElement = event.srcElement;
}
return targetElement;
},
add_filters: function(subject) {
jQuery('div.filter_container.inactive', subject).hide();
jQuery('fieldset.filter_legend', subject).click(function(event) {
jQuery('div.filter_container', jQuery(event.target).parent()).toggle();
});
},
/**
* Change object field value
* @param subject
*/
set_object_field_value: function(subject) {
this.log(jQuery('a.sonata-ba-edit-inline', subject));
jQuery('a.sonata-ba-edit-inline', subject).click(function(event) {
Admin.stopEvent(event);
var subject = jQuery(this);
jQuery.ajax({
url: subject.attr('href'),
type: 'POST',
success: function(json) {
if(json.status === "OK") {
var elm = jQuery(subject).parent();
elm.children().remove();
// fix issue with html comment ...
elm.html(jQuery(json.content.replace(/<!--[\s\S]*?-->/g, "")).html());
elm.effect("highlight", {'color' : '#57A957'}, 2000);
Admin.set_object_field_value(elm);
} else {
jQuery(subject).parent().effect("highlight", {'color' : '#C43C35'}, 2000);
}
}
});
});
},
setup_collection_buttons: function(subject) {
jQuery(subject).on('click', '.sonata-collection-add', function(event) {
Admin.stopEvent(event);
var container = jQuery(this).closest('[data-prototype]');
var proto = container.attr('data-prototype');
// Set field id
var idRegexp = new RegExp(container.attr('id')+'___name__','g');
proto = proto.replace(idRegexp, container.attr('id')+'_'+container.children().length);
// Set field name
var parts = container.attr('id').split('_');
var nameRegexp = new RegExp(parts[parts.length-1]+'\\]\\[__name__','g');
proto = proto.replace(nameRegexp, parts[parts.length-1]+']['+container.children().length);
jQuery(proto).insertBefore(jQuery(this).parent());
jQuery(this).trigger('sonata-collection-item-added');
});
jQuery(subject).on('click', '.sonata-collection-delete', function(event) {
Admin.stopEvent(event);
jQuery(this).closest('.sonata-collection-row').remove();
jQuery(this).trigger('sonata-collection-item-deleted');
});
}
}
| Fix issue with adding new elements in an array field. The offset starts
at 0 and not at 1, however the code was adding elements at the nth+1
element. Example:
Existing:
0: asdf
1: hjkl
Add element did this:
0: asdf
1: hjkl
3: <new element>
With this patch it should do this:
0: asdf
1: hjkl
2: <new element>
| Resources/public/base.js | Fix issue with adding new elements in an array field. The offset starts at 0 and not at 1, however the code was adding elements at the nth+1 element. Example: | <ide><path>esources/public/base.js
<ide> var proto = container.attr('data-prototype');
<ide> // Set field id
<ide> var idRegexp = new RegExp(container.attr('id')+'___name__','g');
<del> proto = proto.replace(idRegexp, container.attr('id')+'_'+container.children().length);
<add> proto = proto.replace(idRegexp, container.attr('id')+'_'+(container.children().length - 1));
<ide>
<ide> // Set field name
<ide> var parts = container.attr('id').split('_');
<ide> var nameRegexp = new RegExp(parts[parts.length-1]+'\\]\\[__name__','g');
<del> proto = proto.replace(nameRegexp, parts[parts.length-1]+']['+container.children().length);
<add> proto = proto.replace(nameRegexp, parts[parts.length-1]+']['+(container.children().length - 1));
<ide> jQuery(proto).insertBefore(jQuery(this).parent());
<ide>
<ide> jQuery(this).trigger('sonata-collection-item-added'); |
|
Java | mit | d41b9804aa3b1c1fb3dd7cbea6860a6224bf70ed | 0 | matthieu-vergne/jMetal | package org.uma.jmetal.algorithm.multiobjective.nsgaiii;
import org.uma.jmetal.algorithm.impl.AbstractGeneticAlgorithm;
import org.uma.jmetal.algorithm.multiobjective.nsgaiii.util.EnvironmentalSelection;
import org.uma.jmetal.algorithm.multiobjective.nsgaiii.util.ReferencePoint;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.SolutionListUtils;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import org.uma.jmetal.util.solutionattribute.Ranking;
import org.uma.jmetal.util.solutionattribute.impl.DominanceRanking;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Created by ajnebro on 30/10/14.
* Modified by Juanjo on 13/11/14
*
* This implementation is based on the code of Tsung-Che Chiang
* http://web.ntnu.edu.tw/~tcchiang/publications/nsga3cpp/nsga3cpp.htm
*/
@SuppressWarnings("serial")
public class NSGAIII<S extends Solution<?>> extends AbstractGeneticAlgorithm<S, List<S>> {
protected int iterations ;
protected int maxIterations ;
protected SolutionListEvaluator<S> evaluator ;
protected Vector<Integer> numberOfDivisions ;
protected List<ReferencePoint<S>> referencePoints = new Vector<>() ;
/** Constructor */
public NSGAIII(NSGAIIIBuilder<S> builder) { // can be created from the NSGAIIIBuilder within the same package
super(builder.getProblem()) ;
maxIterations = builder.getMaxIterations() ;
crossoverOperator = builder.getCrossoverOperator() ;
mutationOperator = builder.getMutationOperator() ;
selectionOperator = builder.getSelectionOperator() ;
evaluator = builder.getEvaluator() ;
/// NSGAIII
numberOfDivisions = new Vector<>(1) ;
numberOfDivisions.add(12) ; // Default value for 3D problems
(new ReferencePoint<S>()).generateReferencePoints(referencePoints,getProblem().getNumberOfObjectives() , numberOfDivisions);
int populationSize = referencePoints.size();
System.out.println(referencePoints.size());
while (populationSize%4>0) {
populationSize++;
}
setMaxPopulationSize(populationSize);
JMetalLogger.logger.info("rpssize: " + referencePoints.size()); ;
}
@Override
protected void initProgress() {
iterations = 1 ;
}
@Override
protected void updateProgress() {
iterations++ ;
}
@Override
protected boolean isStoppingConditionReached() {
return iterations >= maxIterations;
}
@Override
protected List<S> evaluatePopulation(List<S> population) {
population = evaluator.evaluate(population, getProblem()) ;
return population ;
}
@Override
protected List<S> selection(List<S> population) {
List<S> matingPopulation = new ArrayList<>(population.size()) ;
for (int i = 0; i < getMaxPopulationSize(); i++) {
S solution = selectionOperator.execute(population);
matingPopulation.add(solution) ;
}
return matingPopulation;
}
@Override
protected List<S> reproduction(List<S> population) {
List<S> offspringPopulation = new ArrayList<>(getMaxPopulationSize());
for (int i = 0; i < getMaxPopulationSize(); i+=2) {
List<S> parents = new ArrayList<>(2);
parents.add(population.get(i));
parents.add(population.get(Math.min(i + 1, getMaxPopulationSize()-1)));
List<S> offspring = crossoverOperator.execute(parents);
mutationOperator.execute(offspring.get(0));
mutationOperator.execute(offspring.get(1));
offspringPopulation.add(offspring.get(0));
offspringPopulation.add(offspring.get(1));
}
return offspringPopulation ;
}
private List<ReferencePoint<S>> getReferencePointsCopy() {
List<ReferencePoint<S>> copy = new ArrayList<>();
for (ReferencePoint<S> r : this.referencePoints) {
copy.add(new ReferencePoint<>(r));
}
return copy;
}
@Override
protected List<S> replacement(List<S> population, List<S> offspringPopulation) {
List<S> jointPopulation = new ArrayList<>();
jointPopulation.addAll(population) ;
jointPopulation.addAll(offspringPopulation) ;
Ranking<S> ranking = computeRanking(jointPopulation);
//List<Solution> pop = crowdingDistanceSelection(ranking);
List<S> pop = new ArrayList<>();
List<List<S>> fronts = new ArrayList<>();
int rankingIndex = 0;
int candidateSolutions = 0;
while (candidateSolutions < getMaxPopulationSize()) {
fronts.add(ranking.getSubfront(rankingIndex));
candidateSolutions += ranking.getSubfront(rankingIndex).size();
if ((pop.size() + ranking.getSubfront(rankingIndex).size()) <= getMaxPopulationSize())
addRankedSolutionsToPopulation(ranking, rankingIndex, pop);
rankingIndex++;
}
// A copy of the reference list should be used as parameter of the environmental selection
EnvironmentalSelection<S> selection =
new EnvironmentalSelection<>(fronts,getMaxPopulationSize(),getReferencePointsCopy(),
getProblem().getNumberOfObjectives());
pop = selection.execute(pop);
return pop;
}
@Override
public List<S> getResult() {
return getNonDominatedSolutions(getPopulation()) ;
}
protected Ranking<S> computeRanking(List<S> solutionList) {
Ranking<S> ranking = new DominanceRanking<>() ;
ranking.computeRanking(solutionList) ;
return ranking ;
}
protected void addRankedSolutionsToPopulation(Ranking<S> ranking, int rank, List<S> population) {
List<S> front ;
front = ranking.getSubfront(rank);
for (int i = 0 ; i < front.size(); i++) {
population.add(front.get(i));
}
}
protected List<S> getNonDominatedSolutions(List<S> solutionList) {
return SolutionListUtils.getNondominatedSolutions(solutionList) ;
}
@Override public String getName() {
return "NSGAIII" ;
}
@Override public String getDescription() {
return "Nondominated Sorting Genetic Algorithm version III" ;
}
}
| jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/nsgaiii/NSGAIII.java | package org.uma.jmetal.algorithm.multiobjective.nsgaiii;
import org.uma.jmetal.algorithm.impl.AbstractGeneticAlgorithm;
import org.uma.jmetal.algorithm.multiobjective.nsgaiii.util.EnvironmentalSelection;
import org.uma.jmetal.algorithm.multiobjective.nsgaiii.util.ReferencePoint;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.SolutionListUtils;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import org.uma.jmetal.util.solutionattribute.Ranking;
import org.uma.jmetal.util.solutionattribute.impl.DominanceRanking;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Created by ajnebro on 30/10/14.
* Modified by Juanjo on 13/11/14
*
* This implementation is based on the code of Tsung-Che Chiang
* http://web.ntnu.edu.tw/~tcchiang/publications/nsga3cpp/nsga3cpp.htm
*/
@SuppressWarnings("serial")
public class NSGAIII<S extends Solution<?>> extends AbstractGeneticAlgorithm<S, List<S>> {
protected int iterations ;
protected int maxIterations ;
protected SolutionListEvaluator<S> evaluator ;
protected Vector<Integer> numberOfDivisions ;
protected List<ReferencePoint<S>> referencePoints = new Vector<>() ;
/** Constructor */
public NSGAIII(NSGAIIIBuilder<S> builder) { // can be created from the NSGAIIIBuilder within the same package
super(builder.getProblem()) ;
maxIterations = builder.getMaxIterations() ;
crossoverOperator = builder.getCrossoverOperator() ;
mutationOperator = builder.getMutationOperator() ;
selectionOperator = builder.getSelectionOperator() ;
evaluator = builder.getEvaluator() ;
/// NSGAIII
numberOfDivisions = new Vector<>(1) ;
numberOfDivisions.add(12) ; // Default value for 3D problems
(new ReferencePoint<S>()).generateReferencePoints(referencePoints,getProblem().getNumberOfObjectives() , numberOfDivisions);
int populationSize = referencePoints.size();
System.out.println(referencePoints.size());
while (populationSize%4>0) {
populationSize++;
}
setMaxPopulationSize(populationSize);
JMetalLogger.logger.info("rpssize: " + referencePoints.size()); ;
}
@Override
protected void initProgress() {
iterations = 1 ;
}
@Override
protected void updateProgress() {
iterations++ ;
}
@Override
protected boolean isStoppingConditionReached() {
return iterations >= maxIterations;
}
@Override
protected List<S> evaluatePopulation(List<S> population) {
population = evaluator.evaluate(population, getProblem()) ;
return population ;
}
@Override
protected List<S> selection(List<S> population) {
List<S> matingPopulation = new ArrayList<>(population.size()) ;
for (int i = 0; i < getMaxPopulationSize(); i++) {
S solution = selectionOperator.execute(population);
matingPopulation.add(solution) ;
}
return matingPopulation;
}
@Override
protected List<S> reproduction(List<S> population) {
List<S> offspringPopulation = new ArrayList<>(getMaxPopulationSize());
for (int i = 0; i < getMaxPopulationSize(); i+=2) {
List<S> parents = new ArrayList<>(2);
parents.add(population.get(i));
parents.add(population.get(i+1));
List<S> offspring = crossoverOperator.execute(parents);
mutationOperator.execute(offspring.get(0));
mutationOperator.execute(offspring.get(1));
offspringPopulation.add(offspring.get(0));
offspringPopulation.add(offspring.get(1));
}
return offspringPopulation ;
}
private List<ReferencePoint<S>> getReferencePointsCopy() {
List<ReferencePoint<S>> copy = new ArrayList<>();
for (ReferencePoint<S> r : this.referencePoints) {
copy.add(new ReferencePoint<>(r));
}
return copy;
}
@Override
protected List<S> replacement(List<S> population, List<S> offspringPopulation) {
List<S> jointPopulation = new ArrayList<>();
jointPopulation.addAll(population) ;
jointPopulation.addAll(offspringPopulation) ;
Ranking<S> ranking = computeRanking(jointPopulation);
//List<Solution> pop = crowdingDistanceSelection(ranking);
List<S> pop = new ArrayList<>();
List<List<S>> fronts = new ArrayList<>();
int rankingIndex = 0;
int candidateSolutions = 0;
while (candidateSolutions < getMaxPopulationSize()) {
fronts.add(ranking.getSubfront(rankingIndex));
candidateSolutions += ranking.getSubfront(rankingIndex).size();
if ((pop.size() + ranking.getSubfront(rankingIndex).size()) <= getMaxPopulationSize())
addRankedSolutionsToPopulation(ranking, rankingIndex, pop);
rankingIndex++;
}
// A copy of the reference list should be used as parameter of the environmental selection
EnvironmentalSelection<S> selection =
new EnvironmentalSelection<>(fronts,getMaxPopulationSize(),getReferencePointsCopy(),
getProblem().getNumberOfObjectives());
pop = selection.execute(pop);
return pop;
}
@Override
public List<S> getResult() {
return getNonDominatedSolutions(getPopulation()) ;
}
protected Ranking<S> computeRanking(List<S> solutionList) {
Ranking<S> ranking = new DominanceRanking<>() ;
ranking.computeRanking(solutionList) ;
return ranking ;
}
protected void addRankedSolutionsToPopulation(Ranking<S> ranking, int rank, List<S> population) {
List<S> front ;
front = ranking.getSubfront(rank);
for (int i = 0 ; i < front.size(); i++) {
population.add(front.get(i));
}
}
protected List<S> getNonDominatedSolutions(List<S> solutionList) {
return SolutionListUtils.getNondominatedSolutions(solutionList) ;
}
@Override public String getName() {
return "NSGAIII" ;
}
@Override public String getDescription() {
return "Nondominated Sorting Genetic Algorithm version III" ;
}
}
| Fix for odd population size
| jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/nsgaiii/NSGAIII.java | Fix for odd population size | <ide><path>metal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/nsgaiii/NSGAIII.java
<ide> for (int i = 0; i < getMaxPopulationSize(); i+=2) {
<ide> List<S> parents = new ArrayList<>(2);
<ide> parents.add(population.get(i));
<del> parents.add(population.get(i+1));
<add> parents.add(population.get(Math.min(i + 1, getMaxPopulationSize()-1)));
<ide>
<ide> List<S> offspring = crossoverOperator.execute(parents);
<ide> |
|
Java | apache-2.0 | 667a19e7040664be063a8478a3968a8bc508690e | 0 | lexs/webimageloader | package com.webimageloader.loader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.webimageloader.Request;
import com.webimageloader.concurrent.ExecutorHelper;
import com.webimageloader.concurrent.ListenerFuture;
import com.webimageloader.util.Android;
import com.webimageloader.util.PriorityThreadFactory;
import android.net.Uri;
import android.os.Process;
import android.util.Log;
public class NetworkLoader implements Loader {
private static final String TAG = "NetworkLoader";
private Map<String, URLStreamHandler> streamHandlers;
private int connectTimeout;
private int readTimeout;
private ExecutorHelper executorHelper;
public NetworkLoader(Map<String, URLStreamHandler> streamHandlers, int connectionTimeout, int readTimeout) {
this.streamHandlers = Collections.unmodifiableMap(streamHandlers);
this.connectTimeout = connectionTimeout;
this.readTimeout = readTimeout;
ExecutorService executor = Executors.newFixedThreadPool(2, new PriorityThreadFactory("Network", Process.THREAD_PRIORITY_BACKGROUND));
executorHelper = new ExecutorHelper(executor);
}
@Override
public void load(Request request, Iterator<Loader> chain, Listener listener) {
ListenerFuture.Task task = new DownloadTask(request);
executorHelper.run(request, listener, task);
}
@Override
public void cancel(Request request) {
executorHelper.cancel(request);
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
private static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!Android.isAPI(8)) {
System.setProperty("http.keepAlive", "false");
}
}
private static String getProtocol(String url) {
int i = url.indexOf(':');
return i == -1 ? null : url.substring(0, i);
}
private URLStreamHandler getURLStreamHandler(String protocol) {
return streamHandlers.get(protocol);
}
private class DownloadTask implements ListenerFuture.Task {
private Request request;
public DownloadTask(Request request) {
this.request = request;
}
@Override
public void run(Listener listener) throws Exception {
String url = request.getUrl();
disableConnectionReuseIfNecessary();
String protocol = getProtocol(url);
URLStreamHandler streamHandler = getURLStreamHandler(protocol);
URLConnection urlConnection = new URL(null, url, streamHandler).openConnection();
if (connectTimeout > 0) {
urlConnection.setConnectTimeout(connectTimeout);
}
if (readTimeout > 0) {
urlConnection.setReadTimeout(readTimeout);
}
InputStream is = urlConnection.getInputStream();
Log.v(TAG, "Loaded " + request + " from network");
try {
listener.onStreamLoaded(is);
} finally {
is.close();
}
}
}
}
| webimageloader/src/com/webimageloader/loader/NetworkLoader.java | package com.webimageloader.loader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.webimageloader.Request;
import com.webimageloader.concurrent.ExecutorHelper;
import com.webimageloader.concurrent.ListenerFuture;
import com.webimageloader.util.Android;
import com.webimageloader.util.PriorityThreadFactory;
import android.net.Uri;
import android.os.Process;
import android.util.Log;
public class NetworkLoader implements Loader {
private static final String TAG = "NetworkLoader";
private Map<String, URLStreamHandler> streamHandlers;
private int connectTimeout;
private int readTimeout;
private ExecutorHelper executorHelper;
public NetworkLoader(Map<String, URLStreamHandler> streamHandlers, int connectionTimeout, int readTimeout) {
this.streamHandlers = Collections.unmodifiableMap(streamHandlers);
this.connectTimeout = connectionTimeout;
this.readTimeout = readTimeout;
ExecutorService executor = Executors.newFixedThreadPool(2, new PriorityThreadFactory("Network", Process.THREAD_PRIORITY_BACKGROUND));
executorHelper = new ExecutorHelper(executor);
}
@Override
public void load(Request request, Iterator<Loader> chain, Listener listener) {
ListenerFuture.Task task = new DownloadTask(request);
executorHelper.run(request, listener, task);
}
@Override
public void cancel(Request request) {
executorHelper.cancel(request);
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
private static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!Android.isAPI(8)) {
System.setProperty("http.keepAlive", "false");
}
}
private static String getProtocol(String url) {
Uri uri = Uri.parse(url);
return uri.getScheme();
}
private URLStreamHandler getURLStreamHandler(String protocol) {
return streamHandlers.get(protocol);
}
private class DownloadTask implements ListenerFuture.Task {
private Request request;
public DownloadTask(Request request) {
this.request = request;
}
@Override
public void run(Listener listener) throws Exception {
String url = request.getUrl();
disableConnectionReuseIfNecessary();
String protocol = getProtocol(url);
URLStreamHandler streamHandler = getURLStreamHandler(protocol);
URLConnection urlConnection = new URL(null, url, streamHandler).openConnection();
if (connectTimeout > 0) {
urlConnection.setConnectTimeout(connectTimeout);
}
if (readTimeout > 0) {
urlConnection.setReadTimeout(readTimeout);
}
InputStream is = urlConnection.getInputStream();
Log.v(TAG, "Loaded " + request + " from network");
try {
listener.onStreamLoaded(is);
} finally {
is.close();
}
}
}
}
| Avoid allocations when getting scheme
| webimageloader/src/com/webimageloader/loader/NetworkLoader.java | Avoid allocations when getting scheme | <ide><path>ebimageloader/src/com/webimageloader/loader/NetworkLoader.java
<ide> }
<ide>
<ide> private static String getProtocol(String url) {
<del> Uri uri = Uri.parse(url);
<del> return uri.getScheme();
<add> int i = url.indexOf(':');
<add> return i == -1 ? null : url.substring(0, i);
<ide> }
<ide>
<ide> private URLStreamHandler getURLStreamHandler(String protocol) { |
|
Java | mit | f61f0de8005f01a9ef6c8552a55de96350a4229b | 0 | alexanderwe/bananaj | package com.github.alexanderwe.bananaj.connection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* Created by Alexander on 10.08.2016.
*/
public class Connection {
public String do_Get(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url.toURI());
httpget.addHeader("Authorization", authorization);
CloseableHttpResponse response = httpclient. execute(httpget);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " GET " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Post(URL url, String post_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url.toURI());
httppost.addHeader("Authorization", authorization);
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
httppost.setEntity(EntityBuilder.create().setText(post_string).build());
CloseableHttpResponse response = httpclient. execute(httppost);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " POST " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Patch(URL url, String patch_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPatch httppatch = new HttpPatch(url.toURI());
httppatch.addHeader("Authorization", authorization);
httppatch.addHeader("Content-Type", "application/json; charset=UTF-8");
httppatch.setEntity(EntityBuilder.create().setText(patch_string).build());
CloseableHttpResponse response = httpclient. execute(httppatch);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " PATCH " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Put(URL url, String put_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut httpput = new HttpPut(url.toURI());
httpput.addHeader("Authorization", authorization);
httpput.addHeader("Content-Type", "application/json; charset=UTF-8");
httpput.setEntity(EntityBuilder.create().setText(put_string).build());
CloseableHttpResponse response = httpclient. execute(httpput);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " PUT " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Post(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url.toURI());
httppost.addHeader("Authorization", authorization);
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
CloseableHttpResponse response = httpclient. execute(httppost);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " POST " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Delete(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpdelete = new HttpDelete(url.toURI());
httpdelete.addHeader("Authorization", authorization);
httpdelete.addHeader("Content-Type", "application/json; charset=UTF-8");
CloseableHttpResponse response = httpclient. execute(httpdelete);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode >= 400) {
throw new Exception("Error: " + responseCode + " DELETE " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
}
| src/main/java/com/github/alexanderwe/bananaj/connection/Connection.java | package com.github.alexanderwe.bananaj.connection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* Created by Alexander on 10.08.2016.
*/
public class Connection {
public String do_Get(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url.toURI());
httpget.addHeader("Authorization", authorization);
CloseableHttpResponse response = httpclient. execute(httpget);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Post(URL url, String post_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url.toURI());
httppost.addHeader("Authorization", authorization);
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
httppost.setEntity(EntityBuilder.create().setText(post_string).build());
CloseableHttpResponse response = httpclient. execute(httppost);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url + System.lineSeparator() + "Send data: " + (post_string.length() > 500 ? post_string.substring(0, 500)+"..." : post_string));
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Patch(URL url, String patch_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPatch httppatch = new HttpPatch(url.toURI());
httppatch.addHeader("Authorization", authorization);
httppatch.addHeader("Content-Type", "application/json; charset=UTF-8");
httppatch.setEntity(EntityBuilder.create().setText(patch_string).build());
CloseableHttpResponse response = httpclient. execute(httppatch);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'PATCH' request to URL : " + url + System.lineSeparator() + "Send data: " + (patch_string.length() > 500 ? patch_string.substring(0, 500)+"..." : patch_string));
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Put(URL url, String put_string, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut httpput = new HttpPut(url.toURI());
httpput.addHeader("Authorization", authorization);
httpput.addHeader("Content-Type", "application/json; charset=UTF-8");
httpput.setEntity(EntityBuilder.create().setText(put_string).build());
CloseableHttpResponse response = httpclient. execute(httpput);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'PUT' request to URL : " + url + System.lineSeparator() + "Send data: " + (put_string.length() > 500 ? put_string.substring(0, 500)+"..." : put_string));
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Post(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url.toURI());
httppost.addHeader("Authorization", authorization);
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
CloseableHttpResponse response = httpclient. execute(httppost);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
public String do_Delete(URL url, String authorization) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpdelete = new HttpDelete(url.toURI());
httpdelete.addHeader("Authorization", authorization);
httpdelete.addHeader("Content-Type", "application/json; charset=UTF-8");
CloseableHttpResponse response = httpclient. execute(httpdelete);
InputStream entityStream = null;
try {
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'DELETE' request to URL : " + url);
System.out.println("Response Code : " + responseCode + "\n");
HttpEntity entity = response.getEntity();
if (entity != null) {
long length = entity.getContentLength();
entityStream = entity.getContent();
StringBuilder strbuilder = new StringBuilder(length > 16 && length < Integer.MAX_VALUE ? (int)length : 200);
try (Reader reader = new BufferedReader(new InputStreamReader
(entityStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
strbuilder.append((char) c);
}
}
return strbuilder.toString();
}
return null;
} finally {
if (entityStream != null) {entityStream.close();}
response.close();
}
}
}
| HTTP requests will now throw an exception for error responses
# Conflicts:
# src/main/java/com/github/alexanderwe/bananaj/connection/Connection.java
| src/main/java/com/github/alexanderwe/bananaj/connection/Connection.java | HTTP requests will now throw an exception for error responses | <ide><path>rc/main/java/com/github/alexanderwe/bananaj/connection/Connection.java
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'GET' request to URL : " + url);
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " GET " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> long length = entity.getContentLength();
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'POST' request to URL : " + url + System.lineSeparator() + "Send data: " + (post_string.length() > 500 ? post_string.substring(0, 500)+"..." : post_string));
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " POST " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> if (entity != null) {
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'PATCH' request to URL : " + url + System.lineSeparator() + "Send data: " + (patch_string.length() > 500 ? patch_string.substring(0, 500)+"..." : patch_string));
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " PATCH " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> if (entity != null) {
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'PUT' request to URL : " + url + System.lineSeparator() + "Send data: " + (put_string.length() > 500 ? put_string.substring(0, 500)+"..." : put_string));
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " PUT " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> if (entity != null) {
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'POST' request to URL : " + url);
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " POST " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> if (entity != null) {
<ide> InputStream entityStream = null;
<ide> try {
<ide> int responseCode = response.getStatusLine().getStatusCode();
<del> System.out.println("\nSending 'DELETE' request to URL : " + url);
<del> System.out.println("Response Code : " + responseCode + "\n");
<add> if (responseCode >= 400) {
<add> throw new Exception("Error: " + responseCode + " DELETE " + url.toExternalForm() + " " + response.getStatusLine().getReasonPhrase());
<add> }
<ide>
<ide> HttpEntity entity = response.getEntity();
<ide> if (entity != null) { |
|
Java | mit | 4e9858dbfad42e178b1dc20ff2a79012b0fcd583 | 0 | ChrisNikolaidis/Undeniable-signature | Message.java | import java.math.BigInteger;
public class Message {
public BigInteger message;
public Message(BigInteger message) {
super();
this.message = message;
}
public Message() {
super();
}
public BigInteger getMessage() {
return message;
}
public void setMessage(BigInteger message) {
this.message = message;
}
}
| Delete Message.java | Message.java | Delete Message.java | <ide><path>essage.java
<del>import java.math.BigInteger;
<del>
<del>public class Message {
<del>
<del> public BigInteger message;
<del>
<del> public Message(BigInteger message) {
<del> super();
<del> this.message = message;
<del> }
<del>
<del> public Message() {
<del> super();
<del> }
<del>
<del>
<del> public BigInteger getMessage() {
<del> return message;
<del> }
<del>
<del> public void setMessage(BigInteger message) {
<del> this.message = message;
<del> }
<del>
<del>
<del>
<del>
<del>} |
||
Java | mit | 8e0960f77ac468c9644030f936ad04d606f1706f | 0 | NyaaCat/RPGitems-reloaded | package think.rpgitems.power.impl;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import org.librazy.nclangchecker.LangKey;
import think.rpgitems.RPGItems;
import think.rpgitems.data.Context;
import think.rpgitems.power.*;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static think.rpgitems.Events.*;
import static think.rpgitems.power.Utils.checkCooldown;
/**
* @Author ReinWD
* @email [email protected]
* Wrote & Maintained by ReinWD
* if you have any issue, please send me email or @ReinWD in issues.
* Accepted language: 中文, English.
*/
@PowerMeta(defaultTrigger = "RIGHT_CLICK")
public class PowerBeam extends BasePower implements PowerPlain, PowerRightClick, PowerLeftClick, PowerSneak, PowerSneaking, PowerSprint, PowerBowShoot, PowerHitTaken, PowerHit, PowerHurt {
@Property
public int length = 10;
@Property
public Particle particle = Particle.LAVA;
@Property
public int amount = 200;
@Property
public Mode mode = Mode.BEAM;
@Property
public boolean pierce = true;
@Property
public boolean ignoreWall = true;
@Property
public double damage = 20;
@Property
public int movementTicks = 40;
@Property
public double offsetX = 0;
@Property
public double offsetY = 0;
@Property
public double offsetZ = 0;
@Property
public double spawnsPerBlock = 2;
double lengthPerSpawn = 1 / spawnsPerBlock;
/**
* Cost of this power
*/
@Property
public int cost = 0;
/**
* Cooldown time of this power
*/
@Property
public long cooldown = 0;
@Property
public boolean cone = false;
@Property
public double coneRange = 30;
@Property
public boolean homing = false;
@Property
public double homingAngle = 1;
@Property
public double homingRange = 30;
@Property
public HomingTargetMode homingTargetMode = HomingTargetMode.ONE_TARGET;
@Property
public Target homingTarget = Target.MOBS;
@Property
public int stepsBeforeHoming = 5;
@Property
public int burstCount = 1;
@Property
public int beamAmount = 1;
@Property
public int burstInterval = 1;
@Property
public int bounce = 0;
@Property
public boolean hitSelfWhenBounced = false;
@Property
public double gravity = 0;
@Property
@Serializer(ExtraDataSerializer.class)
@Deserializer(ExtraDataSerializer.class)
public Object extraData;
@Property
public double speed = 0;
@Property
public boolean requireHurtByEntity = true;
/**
* Whether to suppress the hit trigger
*/
@Property
public boolean suppressMelee = false;
private Set<Material> transp = Stream.of(Material.values())
.filter(material -> material.isBlock())
.filter(material -> !material.isSolid() || !material.isOccluding())
.collect(Collectors.toSet());
@Override
public PowerResult<Void> fire(Player player, ItemStack stack) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
return beam(player, stack);
}
@Override
public @LangKey(skipCheck = true) String getName() {
return "beam";
}
@Override
public String displayText() {
return null;
}
@Override
public PowerResult<Void> leftClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sneak(Player player, ItemStack stack, PlayerToggleSneakEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sneaking(Player player, ItemStack stack) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sprint(Player player, ItemStack stack, PlayerToggleSprintEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Float> bowShoot(Player player, ItemStack itemStack, EntityShootBowEvent e) {
return fire(player, itemStack).with(e.getForce());
}
@Override
public PowerResult<Double> hit(Player player, ItemStack stack, LivingEntity entity, double damage, EntityDamageByEntityEvent event) {
return fire(player, stack).with(event.getDamage());
}
@Override
public PowerResult<Double> takeHit(Player target, ItemStack stack, double damage, EntityDamageEvent event) {
if (!requireHurtByEntity || event instanceof EntityDamageByEntityEvent) {
return fire(target, stack).with(event.getDamage());
}
return PowerResult.noop();
}
private PowerResult<Void> beam(LivingEntity from, ItemStack stack) {
if (burstCount > 0) {
for (int i = 0; i < burstCount; i++) {
new BukkitRunnable() {
@Override
public void run() {
if (cone) {
for (int j = 0; j < beamAmount; j++) {
internalFireBeam(from, stack);
}
} else {
internalFireBeam(from, stack);
}
}
}.runTaskLaterAsynchronously(RPGItems.plugin, i * burstInterval);
}
return PowerResult.ok();
} else {
return internalFireBeam(from, stack);
}
}
final Vector crosser = new Vector(1, 1, 1);
private PowerResult<Void> internalFireBeam(LivingEntity from, ItemStack stack) {
lengthPerSpawn = 1 / spawnsPerBlock;
Location fromLocation = from.getEyeLocation();
Vector towards = from.getEyeLocation().getDirection();
if (cone) {
double phi = random.nextDouble() * 360;
double theta;
if (coneRange > 0) {
theta = random.nextDouble() * coneRange;
Vector clone = towards.clone();
Vector cross = clone.clone().add(crosser);
Vector vertical = clone.getCrossProduct(cross).getCrossProduct(towards);
towards.rotateAroundAxis(vertical, Math.toRadians(theta));
towards.rotateAroundAxis(clone, Math.toRadians(phi));
}
}
Entity target = null;
if (from instanceof Player && homing) {
target = getNextTarget(from.getEyeLocation().getDirection(), fromLocation, from);
// Utils.getLivingEntitiesInCone(Utils.getNearestLivingEntities(this, fromLocation, ((Player) from), Math.min(1000, length), 0), fromLocation.toVector(), homingRange, from.getEyeLocation().getDirection()).stream()
// .filter(livingEntity -> {
// switch (homingTarget) {
// case MOBS:
// return !(livingEntity instanceof Player);
// case PLAYERS:
// return livingEntity instanceof Player && !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
// case ALL:
// return !(livingEntity instanceof Player) || !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
// }
// return true;
// })
// .findFirst().orElse(null);
}
switch (mode) {
case BEAM:
new PlainTask(from, towards, amount, length, target, bounce, stack).runTask(RPGItems.plugin);
break;
case PROJECTILE:
new MovingTask(from, towards, amount, length, target, bounce, stack).runTask(RPGItems.plugin);
break;
}
return PowerResult.ok();
}
private Random random = new Random();
private Vector yUnit = new Vector(0, 1, 0);
@Override
public PowerResult<Void> hurt(Player target, ItemStack stack, EntityDamageEvent event) {
if (!requireHurtByEntity || event instanceof EntityDamageByEntityEvent) {
return fire(target, stack);
}
return PowerResult.noop();
}
class PlainTask extends BukkitRunnable {
private int bounces;
private double length;
private final ItemStack stack;
private LivingEntity from;
private Vector towards;
private final int apS;
private Entity target;
boolean bounced = false;
public PlainTask(LivingEntity from, Vector towards, int amount, double actualLength, Entity target, int bounces, ItemStack stack) {
this.from = from;
this.towards = towards;
this.length = actualLength;
this.stack = stack;
this.apS = amount / ((int) Math.floor(actualLength));
this.target = target;
this.bounces = bounces;
}
@Override
public void run() {
World world = from.getWorld();
towards.normalize();
Location lastLocation = from.getEyeLocation();
double lpT = length / ((double) movementTicks);
double partsPerTick = lpT / lengthPerSpawn;
for (int i = 0; i < movementTicks; i++) {
boolean isStepHit = false;
Vector step = new Vector(0, 0, 0);
for (int j = 0; j < partsPerTick; j++) {
boolean isHit = tryHit(from, lastLocation, stack, bounced && hitSelfWhenBounced);
isStepHit = isHit || isStepHit;
Block block = lastLocation.getBlock();
if (transp.contains(block.getType())) {
spawnParticle(from, world, lastLocation, (int) Math.ceil(apS / partsPerTick));
} else if (!ignoreWall) {
if (bounces > 0) {
bounces--;
bounced = true;
makeBounce(block, towards, lastLocation.clone().subtract(step));
} else {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
}
step = towards.clone().normalize().multiply(lengthPerSpawn);
lastLocation.add(step);
towards = addGravity(towards, partsPerTick);
towards = homingCorrect(towards, lastLocation, target, i, () -> target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from));
}
if (isStepHit && homingTargetMode.equals(HomingTargetMode.MULTI_TARGET)){
target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from);
}
if (isStepHit && !pierce) {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
}
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
}
Vector gravityVector = new Vector(0, -gravity / 20, 0);
private Vector addGravity(Vector towards, double partsPerTick) {
double gravityPerTick = (-gravity / 20d) / partsPerTick;
gravityVector.setY(gravityPerTick);
return towards.add(gravityVector);
}
private class MovingTask extends BukkitRunnable {
private final LivingEntity from;
private int bounces;
private Vector towards;
private final ItemStack stack;
private final int amountPerSec;
private final List<BukkitRunnable> runnables = new LinkedList<>();
private Entity target;
boolean bounced = false;
public MovingTask(LivingEntity from, Vector towards, int apS, double actualLength, Entity target, int bounces, ItemStack stack) {
this.from = from;
this.towards = towards;
this.stack = stack;
this.amountPerSec = apS / ((int) Math.floor(actualLength));
this.target = target;
this.bounces = bounces;
}
@Override
public void run() {
World world = from.getWorld();
double lpT = ((double) length) / ((double) movementTicks);
double partsPerTick = lpT / lengthPerSpawn;
Location lastLocation = from.getEyeLocation();
towards.normalize();
final int[] finalI = {0};
BukkitRunnable bukkitRunnable = new BukkitRunnable() {
@Override
public void run() {
try {
boolean isStepHit = false;
Vector step = new Vector(0, 0, 0);
for (int k = 0; k < partsPerTick; k++) {
boolean isHit = tryHit(from, lastLocation, stack, bounced && hitSelfWhenBounced);
isStepHit = isHit || isStepHit;
Block block = lastLocation.getBlock();
if (transp.contains(block.getType())) {
spawnParticle(from, world, lastLocation, (int) (amountPerSec / spawnsPerBlock));
} else if (!ignoreWall) {
if (bounces > 0) {
bounces--;
bounced = true;
makeBounce(block, towards, lastLocation.clone().subtract(step));
} else {
this.cancel();
return;
}
}
step = towards.clone().normalize().multiply(lengthPerSpawn);
lastLocation.add(step);
towards = addGravity(towards, partsPerTick);
towards = homingCorrect(towards, lastLocation, target, finalI[0], () -> target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from));
}
if (isStepHit && homingTargetMode.equals(HomingTargetMode.MULTI_TARGET)){
target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from);
}
if (isStepHit && !pierce) {
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
if (finalI[0] >= movementTicks) {
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
finalI[0]++;
} catch (Exception ex) {
from.getServer().getLogger().log(Level.WARNING, "", ex);
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
}
};
bukkitRunnable.runTaskTimer(RPGItems.plugin, 0, 1);
}
}
private void makeBounce(Block block, Vector towards, Location lastLocation) {
RayTraceResult rayTraceResult = block.rayTrace(lastLocation, towards, towards.length(), FluidCollisionMode.NEVER);
if (rayTraceResult == null) {
return;
} else {
towards.rotateAroundNonUnitAxis(rayTraceResult.getHitBlockFace().getDirection(), Math.toRadians(180)).multiply(-1);
}
}
private Vector homingCorrect(Vector towards, Location lastLocation, Entity target, int i, Runnable runnable) {
if (target == null || i < stepsBeforeHoming) {
return towards;
}
if (target.isDead()){
runnable.run();
}
Location targetLocation;
if (target instanceof LivingEntity) {
targetLocation = ((LivingEntity) target).getEyeLocation();
} else {
targetLocation = target.getLocation();
}
Vector clone = towards.clone();
Vector targetDirection = targetLocation.toVector().subtract(lastLocation.toVector());
float angle = clone.angle(targetDirection);
Vector crossProduct = clone.clone().getCrossProduct(targetDirection);
double actualAng = homingAngle / spawnsPerBlock;
if (angle > Math.toRadians(actualAng)) {
//↓a legacy but functionable way to rotate.
//will create a enlarging circle
clone.add(clone.clone().getCrossProduct(crossProduct).normalize().multiply(-1 * Math.tan(actualAng)));
// ↓a better way to rotate.
// will create a exact circle.
// clone.rotateAroundAxis(crossProduct, actualAng);
} else {
clone = targetDirection.normalize();
}
return clone;
}
private LivingEntity getNextTarget(Vector towards, Location lastLocation, Entity from) {
int radius = Math.min(this.length, 300);
return Utils.getLivingEntitiesInCone(from.getNearbyEntities(radius, this.length, this.length).stream()
.filter(entity -> entity instanceof LivingEntity && !entity.equals(from) && !entity.isDead())
.map(entity -> ((LivingEntity) entity))
.collect(Collectors.toList())
, lastLocation.toVector(), homingRange, towards).stream()
.filter(livingEntity -> {
switch (homingTarget) {
case MOBS:
return !(livingEntity instanceof Player);
case PLAYERS:
return livingEntity instanceof Player && !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
case ALL:
return !(livingEntity instanceof Player) || !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
}
return true;
})
.findFirst().orElse(null);
}
private void spawnParticle(LivingEntity from, World world, Location lastLocation, int i) {
if ((lastLocation.distance(from.getEyeLocation()) < 1)) {
return;
}
// if (from instanceof Player) {
// ((Player) from).spawnParticle(this.particle, lastLocation, i / 2, offsetX, offsetY, offsetZ, speed, extraData);
// }
world.spawnParticle(this.particle, lastLocation, i, offsetX, offsetY, offsetZ, speed, extraData, true);
}
private boolean tryHit(LivingEntity from, Location loc, ItemStack stack, boolean canHitSelf) {
double offsetLength = new Vector(offsetX, offsetY, offsetZ).length();
double length = Double.isNaN(offsetLength) ? 0 : Math.max(offsetLength, 10);
Collection<Entity> candidates = from.getWorld().getNearbyEntities(loc, length, length, length);
boolean result = false;
if (!pierce) {
List<Entity> collect = candidates.stream()
.filter(entity -> (entity instanceof LivingEntity) && (canHitSelf || !entity.equals(from)) && !entity.isDead())
.filter(entity -> canHit(loc, entity))
.limit(1)
.collect(Collectors.toList());
if (!collect.isEmpty()) {
Entity entity = collect.get(0);
if (entity instanceof LivingEntity) {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, getNamespacedKey().toString());
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, damage);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, suppressMelee);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, stack);
((LivingEntity) entity).damage(damage, from);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, null);
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
return true;
}
} else {
List<Entity> collect = candidates.stream()
.filter(entity -> (entity instanceof LivingEntity) && (canHitSelf || !entity.equals(from)))
.filter(entity -> canHit(loc, entity))
.collect(Collectors.toList());
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, getNamespacedKey().toString());
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, damage);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, suppressMelee);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, stack);
if (!collect.isEmpty()) {
collect.stream()
.map(entity -> ((LivingEntity) entity))
.forEach(livingEntity -> {
livingEntity.damage(damage, from);
});
result = true;
}
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, null);
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
return result;
}
private boolean canHit(Location loc, Entity entity) {
BoundingBox boundingBox = entity.getBoundingBox();
BoundingBox particleBox;
double x = Math.max(offsetX, 0.1);
double y = Math.max(offsetY, 0.1);
double z = Math.max(offsetZ, 0.1);
particleBox = BoundingBox.of(loc, x + 0.1, y + 0.1, z + 0.1);
return boundingBox.overlaps(particleBox) || particleBox.overlaps(boundingBox);
}
private enum Mode {
BEAM,
PROJECTILE,
;
}
public class ExtraDataSerializer implements Getter, Setter {
@Override
public String get(Object object) {
if (object instanceof Particle.DustOptions) {
Color color = ((Particle.DustOptions) object).getColor();
return color.getRed() + "," + color.getGreen() + "," + color.getBlue() + "," + ((Particle.DustOptions) object).getSize();
}
return "";
}
@Override
public Optional set(String value) throws IllegalArgumentException {
String[] split = value.split(",", 4);
int r = Integer.parseInt(split[0]);
int g = Integer.parseInt(split[1]);
int b = Integer.parseInt(split[2]);
float size = Float.parseFloat(split[3]);
return Optional.of(new Particle.DustOptions(Color.fromRGB(r, g, b), size));
}
}
enum Target {
MOBS, PLAYERS, ALL
}
private enum HomingTargetMode {
ONE_TARGET, MULTI_TARGET;
}
}
| src/main/java/think/rpgitems/power/impl/PowerBeam.java | package think.rpgitems.power.impl;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import org.librazy.nclangchecker.LangKey;
import think.rpgitems.RPGItems;
import think.rpgitems.data.Context;
import think.rpgitems.power.*;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static think.rpgitems.Events.*;
import static think.rpgitems.power.Utils.checkCooldown;
/**
* @Author ReinWD
* @email [email protected]
* Wrote & Maintained by ReinWD
* if you have any issue, please send me email or @ReinWD in issues.
* Accepted language: 中文, English.
*/
@PowerMeta(defaultTrigger = "RIGHT_CLICK")
public class PowerBeam extends BasePower implements PowerPlain, PowerRightClick, PowerLeftClick, PowerSneak, PowerSneaking, PowerSprint, PowerBowShoot, PowerHitTaken, PowerHit, PowerHurt {
@Property
public int length = 10;
@Property
public Particle particle = Particle.LAVA;
@Property
public int amount = 200;
@Property
public Mode mode = Mode.BEAM;
@Property
public boolean pierce = true;
@Property
public boolean ignoreWall = true;
@Property
public double damage = 20;
@Property
public int movementTicks = 40;
@Property
public double offsetX = 0;
@Property
public double offsetY = 0;
@Property
public double offsetZ = 0;
@Property
public double spawnsPerBlock = 2;
double lengthPerSpawn = 1 / spawnsPerBlock;
/**
* Cost of this power
*/
@Property
public int cost = 0;
/**
* Cooldown time of this power
*/
@Property
public long cooldown = 0;
@Property
public boolean cone = false;
@Property
public double coneRange = 30;
@Property
public boolean homing = false;
@Property
public double homingAngle = 1;
@Property
public double homingRange = 30;
@Property
public HomingTargetMode homingTargetMode = HomingTargetMode.ONE_TARGET;
@Property
public Target homingTarget = Target.MOBS;
@Property
public int stepsBeforeHoming = 5;
@Property
public int burstCount = 1;
@Property
public int beamAmount = 1;
@Property
public int burstInterval = 1;
@Property
public int bounce = 0;
@Property
public boolean hitSelfWhenBounced = false;
@Property
public double gravity = 0;
@Property
@Serializer(ExtraDataSerializer.class)
@Deserializer(ExtraDataSerializer.class)
public Object extraData;
@Property
public double speed = 0;
/**
* Whether to suppress the hit trigger
*/
@Property
public boolean suppressMelee = false;
private Set<Material> transp = Stream.of(Material.values())
.filter(material -> material.isBlock())
.filter(material -> !material.isSolid() || !material.isOccluding())
.collect(Collectors.toSet());
@Override
public PowerResult<Void> fire(Player player, ItemStack stack) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
return beam(player, stack);
}
@Override
public @LangKey(skipCheck = true) String getName() {
return "beam";
}
@Override
public String displayText() {
return null;
}
@Override
public PowerResult<Void> leftClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sneak(Player player, ItemStack stack, PlayerToggleSneakEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sneaking(Player player, ItemStack stack) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sprint(Player player, ItemStack stack, PlayerToggleSprintEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Float> bowShoot(Player player, ItemStack itemStack, EntityShootBowEvent e) {
return fire(player, itemStack).with(e.getForce());
}
@Override
public PowerResult<Double> hit(Player player, ItemStack stack, LivingEntity entity, double damage, EntityDamageByEntityEvent event) {
return fire(player, stack).with(event.getDamage());
}
@Override
public PowerResult<Double> takeHit(Player target, ItemStack stack, double damage, EntityDamageEvent event) {
return fire(target, stack).with(event.getDamage());
}
private PowerResult<Void> beam(LivingEntity from, ItemStack stack) {
if (burstCount > 0) {
for (int i = 0; i < burstCount; i++) {
new BukkitRunnable() {
@Override
public void run() {
if (cone) {
for (int j = 0; j < beamAmount; j++) {
internalFireBeam(from, stack);
}
} else {
internalFireBeam(from, stack);
}
}
}.runTaskLaterAsynchronously(RPGItems.plugin, i * burstInterval);
}
return PowerResult.ok();
} else {
return internalFireBeam(from, stack);
}
}
final Vector crosser = new Vector(1, 1, 1);
private PowerResult<Void> internalFireBeam(LivingEntity from, ItemStack stack) {
lengthPerSpawn = 1 / spawnsPerBlock;
Location fromLocation = from.getEyeLocation();
Vector towards = from.getEyeLocation().getDirection();
if (cone) {
double phi = random.nextDouble() * 360;
double theta;
if (coneRange > 0) {
theta = random.nextDouble() * coneRange;
Vector clone = towards.clone();
Vector cross = clone.clone().add(crosser);
Vector vertical = clone.getCrossProduct(cross).getCrossProduct(towards);
towards.rotateAroundAxis(vertical, Math.toRadians(theta));
towards.rotateAroundAxis(clone, Math.toRadians(phi));
}
}
Entity target = null;
if (from instanceof Player && homing) {
target = getNextTarget(from.getEyeLocation().getDirection(), fromLocation, from);
// Utils.getLivingEntitiesInCone(Utils.getNearestLivingEntities(this, fromLocation, ((Player) from), Math.min(1000, length), 0), fromLocation.toVector(), homingRange, from.getEyeLocation().getDirection()).stream()
// .filter(livingEntity -> {
// switch (homingTarget) {
// case MOBS:
// return !(livingEntity instanceof Player);
// case PLAYERS:
// return livingEntity instanceof Player && !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
// case ALL:
// return !(livingEntity instanceof Player) || !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
// }
// return true;
// })
// .findFirst().orElse(null);
}
switch (mode) {
case BEAM:
new PlainTask(from, towards, amount, length, target, bounce, stack).runTask(RPGItems.plugin);
break;
case PROJECTILE:
new MovingTask(from, towards, amount, length, target, bounce, stack).runTask(RPGItems.plugin);
break;
}
return PowerResult.ok();
}
private Random random = new Random();
private Vector yUnit = new Vector(0, 1, 0);
@Override
public PowerResult<Void> hurt(Player target, ItemStack stack, EntityDamageEvent event) {
return beam(target, stack);
}
class PlainTask extends BukkitRunnable {
private int bounces;
private double length;
private final ItemStack stack;
private LivingEntity from;
private Vector towards;
private final int apS;
private Entity target;
boolean bounced = false;
public PlainTask(LivingEntity from, Vector towards, int amount, double actualLength, Entity target, int bounces, ItemStack stack) {
this.from = from;
this.towards = towards;
this.length = actualLength;
this.stack = stack;
this.apS = amount / ((int) Math.floor(actualLength));
this.target = target;
this.bounces = bounces;
}
@Override
public void run() {
World world = from.getWorld();
towards.normalize();
Location lastLocation = from.getEyeLocation();
double lpT = length / ((double) movementTicks);
double partsPerTick = lpT / lengthPerSpawn;
for (int i = 0; i < movementTicks; i++) {
boolean isStepHit = false;
Vector step = new Vector(0, 0, 0);
for (int j = 0; j < partsPerTick; j++) {
boolean isHit = tryHit(from, lastLocation, stack, bounced && hitSelfWhenBounced);
isStepHit = isHit || isStepHit;
Block block = lastLocation.getBlock();
if (transp.contains(block.getType())) {
spawnParticle(from, world, lastLocation, (int) Math.ceil(apS / partsPerTick));
} else if (!ignoreWall) {
if (bounces > 0) {
bounces--;
bounced = true;
makeBounce(block, towards, lastLocation.clone().subtract(step));
} else {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
}
step = towards.clone().normalize().multiply(lengthPerSpawn);
lastLocation.add(step);
towards = addGravity(towards, partsPerTick);
towards = homingCorrect(towards, lastLocation, target, i, () -> target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from));
}
if (isStepHit && homingTargetMode.equals(HomingTargetMode.MULTI_TARGET)){
target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from);
}
if (isStepHit && !pierce) {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
}
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
}
Vector gravityVector = new Vector(0, -gravity / 20, 0);
private Vector addGravity(Vector towards, double partsPerTick) {
double gravityPerTick = (-gravity / 20d) / partsPerTick;
gravityVector.setY(gravityPerTick);
return towards.add(gravityVector);
}
private class MovingTask extends BukkitRunnable {
private final LivingEntity from;
private int bounces;
private Vector towards;
private final ItemStack stack;
private final int amountPerSec;
private final List<BukkitRunnable> runnables = new LinkedList<>();
private Entity target;
boolean bounced = false;
public MovingTask(LivingEntity from, Vector towards, int apS, double actualLength, Entity target, int bounces, ItemStack stack) {
this.from = from;
this.towards = towards;
this.stack = stack;
this.amountPerSec = apS / ((int) Math.floor(actualLength));
this.target = target;
this.bounces = bounces;
}
@Override
public void run() {
World world = from.getWorld();
double lpT = ((double) length) / ((double) movementTicks);
double partsPerTick = lpT / lengthPerSpawn;
Location lastLocation = from.getEyeLocation();
towards.normalize();
final int[] finalI = {0};
BukkitRunnable bukkitRunnable = new BukkitRunnable() {
@Override
public void run() {
try {
boolean isStepHit = false;
Vector step = new Vector(0, 0, 0);
for (int k = 0; k < partsPerTick; k++) {
boolean isHit = tryHit(from, lastLocation, stack, bounced && hitSelfWhenBounced);
isStepHit = isHit || isStepHit;
Block block = lastLocation.getBlock();
if (transp.contains(block.getType())) {
spawnParticle(from, world, lastLocation, (int) (amountPerSec / spawnsPerBlock));
} else if (!ignoreWall) {
if (bounces > 0) {
bounces--;
bounced = true;
makeBounce(block, towards, lastLocation.clone().subtract(step));
} else {
this.cancel();
return;
}
}
step = towards.clone().normalize().multiply(lengthPerSpawn);
lastLocation.add(step);
towards = addGravity(towards, partsPerTick);
towards = homingCorrect(towards, lastLocation, target, finalI[0], () -> target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from));
}
if (isStepHit && homingTargetMode.equals(HomingTargetMode.MULTI_TARGET)){
target = getNextTarget(from.getEyeLocation().getDirection(), from.getEyeLocation(), from);
}
if (isStepHit && !pierce) {
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
return;
}
if (finalI[0] >= movementTicks) {
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
finalI[0]++;
} catch (Exception ex) {
from.getServer().getLogger().log(Level.WARNING, "", ex);
this.cancel();
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
}
};
bukkitRunnable.runTaskTimer(RPGItems.plugin, 0, 1);
}
}
private void makeBounce(Block block, Vector towards, Location lastLocation) {
RayTraceResult rayTraceResult = block.rayTrace(lastLocation, towards, towards.length(), FluidCollisionMode.NEVER);
if (rayTraceResult == null) {
return;
} else {
towards.rotateAroundNonUnitAxis(rayTraceResult.getHitBlockFace().getDirection(), Math.toRadians(180)).multiply(-1);
}
}
private Vector homingCorrect(Vector towards, Location lastLocation, Entity target, int i, Runnable runnable) {
if (target == null || i < stepsBeforeHoming) {
return towards;
}
if (target.isDead()){
runnable.run();
}
Location targetLocation;
if (target instanceof LivingEntity) {
targetLocation = ((LivingEntity) target).getEyeLocation();
} else {
targetLocation = target.getLocation();
}
Vector clone = towards.clone();
Vector targetDirection = targetLocation.toVector().subtract(lastLocation.toVector());
float angle = clone.angle(targetDirection);
Vector crossProduct = clone.clone().getCrossProduct(targetDirection);
double actualAng = homingAngle / spawnsPerBlock;
if (angle > Math.toRadians(actualAng)) {
//↓a legacy but functionable way to rotate.
//will create a enlarging circle
clone.add(clone.clone().getCrossProduct(crossProduct).normalize().multiply(-1 * Math.tan(actualAng)));
// ↓a better way to rotate.
// will create a exact circle.
// clone.rotateAroundAxis(crossProduct, actualAng);
} else {
clone = targetDirection.normalize();
}
return clone;
}
private LivingEntity getNextTarget(Vector towards, Location lastLocation, Entity from) {
int radius = Math.min(this.length, 300);
return Utils.getLivingEntitiesInCone(from.getNearbyEntities(radius, this.length, this.length).stream()
.filter(entity -> entity instanceof LivingEntity && !entity.equals(from) && !entity.isDead())
.map(entity -> ((LivingEntity) entity))
.collect(Collectors.toList())
, lastLocation.toVector(), homingRange, towards).stream()
.filter(livingEntity -> {
switch (homingTarget) {
case MOBS:
return !(livingEntity instanceof Player);
case PLAYERS:
return livingEntity instanceof Player && !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
case ALL:
return !(livingEntity instanceof Player) || !((Player) livingEntity).getGameMode().equals(GameMode.SPECTATOR);
}
return true;
})
.findFirst().orElse(null);
}
private void spawnParticle(LivingEntity from, World world, Location lastLocation, int i) {
if ((lastLocation.distance(from.getEyeLocation()) < 1)) {
return;
}
// if (from instanceof Player) {
// ((Player) from).spawnParticle(this.particle, lastLocation, i / 2, offsetX, offsetY, offsetZ, speed, extraData);
// }
world.spawnParticle(this.particle, lastLocation, i, offsetX, offsetY, offsetZ, speed, extraData, true);
}
private boolean tryHit(LivingEntity from, Location loc, ItemStack stack, boolean canHitSelf) {
double offsetLength = new Vector(offsetX, offsetY, offsetZ).length();
double length = Double.isNaN(offsetLength) ? 0 : Math.max(offsetLength, 10);
Collection<Entity> candidates = from.getWorld().getNearbyEntities(loc, length, length, length);
boolean result = false;
if (!pierce) {
List<Entity> collect = candidates.stream()
.filter(entity -> (entity instanceof LivingEntity) && (canHitSelf || !entity.equals(from)) && !entity.isDead())
.filter(entity -> canHit(loc, entity))
.limit(1)
.collect(Collectors.toList());
if (!collect.isEmpty()) {
Entity entity = collect.get(0);
if (entity instanceof LivingEntity) {
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, getNamespacedKey().toString());
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, damage);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, suppressMelee);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, stack);
((LivingEntity) entity).damage(damage, from);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, null);
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
return true;
}
} else {
List<Entity> collect = candidates.stream()
.filter(entity -> (entity instanceof LivingEntity) && (canHitSelf || !entity.equals(from)))
.filter(entity -> canHit(loc, entity))
.collect(Collectors.toList());
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, getNamespacedKey().toString());
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, damage);
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, suppressMelee);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, stack);
if (!collect.isEmpty()) {
collect.stream()
.map(entity -> ((LivingEntity) entity))
.forEach(livingEntity -> {
livingEntity.damage(damage, from);
});
result = true;
}
Context.instance().putTemp(from.getUniqueId(), SUPPRESS_MELEE, null);
Context.instance().putTemp(from.getUniqueId(), OVERRIDING_DAMAGE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE, null);
Context.instance().putTemp(from.getUniqueId(), DAMAGE_SOURCE_ITEM, null);
}
return result;
}
private boolean canHit(Location loc, Entity entity) {
BoundingBox boundingBox = entity.getBoundingBox();
BoundingBox particleBox;
double x = Math.max(offsetX, 0.1);
double y = Math.max(offsetY, 0.1);
double z = Math.max(offsetZ, 0.1);
particleBox = BoundingBox.of(loc, x + 0.1, y + 0.1, z + 0.1);
return boundingBox.overlaps(particleBox) || particleBox.overlaps(boundingBox);
}
private enum Mode {
BEAM,
PROJECTILE,
;
}
public class ExtraDataSerializer implements Getter, Setter {
@Override
public String get(Object object) {
if (object instanceof Particle.DustOptions) {
Color color = ((Particle.DustOptions) object).getColor();
return color.getRed() + "," + color.getGreen() + "," + color.getBlue() + "," + ((Particle.DustOptions) object).getSize();
}
return "";
}
@Override
public Optional set(String value) throws IllegalArgumentException {
String[] split = value.split(",", 4);
int r = Integer.parseInt(split[0]);
int g = Integer.parseInt(split[1]);
int b = Integer.parseInt(split[2]);
float size = Float.parseFloat(split[3]);
return Optional.of(new Particle.DustOptions(Color.fromRGB(r, g, b), size));
}
}
enum Target {
MOBS, PLAYERS, ALL
}
private enum HomingTargetMode {
ONE_TARGET, MULTI_TARGET;
}
}
| Add requireHurtByEntity parameter to power beam
| src/main/java/think/rpgitems/power/impl/PowerBeam.java | Add requireHurtByEntity parameter to power beam | <ide><path>rc/main/java/think/rpgitems/power/impl/PowerBeam.java
<ide> @Property
<ide> public double speed = 0;
<ide>
<add> @Property
<add> public boolean requireHurtByEntity = true;
<add>
<ide>
<ide> /**
<ide> * Whether to suppress the hit trigger
<ide>
<ide> @Override
<ide> public PowerResult<Double> takeHit(Player target, ItemStack stack, double damage, EntityDamageEvent event) {
<del> return fire(target, stack).with(event.getDamage());
<add> if (!requireHurtByEntity || event instanceof EntityDamageByEntityEvent) {
<add> return fire(target, stack).with(event.getDamage());
<add> }
<add> return PowerResult.noop();
<ide> }
<ide>
<ide> private PowerResult<Void> beam(LivingEntity from, ItemStack stack) {
<ide>
<ide> @Override
<ide> public PowerResult<Void> hurt(Player target, ItemStack stack, EntityDamageEvent event) {
<del> return beam(target, stack);
<add> if (!requireHurtByEntity || event instanceof EntityDamageByEntityEvent) {
<add> return fire(target, stack);
<add> }
<add> return PowerResult.noop();
<ide> }
<ide>
<ide> class PlainTask extends BukkitRunnable { |
|
Java | mit | 10ab8126d3f6e4ed546cff29cea012904f2894e3 | 0 | aterai/java-swing-tips,mhcrnl/java-swing-tips,aterai/java-swing-tips,aoguren/java-swing-tips,mhcrnl/java-swing-tips,aoguren/java-swing-tips,aoguren/java-swing-tips,mhcrnl/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips | package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import com.sun.java.swing.plaf.windows.WindowsCheckBoxUI;
public final class MainPanel extends JPanel {
private static final String TEXT = "<html>The vertical alignment of this text gets offset when the font changes.";
private final JCheckBox check1 = new JCheckBox(TEXT);
private final JCheckBox check2 = new JCheckBox(TEXT) {
@Override public void updateUI() {
super.updateUI();
if (getUI() instanceof WindowsCheckBoxUI) {
setUI(new WindowsVerticalAlignmentCheckBoxUI());
} else {
setUI(new BasicVerticalAlignmentCheckBoxUI());
}
setVerticalTextPosition(SwingConstants.TOP);
}
};
private final List<? extends JComponent> list = Arrays.asList(check1, check2);
private final Font font0 = check1.getFont();
private final Font font1 = font0.deriveFont(20f);
private final JToggleButton button = new JToggleButton(new AbstractAction("setFont: 24pt") {
@Override public void actionPerformed(ActionEvent e) {
boolean flag = button.isSelected();
for (JComponent c: list) {
c.setFont(flag ? font1 : font0);
}
}
});
private MainPanel() {
super(new BorderLayout());
check1.setVerticalTextPosition(SwingConstants.TOP);
JPanel p = new JPanel(new GridLayout(1, 2, 2, 2));
p.add(makeTitledPanel(check1, "SwingConstants.TOP"));
p.add(makeTitledPanel(check2, "First line center"));
add(p);
add(button, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
private static JComponent makeTitledPanel(JComponent c, String title) {
JPanel p = new JPanel(new BorderLayout());
p.add(c);
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
final class HtmlViewUtil {
private HtmlViewUtil() { /* Singleton */ }
public static int getFirstLineCenterY(String text, AbstractButton c, Rectangle iconRect) {
int y = 0;
if (text != null && c.getVerticalTextPosition() == SwingConstants.TOP) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v != null) {
try {
Element e = v.getElement().getElement(0);
Shape s = new Rectangle();
Position.Bias b = Position.Bias.Forward;
s = v.modelToView(e.getStartOffset(), b, e.getEndOffset(), b, s);
//System.out.println("v.h: " + s.getBounds());
y = (int) (.5 + Math.abs(s.getBounds().height - iconRect.height) * .5);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
return y;
}
}
class WindowsVerticalAlignmentCheckBoxUI extends WindowsCheckBoxUI {
private Dimension size;
private final Rectangle viewRect = new Rectangle();
private final Rectangle iconRect = new Rectangle();
private final Rectangle textRect = new Rectangle();
@Override public synchronized void paint(Graphics g, JComponent c) {
if (!(c instanceof AbstractButton)) {
return;
}
AbstractButton b = (AbstractButton) c;
Font f = c.getFont();
g.setFont(f);
FontMetrics fm = g.getFontMetrics(f);
Insets i = c.getInsets();
size = b.getSize(size);
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = size.width - i.right - viewRect.x;
viewRect.height = size.height - i.bottom - viewRect.y;
iconRect.setBounds(0, 0, 0, 0); //iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
textRect.setBounds(0, 0, 0, 0); //textRect.x = textRect.y = textRect.width = textRect.height = 0;
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect,
b.getText() == null ? 0 : b.getIconTextGap());
// // fill background
// if (c.isOpaque()) {
// g.setColor(b.getBackground());
// g.fillRect(0, 0, size.width, size.height);
// }
// Paint the radio button
int y = HtmlViewUtil.getFirstLineCenterY(text, b, iconRect);
getDefaultIcon().paintIcon(c, g, iconRect.x, iconRect.y + y);
// Draw the Text
if (text != null) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v == null) {
paintText(g, b, textRect, text);
} else {
v.paint(g, textRect);
}
if (b.hasFocus() && b.isFocusPainted()) {
paintFocus(g, textRect, size);
}
}
}
@Override protected void paintFocus(Graphics g, Rectangle textRect, Dimension size) {
if (textRect.width > 0 && textRect.height > 0) {
super.paintFocus(g, textRect, size);
}
}
}
class BasicVerticalAlignmentCheckBoxUI extends BasicCheckBoxUI {
private Dimension size;
private final Rectangle viewRect = new Rectangle();
private final Rectangle iconRect = new Rectangle();
private final Rectangle textRect = new Rectangle();
@Override public synchronized void paint(Graphics g, JComponent c) {
if (!(c instanceof AbstractButton)) {
return;
}
AbstractButton b = (AbstractButton) c;
Font f = c.getFont();
g.setFont(f);
FontMetrics fm = g.getFontMetrics(f);
Insets i = c.getInsets();
size = b.getSize(size);
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = size.width - i.right - viewRect.x;
viewRect.height = size.height - i.bottom - viewRect.y;
iconRect.setBounds(0, 0, 0, 0); //iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
textRect.setBounds(0, 0, 0, 0); //textRect.x = textRect.y = textRect.width = textRect.height = 0;
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect,
b.getText() == null ? 0 : b.getIconTextGap());
// // fill background
// if (c.isOpaque()) {
// g.setColor(b.getBackground());
// g.fillRect(0, 0, size.width, size.height);
// }
// Paint the radio button
int y = HtmlViewUtil.getFirstLineCenterY(text, b, iconRect);
getDefaultIcon().paintIcon(c, g, iconRect.x, iconRect.y + y);
// Draw the Text
if (text != null) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v == null) {
paintText(g, b, textRect, text);
} else {
v.paint(g, textRect);
}
if (b.hasFocus() && b.isFocusPainted()) {
paintFocus(g, textRect, size);
}
}
}
@Override protected void paintFocus(Graphics g, Rectangle textRect, Dimension size) {
if (textRect.width > 0 && textRect.height > 0) {
super.paintFocus(g, textRect, size);
}
}
}
| VerticalIconAlignMultilineText/src/java/example/MainPanel.java | package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import com.sun.java.swing.plaf.windows.WindowsCheckBoxUI;
public final class MainPanel extends JPanel {
private static final String TEXT = "<html>The vertical alignment of this text gets offset when the font changes.";
private final JCheckBox check1 = new JCheckBox(TEXT);
private final JCheckBox check2 = new JCheckBox(TEXT) {
@Override public void updateUI() {
super.updateUI();
if (getUI() instanceof WindowsCheckBoxUI) {
setUI(new WindowsVerticalAlignmentCheckBoxUI());
} else {
setUI(new BasicVerticalAlignmentCheckBoxUI());
}
setVerticalTextPosition(SwingConstants.TOP);
}
};
private final List<? extends JComponent> list = Arrays.asList(check1, check2);
private final Font font0 = check1.getFont();
private final Font font1 = font0.deriveFont(20f);
private final JToggleButton button = new JToggleButton(new AbstractAction("setFont: 24pt") {
@Override public void actionPerformed(ActionEvent e) {
boolean flag = button.isSelected();
for (JComponent c: list) {
c.setFont(flag ? font1 : font0);
}
}
});
private MainPanel() {
super(new BorderLayout());
check1.setVerticalTextPosition(SwingConstants.TOP);
JPanel p = new JPanel(new GridLayout(1, 2, 2, 2));
p.add(makeTitledPanel(check1, "SwingConstants.TOP"));
p.add(makeTitledPanel(check2, "First line center"));
add(p);
add(button, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
private static JComponent makeTitledPanel(JComponent c, String title) {
JPanel p = new JPanel(new BorderLayout());
p.add(c);
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
final class HtmlViewUtil {
private HtmlViewUtil() { /* Singleton */ }
public static int getFirstLineCenterY(String text, AbstractButton c, Rectangle iconRect) {
int y = 0;
if (text != null && c.getVerticalTextPosition() == SwingConstants.TOP) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v != null) {
try {
Element e = v.getElement().getElement(0);
Shape s = new Rectangle();
Position.Bias b = Position.Bias.Forward;
s = v.modelToView(e.getStartOffset(), b, e.getEndOffset(), b, s);
//System.out.println("v.h: " + s.getBounds());
y = (int) (.5 + Math.abs(s.getBounds().height - iconRect.height) * .5);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
return y;
}
}
class WindowsVerticalAlignmentCheckBoxUI extends WindowsCheckBoxUI {
private Dimension size;
private final Rectangle viewRect = new Rectangle();
private final Rectangle iconRect = new Rectangle();
private final Rectangle textRect = new Rectangle();
@Override public synchronized void paint(Graphics g, JComponent c) {
if (!(c instanceof AbstractButton)) {
return;
}
AbstractButton b = (AbstractButton) c;
Font f = c.getFont();
g.setFont(f);
FontMetrics fm = g.getFontMetrics(f);
Insets i = c.getInsets();
size = b.getSize(size);
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = size.width - i.right - viewRect.x;
viewRect.height = size.height - i.bottom - viewRect.y;
iconRect.setBounds(0, 0, 0, 0); //iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
textRect.setBounds(0, 0, 0, 0); //textRect.x = textRect.y = textRect.width = textRect.height = 0;
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect,
b.getText() == null ? 0 : b.getIconTextGap());
// // fill background
// if (c.isOpaque()) {
// g.setColor(b.getBackground());
// g.fillRect(0, 0, size.width, size.height);
// }
// Paint the radio button
int y = HtmlViewUtil.getFirstLineCenterY(text, b, iconRect);
getDefaultIcon().paintIcon(c, g, iconRect.x, iconRect.y + y);
// Draw the Text
if (text != null) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v == null) {
paintText(g, b, textRect, text);
} else {
v.paint(g, textRect);
}
if (b.hasFocus() && b.isFocusPainted() && textRect.width > 0 && textRect.height > 0) {
paintFocus(g, textRect, size);
}
}
}
}
class BasicVerticalAlignmentCheckBoxUI extends BasicCheckBoxUI {
private Dimension size;
private final Rectangle viewRect = new Rectangle();
private final Rectangle iconRect = new Rectangle();
private final Rectangle textRect = new Rectangle();
@Override public synchronized void paint(Graphics g, JComponent c) {
if (!(c instanceof AbstractButton)) {
return;
}
AbstractButton b = (AbstractButton) c;
Font f = c.getFont();
g.setFont(f);
FontMetrics fm = g.getFontMetrics(f);
Insets i = c.getInsets();
size = b.getSize(size);
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = size.width - i.right - viewRect.x;
viewRect.height = size.height - i.bottom - viewRect.y;
iconRect.setBounds(0, 0, 0, 0); //iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
textRect.setBounds(0, 0, 0, 0); //textRect.x = textRect.y = textRect.width = textRect.height = 0;
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect,
b.getText() == null ? 0 : b.getIconTextGap());
// // fill background
// if (c.isOpaque()) {
// g.setColor(b.getBackground());
// g.fillRect(0, 0, size.width, size.height);
// }
// Paint the radio button
int y = HtmlViewUtil.getFirstLineCenterY(text, b, iconRect);
getDefaultIcon().paintIcon(c, g, iconRect.x, iconRect.y + y);
// Draw the Text
if (text != null) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v == null) {
paintText(g, b, textRect, text);
} else {
v.paint(g, textRect);
}
if (b.hasFocus() && b.isFocusPainted() && textRect.width > 0 && textRect.height > 0) {
paintFocus(g, textRect, size);
}
}
}
}
| refactor: PMD CyclomaticComplexity | VerticalIconAlignMultilineText/src/java/example/MainPanel.java | refactor: PMD CyclomaticComplexity | <ide><path>erticalIconAlignMultilineText/src/java/example/MainPanel.java
<ide> } else {
<ide> v.paint(g, textRect);
<ide> }
<del> if (b.hasFocus() && b.isFocusPainted() && textRect.width > 0 && textRect.height > 0) {
<add> if (b.hasFocus() && b.isFocusPainted()) {
<ide> paintFocus(g, textRect, size);
<ide> }
<add> }
<add> }
<add> @Override protected void paintFocus(Graphics g, Rectangle textRect, Dimension size) {
<add> if (textRect.width > 0 && textRect.height > 0) {
<add> super.paintFocus(g, textRect, size);
<ide> }
<ide> }
<ide> }
<ide> } else {
<ide> v.paint(g, textRect);
<ide> }
<del> if (b.hasFocus() && b.isFocusPainted() && textRect.width > 0 && textRect.height > 0) {
<add> if (b.hasFocus() && b.isFocusPainted()) {
<ide> paintFocus(g, textRect, size);
<ide> }
<ide> }
<ide> }
<del>}
<add> @Override protected void paintFocus(Graphics g, Rectangle textRect, Dimension size) {
<add> if (textRect.width > 0 && textRect.height > 0) {
<add> super.paintFocus(g, textRect, size);
<add> }
<add> }
<add>} |
|
Java | lgpl-2.1 | 28a4cab1abf58fc6075b2806af9a456fa578533f | 0 | jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,janissl/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,lopescan/languagetool,meg0man/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,meg0man/languagetool,jimregan/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool,janissl/languagetool,jimregan/languagetool,lopescan/languagetool,janissl/languagetool,lopescan/languagetool,lopescan/languagetool,languagetool-org/languagetool,meg0man/languagetool,meg0man/languagetool,janissl/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package tools.ltdiff;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* Generates an HTML report of added, deleted and modified rules between versions of LanguageTool.
* See ltdiff.bash.
* @author Markus Brenneis
*/
class VersionDiffGenerator {
public static void main(String[] args) throws IOException {
final VersionDiffGenerator generator = new VersionDiffGenerator();
generator.makeDiff(args[0]);
}
private void makeDiff(String lang) throws IOException {
final List<Rule> oldRules = new ArrayList<Rule>(); // rules in old grammar.xml
final List<Rule> newRules = new ArrayList<Rule>(); // rules in new grammar.xml
final List<Rule> modifiedRules = new ArrayList<Rule>();
for (int i = 0; i < 2; i++) {
final List<Rule> rules;
if (i == 0) {
rules = oldRules;
} else {
rules = newRules;
}
final Scanner scanner = new Scanner(new FileReader(i == 0 ? "tools/ltdiff/old" : "tools/ltdiff/new"));
Rule r = new Rule();
// loop through all lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("id=\"") && line.contains("rule")) {
if (!line.contains("name=\"")) { // merge with the following line if the name is there (e.g. sk)
line += scanner.nextLine();
}
if (r.numberOfExamples() > 0) {
rules.add(r);
r = new Rule();
}
r.id = line;
r.name = line;
r.id = r.id.replaceAll(".*id=\"","").replaceAll("\".*","");
r.name = r.name.replaceAll(".*name=\"","").replaceAll("\".*","");
for (Rule rule : rules) { // ensure that the name is unique
if (r.name.equals(rule.name)) {
r.name += " ";
}
}
} else if (line.contains("type=\"correct\"")) {
while (!line.contains("</example>")) { // merge with the following line(s) if the example continues there
line += scanner.nextLine();
}
r.correct.add(line.replaceAll("marker","b").replaceAll(".*<example.*?>","").replaceAll("</example>.*",""));
} else if (line.contains("type=\"incorrect\"")) {
while (!line.contains("</example>")) {
line += scanner.nextLine();
}
r.incorrect.add(line.replaceAll("marker","b").replaceAll(".*<example.*?>","").replaceAll("</example>.*",""));
}
} // while(readLine)
scanner.close();
}
// sort rules by name
Collections.sort(oldRules);
Collections.sort(newRules);
// create html file containing the tr elements
final FileWriter fileWriter = new FileWriter("changes_" + lang + ".html");
final BufferedWriter out = new BufferedWriter(fileWriter);
for (Rule newRule1 : newRules) {
boolean found = false;
for (int j = 0; j < oldRules.size() && !found; j++) {
if (newRule1.id.equals(oldRules.get(j).id) || newRule1.name.equals(oldRules.get(j).name)) {
found = true;
if (newRule1.numberOfExamples() > oldRules.get(j).numberOfExamples()) { // if the new rules has more examples, it is considered to be improved
final Rule r = newRule1;
for (int k = 0; k < r.correct.size(); k++) { // remove examples which already exist in old rule
for (int l = 0; l < oldRules.get(j).correct.size() && r.correct.size()>0; l++) {
if (r.correct.get(k).equals(oldRules.get(j).correct.get(l))) {
r.correct.remove(k);
if (k > 0) k--;
} // if examples equal
} // for each old correct example
} // for each new correct example
for (int k = 0; k < r.incorrect.size(); k++) { // remove examples which already exist in old rule
for (int l = 0; l < oldRules.get(j).incorrect.size() && r.incorrect.size()>0; l++) {
if (r.incorrect.get(k).equals(oldRules.get(j).incorrect.get(l))) {
r.incorrect.remove(k);
if (k > 0) k--;
} // if examples equal
} // for each old incorrect example
} // for each new incorrect example
modifiedRules.add(r);
} // if new rules has more examples
} // if new rule is not new
} // for each old rule
if (!found) {
out.write("<tr class=\"new\"><td>4NEWRULE</td><td>" + newRule1.name + newRule1.getExamples(false) + "</td></tr>\n");
}
} // for each new rule
for (Rule modifiedRule : modifiedRules) {
out.write("<tr class=\"modified\"><td>6IMPROVEDRULE</td><td>" + modifiedRule.name + modifiedRule.getExamples(true) + "</td></tr>\n");
}
for (Rule oldRule : oldRules) {
boolean found = false;
for (Rule newRule : newRules) {
if (newRule.id.equals(oldRule.id) || newRule.name.equals(oldRule.name)) {
found = true;
}
}
if (!found && !oldRule.name.contains("<")) {
out.write("<tr class=\"removed\"><td>5REMOVEDRULE</td><td>" + oldRule.name + "</td></tr>\n");
}
}
out.close();
}
class Rule implements Comparable<Rule> {
private final List<String> correct = new ArrayList<String>();
private final List<String> incorrect = new ArrayList<String>();
private String name = "";
private String id;
int numberOfExamples() {
return correct.size() + incorrect.size();
}
String getExamples(boolean all) {
String s = "<div>";
for (String anIncorrect : incorrect) {
s += "<span>7FINDERR</span>" + anIncorrect + "<br/>";
}
if (all) {
for (String aCorrect : correct) {
s += "<span>8FINDNOTERR</span>" + aCorrect + "<br/>";
}
}
s = s.substring(0, s.length() - 5) + "</div>";
return s;
}
@Override
public int compareTo(Rule r) {
return this.name.compareTo(r.name);
}
}
} | languagetool-standalone/src/main/dev/tools/ltdiff/VersionDiffGenerator.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package tools.ltdiff;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* Generates an HTML report of added, deleted and modified rules between versions of LanguageTool.
* See ltdiff.bash.
* @author Markus Brenneis
*/
class VersionDiffGenerator {
public static void main(String[] args) throws IOException {
final VersionDiffGenerator generator = new VersionDiffGenerator();
generator.makeDiff(args[0]);
}
private void makeDiff(String lang) throws IOException {
final List<Rule> oldRules = new ArrayList<Rule>(); // rules in old grammar.xml
final List<Rule> newRules = new ArrayList<Rule>(); // rules in new grammar.xml
final List<Rule> modifiedRules = new ArrayList<Rule>();
for (int i = 0; i < 2; i++) {
final List<Rule> rules;
if (i == 0) {
rules = oldRules;
} else {
rules = newRules;
}
final Scanner scanner = new Scanner(new FileReader(i == 0 ? "tools/ltdiff/old" : "tools/ltdiff/new"));
Rule r = new Rule();
// loop through all lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("id=\"") && line.contains("rule")) {
if (!line.contains("name=\"")) { // merge with the following line if the name is there (e.g. sk)
line += scanner.nextLine();
}
if (r.numberOfExamples() > 0) {
rules.add(r);
r = new Rule();
}
r.id = line;
r.name = line;
r.id = r.id.replaceAll(".*id=\"","").replaceAll("\".*","");
r.name = r.name.replaceAll(".*name=\"","").replaceAll("\".*","");
for (Rule rule : rules) { // ensure that the name is unique
if (r.name.equals(rule.name)) {
r.name += " ";
}
}
} else if (line.contains("type=\"correct\"")) {
while (!line.contains("</example>")) { // merge with the following line(s) if the example continues there
line += scanner.nextLine();
}
r.correct.add(line.replaceAll("marker","b").replaceAll(".*<example.*?>","").replaceAll("</example>.*",""));
} else if (line.contains("type=\"incorrect\"")) {
while (!line.contains("</example>")) {
line += scanner.nextLine();
}
r.incorrect.add(line.replaceAll("marker","b").replaceAll(".*<example.*?>","").replaceAll("</example>.*",""));
}
} // while(readLine)
scanner.close();
}
// sort rules by name
Collections.sort(oldRules);
Collections.sort(newRules);
// create html file containing the tr elements
final FileWriter fileWriter = new FileWriter("changes_" + lang + ".html");
final BufferedWriter out = new BufferedWriter(fileWriter);
for (Rule newRule1 : newRules) {
boolean found = false;
for (int j = 0; j < oldRules.size() && !found; j++) {
if (newRule1.id.equals(oldRules.get(j).id) || newRule1.name.equals(oldRules.get(j).name)) {
found = true;
if (newRule1.numberOfExamples() > oldRules.get(j).numberOfExamples()) { // if the new rules has more examples, it is considered to be improved
final Rule r = newRule1;
for (int k = 0; k < r.correct.size(); k++) { // remove examples which already exist in old rule
for (int l = 0; l < oldRules.get(j).correct.size(); l++) {
if (r.correct.get(k).equals(oldRules.get(j).correct.get(l))) {
r.correct.remove(k);
if (k > 0) k--;
} // if examples equal
} // for each old correct example
} // for each new correct example
for (int k = 0; k < r.incorrect.size(); k++) { // remove examples which already exist in old rule
for (int l = 0; l < oldRules.get(j).incorrect.size(); l++) {
if (r.incorrect.get(k).equals(oldRules.get(j).incorrect.get(l))) {
r.incorrect.remove(k);
if (k > 0) k--;
} // if examples equal
} // for each old incorrect example
} // for each new incorrect example
modifiedRules.add(r);
} // if new rules has more examples
} // if new rule is not new
} // for each old rule
if (!found) {
out.write("<tr class=\"new\"><td>4NEWRULE</td><td>" + newRule1.name + newRule1.getExamples(false) + "</td></tr>\n");
}
} // for each new rule
for (Rule modifiedRule : modifiedRules) {
out.write("<tr class=\"modified\"><td>6IMPROVEDRULE</td><td>" + modifiedRule.name + modifiedRule.getExamples(true) + "</td></tr>\n");
}
for (Rule oldRule : oldRules) {
boolean found = false;
for (Rule newRule : newRules) {
if (newRule.id.equals(oldRule.id) || newRule.name.equals(oldRule.name)) {
found = true;
}
}
if (!found && !oldRule.name.contains("<")) {
out.write("<tr class=\"removed\"><td>5REMOVEDRULE</td><td>" + oldRule.name + "</td></tr>\n");
}
}
out.close();
}
class Rule implements Comparable<Rule> {
private final List<String> correct = new ArrayList<String>();
private final List<String> incorrect = new ArrayList<String>();
private String name = "";
private String id;
int numberOfExamples() {
return correct.size() + incorrect.size();
}
String getExamples(boolean all) {
String s = "<div>";
for (String anIncorrect : incorrect) {
s += "<span>7FINDERR</span>" + anIncorrect + "<br/>";
}
if (all) {
for (String aCorrect : correct) {
s += "<span>8FINDNOTERR</span>" + aCorrect + "<br/>";
}
}
s = s.substring(0, s.length() - 5) + "</div>";
return s;
}
@Override
public int compareTo(Rule r) {
return this.name.compareTo(r.name);
}
}
} | [ltdiff] prevent crash when number of new incorrect examples is smaller than the number of old incorrect examples and there are no new incorrect examples
| languagetool-standalone/src/main/dev/tools/ltdiff/VersionDiffGenerator.java | [ltdiff] prevent crash when number of new incorrect examples is smaller than the number of old incorrect examples and there are no new incorrect examples | <ide><path>anguagetool-standalone/src/main/dev/tools/ltdiff/VersionDiffGenerator.java
<ide>
<ide> for (int k = 0; k < r.correct.size(); k++) { // remove examples which already exist in old rule
<ide>
<del> for (int l = 0; l < oldRules.get(j).correct.size(); l++) {
<add> for (int l = 0; l < oldRules.get(j).correct.size() && r.correct.size()>0; l++) {
<ide>
<ide> if (r.correct.get(k).equals(oldRules.get(j).correct.get(l))) {
<ide>
<ide>
<ide> for (int k = 0; k < r.incorrect.size(); k++) { // remove examples which already exist in old rule
<ide>
<del> for (int l = 0; l < oldRules.get(j).incorrect.size(); l++) {
<add> for (int l = 0; l < oldRules.get(j).incorrect.size() && r.incorrect.size()>0; l++) {
<ide>
<ide> if (r.incorrect.get(k).equals(oldRules.get(j).incorrect.get(l))) {
<ide> |
|
Java | apache-2.0 | 3830b174a2621a101b0687b65f7f5a72ef2f4404 | 0 | rtyley/roboguice-sherlock | /*
* Copyright 2012 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.github.rtyley.android.sherlock.roboguice.activity;
import roboguice.RoboGuice;
import roboguice.activity.event.OnActivityResultEvent;
import roboguice.activity.event.OnConfigurationChangedEvent;
import roboguice.activity.event.OnContentChangedEvent;
import roboguice.activity.event.OnCreateEvent;
import roboguice.activity.event.OnDestroyEvent;
import roboguice.activity.event.OnNewIntentEvent;
import roboguice.activity.event.OnPauseEvent;
import roboguice.activity.event.OnRestartEvent;
import roboguice.activity.event.OnResumeEvent;
import roboguice.activity.event.OnStartEvent;
import roboguice.activity.event.OnStopEvent;
import roboguice.event.EventManager;
import roboguice.inject.ContentViewListener;
import roboguice.inject.ContextScope;
import roboguice.inject.PreferenceListener;
import roboguice.inject.RoboInjector;
import roboguice.util.RoboContext;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceScreen;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.google.inject.Inject;
import com.google.inject.Key;
import java.util.HashMap;
import java.util.Map;
/**
* An example of how to make your own Robo-enabled Sherlock activity. Feel free
* to do with with any of the other Sherlock activity types!
*/
public class RoboSherlockPreferenceActivity extends SherlockPreferenceActivity implements RoboContext {
protected EventManager eventManager;
protected PreferenceListener preferenceListener;
protected HashMap<Key<?>, Object> scopedObjects = new HashMap<Key<?>, Object>();
@Inject
ContentViewListener ignored; // BUG find a better place to put this
@Override
protected void onCreate(Bundle savedInstanceState) {
final RoboInjector injector = RoboGuice.getInjector(this);
eventManager = injector.getInstance(EventManager.class);
preferenceListener = injector.getInstance(PreferenceListener.class);
injector.injectMembersWithoutViews(this);
super.onCreate(savedInstanceState);
eventManager.fire(new OnCreateEvent(savedInstanceState));
}
@Override
public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
super.setPreferenceScreen(preferenceScreen);
final ContextScope scope = RoboGuice.getInjector(this).getInstance(ContextScope.class);
synchronized (ContextScope.class) {
scope.enter(this);
try {
preferenceListener.injectPreferenceViews();
} finally {
scope.exit(this);
}
}
}
@Override
protected void onRestart() {
super.onRestart();
eventManager.fire(new OnRestartEvent());
}
@Override
protected void onStart() {
super.onStart();
eventManager.fire(new OnStartEvent());
}
@Override
protected void onResume() {
super.onResume();
eventManager.fire(new OnResumeEvent());
}
@Override
protected void onPause() {
super.onPause();
eventManager.fire(new OnPauseEvent());
}
@Override
protected void onNewIntent( Intent intent ) {
super.onNewIntent(intent);
eventManager.fire(new OnNewIntentEvent());
}
@Override
protected void onStop() {
try {
eventManager.fire(new OnStopEvent());
} finally {
super.onStop();
}
}
@Override
protected void onDestroy() {
try {
eventManager.fire(new OnDestroyEvent());
} finally {
try {
RoboGuice.destroyInjector(this);
} finally {
super.onDestroy();
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
final Configuration currentConfig = getResources().getConfiguration();
super.onConfigurationChanged(newConfig);
eventManager.fire(new OnConfigurationChangedEvent(currentConfig, newConfig));
}
@Override
public void onContentChanged() {
super.onContentChanged();
RoboGuice.getInjector(this).injectViewMembers(this);
eventManager.fire(new OnContentChangedEvent());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
eventManager.fire(new OnActivityResultEvent(requestCode, resultCode, data));
}
@Override
public Map<Key<?>, Object> getScopedObjectMap() {
return scopedObjects;
}
}
| src/main/java/com/github/rtyley/android/sherlock/roboguice/activity/RoboSherlockPreferenceActivity.java | /*
* Copyright 2012 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.github.rtyley.android.sherlock.roboguice.activity;
import roboguice.RoboGuice;
import roboguice.activity.event.OnActivityResultEvent;
import roboguice.activity.event.OnConfigurationChangedEvent;
import roboguice.activity.event.OnContentChangedEvent;
import roboguice.activity.event.OnCreateEvent;
import roboguice.activity.event.OnDestroyEvent;
import roboguice.activity.event.OnNewIntentEvent;
import roboguice.activity.event.OnPauseEvent;
import roboguice.activity.event.OnRestartEvent;
import roboguice.activity.event.OnResumeEvent;
import roboguice.activity.event.OnStartEvent;
import roboguice.activity.event.OnStopEvent;
import roboguice.event.EventManager;
import roboguice.inject.ContentViewListener;
import roboguice.inject.PreferenceListener;
import roboguice.inject.RoboInjector;
import roboguice.util.RoboContext;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceScreen;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.google.inject.Inject;
import com.google.inject.Key;
import java.util.HashMap;
import java.util.Map;
/**
* An example of how to make your own Robo-enabled Sherlock activity. Feel free
* to do with with any of the other Sherlock activity types!
*/
public class RoboSherlockPreferenceActivity extends SherlockPreferenceActivity implements RoboContext {
protected EventManager eventManager;
protected PreferenceListener preferenceListener;
protected HashMap<Key<?>, Object> scopedObjects = new HashMap<Key<?>, Object>();
@Inject
ContentViewListener ignored; // BUG find a better place to put this
@Override
protected void onCreate(Bundle savedInstanceState) {
final RoboInjector injector = RoboGuice.getInjector(this);
eventManager = injector.getInstance(EventManager.class);
preferenceListener = injector.getInstance(PreferenceListener.class);
injector.injectMembersWithoutViews(this);
super.onCreate(savedInstanceState);
eventManager.fire(new OnCreateEvent(savedInstanceState));
}
@Override
public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
super.setPreferenceScreen(preferenceScreen);
preferenceListener.injectPreferenceViews();
}
@Override
protected void onRestart() {
super.onRestart();
eventManager.fire(new OnRestartEvent());
}
@Override
protected void onStart() {
super.onStart();
eventManager.fire(new OnStartEvent());
}
@Override
protected void onResume() {
super.onResume();
eventManager.fire(new OnResumeEvent());
}
@Override
protected void onPause() {
super.onPause();
eventManager.fire(new OnPauseEvent());
}
@Override
protected void onNewIntent( Intent intent ) {
super.onNewIntent(intent);
eventManager.fire(new OnNewIntentEvent());
}
@Override
protected void onStop() {
try {
eventManager.fire(new OnStopEvent());
} finally {
super.onStop();
}
}
@Override
protected void onDestroy() {
try {
eventManager.fire(new OnDestroyEvent());
} finally {
try {
RoboGuice.destroyInjector(this);
} finally {
super.onDestroy();
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
final Configuration currentConfig = getResources().getConfiguration();
super.onConfigurationChanged(newConfig);
eventManager.fire(new OnConfigurationChangedEvent(currentConfig, newConfig));
}
@Override
public void onContentChanged() {
super.onContentChanged();
RoboGuice.getInjector(this).injectViewMembers(this);
eventManager.fire(new OnContentChangedEvent());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
eventManager.fire(new OnActivityResultEvent(requestCode, resultCode, data));
}
@Override
public Map<Key<?>, Object> getScopedObjectMap() {
return scopedObjects;
}
}
| Bring RoboSherlockPreferenceActivity in line with RG 2.0 to fix #12
Checked against:
http://code.google.com/p/roboguice/source/browse/roboguice/src/main/java/roboguice/activity/RoboPreferenceActivity.java?spec=svnb705750da32065695a4909646de3d5d19061c068&r=b705750da32065695a4909646de3d5d19061c068
| src/main/java/com/github/rtyley/android/sherlock/roboguice/activity/RoboSherlockPreferenceActivity.java | Bring RoboSherlockPreferenceActivity in line with RG 2.0 to fix #12 | <ide><path>rc/main/java/com/github/rtyley/android/sherlock/roboguice/activity/RoboSherlockPreferenceActivity.java
<ide> import roboguice.activity.event.OnStopEvent;
<ide> import roboguice.event.EventManager;
<ide> import roboguice.inject.ContentViewListener;
<add>import roboguice.inject.ContextScope;
<ide> import roboguice.inject.PreferenceListener;
<ide> import roboguice.inject.RoboInjector;
<ide> import roboguice.util.RoboContext;
<ide> @Override
<ide> public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
<ide> super.setPreferenceScreen(preferenceScreen);
<del> preferenceListener.injectPreferenceViews();
<add>
<add> final ContextScope scope = RoboGuice.getInjector(this).getInstance(ContextScope.class);
<add> synchronized (ContextScope.class) {
<add> scope.enter(this);
<add> try {
<add> preferenceListener.injectPreferenceViews();
<add> } finally {
<add> scope.exit(this);
<add> }
<add> }
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 2e2a8e1314f7e1964a03c0983431c9d5316109f8 | 0 | missioncommand/mil-sym-java,missioncommand/mil-sym-java,missioncommand/mil-sym-java,missioncommand/mil-sym-java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaLineArray;
/**
* Class to process the pixel arrays
* @author Michael Deutch
*/
import java.awt.Color;
import java.util.ArrayList;
import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Area;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import ArmyC2.C2SD.Utilities.RendererSettings;
import java.awt.geom.Rectangle2D;
/*
* A class to calculate the symbol points for the GeneralPath objects.
* @author Michael Deutch
*/
public final class arraysupport
{
private static double maxLength=100;
private static double minLength=5;
private static double dACP=0;
private static String _className="arraysupport";
protected static void setMinLength(double value)
{
minLength=value;
}
private static void FillPoints(POINT2[] pLinePoints,
int counter,
ArrayList<POINT2>points)
{
points.clear();
for(int j=0;j<counter;j++)
{
points.add(pLinePoints[j]);
}
}
/**
* This is the interface function to CELineArray from clsRenderer2
* for non-channel types
*
* @param lineType the line type
* @param pts the client points
* @param shapes the symbol ShapeInfo objects
* @param clipBounds the rectangular clipping bounds
* @param rev the Mil-Standard-2525 revision
*/
public static ArrayList<POINT2> GetLineArray2(int lineType,
ArrayList<POINT2> pts,
ArrayList<Shape2> shapes,
Rectangle2D clipBounds,
int rev) {
ArrayList<POINT2> points = null;
try {
POINT2 pt = null;
POINT2[] pLinePoints2 = null;
POINT2[] pLinePoints = null;
int vblSaveCounter = pts.size();
//get the count from countsupport
int j = 0;
if (pLinePoints2 == null || pLinePoints2.length == 0)//did not get set above
{
pLinePoints = new POINT2[vblSaveCounter];
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y, pt.style);
}
}
//get the number of points the array will require
int vblCounter = countsupport.GetCountersDouble(lineType, vblSaveCounter, pLinePoints, clipBounds,rev);
//resize pLinePoints and fill the first vblSaveCounter elements with the original points
if(vblCounter>0)
pLinePoints = new POINT2[vblCounter];
else
{
shapes=null;
return null;
}
lineutility.InitializePOINT2Array(pLinePoints);
//safeguards added 2-17-11 after CPOF client was allowed to add points to autoshapes
if(vblSaveCounter>pts.size())
vblSaveCounter=pts.size();
if(vblSaveCounter>pLinePoints.length)
vblSaveCounter=pLinePoints.length;
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y,pt.style);
}
//we have to adjust the autoshapes because they are instantiating with fewer points
points = GetLineArray2Double(lineType, pLinePoints, vblCounter, vblSaveCounter, shapes, clipBounds,rev);
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetLineArray2",
new RendererException("GetLineArray2 " + Integer.toString(lineType), exc));
}
return points;
//the caller can get points
}
/**
* A function to calculate the points for FORTL
* @param pLinePoints OUT - the points arry also used for the return points
* @param lineType
* @param vblSaveCounter the number of client points
* @return
*/
private static int GetFORTLPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, bolVertical = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
//long[] segments=null;
//long numpts2=0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
//numpts2=lineutility.BoundPointsCount(pLinePoints,vblSaveCounter);
//segments=new long[numpts2];
//lineutility.BoundPoints(ref pLinePoints,vblSaveCounter,ref segments);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
switch (lineType) {
default:
dIncrement = 20;
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if (dLengthSegment / 20 < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < dLengthSegment / 20 - 1; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 10, 0);
nCounter++;
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 10);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 3, 10);
nCounter++;
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 2, 10);
nCounter++;
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
if (pLinePoints[j].y < pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 1, 10);
nCounter++;
}
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 0, 10);
nCounter++;
}
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], 10, 0);
nCounter++;
}//end for k
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
return nCounter;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetFORTLPointsDouble",
new RendererException("GetFORTLPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static void CoordFEBADouble(
POINT2[] pLinePoints,
int vblCounter) {
try {
//declarations
int j = 0;
POINT2[] pXLinePoints = new POINT2[4 * vblCounter / 32];
POINT2[] pNewLinePoints = new POINT2[vblCounter / 32];
POINT2[] pShortLinePoints = new POINT2[2 * vblCounter / 32];
POINT2[] pArcLinePoints = new POINT2[26 * vblCounter / 32];
double dPrinter = 1.0;
//end declarations
for (j = vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pLinePoints[0]); //initialize the rest of pLinePoints
pLinePoints[j].style = 0;
}
for (j = 0; j < 4 * vblCounter / 32; j++) {
pXLinePoints[j] = new POINT2(pLinePoints[0]); //initialization only for pXLinePoints
pXLinePoints[j].style = 0;
}
for (j = 0; j < vblCounter / 32; j++) //initialize pNewLinePoints
{
pNewLinePoints[j] = new POINT2(pLinePoints[j]);
pNewLinePoints[j].style = 0;
}
for (j = 0; j < 2 * vblCounter / 32; j++) //initialize pShortLinePoints
{
pShortLinePoints[j] = new POINT2(pLinePoints[0]);
pShortLinePoints[j].style = 0;
}
for (j = 0; j < 26 * vblCounter / 32; j++) //initialize pArcLinePoints
{
pArcLinePoints[j] = new POINT2(pLinePoints[0]);
pArcLinePoints[j].style = 0;
}
//first get the X's
lineutility.GetXFEBADouble(pNewLinePoints, 10 * dPrinter, vblCounter / 32,//was 7
pXLinePoints);
for (j = 0; j < 4 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pXLinePoints[j]);
}
pLinePoints[4 * vblCounter / 32 - 1].style = 5;
for (j = 4 * vblCounter / 32; j < 6 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pShortLinePoints[j - 4 * vblCounter / 32]);
pLinePoints[j].style = 5; //toggle invisible lines between feba's
}
pLinePoints[6 * vblCounter / 32 - 1].style = 5;
//last, get the arcs
lineutility.GetArcFEBADouble(14.0 * dPrinter, pNewLinePoints,
vblCounter / 32,
pArcLinePoints);
for (j = 6 * vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pArcLinePoints[j - 6 * vblCounter / 32]);
}
//clean up
pXLinePoints = null;
pNewLinePoints = null;
pShortLinePoints = null;
pArcLinePoints = null;
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "CoordFEBADouble",
new RendererException("CoordFEBADouble", exc));
}
}
private static int GetATWallPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 0;
int limit = 0;
//POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
pSpikePoints[nCounter++] = new POINT2(pLinePoints[0]);
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
if (limit < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = -1; k < limit; k++)//was k=0 to limit
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = new POINT2(pt0);
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0;j < nCounter;j++){
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble", exc));
}
return nCounter;
}
public static int GetInsideOutsideDouble2(POINT2 pt0,
POINT2 pt1,
POINT2[] pLinePoints,
int vblCounter,
int index,
int lineType) {
int nDirection = 0;
try {
//declarations
ref<double[]> m = new ref();
ref<double[]> m0 = new ref();
double b0 = 0;
double b2 = 0;
double b = 0;
double X0 = 0; //segment midpoint X value
double Y0 = 0; //segment midpoint Y value
double X = 0; //X value of horiz line from left intercept with current segment
double Y = 0; //Y value of vertical line from top intercept with current segment
int nInOutCounter = 0;
int j = 0, bolVertical = 0;
int bolVertical2 = 0;
int nOrientation = 0; //will use 0 for horiz line from left, 1 for vertical line from top
int extendLeft = 0;
int extendRight = 1;
int extendAbove = 2;
int extendBelow = 3;
int oppSegment=vblCounter-index-3; //used by BELT1 only
POINT2 pt2=new POINT2();
//end declarations. will use this to determine the direction
//slope of the segment
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m0);
if(m0.value==null)
return 0;
//get the midpoint of the segment
X0 = (pt0.x + pt1.x) / 2;
Y0 = (pt0.y + pt1.y) / 2;
if(lineType==TacticalLines.BELT1 && oppSegment>=0 && oppSegment<vblCounter-1)
{
//get the midpoint of the opposite segment
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
//must calculate the corresponding point on the current segment
//first get the y axis intercept of the perpendicular line for the opposite (short) segment
//calculate this line at the midpoint of the opposite (short) segment
b0=Y0+1/m0.value[0]*X0;
//the y axis intercept of the index segment
b2=pt0.y-m0.value[0]*pt0.x;
if(m0.value[0]!=0 && bolVertical!=0)
{
//calculate the intercept at the midpoint of the shorter segment
pt2=lineutility.CalcTrueIntersectDouble2(-1/m0.value[0],b0,m0.value[0],b2,1,1,0,0);
X0=pt2.x;
Y0=pt2.y;
}
if(m0.value[0]==0 && bolVertical!=0)
{
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pt0.y+pt1.y )/2;
}
if(bolVertical==0)
{
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
X0= ( pt0.x+pt1.x )/2;
}
}
//slope is not too small or is vertical, use left to right
if (Math.abs(m0.value[0]) >= 1 || bolVertical == 0) {
nOrientation = 0; //left to right orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j) {
//for BELT1 we only want to know if the opposing segment is to the
//left of the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j) //change 2
continue;
if ((pLinePoints[j].y <= Y0 && pLinePoints[j + 1].y >= Y0) ||
(pLinePoints[j].y >= Y0 && pLinePoints[j + 1].y <= Y0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 1 && m.value[0] == 0) //current segment is horizontal, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter--;
}
//current segment is vertical, it's x value must be to the left
//of the current segment X0 for the horiz line from the left to cross
if (bolVertical2 == 0) {
if (pLinePoints[j].x < X0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the X value of the intersection between the horiz line
//from the left and the current segment
//b=Y0;
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
X = (Y0 - b) / m.value[0];
if (X < X0) //the horizontal line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
} //end if
else //use top to bottom to get orientation
{
nOrientation = 1; //top down orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j)
{
//for BELT1 we only want to know if the opposing segment is
//above the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j)
continue;
if ((pLinePoints[j].x <= X0 && pLinePoints[j + 1].x >= X0) ||
(pLinePoints[j].x >= X0 && pLinePoints[j + 1].x <= X0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 0) //current segment is vertical, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter--;
}
//current segment is horizontal, it's y value must be above
//the current segment Y0 for the horiz line from the left to cross
if (bolVertical2 == 1 && m.value[0] == 0) {
if (pLinePoints[j].y < Y0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the Y value of the intersection between the vertical line
//from the top and the current segment
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
Y = m.value[0] * X0 + b;
if (Y < Y0) //the vertical line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
}
switch (nInOutCounter % 2) {
case 0:
if (nOrientation == 0) {
nDirection = extendLeft;
} else {
nDirection = extendAbove;
}
break;
case 1:
if (nOrientation == 0) {
nDirection = extendRight;
} else {
nDirection = extendBelow;
}
break;
default:
break;
}
} catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetInsideOutsideDouble2",
new RendererException("GetInsideOutsideDouble2", exc));
}
return nDirection;
}
/**
* BELT1 line and others
* @param pLinePoints
* @param lineType
* @param vblSaveCounter
* @return
*/
protected static int GetZONEPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, n = 0;
int lCount = 0;
double dLengthSegment = 0;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = null, pt2 = null, pt3 = null;
POINT2[] pSpikePoints = null;
int nDirection = 0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
double remainder=0;
//for(j=0;j<numpts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++) {
pt1 = new POINT2(pLinePoints[j]);
pt2 = new POINT2(pLinePoints[j + 1]);
//get the direction for the spikes
nDirection = GetInsideOutsideDouble2(pt1, pt2, pLinePoints, vblSaveCounter, (int) j, lineType);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
//reverse the direction for those lines with inward spikes
if (!(lineType == TacticalLines.BELT) && !(lineType == TacticalLines.BELT1) )
{
if (dLengthSegment < 20) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
switch (nDirection) {
case 0: //extend left
nDirection = 1; //extend right
break;
case 1: //extend right
nDirection = 0; //extend left
break;
case 2: //extend above
nDirection = 3; //extend below
break;
case 3: //extgend below
nDirection = 2; //extend above
break;
default:
break;
}
break;
default:
break;
}
n = (int) (dLengthSegment / 20);
remainder=dLengthSegment-n*20;
for (k = 0; k < n; k++)
{
if(k>0)
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20-remainder/2, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10-remainder/2, 0);//was -10
}
else
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10, 0);//was -10
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 5);
break;
case TacticalLines.STRONG:
case TacticalLines.FORT:
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
break;
default:
break;
}
pSpikePoints[nCounter++] = lineutility.ExtendDirectedLine(pt1, pt2, pt0, nDirection, 10);
//nCounter++;
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
break;
case TacticalLines.STRONG:
pSpikePoints[nCounter] = new POINT2(pSpikePoints[nCounter - 2]);
break;
case TacticalLines.FORT:
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pt1, pt2, pt3, nDirection, 10);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pt3);
break;
default:
break;
}
//}
nCounter++;
//diagnostic
if(lineType==TacticalLines.ENCIRCLE)
pSpikePoints[nCounter++] = new POINT2(pSpikePoints[nCounter-4]);
}//end for k
pSpikePoints[nCounter++] = new POINT2(pLinePoints[j + 1]);
//nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[j].style = 11;
}
}
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[nCounter - 1].style = 12;
} else {
if(nCounter>0)
pSpikePoints[nCounter - 1].style = 5;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
if (j == nCounter - 1) {
if (lineType != (long) TacticalLines.OBSAREA) {
pLinePoints[j].style = 5;
}
}
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetZONEPointsDouble2",
new RendererException("GetZONEPointsDouble2", exc));
}
return nCounter;
}
private static boolean IsTurnArcReversed(POINT2[] pPoints) {
try {
if (pPoints.length < 3) {
return false;
}
POINT2[] ptsSeize = new POINT2[2];
ptsSeize[0] = new POINT2(pPoints[0]);
ptsSeize[1] = new POINT2(pPoints[1]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double d = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize[0] = new POINT2(pPoints[1]);
ptsSeize[1] = new POINT2(pPoints[0]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double dArcReversed = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize = null;
if (dArcReversed > d) {
return true;
} else {
return false;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "IsTurnArcReversed",
new RendererException("IsTurnArcReversed", exc));
}
return false;
}
private static void GetIsolatePointsDouble(POINT2[] pLinePoints,
int lineType) {
try {
//declarations
boolean reverseTurn=false;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = new POINT2(pLinePoints[1]), pt2 = new POINT2(pLinePoints[0]);
if(pt0.x==pt1.x && pt0.y==pt1.y)
pt1.x+=1;
POINT2 C = new POINT2(), E = new POINT2(), midPt = new POINT2();
int j = 0, k = 0, l = 0;
POINT2[] ptsArc = new POINT2[26];
POINT2[] midPts = new POINT2[7];
POINT2[] trianglePts = new POINT2[21];
POINT2[] pArrowPoints = new POINT2[3], reversepArrowPoints = new POINT2[3];
double dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
double dLength = Math.abs(dRadius - 20);
if(dRadius<40)
{
dLength=dRadius/1.5;
}
double d = lineutility.MBRDistance(pLinePoints, 2);
POINT2[] ptsSeize = new POINT2[2];
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(pLinePoints[j]);
}
if (pLinePoints.length >= 3) {
savepoints[2] = new POINT2(pLinePoints[2]);
}
lineutility.InitializePOINT2Array(ptsArc);
lineutility.InitializePOINT2Array(midPts);
lineutility.InitializePOINT2Array(trianglePts);
lineutility.InitializePOINT2Array(pArrowPoints);
lineutility.InitializePOINT2Array(reversepArrowPoints);
lineutility.InitializePOINT2Array(ptsSeize);
if (d / 7 > maxLength) {
d = 7 * maxLength;
}
if (d / 7 < minLength) { //was minLength
d = 7 * minLength; //was minLength
}
//change due to outsized arrow in 6.0, 11-3-10
if(d>140)
d=140;
//calculation points for the SEIZE arrowhead
//for SEIZE calculations
POINT2[] ptsArc2 = new POINT2[26];
lineutility.InitializePOINT2Array(ptsArc2);
//end declarations
E.x = 2 * pt1.x - pt0.x;
E.y = 2 * pt1.y - pt0.y;
ptsArc[0] = new POINT2(pLinePoints[1]);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) d / 7, pArrowPoints, 0);
pLinePoints[25].style = 5;
switch (lineType) {
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.ISOLATE:
for (j = 1; j <= 23; j++) {
if (j % 3 == 0) {
midPts[k].x = pt0.x - (long) ((dLength / dRadius) * (pt0.x - ptsArc[j].x));
midPts[k].y = pt0.y - (long) ((dLength / dRadius) * (pt0.y - ptsArc[j].y));
midPts[k].style = 0;
trianglePts[l] = new POINT2(ptsArc[j - 1]);
l++;
trianglePts[l] = new POINT2(midPts[k]);
l++;
trianglePts[l] = new POINT2(ptsArc[j + 1]);
trianglePts[l].style = 5;
l++;
k++;
}
}
for (j = 26; j < 47; j++) {
pLinePoints[j] = new POINT2(trianglePts[j - 26]);
}
pLinePoints[46].style = 5;
for (j = 47; j < 50; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 47]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.OCCUPY:
midPt.x = (pt1.x + ptsArc[25].x) / 2;
midPt.y = (pt1.y + ptsArc[25].y) / 2;
lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) d / 7, reversepArrowPoints, 0);
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
}
for (j = 29; j < 32; j++) {
pLinePoints[j] = new POINT2(reversepArrowPoints[j - 29]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.SECURE:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
break;
case TacticalLines.TURN:
boolean changeArc = IsTurnArcReversed(savepoints); //change 1
if (reverseTurn == true || changeArc == true) //swap the points
{
pt0.x = pt1.x;
pt0.y = pt1.y;
pt1.x = pt2.x;
pt1.y = pt2.y;
}
ptsSeize[0] = new POINT2(pt0);
ptsSeize[1] = new POINT2(pt1);
dRadius = lineutility.CalcClockwiseCenterDouble(ptsSeize);
C = new POINT2(ptsSeize[0]);
E = new POINT2(ptsSeize[1]);
ptsArc[0] = new POINT2(pt0);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if (changeArc == true)//if(changeArc==false) //change 1
{
lineutility.GetArrowHead4Double(ptsArc[1], pt0, (int) d / 7, (int) d / 7, pArrowPoints, 5);
} else {
lineutility.GetArrowHead4Double(ptsArc[24], pt1, (int) d / 7, (int) d / 7, pArrowPoints, 5);
}
pLinePoints[25].style = 5;
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 9;
}
pLinePoints[28].style = 10;
break;
case TacticalLines.RETAIN:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
//get the extended points for retain
k = 29;
for (j = 1; j < 24; j++) {
pLinePoints[k] = new POINT2(ptsArc[j]);
pLinePoints[k].style = 0;
k++;
pLinePoints[k] = lineutility.ExtendLineDouble(pt0, ptsArc[j], (long) d / 7);
pLinePoints[k].style = 5;
k++;
}
break;
default:
break;
}
//clean up
savepoints = null;
ptsArc = null;
midPts = null;
trianglePts = null;
pArrowPoints = null;
reversepArrowPoints = null;
ptsSeize = null;
ptsArc2 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIsolatePointsDouble",
new RendererException("GetIsolatePointsDouble " + Integer.toString(lineType), exc));
}
return;
}
/**
* @deprecated
* returns the location for the Dummy Hat
* @param pLinePoints
* @return
*/
private static POINT2 getDummyHat(POINT2[]pLinePoints)
{
POINT2 pt=null;
try
{
int j=0;
double minY=Double.MAX_VALUE;
double minX=Double.MAX_VALUE,maxX=-Double.MAX_VALUE;
int index=-1;
//get the highest point
for(j=0;j<pLinePoints.length-3;j++)
{
if(pLinePoints[j].y<minY)
{
minY=pLinePoints[j].y;
index=j;
}
if(pLinePoints[j].x<minX)
minX=pLinePoints[j].x;
if(pLinePoints[j].x>maxX)
maxX=pLinePoints[j].x;
}
pt=new POINT2(pLinePoints[index]);
double deltaMaxX=0;
double deltaMinX=0;
if(pt.x+25>maxX)
{
deltaMaxX=pt.x+25-maxX;
pt.x-=deltaMaxX;
}
if(pt.x-25<minX)
{
deltaMinX=minX-(pt.x-25);
pt.x+=deltaMinX;
}
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "getDummyHat",
new RendererException("getDummyHat", exc));
}
return pt;
}
private static void AreaWithCenterFeatureDouble(POINT2[] pLinePoints,
int vblCounter,
int lineType )
{
try
{
//declarations
int k=0;
POINT2 ptCenter = new POINT2();
double d = lineutility.MBRDistance(pLinePoints, vblCounter);
//11-18-2010
if(d>350)
d=350;
//end declarations
for (k = 0; k < vblCounter; k++) {
pLinePoints[k].style = 0;
}
switch (lineType) {
case TacticalLines.DUMMY:
POINT2 ul=new POINT2();
POINT2 lr=new POINT2();
lineutility.CalcMBRPoints(pLinePoints, vblCounter-3, ul, lr);
//ul=getDummyHat(pLinePoints);
//ul.x-=25;
POINT2 ur=new POINT2(lr);
ur.y=ul.y;
pLinePoints[vblCounter-3]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-3].x-=25;
pLinePoints[vblCounter-3].y-=10;
pLinePoints[vblCounter-2]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-2].y-=35;
pLinePoints[vblCounter-1]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-1].x+=25;
pLinePoints[vblCounter-1].y-=10;
pLinePoints[vblCounter-4].style=5;
break;
case TacticalLines.AIRFIELD:
pLinePoints[vblCounter - 5] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 5].style = 5;
pLinePoints[vblCounter - 4] = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 4].x -= d / 20;
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 3].x = pLinePoints[vblCounter - 4].x + d / 10;
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 2].y += d / 40;
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 3]);
pLinePoints[vblCounter - 1].y -= d / 40;
pLinePoints[vblCounter - 1].style = 0;
break;
case TacticalLines.DMA:
if (lineType == (long) TacticalLines.DMA) {
for (k = 0; k < vblCounter - 4; k++) {
pLinePoints[k].style = 14;
}
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 4].style = 5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 3);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
break;
case TacticalLines.DMAF:
pLinePoints[vblCounter-4].style=5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 3);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
pLinePoints[vblCounter - 1].style = 5;
break;
default:
break;
}
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AreaWithCenterFeatureDouble",
new RendererException("AreaWithCenterFeatureDouble " + Integer.toString(lineType), exc));
}
}
private static int GetATWallPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dRemainder = 0, dSpikeSize = 0;
int limit = 0;
POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
switch (lineType) {
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter] = pLinePoints[0];
pSpikePoints[nCounter].style = 0;
nCounter++;
break;
default:
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
switch (lineType) {
case TacticalLines.UCF:
case TacticalLines.CF:
case TacticalLines.CFG:
case TacticalLines.CFY:
dIncrement = 60;
dSpikeSize = 20;
dRemainder = dLengthSegment / dIncrement - (double) ((int) (dLengthSegment / dIncrement));
if (dRemainder < 0.75) {
limit = (int) (dLengthSegment / dIncrement);
} else {
limit = (int) (dLengthSegment / dIncrement) + 1;
}
break;
default:
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
break;
}
if (limit < 1) {
pSpikePoints[nCounter] = pLinePoints[j];
nCounter++;
pSpikePoints[nCounter] = pLinePoints[j + 1];
nCounter++;
continue;
}
for (k = 0; k < limit; k++) {
switch (lineType) {
case TacticalLines.CFG: //linebreak for dot
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 4, 5); //+2
nCounter++;
//dot
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 1, 20);
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 7, 0); //-4
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
case TacticalLines.CFY: //linebreak for crossed line
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 10, 5); //+2
nCounter++;
//dot
//pSpikePoints[nCounter]=lineutility.ExtendLine2Double(pLinePoints[j+1],pLinePoints[j],-k*dIncrement-1,20);
//nCounter++;
//replace the dot with crossed line segment
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 5, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 10, 5);
nCounter++;
crossPt1 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 1], 2, 5, 0);
crossPt2 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 2], 3, 5, 5);
pSpikePoints[nCounter] = crossPt1;
nCounter++;
pSpikePoints[nCounter] = crossPt2;
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 13, 0); //-4
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
default:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
break;
}
if (lineType == TacticalLines.CF) {
pSpikePoints[nCounter].style = 0;
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - dSpikeSize, 0);
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter].style = 9;
}
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = pt0;
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter - 1].style = 9;
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
//need an extra point for these
switch (lineType) {
case TacticalLines.CF:
pSpikePoints[nCounter].style = 10;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter].style = 10;
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], dSpikeSize, 0);
break;
default:
break;
}
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = pLinePoints[j + 1];
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = pSpikePoints[j];
}
pLinePoints[nCounter-1].style=5;
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static int GetRidgePointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 20;
int limit = 0;
double d = 0;
int bolVertical = 0;
//end delcarations
m.value = new double[1];
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
//for(j=0;j<numPts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++)
{
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
limit = (int) (dLengthSegment / dIncrement);
if (limit < 1)
{
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < limit; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
d = lineutility.CalcDistanceDouble(pLinePoints[j], pSpikePoints[nCounter - 1]);
pt0 = lineutility.ExtendLineDouble(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize / 2);
//the spikes
if (bolVertical != 0) //segment is not vertical
{
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, dSpikeSize);
}
else //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, dSpikeSize);
}
}
else //segment is vertical
{
if (pLinePoints[j + 1].y < pLinePoints[j].y) //extend left of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, dSpikeSize);
}
else //extend right of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, dSpikeSize);
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize, 0);
nCounter++;
}
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
//}
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
for (j = nCounter; j < lCount; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[nCounter - 1]);
}
//clean up
//segments=null;
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRidgePointsDouble",
new RendererException("GetRidgePointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
protected static int GetSquallDouble(POINT2[] pLinePoints,
int amplitude,
int quantity,
int length,
int numPoints)
{
int counter = 0;
try {
int j = 0, k = 0;
POINT2 StartSegPt, EndSegPt;
POINT2 savePoint1 = new POINT2(pLinePoints[0]);
POINT2 savePoint2 = new POINT2(pLinePoints[numPoints - 1]);
ref<int[]> sign = new ref();
int segQty = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints);
POINT2[] pSquallPts = new POINT2[totalQty];
POINT2[] pSquallSegPts = null;
//end declarations
lineutility.InitializePOINT2Array(pSquallPts);
sign.value = new int[1];
sign.value[0] = -1;
if (totalQty == 0) {
return 0;
}
for (j = 0; j < numPoints - 1; j++) {
//if(segments[j]!=0)
//{
StartSegPt = new POINT2(pLinePoints[j]);
EndSegPt = new POINT2(pLinePoints[j + 1]);
segQty = countsupport.GetSquallSegQty(StartSegPt, EndSegPt, quantity, length);
if (segQty > 0)
{
pSquallSegPts = new POINT2[segQty];
lineutility.InitializePOINT2Array(pSquallSegPts);
}
else
{
continue;
}
lineutility.GetSquallSegment(StartSegPt, EndSegPt, pSquallSegPts, sign, amplitude, quantity, length);
for (k = 0; k < segQty; k++)
{
pSquallPts[counter].x = pSquallSegPts[k].x;
pSquallPts[counter].y = pSquallSegPts[k].y;
if (k == 0)
{
pSquallPts[counter] = new POINT2(pLinePoints[j]);
}
if (k == segQty - 1)
{
pSquallPts[counter] = new POINT2(pLinePoints[j + 1]);
}
pSquallPts[counter].style = 0;
counter++;
}
}
//load the squall points into the linepoints array
for (j = 0; j < counter; j++) {
if (j < totalQty)
{
pLinePoints[j].x = pSquallPts[j].x;
pLinePoints[j].y = pSquallPts[j].y;
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
}
if (j == counter - 1)
{
pLinePoints[j] = new POINT2(savePoint2);
}
pLinePoints[j].style = pSquallPts[j].style;
}
}
if (counter == 0)
{
for (j = 0; j < pLinePoints.length; j++)
{
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
} else
{
pLinePoints[j] = new POINT2(savePoint2);
}
}
counter = pLinePoints.length;
}
//clean up
pSquallPts = null;
pSquallSegPts = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSquallDouble",
new RendererException("GetSquallDouble", exc));
}
return counter;
}
protected static int GetSevereSquall(POINT2[] pLinePoints,
int numPoints) {
int l = 0;
try
{
int quantity = 5, length = 30, j = 0, k = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints) + 2 * numPoints;
POINT2[] squallPts = new POINT2[totalQty];
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), pt2 = new POINT2(),
pt3 = new POINT2(), pt4 = new POINT2(), pt5 = new POINT2(), pt6 = new POINT2(),
pt7 = new POINT2(),pt8 = new POINT2();
int segQty = 0;
double dist = 0;
//end declarations
lineutility.InitializePOINT2Array(squallPts);
//each segment looks like this: --- V
for (j = 0; j < numPoints - 1; j++)
{
dist = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
segQty = (int) (dist / 30);
for (k = 0; k < segQty; k++) {
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30);
pt1 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 20);
//pt0.style = 5;
pt5 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 25);
pt6 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 30);
//pt6.style=5;
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 5, 0); //extend above line
pt3 = lineutility.ExtendDirectedLine(pt0, pt5, pt5, 3, 5, 0); //extend below line
pt4 = lineutility.ExtendDirectedLine(pt0, pt6, pt6, 2, 5, 5); //extend above line
pt4.style=5;
squallPts[l++] = new POINT2(pt2);
squallPts[l++] = new POINT2(pt3);
squallPts[l++] = new POINT2(pt4);
pt7 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 5);
pt8 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 10);
pt8.style=5;
squallPts[l++] = new POINT2(pt7);
squallPts[l++] = new POINT2(pt8);
}
//segment remainder
squallPts[l++] = new POINT2(pLinePoints[j + 1]);
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j+1], pLinePoints[j], 5);
pt0.style=5;
squallPts[l++]=new POINT2(pt0);
}
for (j = 0; j < l; j++)
{
if (j < totalQty)
{
pLinePoints[j] = new POINT2(squallPts[j]);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSevereSquall",
new RendererException("GetSevereSquall", exc));
}
return l;
}
private static int GetConvergancePointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = vblCounter;
try {
int j = 0, k = 0;
//int counter=vblCounter;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
pLinePoints[vblCounter - 1].style = 5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 10);
//we don't want too small a remainder
if (d - numJags * 10 < 5)
{
numJags -= 1;
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
//the first spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 10 + 5, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 2, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
//the 2nd spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, (k + 1) * 10, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 3, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetConvergancePointsDouble",
new RendererException("GetConvergancePointsDouble", exc));
}
return counter;
}
private static int GetITDPointsDouble(POINT2[] pLinePoints, int vblCounter)
{
int counter = 0;
try {
int j = 0, k = 0;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0, lineStyle = 19;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
//pLinePoints[vblCounter-1].style=5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 15);
//we don't want too small a remainder
if (d - numJags * 10 < 5) {
numJags -= 1;
}
if(numJags==0)
{
pt0.style=19;
pLinePoints[counter++] = new POINT2(pt0);
pt1.style=5;
pLinePoints[counter++] = new POINT2(pt1);
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 15 + 5, lineStyle);
pLinePoints[counter++] = new POINT2(tempPt);
if (k < numJags - 1) {
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 10, 5);
} else {
tempPt = new POINT2(tempPts[j + 1]);
tempPt.style = 5;
}
pLinePoints[counter++] = new POINT2(tempPt);
if (lineStyle == 19) {
lineStyle = 25;
} else {
lineStyle = 19;
}
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetITDPointsDouble",
new RendererException("GetITDPointsDouble", exc));
}
return counter;
}
private static int GetXPoints(POINT2[] pOriginalLinePoints, POINT2[] XPoints, int vblCounter)
{
int xCounter=0;
try
{
int j=0,k=0;
double d=0;
POINT2 pt0,pt1,pt2,pt3=new POINT2(),pt4=new POINT2(),pt5=new POINT2(),pt6=new POINT2();
int numThisSegment=0;
double distInterval=0;
for(j=0;j<vblCounter-1;j++)
{
d=lineutility.CalcDistanceDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1]);
numThisSegment=(int)( (d-20d)/20d);
//added 4-19-12
distInterval=d/numThisSegment;
for(k=0;k<numThisSegment;k++)
{
//pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1], 10+20*k);
pt0=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j],pOriginalLinePoints[j+1], distInterval/2+distInterval*k);
pt1=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], 5);
pt2=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], -5);
pt3=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 2, 5);
pt4=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 3, 5);
pt4.style=5;
pt5=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 2, 5);
pt6=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 3, 5);
pt6.style=5;
XPoints[xCounter++]=new POINT2(pt3);
XPoints[xCounter++]=new POINT2(pt6);
XPoints[xCounter++]=new POINT2(pt5);
XPoints[xCounter++]=new POINT2(pt4);
}
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return xCounter;
}
/**
* returns a 37 point ellipse
* @param ptCenter
* @param ptWidth
* @param ptHeight
* @return
*/
private static POINT2[] getEllipsePoints(POINT2 ptCenter, POINT2 ptWidth, POINT2 ptHeight)
{
POINT2[]pEllipsePoints=null;
try
{
pEllipsePoints=new POINT2[37];
int l=0;
double dFactor=0;
double a=lineutility.CalcDistanceDouble(ptCenter, ptWidth);
double b=lineutility.CalcDistanceDouble(ptCenter, ptHeight);
lineutility.InitializePOINT2Array(pEllipsePoints);
for (l = 1; l < 37; l++)
{
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints[l - 1].style = 0;
}
pEllipsePoints[36]=new POINT2(pEllipsePoints[0]);
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return pEllipsePoints;
}
private static int GetLVOPoints(POINT2[] pOriginalLinePoints, POINT2[] pLinePoints, int vblCounter)
{
int lEllipseCounter = 0;
try {
//double dAngle = 0, d = 0, a = 13, b = 6, dFactor = 0;
double dAngle = 0, d = 0, a = 4, b = 8, dFactor = 0;
int lHowManyThisSegment = 0, j = 0, k = 0, l = 0, t = 0;
POINT2 ptCenter = new POINT2();
POINT2[] pEllipsePoints2 = new POINT2[37];
double distInterval=0;
//end declarations
for (j = 0; j < vblCounter - 1; j++)
{
lineutility.InitializePOINT2Array(pEllipsePoints2);
d = lineutility.CalcDistanceDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
//lHowManyThisSegment = (int) ((d - 10) / 10);
lHowManyThisSegment = (int) ((d - 20) / 20);
//added 4-19-12
distInterval=d/lHowManyThisSegment;
dAngle = lineutility.CalcSegmentAngleDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
dAngle = dAngle + Math.PI / 2;
for (k = 0; k < lHowManyThisSegment; k++)
{
//t = k;
//ptCenter=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*20+20);
ptCenter=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*distInterval);
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}//end k loop
//extra ellipse on the final segment at the end of the line
if(j==vblCounter-2)
{
ptCenter=pOriginalLinePoints[j+1];
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetLVOPointsDouble",
new RendererException("GetLVOPointsDouble", exc));
}
return lEllipseCounter;
}
private static int GetIcingPointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = 0;
try {
int j = 0;
POINT2[] origPoints = new POINT2[vblCounter];
int nDirection = -1;
int k = 0, numSegments = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), midPt = new POINT2(), pt2 = new POINT2();
//save the original points
for (j = 0; j < vblCounter; j++) {
origPoints[j] = new POINT2(pLinePoints[j]);
}
double distInterval=0;
for (j = 0; j < vblCounter - 1; j++) {
//how many segments for this line segment?
numSegments = (int) lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1]);
numSegments /= 15; //segments are 15 pixels long
//4-19-12
distInterval=lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1])/numSegments;
//get the direction and the quadrant
nDirection = GetInsideOutsideDouble2(origPoints[j], origPoints[j + 1], origPoints, vblCounter, j, TacticalLines.ICING);
for (k = 0; k < numSegments; k++) {
//get the parallel segment
if (k == 0) {
pt0 = new POINT2(origPoints[j]);
} else {
//pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15, 0);
pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval, 0);
}
//pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 10, 5);
pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 10, 5);
//midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 5, 0);
midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 5, 0);
//get the perpendicular segment
pt2 = lineutility.ExtendDirectedLine(origPoints[j], origPoints[j + 1], midPt, nDirection, 5, 5);
pLinePoints[counter] = new POINT2(pt0);
pLinePoints[counter + 1] = new POINT2(pt1);
pLinePoints[counter + 2] = new POINT2(midPt);
pLinePoints[counter + 3] = new POINT2(pt2);
counter += 4;
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIcingPointsDouble",
new RendererException("GetIcingPointsDouble", exc));
}
return counter;
}
protected static int GetAnchorageDouble(POINT2[] vbPoints2, int numPts)
{
int lFlotCounter = 0;
try
{
//declarations
int j = 0, k = 0, l = 0;
int x1 = 0, y1 = 0;
int numSegPts = -1;
int lFlotCount = 0;
int lNumSegs = 0;
double dDistance = 0;
int[] vbPoints = null;
int[] points = null;
int[] points2 = null;
POINT2 pt = new POINT2();
POINT2 pt1 = new POINT2(), pt2 = new POINT2();
//end declarations
lFlotCount = flot.GetAnchorageCountDouble(vbPoints2, numPts);
vbPoints = new int[2 * numPts];
for (j = 0; j < numPts; j++)
{
vbPoints[k] = (int) vbPoints2[j].x;
k++;
vbPoints[k] = (int) vbPoints2[j].y;
k++;
}
k = 0;
ref<int[]> bFlip = new ref();
bFlip.value = new int[1];
ref<int[]> lDirection = new ref();
lDirection.value = new int[1];
ref<int[]> lLastDirection = new ref();
lLastDirection.value = new int[1];
for (l = 0; l < numPts - 1; l++)
{
//pt1=new POINT2();
//pt2=new POINT2();
pt1.x = vbPoints[2 * l];
pt1.y = vbPoints[2 * l + 1];
pt2.x = vbPoints[2 * l + 2];
pt2.y = vbPoints[2 * l + 3];
//for all segments after the first segment we shorten
//the line by 20 so the flots will not abut
if (l > 0)
{
pt1 = lineutility.ExtendAlongLineDouble(pt1, pt2, 20);
}
dDistance = lineutility.CalcDistanceDouble(pt1, pt2);
lNumSegs = (int) (dDistance / 20);
//ref<int[]> bFlip = new ref();
//bFlip.value = new int[1];
//ref<int[]> lDirection = new ref();
//lDirection.value = new int[1];
//ref<int[]> lLastDirection = new ref();
//lLastDirection.value = new int[1];
if (lNumSegs > 0) {
points2 = new int[lNumSegs * 32];
numSegPts = flot.GetAnchorageFlotSegment(vbPoints, (int) pt1.x, (int) pt1.y, (int) pt2.x, (int) pt2.y, l, points2, bFlip, lDirection, lLastDirection);
points = new int[numSegPts];
for (j = 0; j < numSegPts; j++)
{
points[j] = points2[j];
}
for (j = 0; j < numSegPts / 3; j++) //only using half the flots
{
x1 = points[k];
y1 = points[k + 1];
//z = points[k + 2];
k += 3;
if (j % 10 == 0) {
pt.x = x1;
pt.y = y1;
pt.style = 5;
}
else if ((j + 1) % 10 == 0)
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter++].y = y1;
vbPoints2[lFlotCounter++] = new POINT2(pt);
continue;
}
else
{
break;
}
}
if (lFlotCounter < lFlotCount) {
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter].y = y1;
lFlotCounter++;
} else {
break;
}
}
k = 0;
points = null;
} else
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = vbPoints[2 * l];
vbPoints2[lFlotCounter].y = vbPoints[2 * l + 1];
lFlotCounter++;
}
}
}
for (j = lFlotCounter - 1; j < lFlotCount; j++)
{
vbPoints2[j].style = 5;
}
//clean up
vbPoints = null;
points = null;
points2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetAnchorageDouble",
new RendererException("GetAnchorageDouble", exc));
}
return lFlotCounter;
}
private static int GetPipePoints(POINT2[] pLinePoints,
int vblCounter)
{
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2[] xPoints = new POINT2[pLinePoints.length];
int xCounter = 0;
int j=0,k=0;
for (j = 0; j < vblCounter; j++)
{
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0;
double d = 0;
lineutility.InitializePOINT2Array(xPoints);
for (j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 20);
for (k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt1.style = 5;
pt2 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt2.style = 20; //for filled circle
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
xPoints[xCounter++] = new POINT2(pt2);
}
if (numSegs == 0)
{
pLinePoints[counter] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++].style=0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style=5;
}
else
{
pLinePoints[counter] = new POINT2(pLinePoints[counter - 1]);
pLinePoints[counter++].style = 0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style = 5;
}
}
//load the circle points
for (k = 0; k < xCounter; k++)
{
pLinePoints[counter++] = new POINT2(xPoints[k]);
}
//add one more circle
pLinePoints[counter++] = new POINT2(pLinePoints[counter]);
pOriginalPoints = null;
xPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetPipePoints",
new RendererException("GetPipePoints", exc));
}
return counter;
}
private static int GetReefPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
POINT2 pt4 = new POINT2();
//POINT2 pt5=new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0,direction=0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++) {
if(pOriginalPoints[j].x<pOriginalPoints[j+1].x)
direction=2;
else
direction=3;
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 40);
for (int k = 0; k < numSegs; k++) {
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * k);
pt1 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 10);
pt1 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt1, direction, 15);//was 2
pt2 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 20);
pt2 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 5);//was 2
pt3 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 30);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt3, direction, 20);//was 2
pt4 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * (k + 1));
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt4);
}
if (numSegs == 0) {
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetReefPoints",
new RendererException("GetReefPoints", exc));
}
return counter;
}
private static int GetRestrictedAreaPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int direction=0;
int numSegs = 0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 15);
if(pOriginalPoints[j].x < pOriginalPoints[j+1].x)
direction=3;
else
direction=2;
for (int k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k + 10);
pt1.style = 5;
pt2 = lineutility.MidPointDouble(pt0, pt1, 0);
//pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 10);
pt3.style = 5;
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
}
if (numSegs == 0)
{
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter - 1].style = 0;
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRestrictedAreaPoints",
new RendererException("GetRestrictedAreaPoints", exc));
}
return counter;
}
//there should be two linetypes depending on scale
private static int getOverheadWire(POINT2[]pLinePoints, int vblCounter)
{
int counter=0;
try
{
int j=0;
POINT2 pt=null,pt2=null;
double x=0,y=0;
ArrayList<POINT2>pts=new ArrayList();
for(j=0;j<vblCounter;j++)
{
pt=new POINT2(pLinePoints[j]);
x=pt.x;
y=pt.y;
//tower
pt2=new POINT2(pt);
pt2.y -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=5;
pt2.style=5;
pts.add(pt2);
//low cross piece
pt2=new POINT2(pt);
pt2.x -=2;
pt2.y-=10;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=2;
pt2.y-=10;
pt2.style=5;
pts.add(pt2);
//high cross piece
pt2=new POINT2(pt);
pt2.x -=7;
pt2.y-=17;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=7;
pt2.y-=17;
pt2.style=5;
pts.add(pt2);
//angle piece
pt2=new POINT2(pt);
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x+=8;
pt2.y-=12;
pt2.style=5;
pts.add(pt2);
}
//connect the towers
for(j=0;j<vblCounter-1;j++)
{
pt=new POINT2(pLinePoints[j]);
pt2=new POINT2(pLinePoints[j+1]);
if(pt.x<pt2.x)
{
pt.x+=5;
pt.y -=10;
pt2.x-=5;
pt2.y-=10;
pt2.style=5;
}
else
{
pt.x-=5;
pt.y -=10;
pt2.x+=5;
pt2.y-=10;
pt2.style=5;
}
pts.add(pt);
pts.add(pt2);
}
for(j=0;j<pts.size();j++)
{
pLinePoints[j]=pts.get(j);
counter++;
}
for(j=counter;j<pLinePoints.length;j++)
pLinePoints[j]=new POINT2(pLinePoints[counter-1]);
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetOverheadWire",
new RendererException("GetOverheadWire", exc));
}
return counter;
}
//private static int linetype=-1; //use for BLOCK, CONTIAN
/**
* Calculates the points for the non-channel symbols.
* The points will be stored in the original POINT2 array in pixels, pLinePoints.
* The client points occupy the first vblSaveCounter positions in pLinePoints
* and will be overwritten by the symbol points.
*
* @param lineType the line type
* @param pLinePoints - OUT - an array of POINT2
* @param vblCounter the number of points allocated
* @param vblSaveCounter the number of client points
*
* @return the symbol point count
*/
private static ArrayList<POINT2> GetLineArray2Double(int lineType,
POINT2[] pLinePoints,
int vblCounter,
int vblSaveCounter,
ArrayList<Shape2>shapes,
Rectangle2D clipBounds,
int rev)
{
ArrayList<POINT2> points=new ArrayList();
try
{
String client=CELineArray.getClient();
if(pLinePoints==null || pLinePoints.length<2)
return null;
//declarations
int[] segments=null;
double dMRR=0;
int n=0,bolVertical=0;
double dExtendLength=0;
double dWidth=0;
int nQuadrant=0;
int lLinestyle=0,pointCounter=0;
ref<double[]> offsetX=new ref(),offsetY=new ref();
double b=0,b1=0,dRadius=0,d1=0,d=0,d2=0;
ref<double[]>m=new ref();
int direction=0;
int nCounter=0;
int j=0,k=0,middleSegment=-1;
double dMBR=lineutility.MBRDistance(pLinePoints,vblSaveCounter);
POINT2 pt0=new POINT2(pLinePoints[0]), //calculation points for autoshapes
pt1=new POINT2(pLinePoints[1]),
pt2=new POINT2(pLinePoints[1]),
pt3=new POINT2(pLinePoints[0]),
pt4=new POINT2(pLinePoints[0]),
pt5=new POINT2(pLinePoints[0]),
pt6=new POINT2(pLinePoints[0]),
pt7=new POINT2(pLinePoints[0]),
pt8=new POINT2(pLinePoints[0]),
ptYIntercept=new POINT2(pLinePoints[0]),
ptYIntercept1=new POINT2(pLinePoints[0]),
ptCenter=new POINT2(pLinePoints[0]);
POINT2[] pArrowPoints=new POINT2[3],
arcPts=new POINT2[26],
circlePoints=new POINT2[100],
pts=null,pts2=null;
POINT2 midpt=new POINT2(pLinePoints[0]),midpt1=new POINT2(pLinePoints[0]);
POINT2[]pOriginalLinePoints=null;
POINT2[] pUpperLinePoints = null;
POINT2[] pLowerLinePoints = null;
POINT2[] pUpperLowerLinePoints = null;
POINT2 calcPoint0=new POINT2(),
calcPoint1=new POINT2(),
calcPoint2=new POINT2(),
calcPoint3=new POINT2(),
calcPoint4=new POINT2();
POINT2 ptTemp=new POINT2(pLinePoints[0]);
int acCounter=0;
POINT2[] acPoints=new POINT2[6];
int lFlotCount=0;
//end declarations
//Bearing line and others only have 2 points
if(vblCounter>2)
pt2=new POINT2(pLinePoints[2]);
//strcpy(CurrentFunction,"GetLineArray2");
pt0.style=0;
pt1.style=0;
pt2.style=0;
//set jaggylength in clsDISMSupport before the points get bounded
//clsDISMSupport.JaggyLength = Math.Sqrt ( (pLinePoints[1].x-pLinePoints[0].x) * (pLinePoints[1].x-pLinePoints[0].x) +
// (pLinePoints[1].y-pLinePoints[0].y) * (pLinePoints[1].y-pLinePoints[0].y) );
//double saveMaxPixels=CELineArrayGlobals.MaxPixels2;
//double saveMaxPixels=2000;
ArrayList xPoints=null;
pOriginalLinePoints = new POINT2[vblSaveCounter];
for(j = 0;j<vblSaveCounter;j++)
{
pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
}
//resize the array and get the line array
//for the specified non-channel line type
switch(lineType)
{
case TacticalLines.BBS_AREA:
lineutility.getExteriorPoints(pLinePoints, vblSaveCounter, lineType, false);
acCounter=vblSaveCounter;
break;
case TacticalLines.BS_CROSS:
pt0=new POINT2(pLinePoints[0]);
pLinePoints[0]=new POINT2(pt0);
pLinePoints[0].x-=10;
pLinePoints[1]=new POINT2(pt0);
pLinePoints[1].x+=10;
pLinePoints[1].style=10;
pLinePoints[2]=new POINT2(pt0);
pLinePoints[2].y+=10;
pLinePoints[3]=new POINT2(pt0);
pLinePoints[3].y-=10;
acCounter=4;
break;
case TacticalLines.BS_RECTANGLE:
pt0=new POINT2(pLinePoints[0]);//the center of the ellipse
pt2=new POINT2(pLinePoints[1]);//the width of the ellipse
pt1=new POINT2(pt0);
pt1.y=pt2.y;
pt3=new POINT2(pt2);
pt3.y=pt0.y;
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BBS_RECTANGLE:
double xmax=pLinePoints[0].x,xmin=pLinePoints[1].x,ymax=pLinePoints[0].y,ymin=pLinePoints[1].y;
double buffer=pLinePoints[0].style;
if(pLinePoints[0].x<pLinePoints[1].x)
{
xmax=pLinePoints[1].x;
xmin=pLinePoints[0].x;
}
if(pLinePoints[0].y<pLinePoints[1].y)
{
ymax=pLinePoints[1].y;
ymin=pLinePoints[0].y;
}
if(xmax-xmin>ymax-ymin)
ymax=ymin+(xmax-xmin);
else
xmax=xmin+(ymax-ymin);
pt0=new POINT2(xmin-buffer,ymin-buffer);
pt2=new POINT2(xmax+buffer,ymax+buffer);
pt1=new POINT2(pt0);
pt1.y=pt2.y;
pt3=new POINT2(pt2);
pt3.y=pt0.y;
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BS_ELLIPSE:
pt0=pLinePoints[0];//the center of the ellipse
pt1=pLinePoints[1];//the width of the ellipse
pt2=pLinePoints[2];//the height of the ellipse
pLinePoints=getEllipsePoints(pt0,pt1,pt2);
acCounter=37;
break;
case TacticalLines.OVERHEAD_WIRE:
acCounter=getOverheadWire(pLinePoints,vblSaveCounter);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for(j=0;j<vblSaveCounter;j++)
{
//pLinePoints[j]=new POINT2(pOriginalLinePoints[j]);
pLinePoints[j].style=1;
}
//pLinePoints[vblSaveCounter-1].style=5;
for(j=vblSaveCounter;j<2*vblSaveCounter;j++)
{
pLinePoints[j]=new POINT2(pOriginalLinePoints[j-vblSaveCounter]);
pLinePoints[j].style=20;
}
//pLinePoints[2*vblSaveCounter-1].style=5;
acCounter=pLinePoints.length;
break;
case TacticalLines.BOUNDARY:
acCounter=pLinePoints.length;
break;
case TacticalLines.REEF:
vblCounter = GetReefPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ICE_DRIFT:
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-5], pLinePoints[vblCounter - 4], 10, 10,pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RESTRICTED_AREA:
vblCounter=GetRestrictedAreaPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TRAINING_AREA:
for (j = 0; j < vblSaveCounter; j++)
{
pLinePoints[j].style = 1;
}
pLinePoints[vblSaveCounter - 1].style = 5;
pt0 = lineutility.CalcCenterPointDouble(pLinePoints, vblSaveCounter - 1);
lineutility.CalcCircleDouble(pt0, 20, 26, arcPts, 0);
for (j = vblSaveCounter; j < vblSaveCounter + 26; j++)
{
pLinePoints[j] = new POINT2(arcPts[j - vblSaveCounter]);
}
pLinePoints[j-1].style = 5;
//! inside the circle
pt1 = new POINT2(pt0);
pt1.y -= 12;
pt1.style = 0;
pt2 = new POINT2(pt1);
pt2.y += 12;
pt2.style = 5;
pt3 = new POINT2(pt2);
pt3.y += 3;
pt3.style = 0;
pt4 = new POINT2(pt3);
pt4.y += 3;
pLinePoints[j++] = new POINT2(pt1);
pLinePoints[j++] = new POINT2(pt2);
pLinePoints[j++] = new POINT2(pt3);
pt4.style = 5;
pLinePoints[j++] = new POINT2(pt4);
vblCounter = j;
acCounter=vblCounter;
break;
case TacticalLines.PIPE:
vblCounter=GetPipePoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ANCHORAGE_AREA:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 1: //extend left
case 2: //extend below
break;
case 0: //extend right
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 1: //extend left
case 3: //extend above
break;
case 0: //extend right
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 1: //extend left
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 3: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 1: //extend left
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 2: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = GetAnchorageDouble(pLinePoints, vblSaveCounter);
acCounter = lFlotCount;
break;
case TacticalLines.ANCHORAGE_LINE:
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
acCounter=GetAnchorageDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.LRO:
int xCount=countsupport.GetXPointsCount(pOriginalLinePoints, vblSaveCounter);
POINT2 []xPoints2=new POINT2[xCount];
int lvoCount=countsupport.GetLVOCount(pOriginalLinePoints, vblSaveCounter);
POINT2 []lvoPoints=new POINT2[lvoCount];
xCount=GetXPoints(pOriginalLinePoints,xPoints2,vblSaveCounter);
lvoCount=GetLVOPoints(pOriginalLinePoints,lvoPoints,vblSaveCounter);
for(k=0;k<xCount;k++)
{
pLinePoints[k]=new POINT2(xPoints2[k]);
}
pLinePoints[xCount-1].style=5;
for(k=0;k<lvoCount;k++)
{
pLinePoints[xCount+k]=new POINT2(lvoPoints[k]);
}
acCounter=xCount+lvoCount;
break;
case TacticalLines.UNDERCAST:
if(pLinePoints[0].x<pLinePoints[1].x)
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
lFlotCount=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.LVO:
acCounter=GetLVOPoints(pOriginalLinePoints,pLinePoints,vblSaveCounter);
break;
case TacticalLines.ICING:
vblCounter=GetIcingPointsDouble(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.MVFR:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 0: //extend left
case 3: //extend below
break;
case 1: //extend right
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 0: //extend left
case 2: //extend above
break;
case 1: //extend right
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 0: //extend left
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 2: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 0: //extend left
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 3: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = flot.GetFlotDouble(pLinePoints, vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.ITD:
acCounter=GetITDPointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.CONVERGANCE:
acCounter=GetConvergancePointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.RIDGE:
vblCounter=GetRidgePointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TROUGH:
case TacticalLines.INSTABILITY:
case TacticalLines.SHEAR:
//case TacticalLines.SQUALL:
//CELineArrayGlobals.MaxPixels2=saveMaxPixels+100;
vblCounter=GetSquallDouble(pLinePoints,10,6,30,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.SQUALL:
//vblCounter = GetSquallDouble(pLinePoints, 10, 6, 30, vblSaveCounter);
vblCounter=GetSevereSquall(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.USF:
case TacticalLines.SFG:
case TacticalLines.SFY:
vblCounter=flot.GetSFPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.SF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.OFY:
vblCounter=flot.GetOFYPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.OCCLUDED:
case TacticalLines.UOF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.WF:
case TacticalLines.UWF:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter-vblSaveCounter+j]=pOriginalLinePoints[j];
acCounter=lFlotCount+vblSaveCounter;
break;
case TacticalLines.WFG:
case TacticalLines.WFY:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
acCounter=lFlotCount;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.CF:
case TacticalLines.UCF:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
pLinePoints[vblCounter-1].style=5;
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
pLinePoints[vblCounter-1].style=5;
acCounter=vblCounter;
break;
case TacticalLines.IL:
case TacticalLines.PLANNED:
case TacticalLines.ESR1:
case TacticalLines.ESR2:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
d=lineutility.CalcDistanceDouble(pLinePoints[0], pt0);
pt4 = lineutility.ExtendLineDouble(pt0, pLinePoints[0], d);
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt4, pt2, pt3);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
pLinePoints[2] = new POINT2(pt3);
pLinePoints[3] = new POINT2(pt2);
switch (lineType) {
case TacticalLines.IL:
case TacticalLines.ESR2:
pLinePoints[0].style = 0;
pLinePoints[1].style = 5;
pLinePoints[2].style = 0;
break;
case TacticalLines.PLANNED:
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2].style = 1;
break;
case TacticalLines.ESR1:
pLinePoints[1].style = 5;
if (pt0.x <= pt1.x) {
if (pLinePoints[1].y <= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
} else {
if (pLinePoints[1].y >= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
}
break;
default:
break;
}
acCounter=4;
break;
case TacticalLines.FORDSITE:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2] = new POINT2(pt0);
pLinePoints[2].style = 1;
pLinePoints[3] = new POINT2(pt1);
pLinePoints[3].style = 5;
acCounter=4;
break;
case TacticalLines.ROADBLK:
pts = new POINT2[4];
for (j = 0; j < 4; j++) {
pts[j] = new POINT2(pLinePoints[j]);
}
dRadius = lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
d = lineutility.CalcDistanceToLineDouble(pLinePoints[0], pLinePoints[1], pLinePoints[2]);
//first two lines
pLinePoints[0] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], d, 0);
pLinePoints[1] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], d, 5);
pLinePoints[2] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], -d, 0);
pLinePoints[3] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], -d, 5);
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[0], midpt, d);
//the next line
pLinePoints[4] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[5] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[5].style = 5;
//recompute the original midpt because it was moved
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[1], midpt, d);
//the last line
pLinePoints[6] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[7] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[7].style = 5;
acCounter=8;
break;
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
acCounter=vblCounter;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PNO:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DMAF:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
pLinePoints[vblCounter-1].style=5;
FillPoints(pLinePoints,vblCounter,points);
xPoints=lineutility.LineOfXPoints(pOriginalLinePoints);
for(j=0;j<xPoints.size();j++)
{
points.add((POINT2)xPoints.get(j));
}
acCounter=points.size();
break;
case TacticalLines.FOXHOLE:
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical==0) //line is vertical
{
if (pt0.y > pt1.y) {
direction = 0;
} else {
direction = 1;
}
}
if (bolVertical != 0 && m.value[0] <= 1) {
if (pt0.x < pt1.x) {
direction = 3;
} else {
direction = 2;
}
}
if (bolVertical != 0 && m.value[0] > 1) {
if (pt0.x < pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x < pt1.x && pt0.y < pt1.y) {
direction = 0;
}
if (pt0.x > pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x > pt1.x && pt0.y < pt1.y) {
direction = 0;
}
}
//M. Deutch 8-19-04
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<250)
dMBR=250;
if(dMBR>500)
dMBR=500;
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, direction, dMBR / 20);
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, direction, dMBR / 20);
acCounter=4;
break;
case TacticalLines.ISOLATE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.OCCUPY:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=32;
break;
case TacticalLines.RETAIN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=75;
break;
case TacticalLines.SECURE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.TURN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.ENCIRCLE:
//pOriginalLinePoints=null;
//pOriginalLinePoints = new POINT2[vblSaveCounter+2];
//for(j = 0;j<vblSaveCounter;j++)
// pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
//pOriginalLinePoints[vblSaveCounter] = new POINT2(pLinePoints[0]);
//pOriginalLinePoints[vblSaveCounter+1] = new POINT2(pLinePoints[1]);
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
//for(j=0;j<vblSaveCounter+2;j++)
// pLinePoints[pointCounter+j]=new POINT2(pOriginalLinePoints[j]);
//pointCounter += vblSaveCounter+1;
//acCounter=pointCounter;
break;
case TacticalLines.BELT1:
pUpperLinePoints=new POINT2[vblSaveCounter];
pLowerLinePoints=new POINT2[vblSaveCounter];
pUpperLowerLinePoints=new POINT2[2*vblCounter];
for(j=0;j<vblSaveCounter;j++)
pLowerLinePoints[j]=new POINT2(pLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLinePoints[j]=new POINT2(pLinePoints[j]);
pUpperLinePoints = Channels.CoordIL2Double(1,pUpperLinePoints,1,vblSaveCounter,lineType,30);
pLowerLinePoints = Channels.CoordIL2Double(1,pLowerLinePoints,0,vblSaveCounter,lineType,30);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j]=new POINT2(pUpperLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j+vblSaveCounter]=new POINT2(pLowerLinePoints[vblSaveCounter-j-1]);
pUpperLowerLinePoints[2*vblSaveCounter]=new POINT2(pUpperLowerLinePoints[0]);
vblCounter=GetZONEPointsDouble2(pUpperLowerLinePoints,lineType,2*vblSaveCounter+1);
for(j=0;j<vblCounter;j++)
pLinePoints[j]=new POINT2(pUpperLowerLinePoints[j]);
//pLinePoints[j]=pLinePoints[0];
//vblCounter++;
acCounter=vblCounter;
break;
case TacticalLines.BELT: //change 2
case TacticalLines.ZONE:
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.STRONG:
case TacticalLines.FORT:
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.ATWALL:
case TacticalLines.LINE: //7-9-07
acCounter = GetATWallPointsDouble2(pLinePoints, lineType, vblSaveCounter);
break;
// case TacticalLines.ATWALL3D:
// acCounter = GetATWallPointsDouble3D(pLinePoints, lineType, vblSaveCounter);
// break;
case TacticalLines.PLD:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.FEBA:
CoordFEBADouble(pLinePoints,vblCounter);
acCounter=pLinePoints.length;
break;
case TacticalLines.UAV:
case TacticalLines.MRR:
if(rev==RendererSettings.Symbology_2525Bch2_USAS_13_14)
{
dMRR=pOriginalLinePoints[0].style;
if (dMRR <= 0) {
dMRR = 1;//was 14
}
lineutility.GetSAAFRSegment(pLinePoints, lineType, dMRR,rev);
acCounter=6;
}
if(rev==RendererSettings.Symbology_2525C)
{
return GetLineArray2Double(TacticalLines.SAAFR,pLinePoints,vblCounter,vblSaveCounter,shapes,clipBounds,rev);
}
break;
case TacticalLines.MRR_USAS:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR: //added 5-4-07
case TacticalLines.SAAFR: //these have multiple segments
case TacticalLines.AC:
dMRR = dACP;
// if (dMRR <= 0) {
// dMRR = 14;
// }
lineutility.InitializePOINT2Array(acPoints);
lineutility.InitializePOINT2Array(arcPts);
acCounter = 0;
for (j = 0; j < vblSaveCounter;j++)
if(pOriginalLinePoints[j].style<=0)
pOriginalLinePoints[j].style=1; //was 14
//get the SAAFR segments
for (j = 0; j < vblSaveCounter - 1; j++) {
//diagnostic: use style member for dMBR
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRSegment(acPoints, lineType, dMBR,rev);//was dMRR
for (k = 0; k < 6; k++)
{
pLinePoints[acCounter] = new POINT2(acPoints[k]);
acCounter++;
}
}
//get the circles
int nextCircleSize=0,currentCircleSize=0;
for (j = 0; j < vblSaveCounter-1; j++)
{
currentCircleSize=pOriginalLinePoints[j].style;
nextCircleSize=pOriginalLinePoints[j+1].style;
//draw the circle at the segment front end
arcPts[0] = new POINT2(pOriginalLinePoints[j]);
//diagnostic: use style member for dMBR
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
//draw the circle at the segment back end
arcPts[0] = new POINT2(pOriginalLinePoints[j+1]);
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
}
//acPoints = null;
break;
case TacticalLines.MINED:
case TacticalLines.UXO:
acCounter=vblCounter;
break;
case TacticalLines.BEARING:
case TacticalLines.ACOUSTIC:
case TacticalLines.ELECTRO:
case TacticalLines.TORPEDO:
case TacticalLines.OPTICAL:
acCounter=vblCounter;
break;
case TacticalLines.MSDZ:
lineutility.InitializePOINT2Array(circlePoints);
pt3 = new POINT2(pLinePoints[3]);
dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[j] = new POINT2(circlePoints[j]);
}
pLinePoints[99].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt2);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[100 + j] = new POINT2(circlePoints[j]);
}
pLinePoints[199].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt3);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[200 + j] = new POINT2(circlePoints[j]);
}
acCounter=300;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.CONVOY:
d=lineutility.CalcDistanceDouble(pt0, pt1);
if(d<=30)
{
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
pt0 = lineutility.ExtendLine2Double(pt1, pt0, -30, 0);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 30);
lineutility.GetArrowHead4Double(pt0, pt2, 30, 30, pArrowPoints, 0);
d = lineutility.CalcDistanceDouble(pLinePoints[0], pArrowPoints[0]);
d1 = lineutility.CalcDistanceDouble(pLinePoints[3], pArrowPoints[0]);
pLinePoints[3].style = 5;
if (d < d1) {
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[4].style = 0;
pLinePoints[5] = new POINT2(pArrowPoints[0]);
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pArrowPoints[1]);
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pArrowPoints[2]);
pLinePoints[7].style = 0;
pLinePoints[8] = new POINT2(pLinePoints[3]);
} else {
pLinePoints[4] = pLinePoints[3];
pLinePoints[4].style = 0;
pLinePoints[5] = pArrowPoints[0];
pLinePoints[5].style = 0;
pLinePoints[6] = pArrowPoints[1];
pLinePoints[6].style = 0;
pLinePoints[7] = pArrowPoints[2];
pLinePoints[7].style = 0;
pLinePoints[8] = pLinePoints[0];
}
acCounter=9;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.HCONVOY:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
pt2.x = (pt0.x + pt1.x) / 2;
pt2.y = (pt0.y + pt1.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[5] = new POINT2(pt0);
pLinePoints[5].style = 0;
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 50);
lineutility.GetArrowHead4Double(pt2, pt0, 20, 20, pArrowPoints, 0);
// for (j = 0; j < 3; j++)
// {
// pLinePoints[j + 6] = new POINT2(pArrowPoints[j]);
// }
// pLinePoints[8].style = 0;
// pLinePoints[9] = new POINT2(pArrowPoints[0]);
pLinePoints[6]=new POINT2(pArrowPoints[1]);
pLinePoints[7]=new POINT2(pArrowPoints[0]);
pLinePoints[8]=new POINT2(pArrowPoints[2]);
pLinePoints[8].style = 0;
pLinePoints[9] = new POINT2(pArrowPoints[1]);
acCounter=10;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.ONEWAY:
case TacticalLines.ALT:
case TacticalLines.TWOWAY:
nCounter = (int) vblSaveCounter;
pLinePoints[vblSaveCounter - 1].style = 5;
for (j = 0; j < vblSaveCounter - 1; j++) {
d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if(d<20) //too short
continue;
pt0 = new POINT2(pLinePoints[j]);
pt1 = new POINT2(pLinePoints[j + 1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1],m);
d=lineutility.CalcDistanceDouble(pLinePoints[j],pLinePoints[j+1]);
pt2 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -3 * d / 4, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -1 * d / 4, 5);
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
d = 10;
if (dMBR / 20 < minLength) {
d = 5;
}
lineutility.GetArrowHead4Double(pt2, pt3, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
if (lineType == (long) TacticalLines.ALT) {
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
if (lineType == (long) TacticalLines.TWOWAY) {
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
}
acCounter=nCounter;
break;
case TacticalLines.CFL:
for(j=0;j<vblCounter;j++) //dashed lines
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKFNT: //extra three for arrow plus extra three for feint
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<20)//was 10
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], 21);//was 11
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], 20); //was 10
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
d = dMBR;
pt0=lineutility.ExtendLineDouble(pLinePoints[vblCounter-8], pLinePoints[vblCounter - 7], 20); //was 10
pt1 = new POINT2(pLinePoints[vblCounter - 8]);
pt2 = new POINT2(pLinePoints[vblCounter - 7]);
if (d / 10 > maxLength) {
d = 10 * maxLength;
}
if (d / 10 < minLength) {
d = 10 * minLength;
}
if(d<250)
d=250;
if(d>500)
d=250;
lineutility.GetArrowHead4Double(pt1, pt2, (int) d / 10, (int) d / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = pArrowPoints[k];
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) d / 10, (int) d / 10,
pArrowPoints,18);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = pArrowPoints[k];
}
acCounter=vblCounter;
break;
case TacticalLines.FORDIF:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2], pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
for (j = 0; j < vblCounter; j++) {
pLinePoints[j].style = 1;
}
//CommandSight section
//comment 2 lines for CS
pt0 = lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
pt1 = lineutility.MidPointDouble(pLinePoints[2], pLinePoints[3], 0);
//uncomment 3 line for CS
//pt0=new POINT2(pt2);
//d=lineutility.CalcDistanceDouble(pt4, pt2);
//pt1=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], d);
//end section
// pts = new POINT2[2];
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// pointCounter = lineutility.BoundPointsCount(pts, 2);
// segments = new int[pointCounter];
// pts = new POINT2[pointCounter];
// lineutility.InitializePOINT2Array(pts);
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// lineutility.BoundPoints(pts, 2, segments);
// for (j = 0; j < pointCounter - 1; j++) {
// if (segments[j] == 1) {
// pt0 = new POINT2(pts[j]);
// pt1 = new POINT2(pts[j + 1]);
// break;
// }
// }
// for (j = 3; j < vblCounter; j++) {
// pLinePoints[j] = new POINT2(pLinePoints[3]);
// pLinePoints[j].style = 5;
// }
// pLinePoints[1].style = 5;
//
//added section 10-27-20
POINT2[]savepoints=null;
Boolean drawJaggies=true;
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints=lineutility.BoundOneSegment(pt0, pt1, ul, lr);
if(savepoints != null && savepoints.length>1)
{
pt0=savepoints[0];
pt1=savepoints[1];
}
midpt=lineutility.MidPointDouble(pt0, pt1, 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
}
else
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
}
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
//end section
}
else
{
midpt=lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
else
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
}
//end section
//calculate start, end points for upper and lower lines
//across the middle
pt2 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, -10, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, -10, 0);
pt4 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, 10, 0);
pt5 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, 10, 0);
dWidth = lineutility.CalcDistanceDouble(pt0, pt1);
pointCounter = 4;
n = 1;
pLinePoints[pointCounter] = new POINT2(pt0);
pLinePoints[pointCounter].style = 0;
pointCounter++;
//while (dExtendLength < dWidth - 20)
if(drawJaggies)
while (dExtendLength < dWidth - 10)
{
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt2, pt3, dExtendLength - dWidth, 0);
pointCounter++;
n++;
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt4, pt5, dExtendLength - dWidth, 0);
pointCounter++;
n++;
}
pLinePoints[pointCounter] = new POINT2(pt1);
pLinePoints[pointCounter].style = 5;
pointCounter++;
acCounter=pointCounter;
break;
case TacticalLines.ATDITCH:
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
break;
case (int)TacticalLines.ATDITCHC: //extra Points were calculated by a function
pLinePoints[0].style=9;
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
pLinePoints[vblCounter-1].style=10;
break;
case TacticalLines.ATDITCHM:
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pLinePoints[0].style = 9;
acCounter = lineutility.GetDitchSpikeDouble(
pLinePoints,
vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style = 20;
break;
case TacticalLines.DIRATKGND:
//reverse the points
//lineutility.ReversePointsDouble2(
//pLinePoints,
//vblSaveCounter);
//was 20
if (dMBR / 30 > maxLength) {
dMBR = 30 * maxLength;
}
if (dMBR / 30 < minLength) {
dMBR = 30 * minLength;
}
//if(dMBR<250)
// dMBR = 250;
if(dMBR<500)
dMBR = 500;
if(dMBR>750)
dMBR = 500;
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<dMBR/40)
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], dMBR/40+1);
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1],dMBR/40);
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pt0 = new POINT2(pLinePoints[vblCounter - 12]);
pt1 = new POINT2(pLinePoints[vblCounter - 11]);
pt2 = lineutility.ExtendLineDouble(pt0, pt1, dMBR / 40);
lineutility.GetArrowHead4Double(pt0, pt1, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 10 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pt0, pt2, (int) (dMBR / 13.33), (int) (dMBR / 13.33),
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 7 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[vblCounter - 10]);
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 7]);
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 5]);
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.MFLANE:
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RAFT: //extra eight Points for hash marks either end
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>200)
dMBR=200;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKAIR:
//added section for click-drag mode
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
for(k=vblSaveCounter-1;k>0;k--)
{
d += lineutility.CalcDistanceDouble(pLinePoints[k],pLinePoints[k-1]);
if(d>60)
break;
}
if(d>60)
{
middleSegment=k;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
else
{
if(vblSaveCounter<=3)
middleSegment=1;
else
middleSegment=2;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
pt0 = new POINT2(pLinePoints[0]);
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<150)
dMBR=150;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pLinePoints[vblCounter - 10], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 9 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 6].x = (pLinePoints[vblCounter - 11].x + pLinePoints[vblCounter - 10].x) / 2;
pLinePoints[vblCounter - 6].y = (pLinePoints[vblCounter - 11].y + pLinePoints[vblCounter - 10].y) / 2;
pt0 = new POINT2(pLinePoints[vblCounter - 6]);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt3, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 6 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 10], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt2, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
//this section was added to remove fill from the bow tie feature
ArrayList<POINT2> airPts=new ArrayList();
pLinePoints[middleSegment-1].style=5;
//pLinePoints[middleSegment].style=14;
if(vblSaveCounter==2)
pLinePoints[1].style=5;
for(j=0;j<vblCounter;j++)
airPts.add(new POINT2(pLinePoints[j]));
midpt=lineutility.MidPointDouble(pLinePoints[middleSegment-1], pLinePoints[middleSegment], 0);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment]);
pt1.style=5;
airPts.add(pt1);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment-1], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment-1]);
pt1.style=5;
airPts.add(pt1);
//re-dimension pLinePoints so that it can hold the
//the additional points required by the shortened middle segment
//which has the bow tie feature
vblCounter=airPts.size();
pLinePoints=new POINT2[airPts.size()];
for(j=0;j<airPts.size();j++)
pLinePoints[j]=new POINT2(airPts.get(j));
//end section
acCounter=vblCounter;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PDF:
//reverse pt0 and pt1 8-1-08
pt0 = new POINT2(pLinePoints[1]);
pt1 = new POINT2(pLinePoints[0]);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
//end section
pts2 = new POINT2[3];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts2[2] = new POINT2(pt2);
lineutility.GetPixelsMin(pts2, 3,
offsetX,
offsetY);
if(offsetX.value[0]<0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
pLinePoints[2].style = 5;
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR < minLength) {
dMBR = 20 * minLength;
}
if(dMBR>250)
dMBR=250;
pt2 = lineutility.ExtendLineDouble(pt0, pt1, -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[3] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
pLinePoints[3].style = 0;
pLinePoints[4] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[4].style = 0;
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].y = pt2.y - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].y = pt2.y + 2;
pLinePoints[4].style = 0;
}
if (bolVertical == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].x = pt2.x - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].x = pt2.x + 2;
pLinePoints[4].style = 0;
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, -dMBR / 10);
if (bolVertical != 0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
//get the Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[5] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[5].style = 0;
pLinePoints[6] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].y = pt2.y + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].y = pt2.y - 2;
}
if (bolVertical == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].x = pt2.x + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].x = pt2.x - 2;
}
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pLinePoints[3]);
pLinePoints[7].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[8 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[2], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[11 + j] = new POINT2(pArrowPoints[j]);
pLinePoints[11 + j].style = 0;
}
//FillPoints(pLinePoints,14,points,lineType);
acCounter=14;
break;
case TacticalLines.DIRATKSPT:
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if(dMBR/20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(client.startsWith("cpof"))
{
if(dMBR<250)
dMBR=250;
}
else
{
if(dMBR<150)
dMBR=150;
}
if(dMBR>500)
dMBR=500;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 5], pLinePoints[vblCounter - 4], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - k - 1] = new POINT2(pArrowPoints[k]);
}
acCounter=vblCounter;
break;
case TacticalLines.ABATIS:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
lineutility.GetPixelsMin(pts2, 2,
offsetX,
offsetY);
if(offsetX.value[0]<=0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
if(dMBR>300)
dMBR=300;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
midpt.x=(pt0.x+pLinePoints[0].x) / 2;
midpt.y = (pt0.y + pLinePoints[0].y) / 2;
pLinePoints[vblCounter - 3] = new POINT2(pt0);
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 3].style = 0;
if (bolVertical != 0 && m.value[0] != 0) {
b = midpt.y + (1 / m.value[0]) * midpt.x; //the line equation
//get Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, dMBR / 20);
if (pLinePoints[vblCounter - 2].y >= midpt.y) {
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dMBR / 20);
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].y = midpt.y - dMBR / 20;
}
if (bolVertical == 0) {
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].x = midpt.x - dMBR / 20;
}
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[0]);
//put the abatis feature on the front
// ArrayList<POINT2>abatisPts=new ArrayList();
// for(j=3;j<vblCounter;j++)
// abatisPts.add(new POINT2(pLinePoints[j-3]));
//
// abatisPts.add(0,new POINT2(pLinePoints[vblCounter-3]));
// abatisPts.add(1,new POINT2(pLinePoints[vblCounter-2]));
// abatisPts.add(2,new POINT2(pLinePoints[vblCounter-1]));
//
// for(j=0;j<abatisPts.size();j++)
// pLinePoints[j]=new POINT2(abatisPts.get(j));
//end section
FillPoints(pLinePoints,vblCounter,points);
acCounter=vblCounter;
break;
case TacticalLines.CLUSTER:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
//for some reason occulus puts the points on top of one another
if(Math.abs(pt0.y-pt1.y)<1)
{
pt1.y = pt0.y +1;
}
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts = new POINT2[26];
dRadius = lineutility.CalcDistanceDouble(pt0, pt1) / 2;
midpt.x = (pt1.x + pt0.x) / 2;
midpt.y = (pt1.y + pt0.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical!=0 && m.value[0] != 0) //not vertical or horizontal
{
b = midpt.y + (1 / m.value[0]) * midpt.x; //normal y intercept at x=0
//we want to get the y intercept at x=offsetX
//b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
//ptYIntercept.x = offsetX.value[0];
ptYIntercept.x=0;
//ptYIntercept.y = b1;
ptYIntercept.y = b;
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, dRadius);
if (pLinePoints[0].x <= pLinePoints[1].x) {
if (pt2.y >= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
} else {
if (pt2.y <= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pt2 = midpt;
if (pLinePoints[0].x <= pLinePoints[1].x) {
pt2.y = midpt.y - dRadius;
} else {
pt2.y = midpt.y + dRadius;
}
}
if (bolVertical == 0) //vertical line
{
pt2 = midpt;
if (pLinePoints[0].y <= pLinePoints[1].y) {
pt2.x = midpt.x + dRadius;
} else {
pt2.x = midpt.x - dRadius;
}
}
pt1 = lineutility.ExtendLineDouble(midpt, pt2, 100);
pts[0] = new POINT2(pt2);
pts[1] = new POINT2(pt1);
lineutility.ArcArrayDouble(
pts,
0,dRadius,
lineType);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
for (j = 0; j < 26; j++) {
pLinePoints[2 + j] = new POINT2(pts[j]);
pLinePoints[2 + j].style = 1;
}
acCounter=28;
break;
case TacticalLines.TRIP:
dRadius = lineutility.CalcDistanceToLineDouble(pt0, pt1, pt2);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt1.y + 1 / m.value[0] * pt1.x;
b1 = pt2.y - m.value[0] * pt2.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
b = calcPoint1.y + 1 / m.value[0] * calcPoint1.x;
calcPoint3 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
b = calcPoint2.y + 1 / m.value[0] * calcPoint2.x;
calcPoint4 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
b = pt1.y + 1 / m.value[0] * pt1.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical != 0 && m.value[0] == 0) {
calcPoint0.x = pt1.x;
calcPoint0.y = pt2.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.x = calcPoint0.x + dRadius / 2;
calcPoint3.y = calcPoint0.y;
calcPoint4.x = pt1.x + dRadius;
calcPoint4.y = pt2.y;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical == 0) {
calcPoint0.x = pt2.x;
calcPoint0.y = pt1.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.y = calcPoint0.y + dRadius / 2;
calcPoint3.x = calcPoint0.x;
calcPoint4.y = pt1.y + dRadius;
calcPoint4.x = pt2.x;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
arcPts[0] = new POINT2(calcPoint1);
arcPts[1] = new POINT2(calcPoint3);
lineutility.ArcArrayDouble(
arcPts,
0,dRadius,
lineType);
pLinePoints[0].style = 5;
pLinePoints[1].style = 5;
for (k = 0; k < 26; k++) {
pLinePoints[k] = new POINT2(arcPts[k]);
}
for (k = 25; k < vblCounter; k++) {
pLinePoints[k].style = 5;
}
pLinePoints[26] = new POINT2(pt1);
dRadius = lineutility.CalcDistanceDouble(pt1, pt0);
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 - 7, 0);
pLinePoints[27] = new POINT2(midpt);
pLinePoints[27].style = 0;
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 + 7, 0);
pLinePoints[28] = new POINT2(midpt);
pLinePoints[29] = new POINT2(pt0);
pLinePoints[29].style = 5;
lineutility.GetArrowHead4Double(pt1, pt0, 15, 15, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[30 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 0; k < 3; k++) {
pLinePoints[30 + k].style = 5;
}
midpt = lineutility.MidPointDouble(pt0, pt1, 0);
d = lineutility.CalcDistanceDouble(pt1, calcPoint0);
//diagnostic for CS
//pLinePoints[33] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, d, 0);
//pLinePoints[34] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, -d, 5);
pLinePoints[33]=pt2;
pt3=lineutility.PointRelativeToLine(pt0, pt1, pt0, pt2);
d=lineutility.CalcDistanceDouble(pt3, pt2);
pt4=lineutility.ExtendAlongLineDouble(pt0, pt1, d);
d=lineutility.CalcDistanceDouble(pt2, pt4);
pLinePoints[34]=lineutility.ExtendLineDouble(pt2, pt4, d);
//end section
acCounter=35;
break;
case TacticalLines.FOLLA:
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(client.startsWith("cpof"))
d2=20;
else
d2=30;
if(d<d2)
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>150)
dMBR=150;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -2 * dMBR / 10);
for (k = 0; k < vblCounter - 14; k++) {
pLinePoints[k].style = 18;
}
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], 5 * dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
pLinePoints[vblCounter - 12].style = 0;
pLinePoints[vblCounter - 11] = new POINT2(pArrowPoints[2]);
pLinePoints[vblCounter - 11].style = 0;
pLinePoints[vblCounter - 10] = new POINT2(pArrowPoints[0]);
pLinePoints[vblCounter - 10].style = 0;
pLinePoints[vblCounter - 9] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 9].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 8 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 6].style = 0;
//diagnostic to make first point tip of arrowhead 6-14-12
//pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], 0.75 * dMBR / 10);
pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], -0.75 * dMBR / 10);
pLinePoints[1]=pt3;
pLinePoints[1].style=5;
//lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (1.25 * dMBR / 10), (int) (1.25 * dMBR / 10), pArrowPoints, 0);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (dMBR / 10), (int) (dMBR / 10), pArrowPoints, 0);
//end section
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 5 + k] = new POINT2(pArrowPoints[2 - k]);
}
pLinePoints[vblCounter - 5].style = 0;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 5;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 7]);
acCounter=16;
break;
case TacticalLines.FOLSP:
if(client.startsWith("cpof"))
d2=25;
else
d2=25;
double folspDist=0;
folspDist=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(folspDist<d2) //was 10
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(lineType, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
// else if(folspDist<d2)//was 25
// {
// lineType=TacticalLines.FOLLA;
// GetLineArray2Double(lineType, pLinePoints,16,2,shapes,clipBounds,rev);
// for(k=0;k<pLinePoints.length;k++)
// if(pLinePoints[k].style==18)
// pLinePoints[k].style=0;
//
// //lineType=TacticalLines.FOLSP;
// //acCounter=16;
// break;
// }
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
if(client.startsWith("cpof"))
{
if(folspDist<25)
dMBR=125;
if(folspDist<75)
dMBR=150;
if(folspDist<100)
dMBR=175;
if(folspDist<125)
dMBR=200;
}
else
{
dMBR*=1.5;
}
//make tail larger 6-10-11 m. Deutch
//pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 8.75);
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 4);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(k=0; k < 3; k++)
{
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 12].style = 0;
//make tail larger 6-10-11 m. Deutch
//pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 20);
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 15);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 11 + k] = new POINT2(pArrowPoints[2 - k]);
pLinePoints[vblCounter - 11 + k].style = 0;
}
pLinePoints[vblCounter - 8] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 8].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 20, (int) dMBR / 20,pArrowPoints,9);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 7 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 4; k > 0; k--)
{
pLinePoints[vblCounter - k].style = 5;
}
acCounter=12;
break;
case TacticalLines.FERRY:
lLinestyle=9;
if(dMBR/10>maxLength)
dMBR=10*maxLength;
if(dMBR/10<minLength)
dMBR=10*minLength;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-8],pLinePoints[vblCounter-7],(int)dMBR/10,(int)dMBR/10,pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-6+k]=new POINT2(pArrowPoints[k]);
lineutility.GetArrowHead4Double(pLinePoints[1],pLinePoints[0],(int)dMBR/10,(int)dMBR/10, pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-3+k]=new POINT2(pArrowPoints[k]);
acCounter=8;
break;
case TacticalLines.NAVIGATION:
pt3 = lineutility.ExtendLine2Double(pt1, pt0, -10, 0);
pt4 = lineutility.ExtendLine2Double(pt0, pt1, -10, 0);
pt5 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, 10, 0);
pt6 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, -10, 0);
pt7 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, 10, 0);
pt8 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, -10, 0);
if (pt5.y < pt6.y) {
pLinePoints[0] = new POINT2(pt5);
} else {
pLinePoints[0] = new POINT2(pt6);
}
if (pt7.y > pt8.y) {
pLinePoints[3] = new POINT2(pt7);
} else {
pLinePoints[3] = new POINT2(pt8);
}
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
acCounter=4;
break;
case TacticalLines.FORTL:
acCounter=GetFORTLPointsDouble(pLinePoints,lineType,vblSaveCounter);
break;
// case TacticalLines.HOLD:
// case TacticalLines.BRDGHD:
// lineutility.ReorderPoints(pLinePoints);
// acCounter=pLinePoints.length;
// FillPoints(pLinePoints,acCounter,points);
// break;
case TacticalLines.CANALIZE:
acCounter = DISMSupport.GetDISMCanalizeDouble(pLinePoints,lineType);
break;
case TacticalLines.BREACH:
acCounter=DISMSupport.GetDISMBreachDouble( pLinePoints,lineType);
break;
case TacticalLines.SCREEN:
case TacticalLines.GUARD:
case TacticalLines.COVER:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SCREEN_REVC: //works for 3 or 4 points
case TacticalLines.GUARD_REVC:
case TacticalLines.COVER_REVC:
acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SARA:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=14;
break;
case TacticalLines.DISRUPT:
acCounter=DISMSupport.GetDISMDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.CONTAIN:
acCounter=DISMSupport.GetDISMContainDouble(pLinePoints,lineType);
//FillPoints(pLinePoints,acCounter,points,lineType);
break;
case TacticalLines.PENETRATE:
DISMSupport.GetDISMPenetrateDouble(pLinePoints,lineType);
acCounter=7;
break;
case TacticalLines.MNFLDBLK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.BLOCK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
//FillPoints(pLinePoints,4,points,lineType);
acCounter=4;
break;
case TacticalLines.LINTGT:
case TacticalLines.LINTGTS:
case TacticalLines.FPF:
acCounter=DISMSupport.GetDISMLinearTargetDouble(pLinePoints, lineType, vblCounter);
break;
case TacticalLines.GAP:
case TacticalLines.ASLTXING:
case TacticalLines.BRIDGE: //change 1
DISMSupport.GetDISMGapDouble(
pLinePoints,
lineType);
acCounter=12;
break;
case TacticalLines.MNFLDDIS:
acCounter=DISMSupport.GetDISMMinefieldDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.SPTBYFIRE:
acCounter=DISMSupport.GetDISMSupportByFireDouble(pLinePoints,lineType);
break;
case TacticalLines.ATKBYFIRE:
acCounter=DISMSupport.GetDISMATKBYFIREDouble(pLinePoints,lineType);
break;
case TacticalLines.BYIMP:
acCounter=DISMSupport.GetDISMByImpDouble(pLinePoints,lineType);
break;
case TacticalLines.CLEAR:
acCounter=DISMSupport.GetDISMClearDouble(pLinePoints,lineType);
break;
case TacticalLines.BYDIF:
acCounter=DISMSupport.GetDISMByDifDouble(pLinePoints,lineType,clipBounds);
break;
case TacticalLines.SEIZE:
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,0);
break;
case TacticalLines.SEIZE_REVC: //works for 3 or 4 points
double radius=0;
if(rev==RendererSettings.Symbology_2525C)
{
radius=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
pLinePoints[1]=new POINT2(pLinePoints[3]);
pLinePoints[2]=new POINT2(pLinePoints[2]);
}
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,radius);
break;
case TacticalLines.FIX:
case TacticalLines.MNFLDFIX:
acCounter = DISMSupport.GetDISMFixDouble(pLinePoints, lineType,clipBounds);
break;
case TacticalLines.RIP:
acCounter = DISMSupport.GetDISMRIPDouble(pLinePoints,lineType);
break;
case TacticalLines.DELAY:
case TacticalLines.WITHDRAW:
case TacticalLines.WDRAWUP:
case TacticalLines.RETIRE:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
acCounter=DISMSupport.GetDelayGraphicEtcDouble(pLinePoints);
break;
case TacticalLines.EASY:
acCounter=DISMSupport.GetDISMEasyDouble(pLinePoints,lineType);
break;
case TacticalLines.DECEIVE:
DISMSupport.GetDISMDeceiveDouble(pLinePoints);
acCounter=4;
break;
case TacticalLines. BYPASS:
acCounter=DISMSupport.GetDISMBypassDouble(pLinePoints,lineType);
break;
case TacticalLines.PAA_RECTANGULAR:
DISMSupport.GetDISMPAADouble(pLinePoints,lineType);
acCounter=5;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.AMBUSH:
acCounter=DISMSupport.AmbushPointsDouble(pLinePoints);
break;
case TacticalLines.FLOT:
acCounter=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
break;
default:
acCounter=vblSaveCounter;
break;
}
//diagnostic
//lineutility.WriteFile(Double.toString(pLinePoints[0].x)+" to "+Double.toString(pLinePoints[1].x));
//end diagnostic
//Fill points
//and/or return points if shapes is null
switch(lineType)
{
case TacticalLines.BOUNDARY:
FillPoints(pLinePoints,acCounter,points);
//break;
return points;
case TacticalLines.CONTAIN:
case TacticalLines.BLOCK:
//case TacticalLines.DMAF: //points are already filled for DMAF
case TacticalLines.COVER:
case TacticalLines.SCREEN: //note: screen, cover, guard are getting their modifiers before the call to getlinearray
case TacticalLines.GUARD:
case TacticalLines.COVER_REVC:
case TacticalLines.SCREEN_REVC:
case TacticalLines.GUARD_REVC:
//case TacticalLines.DUMMY: //commented 5-3-10
case TacticalLines.PAA_RECTANGULAR:
case TacticalLines.FOLSP:
case TacticalLines.FOLLA:
//add these for rev c 3-12-12
case TacticalLines.BREACH:
case TacticalLines.BYPASS:
case TacticalLines.CANALIZE:
case TacticalLines.CLEAR:
case TacticalLines.DISRUPT:
case TacticalLines.FIX:
case TacticalLines.ISOLATE:
case TacticalLines.OCCUPY:
case TacticalLines.PENETRATE:
case TacticalLines.RETAIN:
case TacticalLines.SECURE:
case TacticalLines.SEIZE:
case TacticalLines.SEIZE_REVC:
FillPoints(pLinePoints,acCounter,points);
break;
default:
//if shapes is null then it is a non-CPOF client, dependent upon pixels
//instead of shapes
if(shapes==null)
{
FillPoints(pLinePoints,acCounter,points);
return points;
}
break;
}
//the shapes require pLinePoints
//if the shapes are null then it is a non-CPOF client,
if(shapes==null)
return points;
Shape2 shape=null;
Shape gp=null;
Shape2 redShape=null,blueShape=null,paleBlueShape=null,whiteShape=null;
Shape2 redFillShape=null,blueFillShape=null,blackShape=null;
BasicStroke blueStroke,paleBlueStroke;
Area blueArea=null;
Area paleBlueArea=null;
Area whiteArea=null;
boolean beginLine=true;
Polygon poly=null;
//a loop for the outline shapes
switch(lineType)
{
case TacticalLines.DIRATKGND:
//create two shapes. the first shape is for the line
//the second shape is for the arrow
//renderer will know to use a skinny stroke for the arrow shape
//the line shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
shape.moveTo(pLinePoints[0]);
for(j=0;j<acCounter-10;j++)
{
//shape.lineTo(pLinePoints[j].x,pLinePoints[j].y);
shape.lineTo(pLinePoints[j]);
}
shapes.add(shape);
//the arrow shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[acCounter-10].x,pLinePoints[acCounter-10].y);
shape.moveTo(pLinePoints[acCounter-10]);
for(j=9;j>0;j--)
{
if(pLinePoints[acCounter-j-1].style == 5)
{
//shape.moveTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.moveTo(pLinePoints[acCounter-j]);
}
else
{
//shape.lineTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.lineTo(pLinePoints[acCounter-j]);
}
}
//shape.lineTo(pLinePoints[acCounter-1].x,pLinePoints[acCounter-1].y);
shapes.add(shape);
break;
// case TacticalLines.BBS_LINE:
// Shape2 outerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//line color
// Shape2 innerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//fill color
// BasicStroke wideStroke=new BasicStroke(pLinePoints[0].style);
// BasicStroke thinStroke=new BasicStroke(pLinePoints[0].style-1);
// for(k=0;k<vblSaveCounter;k++)
// {
// if(k==0)
// {
// outerShape.moveTo(pLinePoints[k]);
// innerShape.moveTo(pLinePoints[k]);
// }
// else
// {
// outerShape.lineTo(pLinePoints[k]);
// innerShape.lineTo(pLinePoints[k]);
// }
// }
// outerShape.setStroke(wideStroke);
// innerShape.setStroke(thinStroke);
// shapes.add(outerShape);
// shapes.add(innerShape);
// break;
case TacticalLines.DEPTH_AREA:
paleBlueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
paleBlueShape.setFillColor(new Color(153,204,255));
paleBlueStroke=new BasicStroke(28);
blueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
blueShape.setFillColor(new Color(30,144,255));
blueStroke=new BasicStroke(14);
whiteShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
whiteShape.setFillColor(Color.WHITE);
poly=new Polygon();
for(k=0;k<vblSaveCounter;k++)
{
poly.addPoint((int)pLinePoints[k].x, (int)pLinePoints[k].y);
if(k==0)
whiteShape.moveTo(pLinePoints[k]);
else
whiteShape.lineTo(pLinePoints[k]);
}
whiteArea=new Area(poly);
blueArea=new Area(blueStroke.createStrokedShape(poly));
blueArea.intersect(whiteArea);
blueShape.setShape(lineutility.createStrokedShape(blueArea));
paleBlueArea=new Area(paleBlueStroke.createStrokedShape(poly));
paleBlueArea.intersect(whiteArea);
paleBlueShape.setShape(lineutility.createStrokedShape(paleBlueArea));
shapes.add(whiteShape);
shapes.add(paleBlueShape);
shapes.add(blueShape);
break;
case TacticalLines.TRAINING_AREA:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for outline
redShape.set_Style(1);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for symbol
blueShape.set_Style(0);
redShape.moveTo(pLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
redShape.lineTo(pLinePoints[k]);
//blueShape.moveTo(pLinePoints[vblSaveCounter]);
beginLine=true;
for(k=vblSaveCounter;k<acCounter;k++)
{
if(pLinePoints[k].style==0)
{
if(beginLine)
{
blueShape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
blueShape.lineTo(pLinePoints[k]);
}
if(pLinePoints[k].style==5)
{
blueShape.lineTo(pLinePoints[k]);
beginLine=true;
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.ITD:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.GREEN);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFY:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//flots and spikes (triangles)
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
//blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
//blackShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//red and blue short segments (between the flots)
for(k=0;k<vblCounter-1;k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFG:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes red outline
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==22)
{
POINT2[] CirclePoints=new POINT2[8];
redShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
redShape.setFillColor(Color.RED);
if(redShape !=null && redShape.getShape() != null)
shapes.add(redShape);
}
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
blueShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
blueShape.setFillColor(Color.BLUE);
if(blueShape !=null && blueShape.getShape() != null)
shapes.add(blueShape);
}
}
break;
case TacticalLines.USF:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
beginLine=true;
//int color=0;//red
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==19)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==25)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SF:
blackShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blackShape.setLineColor(Color.BLACK);
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23)
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//12-30-11
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
blackShape.lineTo(pLinePoints[l]);
}
redFillShape.lineTo(pLinePoints[k-9]); //12-30-11
shapes.add(redFillShape); //12-30-11
}
if(pLinePoints[k].style==24)
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
blueFillShape.lineTo(pLinePoints[k-2]);
shapes.add(blueFillShape); //12-30-11
blackShape.moveTo(pLinePoints[k-2]);
blackShape.lineTo(pLinePoints[k-1]);
blackShape.lineTo(pLinePoints[k]);
}
}
//the corners
blackShape.moveTo(pOriginalLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
blackShape.lineTo(pOriginalLinePoints[k]);
//shapes.add(redFillShape); //12-30-11
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
shapes.add(blackShape);
break;
case TacticalLines.WFG:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.FOLLA:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1); //dashed line
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(0); //dashed line
//shape.moveTo(pLinePoints[2]);
for(j=2;j<vblCounter;j++)
{
if(pLinePoints[j-1].style != 5)
shape.lineTo(pLinePoints[j]);
else
shape.moveTo(pLinePoints[j]);
}
shapes.add(shape);
break;
case TacticalLines.CFG:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==9)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
d=lineutility.CalcDistanceDouble(pLinePoints[k], pLinePoints[k+1]);
pt0=lineutility.ExtendAlongLineDouble(pLinePoints[k], pLinePoints[k+1], d-5);
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pt0.x,pt0.y);
shape.lineTo(pt0);
}
if(pLinePoints[k].style==0 && k==acCounter-2)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.PIPE:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==1)
{
if(k==0)
{
shape.moveTo(pLinePoints[k]);
}
else
shape.lineTo(pLinePoints[k]);
}
}
shapes.add(shape);
break;
case TacticalLines.ATDITCHM:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 4, 8, CirclePoints, 9);//was 3
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
if(k<acCounter-2)
{
if(pLinePoints[k].style!=0 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==10)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
//use shapes instead of pixels
// if(shape==null)
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//
// if(beginLine)
// {
// if(k==0)
// shape.set_Style(pLinePoints[k].style);
//
// shape.moveTo(pLinePoints[k]);
// beginLine=false;
// }
// else
// {
// //diagnostic 1-8-13
// if(k<acCounter-1)
// {
// if(pLinePoints[k].style==5)
// {
// shape.moveTo(pLinePoints[k]);
// continue;
// }
// }
// //end section
// shape.lineTo(pLinePoints[k]);
// //diagnostic 1-8-13
// //if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
// if(pLinePoints[k].style==10)
// {
// beginLine=true;
// }
// }
// if(pLinePoints[k+1].style==20)
// {
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
// }
if(k<acCounter-2)
{
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
}//end for
break;
case TacticalLines.DIRATKFNT:
//the solid lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18)
continue;
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k>0) //doubled points with linestyle=5
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
continue;//shape.lineTo(pLinePoints[k]);
if(k==0)
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==vblCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
//the dashed lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18 && pLinePoints[k-1].style == 5)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.set_Style(pLinePoints[k].style);
shape.set_Style(1);
shape.moveTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==18 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
}
else
continue;
}
break;
case TacticalLines.ESR1:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[2].style);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
break;
case TacticalLines.DUMMY: //commented 5-3-10
//first shape is the original points
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.set_Style(1);
// shape.moveTo(pLinePoints[acCounter-1]);
// shape.lineTo(pLinePoints[acCounter-2]);
// shape.lineTo(pLinePoints[acCounter-3]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for (k = 0; k < acCounter-3; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k==0)
shape.set_Style(pLinePoints[k].style);
//if(k>0) //doubled points with linestyle=5
// if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
// shape.lineTo(pLinePoints[k]);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-4) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1);
shape.moveTo(pLinePoints[acCounter-1]);
shape.lineTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-3]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMA:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[vblCounter-3]);
shape.set_Style(1);
shape.lineTo(pLinePoints[vblCounter-2]);
shape.lineTo(pLinePoints[vblCounter-1]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.FORDIF:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[4].style);
shape.moveTo(pLinePoints[4]);
for(k=5;k<acCounter;k++)
{
if(pLinePoints[k-1].style != 5)
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMAF:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(points.get(0).style);
shape.moveTo(points.get(0));
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(points.get(k));
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(points.get(vblCounter-3));
shape.set_Style(1);
shape.lineTo(points.get(vblCounter-2));
shape.lineTo(points.get(vblCounter-1));
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for(k=vblCounter;k<points.size();k++)
{
if(beginLine)
{
if(k==0)
shape.set_Style(points.get(k).style);
if(k>0) //doubled points with linestyle=5
if(points.get(k).style==5 && points.get(k-1).style==5)
shape.lineTo(points.get(k));
shape.moveTo(points.get(k));
beginLine=false;
}
else
{
shape.lineTo(points.get(k));
if(points.get(k).style==5 || points.get(k).style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==points.size()-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.AIRFIELD:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for (k = 1; k < acCounter-5; k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[acCounter-4]);
shape.lineTo(pLinePoints[acCounter-3]);
shape.moveTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-1]);
shapes.add(shape);
//we need an extra shape to outline the center feature
//in case there is opaque fill that obliterates it
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.MIN_POINTS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for(k=1;k<pLinePoints.length;k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
break;
default:
for (k = 0; k < acCounter; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
//if(pLinePoints[k].style==5)
// continue;
if(k==0)
shape.set_Style(pLinePoints[k].style);
if(k>0) //doubled points with linestyle=5
{
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5 && k< acCounter-1)
continue;
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==10) //CF
continue;
}
if(k==0 && pLinePoints.length>1)
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==5)
continue;
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
break;
}//end switch
//a loop for arrowheads with fill
//these require a separate shape for fill
switch(lineType)
{
case TacticalLines.BELT1://requires non-decorated fill shape
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pUpperLinePoints[0]);
for(j=1;j<pUpperLinePoints.length;j++)
{
shape.lineTo(pUpperLinePoints[j]);
//lineutility.SegmentLineShape(pUpperLinePoints[j], pUpperLinePoints[j+1], shape);
}
shape.lineTo(pLowerLinePoints[pLowerLinePoints.length-1]);
for(j=pLowerLinePoints.length-1;j>=0;j--)
{
shape.lineTo(pLowerLinePoints[j]);
//lineutility.SegmentLineShape(pLowerLinePoints[j], pLowerLinePoints[j-1], shape);
}
shape.lineTo(pUpperLinePoints[0]);
shapes.add(0,shape);
break;
case TacticalLines.DIRATKAIR:
//added this section to not fill the bow tie and instead
//add a shape to close what had been the bow tie fill areas with
//a line segment for each one
int outLineCounter=0;
POINT2[]ptOutline=new POINT2[4];
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==10)
{
//shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[k-2]);
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(1,shape);
//collect these four points
ptOutline[outLineCounter++]=pLinePoints[k-2];
ptOutline[outLineCounter++]=pLinePoints[k];
}
}//end for
//build a shape from the to use as outline for the feature
//if fill alpha is high
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.moveTo(ptOutline[0]);
// shape.lineTo(ptOutline[1]);
// shape.lineTo(ptOutline[3]);
// shape.lineTo(ptOutline[2]);
// shape.lineTo(ptOutline[0]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(0,shape);
break;
case TacticalLines.OFY:
case TacticalLines.OCCLUDED:
case TacticalLines.WF:
case TacticalLines.WFG:
case TacticalLines.WFY:
case TacticalLines.CF:
case TacticalLines.CFY:
case TacticalLines.CFG:
//case TacticalLines.SF:
//case TacticalLines.SFY:
//case TacticalLines.SFG:
case TacticalLines.SARA:
case TacticalLines.FERRY:
case TacticalLines.EASY:
case TacticalLines.BYDIF:
case TacticalLines.BYIMP:
case TacticalLines.FOLSP:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
case TacticalLines.MNFLDFIX:
case TacticalLines.TURN:
case TacticalLines.MNFLDDIS:
//POINT2 initialFillPt=null;
for (k = 0; k < acCounter; k++)
{
if(k==0)
{
if(pLinePoints[k].style==9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
}
else //k>0
{
if(pLinePoints[k].style==9 && pLinePoints[k-1].style != 9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
if(pLinePoints[k].style==9 && pLinePoints[k-1].style==9) //9,9,...,9,10
{
shape.lineTo(pLinePoints[k]);
}
}
if(pLinePoints[k].style==10)
{
shape.lineTo(pLinePoints[k]);
if(lineType==TacticalLines.SARA)
shape.lineTo(pLinePoints[k-2]);
if(shape !=null && shape.getShape() != null)
{
//must line to the initial fill point to close the shape
//this is a requirement for the java linear ring (map3D java client)
//if(initialFillPt != null)
//shape.lineTo(initialFillPt);
shapes.add(0,shape);
//initialFillPt=null;
}
}
}//end for
break;
default:
break;
}
//CELineArray.add_Shapes(shapes);
//clean up
pArrowPoints=null;
arcPts=null;
circlePoints=null;
pOriginalLinePoints=null;
pts2=null;
pts=null;
segments=null;
pUpperLinePoints=null;
pLowerLinePoints=null;
pUpperLowerLinePoints=null;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetLineArray2Double",
new RendererException("GetLineArray2Dboule " + Integer.toString(lineType), exc));
}
return points;
}
}
| core/JavaLineArray/src/main/java/JavaLineArray/arraysupport.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaLineArray;
/**
* Class to process the pixel arrays
* @author Michael Deutch
*/
import java.awt.Color;
import java.util.ArrayList;
import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Area;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import ArmyC2.C2SD.Utilities.RendererSettings;
import java.awt.geom.Rectangle2D;
/*
* A class to calculate the symbol points for the GeneralPath objects.
* @author Michael Deutch
*/
public final class arraysupport
{
private static double maxLength=100;
private static double minLength=5;
private static double dACP=0;
private static String _className="arraysupport";
protected static void setMinLength(double value)
{
minLength=value;
}
private static void FillPoints(POINT2[] pLinePoints,
int counter,
ArrayList<POINT2>points)
{
points.clear();
for(int j=0;j<counter;j++)
{
points.add(pLinePoints[j]);
}
}
/**
* This is the interface function to CELineArray from clsRenderer2
* for non-channel types
*
* @param lineType the line type
* @param pts the client points
* @param shapes the symbol ShapeInfo objects
* @param clipBounds the rectangular clipping bounds
* @param rev the Mil-Standard-2525 revision
*/
public static ArrayList<POINT2> GetLineArray2(int lineType,
ArrayList<POINT2> pts,
ArrayList<Shape2> shapes,
Rectangle2D clipBounds,
int rev) {
ArrayList<POINT2> points = null;
try {
POINT2 pt = null;
POINT2[] pLinePoints2 = null;
POINT2[] pLinePoints = null;
int vblSaveCounter = pts.size();
//get the count from countsupport
int j = 0;
if (pLinePoints2 == null || pLinePoints2.length == 0)//did not get set above
{
pLinePoints = new POINT2[vblSaveCounter];
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y, pt.style);
}
}
//get the number of points the array will require
int vblCounter = countsupport.GetCountersDouble(lineType, vblSaveCounter, pLinePoints, clipBounds,rev);
//resize pLinePoints and fill the first vblSaveCounter elements with the original points
if(vblCounter>0)
pLinePoints = new POINT2[vblCounter];
else
{
shapes=null;
return null;
}
lineutility.InitializePOINT2Array(pLinePoints);
//safeguards added 2-17-11 after CPOF client was allowed to add points to autoshapes
if(vblSaveCounter>pts.size())
vblSaveCounter=pts.size();
if(vblSaveCounter>pLinePoints.length)
vblSaveCounter=pLinePoints.length;
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y,pt.style);
}
//we have to adjust the autoshapes because they are instantiating with fewer points
points = GetLineArray2Double(lineType, pLinePoints, vblCounter, vblSaveCounter, shapes, clipBounds,rev);
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetLineArray2",
new RendererException("GetLineArray2 " + Integer.toString(lineType), exc));
}
return points;
//the caller can get points
}
/**
* A function to calculate the points for FORTL
* @param pLinePoints OUT - the points arry also used for the return points
* @param lineType
* @param vblSaveCounter the number of client points
* @return
*/
private static int GetFORTLPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, bolVertical = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
//long[] segments=null;
//long numpts2=0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
//numpts2=lineutility.BoundPointsCount(pLinePoints,vblSaveCounter);
//segments=new long[numpts2];
//lineutility.BoundPoints(ref pLinePoints,vblSaveCounter,ref segments);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
switch (lineType) {
default:
dIncrement = 20;
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if (dLengthSegment / 20 < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < dLengthSegment / 20 - 1; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 10, 0);
nCounter++;
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 10);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 3, 10);
nCounter++;
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 2, 10);
nCounter++;
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
if (pLinePoints[j].y < pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 1, 10);
nCounter++;
}
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 0, 10);
nCounter++;
}
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], 10, 0);
nCounter++;
}//end for k
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
return nCounter;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetFORTLPointsDouble",
new RendererException("GetFORTLPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static void CoordFEBADouble(
POINT2[] pLinePoints,
int vblCounter) {
try {
//declarations
int j = 0;
POINT2[] pXLinePoints = new POINT2[4 * vblCounter / 32];
POINT2[] pNewLinePoints = new POINT2[vblCounter / 32];
POINT2[] pShortLinePoints = new POINT2[2 * vblCounter / 32];
POINT2[] pArcLinePoints = new POINT2[26 * vblCounter / 32];
double dPrinter = 1.0;
//end declarations
for (j = vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pLinePoints[0]); //initialize the rest of pLinePoints
pLinePoints[j].style = 0;
}
for (j = 0; j < 4 * vblCounter / 32; j++) {
pXLinePoints[j] = new POINT2(pLinePoints[0]); //initialization only for pXLinePoints
pXLinePoints[j].style = 0;
}
for (j = 0; j < vblCounter / 32; j++) //initialize pNewLinePoints
{
pNewLinePoints[j] = new POINT2(pLinePoints[j]);
pNewLinePoints[j].style = 0;
}
for (j = 0; j < 2 * vblCounter / 32; j++) //initialize pShortLinePoints
{
pShortLinePoints[j] = new POINT2(pLinePoints[0]);
pShortLinePoints[j].style = 0;
}
for (j = 0; j < 26 * vblCounter / 32; j++) //initialize pArcLinePoints
{
pArcLinePoints[j] = new POINT2(pLinePoints[0]);
pArcLinePoints[j].style = 0;
}
//first get the X's
lineutility.GetXFEBADouble(pNewLinePoints, 10 * dPrinter, vblCounter / 32,//was 7
pXLinePoints);
for (j = 0; j < 4 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pXLinePoints[j]);
}
pLinePoints[4 * vblCounter / 32 - 1].style = 5;
for (j = 4 * vblCounter / 32; j < 6 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pShortLinePoints[j - 4 * vblCounter / 32]);
pLinePoints[j].style = 5; //toggle invisible lines between feba's
}
pLinePoints[6 * vblCounter / 32 - 1].style = 5;
//last, get the arcs
lineutility.GetArcFEBADouble(14.0 * dPrinter, pNewLinePoints,
vblCounter / 32,
pArcLinePoints);
for (j = 6 * vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pArcLinePoints[j - 6 * vblCounter / 32]);
}
//clean up
pXLinePoints = null;
pNewLinePoints = null;
pShortLinePoints = null;
pArcLinePoints = null;
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "CoordFEBADouble",
new RendererException("CoordFEBADouble", exc));
}
}
private static int GetATWallPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 0;
int limit = 0;
//POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
pSpikePoints[nCounter++] = new POINT2(pLinePoints[0]);
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
if (limit < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = -1; k < limit; k++)//was k=0 to limit
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = new POINT2(pt0);
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0;j < nCounter;j++){
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble", exc));
}
return nCounter;
}
public static int GetInsideOutsideDouble2(POINT2 pt0,
POINT2 pt1,
POINT2[] pLinePoints,
int vblCounter,
int index,
int lineType) {
int nDirection = 0;
try {
//declarations
ref<double[]> m = new ref();
ref<double[]> m0 = new ref();
double b0 = 0;
double b2 = 0;
double b = 0;
double X0 = 0; //segment midpoint X value
double Y0 = 0; //segment midpoint Y value
double X = 0; //X value of horiz line from left intercept with current segment
double Y = 0; //Y value of vertical line from top intercept with current segment
int nInOutCounter = 0;
int j = 0, bolVertical = 0;
int bolVertical2 = 0;
int nOrientation = 0; //will use 0 for horiz line from left, 1 for vertical line from top
int extendLeft = 0;
int extendRight = 1;
int extendAbove = 2;
int extendBelow = 3;
int oppSegment=vblCounter-index-3; //used by BELT1 only
POINT2 pt2=new POINT2();
//end declarations. will use this to determine the direction
//slope of the segment
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m0);
if(m0.value==null)
return 0;
//get the midpoint of the segment
X0 = (pt0.x + pt1.x) / 2;
Y0 = (pt0.y + pt1.y) / 2;
if(lineType==TacticalLines.BELT1 && oppSegment>=0 && oppSegment<vblCounter-1)
{
//get the midpoint of the opposite segment
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
//must calculate the corresponding point on the current segment
//first get the y axis intercept of the perpendicular line for the opposite (short) segment
//calculate this line at the midpoint of the opposite (short) segment
b0=Y0+1/m0.value[0]*X0;
//the y axis intercept of the index segment
b2=pt0.y-m0.value[0]*pt0.x;
if(m0.value[0]!=0 && bolVertical!=0)
{
//calculate the intercept at the midpoint of the shorter segment
pt2=lineutility.CalcTrueIntersectDouble2(-1/m0.value[0],b0,m0.value[0],b2,1,1,0,0);
X0=pt2.x;
Y0=pt2.y;
}
if(m0.value[0]==0 && bolVertical!=0)
{
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pt0.y+pt1.y )/2;
}
if(bolVertical==0)
{
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
X0= ( pt0.x+pt1.x )/2;
}
}
//slope is not too small or is vertical, use left to right
if (Math.abs(m0.value[0]) >= 1 || bolVertical == 0) {
nOrientation = 0; //left to right orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j) {
//for BELT1 we only want to know if the opposing segment is to the
//left of the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j) //change 2
continue;
if ((pLinePoints[j].y <= Y0 && pLinePoints[j + 1].y >= Y0) ||
(pLinePoints[j].y >= Y0 && pLinePoints[j + 1].y <= Y0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 1 && m.value[0] == 0) //current segment is horizontal, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter--;
}
//current segment is vertical, it's x value must be to the left
//of the current segment X0 for the horiz line from the left to cross
if (bolVertical2 == 0) {
if (pLinePoints[j].x < X0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the X value of the intersection between the horiz line
//from the left and the current segment
//b=Y0;
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
X = (Y0 - b) / m.value[0];
if (X < X0) //the horizontal line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
} //end if
else //use top to bottom to get orientation
{
nOrientation = 1; //top down orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j)
{
//for BELT1 we only want to know if the opposing segment is
//above the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j)
continue;
if ((pLinePoints[j].x <= X0 && pLinePoints[j + 1].x >= X0) ||
(pLinePoints[j].x >= X0 && pLinePoints[j + 1].x <= X0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 0) //current segment is vertical, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter--;
}
//current segment is horizontal, it's y value must be above
//the current segment Y0 for the horiz line from the left to cross
if (bolVertical2 == 1 && m.value[0] == 0) {
if (pLinePoints[j].y < Y0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the Y value of the intersection between the vertical line
//from the top and the current segment
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
Y = m.value[0] * X0 + b;
if (Y < Y0) //the vertical line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
}
switch (nInOutCounter % 2) {
case 0:
if (nOrientation == 0) {
nDirection = extendLeft;
} else {
nDirection = extendAbove;
}
break;
case 1:
if (nOrientation == 0) {
nDirection = extendRight;
} else {
nDirection = extendBelow;
}
break;
default:
break;
}
} catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetInsideOutsideDouble2",
new RendererException("GetInsideOutsideDouble2", exc));
}
return nDirection;
}
/**
* BELT1 line and others
* @param pLinePoints
* @param lineType
* @param vblSaveCounter
* @return
*/
protected static int GetZONEPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, n = 0;
int lCount = 0;
double dLengthSegment = 0;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = null, pt2 = null, pt3 = null;
POINT2[] pSpikePoints = null;
int nDirection = 0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
double remainder=0;
//for(j=0;j<numpts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++) {
pt1 = new POINT2(pLinePoints[j]);
pt2 = new POINT2(pLinePoints[j + 1]);
//get the direction for the spikes
nDirection = GetInsideOutsideDouble2(pt1, pt2, pLinePoints, vblSaveCounter, (int) j, lineType);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
//reverse the direction for those lines with inward spikes
if (!(lineType == TacticalLines.BELT) && !(lineType == TacticalLines.BELT1) )
{
if (dLengthSegment < 20) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
switch (nDirection) {
case 0: //extend left
nDirection = 1; //extend right
break;
case 1: //extend right
nDirection = 0; //extend left
break;
case 2: //extend above
nDirection = 3; //extend below
break;
case 3: //extgend below
nDirection = 2; //extend above
break;
default:
break;
}
break;
default:
break;
}
n = (int) (dLengthSegment / 20);
remainder=dLengthSegment-n*20;
for (k = 0; k < n; k++)
{
if(k>0)
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20-remainder/2, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10-remainder/2, 0);//was -10
}
else
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10, 0);//was -10
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 5);
break;
case TacticalLines.STRONG:
case TacticalLines.FORT:
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
break;
default:
break;
}
pSpikePoints[nCounter++] = lineutility.ExtendDirectedLine(pt1, pt2, pt0, nDirection, 10);
//nCounter++;
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
break;
case TacticalLines.STRONG:
pSpikePoints[nCounter] = new POINT2(pSpikePoints[nCounter - 2]);
break;
case TacticalLines.FORT:
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pt1, pt2, pt3, nDirection, 10);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pt3);
break;
default:
break;
}
//}
nCounter++;
//diagnostic
if(lineType==TacticalLines.ENCIRCLE)
pSpikePoints[nCounter++] = new POINT2(pSpikePoints[nCounter-4]);
}//end for k
pSpikePoints[nCounter++] = new POINT2(pLinePoints[j + 1]);
//nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[j].style = 11;
}
}
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[nCounter - 1].style = 12;
} else {
if(nCounter>0)
pSpikePoints[nCounter - 1].style = 5;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
if (j == nCounter - 1) {
if (lineType != (long) TacticalLines.OBSAREA) {
pLinePoints[j].style = 5;
}
}
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetZONEPointsDouble2",
new RendererException("GetZONEPointsDouble2", exc));
}
return nCounter;
}
private static boolean IsTurnArcReversed(POINT2[] pPoints) {
try {
if (pPoints.length < 3) {
return false;
}
POINT2[] ptsSeize = new POINT2[2];
ptsSeize[0] = new POINT2(pPoints[0]);
ptsSeize[1] = new POINT2(pPoints[1]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double d = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize[0] = new POINT2(pPoints[1]);
ptsSeize[1] = new POINT2(pPoints[0]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double dArcReversed = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize = null;
if (dArcReversed > d) {
return true;
} else {
return false;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "IsTurnArcReversed",
new RendererException("IsTurnArcReversed", exc));
}
return false;
}
private static void GetIsolatePointsDouble(POINT2[] pLinePoints,
int lineType) {
try {
//declarations
boolean reverseTurn=false;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = new POINT2(pLinePoints[1]), pt2 = new POINT2(pLinePoints[0]);
if(pt0.x==pt1.x && pt0.y==pt1.y)
pt1.x+=1;
POINT2 C = new POINT2(), E = new POINT2(), midPt = new POINT2();
int j = 0, k = 0, l = 0;
POINT2[] ptsArc = new POINT2[26];
POINT2[] midPts = new POINT2[7];
POINT2[] trianglePts = new POINT2[21];
POINT2[] pArrowPoints = new POINT2[3], reversepArrowPoints = new POINT2[3];
double dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
double dLength = Math.abs(dRadius - 20);
if(dRadius<40)
{
dLength=dRadius/1.5;
}
double d = lineutility.MBRDistance(pLinePoints, 2);
POINT2[] ptsSeize = new POINT2[2];
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(pLinePoints[j]);
}
if (pLinePoints.length >= 3) {
savepoints[2] = new POINT2(pLinePoints[2]);
}
lineutility.InitializePOINT2Array(ptsArc);
lineutility.InitializePOINT2Array(midPts);
lineutility.InitializePOINT2Array(trianglePts);
lineutility.InitializePOINT2Array(pArrowPoints);
lineutility.InitializePOINT2Array(reversepArrowPoints);
lineutility.InitializePOINT2Array(ptsSeize);
if (d / 7 > maxLength) {
d = 7 * maxLength;
}
if (d / 7 < minLength) { //was minLength
d = 7 * minLength; //was minLength
}
//change due to outsized arrow in 6.0, 11-3-10
if(d>140)
d=140;
//calculation points for the SEIZE arrowhead
//for SEIZE calculations
POINT2[] ptsArc2 = new POINT2[26];
lineutility.InitializePOINT2Array(ptsArc2);
//end declarations
E.x = 2 * pt1.x - pt0.x;
E.y = 2 * pt1.y - pt0.y;
ptsArc[0] = new POINT2(pLinePoints[1]);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) d / 7, pArrowPoints, 0);
pLinePoints[25].style = 5;
switch (lineType) {
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.ISOLATE:
for (j = 1; j <= 23; j++) {
if (j % 3 == 0) {
midPts[k].x = pt0.x - (long) ((dLength / dRadius) * (pt0.x - ptsArc[j].x));
midPts[k].y = pt0.y - (long) ((dLength / dRadius) * (pt0.y - ptsArc[j].y));
midPts[k].style = 0;
trianglePts[l] = new POINT2(ptsArc[j - 1]);
l++;
trianglePts[l] = new POINT2(midPts[k]);
l++;
trianglePts[l] = new POINT2(ptsArc[j + 1]);
trianglePts[l].style = 5;
l++;
k++;
}
}
for (j = 26; j < 47; j++) {
pLinePoints[j] = new POINT2(trianglePts[j - 26]);
}
pLinePoints[46].style = 5;
for (j = 47; j < 50; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 47]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.OCCUPY:
midPt.x = (pt1.x + ptsArc[25].x) / 2;
midPt.y = (pt1.y + ptsArc[25].y) / 2;
lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) d / 7, reversepArrowPoints, 0);
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
}
for (j = 29; j < 32; j++) {
pLinePoints[j] = new POINT2(reversepArrowPoints[j - 29]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.SECURE:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
break;
case TacticalLines.TURN:
boolean changeArc = IsTurnArcReversed(savepoints); //change 1
if (reverseTurn == true || changeArc == true) //swap the points
{
pt0.x = pt1.x;
pt0.y = pt1.y;
pt1.x = pt2.x;
pt1.y = pt2.y;
}
ptsSeize[0] = new POINT2(pt0);
ptsSeize[1] = new POINT2(pt1);
dRadius = lineutility.CalcClockwiseCenterDouble(ptsSeize);
C = new POINT2(ptsSeize[0]);
E = new POINT2(ptsSeize[1]);
ptsArc[0] = new POINT2(pt0);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if (changeArc == true)//if(changeArc==false) //change 1
{
lineutility.GetArrowHead4Double(ptsArc[1], pt0, (int) d / 7, (int) d / 7, pArrowPoints, 5);
} else {
lineutility.GetArrowHead4Double(ptsArc[24], pt1, (int) d / 7, (int) d / 7, pArrowPoints, 5);
}
pLinePoints[25].style = 5;
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 9;
}
pLinePoints[28].style = 10;
break;
case TacticalLines.RETAIN:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
//get the extended points for retain
k = 29;
for (j = 1; j < 24; j++) {
pLinePoints[k] = new POINT2(ptsArc[j]);
pLinePoints[k].style = 0;
k++;
pLinePoints[k] = lineutility.ExtendLineDouble(pt0, ptsArc[j], (long) d / 7);
pLinePoints[k].style = 5;
k++;
}
break;
default:
break;
}
//clean up
savepoints = null;
ptsArc = null;
midPts = null;
trianglePts = null;
pArrowPoints = null;
reversepArrowPoints = null;
ptsSeize = null;
ptsArc2 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIsolatePointsDouble",
new RendererException("GetIsolatePointsDouble " + Integer.toString(lineType), exc));
}
return;
}
/**
* @deprecated
* returns the location for the Dummy Hat
* @param pLinePoints
* @return
*/
private static POINT2 getDummyHat(POINT2[]pLinePoints)
{
POINT2 pt=null;
try
{
int j=0;
double minY=Double.MAX_VALUE;
double minX=Double.MAX_VALUE,maxX=-Double.MAX_VALUE;
int index=-1;
//get the highest point
for(j=0;j<pLinePoints.length-3;j++)
{
if(pLinePoints[j].y<minY)
{
minY=pLinePoints[j].y;
index=j;
}
if(pLinePoints[j].x<minX)
minX=pLinePoints[j].x;
if(pLinePoints[j].x>maxX)
maxX=pLinePoints[j].x;
}
pt=new POINT2(pLinePoints[index]);
double deltaMaxX=0;
double deltaMinX=0;
if(pt.x+25>maxX)
{
deltaMaxX=pt.x+25-maxX;
pt.x-=deltaMaxX;
}
if(pt.x-25<minX)
{
deltaMinX=minX-(pt.x-25);
pt.x+=deltaMinX;
}
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "getDummyHat",
new RendererException("getDummyHat", exc));
}
return pt;
}
private static void AreaWithCenterFeatureDouble(POINT2[] pLinePoints,
int vblCounter,
int lineType )
{
try
{
//declarations
int k=0;
POINT2 ptCenter = new POINT2();
double d = lineutility.MBRDistance(pLinePoints, vblCounter);
//11-18-2010
if(d>350)
d=350;
//end declarations
for (k = 0; k < vblCounter; k++) {
pLinePoints[k].style = 0;
}
switch (lineType) {
case TacticalLines.DUMMY:
POINT2 ul=new POINT2();
POINT2 lr=new POINT2();
lineutility.CalcMBRPoints(pLinePoints, vblCounter-3, ul, lr);
//ul=getDummyHat(pLinePoints);
//ul.x-=25;
POINT2 ur=new POINT2(lr);
ur.y=ul.y;
pLinePoints[vblCounter-3]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-3].x-=25;
pLinePoints[vblCounter-3].y-=10;
pLinePoints[vblCounter-2]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-2].y-=35;
pLinePoints[vblCounter-1]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-1].x+=25;
pLinePoints[vblCounter-1].y-=10;
pLinePoints[vblCounter-4].style=5;
break;
case TacticalLines.AIRFIELD:
pLinePoints[vblCounter - 5] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 5].style = 5;
pLinePoints[vblCounter - 4] = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 4].x -= d / 20;
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 3].x = pLinePoints[vblCounter - 4].x + d / 10;
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 2].y += d / 40;
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 3]);
pLinePoints[vblCounter - 1].y -= d / 40;
pLinePoints[vblCounter - 1].style = 0;
break;
case TacticalLines.DMA:
if (lineType == (long) TacticalLines.DMA) {
for (k = 0; k < vblCounter - 4; k++) {
pLinePoints[k].style = 14;
}
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 4].style = 5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 3);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
break;
case TacticalLines.DMAF:
pLinePoints[vblCounter-4].style=5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 3);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
pLinePoints[vblCounter - 1].style = 5;
break;
default:
break;
}
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AreaWithCenterFeatureDouble",
new RendererException("AreaWithCenterFeatureDouble " + Integer.toString(lineType), exc));
}
}
private static int GetATWallPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dRemainder = 0, dSpikeSize = 0;
int limit = 0;
POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
switch (lineType) {
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter] = pLinePoints[0];
pSpikePoints[nCounter].style = 0;
nCounter++;
break;
default:
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
switch (lineType) {
case TacticalLines.UCF:
case TacticalLines.CF:
case TacticalLines.CFG:
case TacticalLines.CFY:
dIncrement = 60;
dSpikeSize = 20;
dRemainder = dLengthSegment / dIncrement - (double) ((int) (dLengthSegment / dIncrement));
if (dRemainder < 0.75) {
limit = (int) (dLengthSegment / dIncrement);
} else {
limit = (int) (dLengthSegment / dIncrement) + 1;
}
break;
default:
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
break;
}
if (limit < 1) {
pSpikePoints[nCounter] = pLinePoints[j];
nCounter++;
pSpikePoints[nCounter] = pLinePoints[j + 1];
nCounter++;
continue;
}
for (k = 0; k < limit; k++) {
switch (lineType) {
case TacticalLines.CFG: //linebreak for dot
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 4, 5); //+2
nCounter++;
//dot
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 1, 20);
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 7, 0); //-4
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
case TacticalLines.CFY: //linebreak for crossed line
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 10, 5); //+2
nCounter++;
//dot
//pSpikePoints[nCounter]=lineutility.ExtendLine2Double(pLinePoints[j+1],pLinePoints[j],-k*dIncrement-1,20);
//nCounter++;
//replace the dot with crossed line segment
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 5, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 10, 5);
nCounter++;
crossPt1 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 1], 2, 5, 0);
crossPt2 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 2], 3, 5, 5);
pSpikePoints[nCounter] = crossPt1;
nCounter++;
pSpikePoints[nCounter] = crossPt2;
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 13, 0); //-4
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
default:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
break;
}
if (lineType == TacticalLines.CF) {
pSpikePoints[nCounter].style = 0;
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - dSpikeSize, 0);
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter].style = 9;
}
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = pt0;
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter - 1].style = 9;
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
//need an extra point for these
switch (lineType) {
case TacticalLines.CF:
pSpikePoints[nCounter].style = 10;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter].style = 10;
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], dSpikeSize, 0);
break;
default:
break;
}
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = pLinePoints[j + 1];
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = pSpikePoints[j];
}
pLinePoints[nCounter-1].style=5;
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static int GetRidgePointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 20;
int limit = 0;
double d = 0;
int bolVertical = 0;
//end delcarations
m.value = new double[1];
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
//for(j=0;j<numPts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++)
{
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
limit = (int) (dLengthSegment / dIncrement);
if (limit < 1)
{
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < limit; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
d = lineutility.CalcDistanceDouble(pLinePoints[j], pSpikePoints[nCounter - 1]);
pt0 = lineutility.ExtendLineDouble(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize / 2);
//the spikes
if (bolVertical != 0) //segment is not vertical
{
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, dSpikeSize);
}
else //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, dSpikeSize);
}
}
else //segment is vertical
{
if (pLinePoints[j + 1].y < pLinePoints[j].y) //extend left of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, dSpikeSize);
}
else //extend right of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, dSpikeSize);
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize, 0);
nCounter++;
}
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
//}
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
for (j = nCounter; j < lCount; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[nCounter - 1]);
}
//clean up
//segments=null;
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRidgePointsDouble",
new RendererException("GetRidgePointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
protected static int GetSquallDouble(POINT2[] pLinePoints,
int amplitude,
int quantity,
int length,
int numPoints)
{
int counter = 0;
try {
int j = 0, k = 0;
POINT2 StartSegPt, EndSegPt;
POINT2 savePoint1 = new POINT2(pLinePoints[0]);
POINT2 savePoint2 = new POINT2(pLinePoints[numPoints - 1]);
ref<int[]> sign = new ref();
int segQty = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints);
POINT2[] pSquallPts = new POINT2[totalQty];
POINT2[] pSquallSegPts = null;
//end declarations
lineutility.InitializePOINT2Array(pSquallPts);
sign.value = new int[1];
sign.value[0] = -1;
if (totalQty == 0) {
return 0;
}
for (j = 0; j < numPoints - 1; j++) {
//if(segments[j]!=0)
//{
StartSegPt = new POINT2(pLinePoints[j]);
EndSegPt = new POINT2(pLinePoints[j + 1]);
segQty = countsupport.GetSquallSegQty(StartSegPt, EndSegPt, quantity, length);
if (segQty > 0)
{
pSquallSegPts = new POINT2[segQty];
lineutility.InitializePOINT2Array(pSquallSegPts);
}
else
{
continue;
}
lineutility.GetSquallSegment(StartSegPt, EndSegPt, pSquallSegPts, sign, amplitude, quantity, length);
for (k = 0; k < segQty; k++)
{
pSquallPts[counter].x = pSquallSegPts[k].x;
pSquallPts[counter].y = pSquallSegPts[k].y;
if (k == 0)
{
pSquallPts[counter] = new POINT2(pLinePoints[j]);
}
if (k == segQty - 1)
{
pSquallPts[counter] = new POINT2(pLinePoints[j + 1]);
}
pSquallPts[counter].style = 0;
counter++;
}
}
//load the squall points into the linepoints array
for (j = 0; j < counter; j++) {
if (j < totalQty)
{
pLinePoints[j].x = pSquallPts[j].x;
pLinePoints[j].y = pSquallPts[j].y;
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
}
if (j == counter - 1)
{
pLinePoints[j] = new POINT2(savePoint2);
}
pLinePoints[j].style = pSquallPts[j].style;
}
}
if (counter == 0)
{
for (j = 0; j < pLinePoints.length; j++)
{
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
} else
{
pLinePoints[j] = new POINT2(savePoint2);
}
}
counter = pLinePoints.length;
}
//clean up
pSquallPts = null;
pSquallSegPts = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSquallDouble",
new RendererException("GetSquallDouble", exc));
}
return counter;
}
protected static int GetSevereSquall(POINT2[] pLinePoints,
int numPoints) {
int l = 0;
try
{
int quantity = 5, length = 30, j = 0, k = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints) + 2 * numPoints;
POINT2[] squallPts = new POINT2[totalQty];
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), pt2 = new POINT2(),
pt3 = new POINT2(), pt4 = new POINT2(), pt5 = new POINT2(), pt6 = new POINT2(),
pt7 = new POINT2(),pt8 = new POINT2();
int segQty = 0;
double dist = 0;
//end declarations
lineutility.InitializePOINT2Array(squallPts);
//each segment looks like this: --- V
for (j = 0; j < numPoints - 1; j++)
{
dist = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
segQty = (int) (dist / 30);
for (k = 0; k < segQty; k++) {
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30);
pt1 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 20);
//pt0.style = 5;
pt5 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 25);
pt6 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 30);
//pt6.style=5;
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 5, 0); //extend above line
pt3 = lineutility.ExtendDirectedLine(pt0, pt5, pt5, 3, 5, 0); //extend below line
pt4 = lineutility.ExtendDirectedLine(pt0, pt6, pt6, 2, 5, 5); //extend above line
pt4.style=5;
squallPts[l++] = new POINT2(pt2);
squallPts[l++] = new POINT2(pt3);
squallPts[l++] = new POINT2(pt4);
pt7 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 5);
pt8 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 10);
pt8.style=5;
squallPts[l++] = new POINT2(pt7);
squallPts[l++] = new POINT2(pt8);
}
//segment remainder
squallPts[l++] = new POINT2(pLinePoints[j + 1]);
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j+1], pLinePoints[j], 5);
pt0.style=5;
squallPts[l++]=new POINT2(pt0);
}
for (j = 0; j < l; j++)
{
if (j < totalQty)
{
pLinePoints[j] = new POINT2(squallPts[j]);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSevereSquall",
new RendererException("GetSevereSquall", exc));
}
return l;
}
private static int GetConvergancePointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = vblCounter;
try {
int j = 0, k = 0;
//int counter=vblCounter;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
pLinePoints[vblCounter - 1].style = 5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 10);
//we don't want too small a remainder
if (d - numJags * 10 < 5)
{
numJags -= 1;
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
//the first spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 10 + 5, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 2, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
//the 2nd spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, (k + 1) * 10, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 3, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetConvergancePointsDouble",
new RendererException("GetConvergancePointsDouble", exc));
}
return counter;
}
private static int GetITDPointsDouble(POINT2[] pLinePoints, int vblCounter)
{
int counter = 0;
try {
int j = 0, k = 0;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0, lineStyle = 19;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
//pLinePoints[vblCounter-1].style=5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 15);
//we don't want too small a remainder
if (d - numJags * 10 < 5) {
numJags -= 1;
}
if(numJags==0)
{
pt0.style=19;
pLinePoints[counter++] = new POINT2(pt0);
pt1.style=5;
pLinePoints[counter++] = new POINT2(pt1);
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 15 + 5, lineStyle);
pLinePoints[counter++] = new POINT2(tempPt);
if (k < numJags - 1) {
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 10, 5);
} else {
tempPt = new POINT2(tempPts[j + 1]);
tempPt.style = 5;
}
pLinePoints[counter++] = new POINT2(tempPt);
if (lineStyle == 19) {
lineStyle = 25;
} else {
lineStyle = 19;
}
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetITDPointsDouble",
new RendererException("GetITDPointsDouble", exc));
}
return counter;
}
private static int GetXPoints(POINT2[] pOriginalLinePoints, POINT2[] XPoints, int vblCounter)
{
int xCounter=0;
try
{
int j=0,k=0;
double d=0;
POINT2 pt0,pt1,pt2,pt3=new POINT2(),pt4=new POINT2(),pt5=new POINT2(),pt6=new POINT2();
int numThisSegment=0;
double distInterval=0;
for(j=0;j<vblCounter-1;j++)
{
d=lineutility.CalcDistanceDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1]);
numThisSegment=(int)( (d-20d)/20d);
//added 4-19-12
distInterval=d/numThisSegment;
for(k=0;k<numThisSegment;k++)
{
//pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1], 10+20*k);
pt0=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j],pOriginalLinePoints[j+1], distInterval/2+distInterval*k);
pt1=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], 5);
pt2=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], -5);
pt3=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 2, 5);
pt4=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 3, 5);
pt4.style=5;
pt5=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 2, 5);
pt6=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 3, 5);
pt6.style=5;
XPoints[xCounter++]=new POINT2(pt3);
XPoints[xCounter++]=new POINT2(pt6);
XPoints[xCounter++]=new POINT2(pt5);
XPoints[xCounter++]=new POINT2(pt4);
}
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return xCounter;
}
/**
* returns a 37 point ellipse
* @param ptCenter
* @param ptWidth
* @param ptHeight
* @return
*/
private static POINT2[] getEllipsePoints(POINT2 ptCenter, POINT2 ptWidth, POINT2 ptHeight)
{
POINT2[]pEllipsePoints=null;
try
{
pEllipsePoints=new POINT2[37];
int l=0;
double dFactor=0;
double a=lineutility.CalcDistanceDouble(ptCenter, ptWidth);
double b=lineutility.CalcDistanceDouble(ptCenter, ptHeight);
lineutility.InitializePOINT2Array(pEllipsePoints);
for (l = 1; l < 37; l++)
{
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints[l - 1].style = 0;
}
pEllipsePoints[36]=new POINT2(pEllipsePoints[0]);
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return pEllipsePoints;
}
private static int GetLVOPoints(POINT2[] pOriginalLinePoints, POINT2[] pLinePoints, int vblCounter)
{
int lEllipseCounter = 0;
try {
//double dAngle = 0, d = 0, a = 13, b = 6, dFactor = 0;
double dAngle = 0, d = 0, a = 4, b = 8, dFactor = 0;
int lHowManyThisSegment = 0, j = 0, k = 0, l = 0, t = 0;
POINT2 ptCenter = new POINT2();
POINT2[] pEllipsePoints2 = new POINT2[37];
double distInterval=0;
//end declarations
for (j = 0; j < vblCounter - 1; j++)
{
lineutility.InitializePOINT2Array(pEllipsePoints2);
d = lineutility.CalcDistanceDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
//lHowManyThisSegment = (int) ((d - 10) / 10);
lHowManyThisSegment = (int) ((d - 20) / 20);
//added 4-19-12
distInterval=d/lHowManyThisSegment;
dAngle = lineutility.CalcSegmentAngleDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
dAngle = dAngle + Math.PI / 2;
for (k = 0; k < lHowManyThisSegment; k++)
{
//t = k;
//ptCenter=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*20+20);
ptCenter=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*distInterval);
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}//end k loop
//extra ellipse on the final segment at the end of the line
if(j==vblCounter-2)
{
ptCenter=pOriginalLinePoints[j+1];
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetLVOPointsDouble",
new RendererException("GetLVOPointsDouble", exc));
}
return lEllipseCounter;
}
private static int GetIcingPointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = 0;
try {
int j = 0;
POINT2[] origPoints = new POINT2[vblCounter];
int nDirection = -1;
int k = 0, numSegments = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), midPt = new POINT2(), pt2 = new POINT2();
//save the original points
for (j = 0; j < vblCounter; j++) {
origPoints[j] = new POINT2(pLinePoints[j]);
}
double distInterval=0;
for (j = 0; j < vblCounter - 1; j++) {
//how many segments for this line segment?
numSegments = (int) lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1]);
numSegments /= 15; //segments are 15 pixels long
//4-19-12
distInterval=lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1])/numSegments;
//get the direction and the quadrant
nDirection = GetInsideOutsideDouble2(origPoints[j], origPoints[j + 1], origPoints, vblCounter, j, TacticalLines.ICING);
for (k = 0; k < numSegments; k++) {
//get the parallel segment
if (k == 0) {
pt0 = new POINT2(origPoints[j]);
} else {
//pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15, 0);
pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval, 0);
}
//pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 10, 5);
pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 10, 5);
//midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 5, 0);
midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 5, 0);
//get the perpendicular segment
pt2 = lineutility.ExtendDirectedLine(origPoints[j], origPoints[j + 1], midPt, nDirection, 5, 5);
pLinePoints[counter] = new POINT2(pt0);
pLinePoints[counter + 1] = new POINT2(pt1);
pLinePoints[counter + 2] = new POINT2(midPt);
pLinePoints[counter + 3] = new POINT2(pt2);
counter += 4;
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIcingPointsDouble",
new RendererException("GetIcingPointsDouble", exc));
}
return counter;
}
protected static int GetAnchorageDouble(POINT2[] vbPoints2, int numPts)
{
int lFlotCounter = 0;
try
{
//declarations
int j = 0, k = 0, l = 0;
int x1 = 0, y1 = 0;
int numSegPts = -1;
int lFlotCount = 0;
int lNumSegs = 0;
double dDistance = 0;
int[] vbPoints = null;
int[] points = null;
int[] points2 = null;
POINT2 pt = new POINT2();
POINT2 pt1 = new POINT2(), pt2 = new POINT2();
//end declarations
lFlotCount = flot.GetAnchorageCountDouble(vbPoints2, numPts);
vbPoints = new int[2 * numPts];
for (j = 0; j < numPts; j++)
{
vbPoints[k] = (int) vbPoints2[j].x;
k++;
vbPoints[k] = (int) vbPoints2[j].y;
k++;
}
k = 0;
ref<int[]> bFlip = new ref();
bFlip.value = new int[1];
ref<int[]> lDirection = new ref();
lDirection.value = new int[1];
ref<int[]> lLastDirection = new ref();
lLastDirection.value = new int[1];
for (l = 0; l < numPts - 1; l++)
{
//pt1=new POINT2();
//pt2=new POINT2();
pt1.x = vbPoints[2 * l];
pt1.y = vbPoints[2 * l + 1];
pt2.x = vbPoints[2 * l + 2];
pt2.y = vbPoints[2 * l + 3];
//for all segments after the first segment we shorten
//the line by 20 so the flots will not abut
if (l > 0)
{
pt1 = lineutility.ExtendAlongLineDouble(pt1, pt2, 20);
}
dDistance = lineutility.CalcDistanceDouble(pt1, pt2);
lNumSegs = (int) (dDistance / 20);
//ref<int[]> bFlip = new ref();
//bFlip.value = new int[1];
//ref<int[]> lDirection = new ref();
//lDirection.value = new int[1];
//ref<int[]> lLastDirection = new ref();
//lLastDirection.value = new int[1];
if (lNumSegs > 0) {
points2 = new int[lNumSegs * 32];
numSegPts = flot.GetAnchorageFlotSegment(vbPoints, (int) pt1.x, (int) pt1.y, (int) pt2.x, (int) pt2.y, l, points2, bFlip, lDirection, lLastDirection);
points = new int[numSegPts];
for (j = 0; j < numSegPts; j++)
{
points[j] = points2[j];
}
for (j = 0; j < numSegPts / 3; j++) //only using half the flots
{
x1 = points[k];
y1 = points[k + 1];
//z = points[k + 2];
k += 3;
if (j % 10 == 0) {
pt.x = x1;
pt.y = y1;
pt.style = 5;
}
else if ((j + 1) % 10 == 0)
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter++].y = y1;
vbPoints2[lFlotCounter++] = new POINT2(pt);
continue;
}
else
{
break;
}
}
if (lFlotCounter < lFlotCount) {
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter].y = y1;
lFlotCounter++;
} else {
break;
}
}
k = 0;
points = null;
} else
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = vbPoints[2 * l];
vbPoints2[lFlotCounter].y = vbPoints[2 * l + 1];
lFlotCounter++;
}
}
}
for (j = lFlotCounter - 1; j < lFlotCount; j++)
{
vbPoints2[j].style = 5;
}
//clean up
vbPoints = null;
points = null;
points2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetAnchorageDouble",
new RendererException("GetAnchorageDouble", exc));
}
return lFlotCounter;
}
private static int GetPipePoints(POINT2[] pLinePoints,
int vblCounter)
{
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2[] xPoints = new POINT2[pLinePoints.length];
int xCounter = 0;
int j=0,k=0;
for (j = 0; j < vblCounter; j++)
{
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0;
double d = 0;
lineutility.InitializePOINT2Array(xPoints);
for (j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 20);
for (k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt1.style = 5;
pt2 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt2.style = 20; //for filled circle
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
xPoints[xCounter++] = new POINT2(pt2);
}
if (numSegs == 0)
{
pLinePoints[counter] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++].style=0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style=5;
}
else
{
pLinePoints[counter] = new POINT2(pLinePoints[counter - 1]);
pLinePoints[counter++].style = 0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style = 5;
}
}
//load the circle points
for (k = 0; k < xCounter; k++)
{
pLinePoints[counter++] = new POINT2(xPoints[k]);
}
//add one more circle
pLinePoints[counter++] = new POINT2(pLinePoints[counter]);
pOriginalPoints = null;
xPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetPipePoints",
new RendererException("GetPipePoints", exc));
}
return counter;
}
private static int GetReefPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
POINT2 pt4 = new POINT2();
//POINT2 pt5=new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0,direction=0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++) {
if(pOriginalPoints[j].x<pOriginalPoints[j+1].x)
direction=2;
else
direction=3;
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 40);
for (int k = 0; k < numSegs; k++) {
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * k);
pt1 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 10);
pt1 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt1, direction, 15);//was 2
pt2 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 20);
pt2 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 5);//was 2
pt3 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 30);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt3, direction, 20);//was 2
pt4 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * (k + 1));
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt4);
}
if (numSegs == 0) {
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetReefPoints",
new RendererException("GetReefPoints", exc));
}
return counter;
}
private static int GetRestrictedAreaPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int direction=0;
int numSegs = 0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 15);
if(pOriginalPoints[j].x < pOriginalPoints[j+1].x)
direction=3;
else
direction=2;
for (int k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k + 10);
pt1.style = 5;
pt2 = lineutility.MidPointDouble(pt0, pt1, 0);
//pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 10);
pt3.style = 5;
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
}
if (numSegs == 0)
{
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter - 1].style = 0;
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRestrictedAreaPoints",
new RendererException("GetRestrictedAreaPoints", exc));
}
return counter;
}
//there should be two linetypes depending on scale
private static int getOverheadWire(POINT2[]pLinePoints, int vblCounter)
{
int counter=0;
try
{
int j=0;
POINT2 pt=null,pt2=null;
double x=0,y=0;
ArrayList<POINT2>pts=new ArrayList();
for(j=0;j<vblCounter;j++)
{
pt=new POINT2(pLinePoints[j]);
x=pt.x;
y=pt.y;
//tower
pt2=new POINT2(pt);
pt2.y -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=5;
pt2.style=5;
pts.add(pt2);
//low cross piece
pt2=new POINT2(pt);
pt2.x -=2;
pt2.y-=10;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=2;
pt2.y-=10;
pt2.style=5;
pts.add(pt2);
//high cross piece
pt2=new POINT2(pt);
pt2.x -=7;
pt2.y-=17;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=7;
pt2.y-=17;
pt2.style=5;
pts.add(pt2);
//angle piece
pt2=new POINT2(pt);
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x+=8;
pt2.y-=12;
pt2.style=5;
pts.add(pt2);
}
//connect the towers
for(j=0;j<vblCounter-1;j++)
{
pt=new POINT2(pLinePoints[j]);
pt2=new POINT2(pLinePoints[j+1]);
if(pt.x<pt2.x)
{
pt.x+=5;
pt.y -=10;
pt2.x-=5;
pt2.y-=10;
pt2.style=5;
}
else
{
pt.x-=5;
pt.y -=10;
pt2.x+=5;
pt2.y-=10;
pt2.style=5;
}
pts.add(pt);
pts.add(pt2);
}
for(j=0;j<pts.size();j++)
{
pLinePoints[j]=pts.get(j);
counter++;
}
for(j=counter;j<pLinePoints.length;j++)
pLinePoints[j]=new POINT2(pLinePoints[counter-1]);
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetOverheadWire",
new RendererException("GetOverheadWire", exc));
}
return counter;
}
//private static int linetype=-1; //use for BLOCK, CONTIAN
/**
* Calculates the points for the non-channel symbols.
* The points will be stored in the original POINT2 array in pixels, pLinePoints.
* The client points occupy the first vblSaveCounter positions in pLinePoints
* and will be overwritten by the symbol points.
*
* @param lineType the line type
* @param pLinePoints - OUT - an array of POINT2
* @param vblCounter the number of points allocated
* @param vblSaveCounter the number of client points
*
* @return the symbol point count
*/
private static ArrayList<POINT2> GetLineArray2Double(int lineType,
POINT2[] pLinePoints,
int vblCounter,
int vblSaveCounter,
ArrayList<Shape2>shapes,
Rectangle2D clipBounds,
int rev)
{
ArrayList<POINT2> points=new ArrayList();
try
{
String client=CELineArray.getClient();
if(pLinePoints==null || pLinePoints.length<2)
return null;
//declarations
int[] segments=null;
double dMRR=0;
int n=0,bolVertical=0;
double dExtendLength=0;
double dWidth=0;
int nQuadrant=0;
int lLinestyle=0,pointCounter=0;
ref<double[]> offsetX=new ref(),offsetY=new ref();
double b=0,b1=0,dRadius=0,d1=0,d=0,d2=0;
ref<double[]>m=new ref();
int direction=0;
int nCounter=0;
int j=0,k=0,middleSegment=-1;
double dMBR=lineutility.MBRDistance(pLinePoints,vblSaveCounter);
POINT2 pt0=new POINT2(pLinePoints[0]), //calculation points for autoshapes
pt1=new POINT2(pLinePoints[1]),
pt2=new POINT2(pLinePoints[1]),
pt3=new POINT2(pLinePoints[0]),
pt4=new POINT2(pLinePoints[0]),
pt5=new POINT2(pLinePoints[0]),
pt6=new POINT2(pLinePoints[0]),
pt7=new POINT2(pLinePoints[0]),
pt8=new POINT2(pLinePoints[0]),
ptYIntercept=new POINT2(pLinePoints[0]),
ptYIntercept1=new POINT2(pLinePoints[0]),
ptCenter=new POINT2(pLinePoints[0]);
POINT2[] pArrowPoints=new POINT2[3],
arcPts=new POINT2[26],
circlePoints=new POINT2[100],
pts=null,pts2=null;
POINT2 midpt=new POINT2(pLinePoints[0]),midpt1=new POINT2(pLinePoints[0]);
POINT2[]pOriginalLinePoints=null;
POINT2[] pUpperLinePoints = null;
POINT2[] pLowerLinePoints = null;
POINT2[] pUpperLowerLinePoints = null;
POINT2 calcPoint0=new POINT2(),
calcPoint1=new POINT2(),
calcPoint2=new POINT2(),
calcPoint3=new POINT2(),
calcPoint4=new POINT2();
POINT2 ptTemp=new POINT2(pLinePoints[0]);
int acCounter=0;
POINT2[] acPoints=new POINT2[6];
int lFlotCount=0;
//end declarations
//Bearing line and others only have 2 points
if(vblCounter>2)
pt2=new POINT2(pLinePoints[2]);
//strcpy(CurrentFunction,"GetLineArray2");
pt0.style=0;
pt1.style=0;
pt2.style=0;
//set jaggylength in clsDISMSupport before the points get bounded
//clsDISMSupport.JaggyLength = Math.Sqrt ( (pLinePoints[1].x-pLinePoints[0].x) * (pLinePoints[1].x-pLinePoints[0].x) +
// (pLinePoints[1].y-pLinePoints[0].y) * (pLinePoints[1].y-pLinePoints[0].y) );
//double saveMaxPixels=CELineArrayGlobals.MaxPixels2;
//double saveMaxPixels=2000;
ArrayList xPoints=null;
pOriginalLinePoints = new POINT2[vblSaveCounter];
for(j = 0;j<vblSaveCounter;j++)
{
pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
}
//resize the array and get the line array
//for the specified non-channel line type
switch(lineType)
{
case TacticalLines.BBS_AREA:
lineutility.getExteriorPoints(pLinePoints, vblSaveCounter, lineType, false);
acCounter=vblSaveCounter;
break;
case TacticalLines.BS_CROSS:
pt0=new POINT2(pLinePoints[0]);
pLinePoints[0]=new POINT2(pt0);
pLinePoints[0].x-=10;
pLinePoints[1]=new POINT2(pt0);
pLinePoints[1].x+=10;
pLinePoints[1].style=10;
pLinePoints[2]=new POINT2(pt0);
pLinePoints[2].y+=10;
pLinePoints[3]=new POINT2(pt0);
pLinePoints[3].y-=10;
acCounter=4;
break;
case TacticalLines.BS_RECTANGLE:
pt0=new POINT2(pLinePoints[0]);//the center of the ellipse
pt2=new POINT2(pLinePoints[1]);//the width of the ellipse
pt1=new POINT2(pt0);
pt1.y=pt2.y;
pt3=new POINT2(pt2);
pt3.y=pt0.y;
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BBS_RECTANGLE:
double xmax=pLinePoints[0].x,xmin=pLinePoints[1].x,ymax=pLinePoints[0].y,ymin=pLinePoints[1].y;
double buffer=pLinePoints[0].style;
if(pLinePoints[0].x<pLinePoints[1].x)
{
xmax=pLinePoints[1].x;
xmin=pLinePoints[0].x;
}
if(pLinePoints[0].y<pLinePoints[1].y)
{
ymax=pLinePoints[1].y;
ymin=pLinePoints[0].y;
}
pt0=new POINT2(xmin-buffer,ymin-buffer);
pt2=new POINT2(xmax+buffer,ymax+buffer);
pt1=new POINT2(pt0);
pt1.y=pt2.y;
pt3=new POINT2(pt2);
pt3.y=pt0.y;
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BS_ELLIPSE:
pt0=pLinePoints[0];//the center of the ellipse
pt1=pLinePoints[1];//the width of the ellipse
pt2=pLinePoints[2];//the height of the ellipse
pLinePoints=getEllipsePoints(pt0,pt1,pt2);
acCounter=37;
break;
case TacticalLines.OVERHEAD_WIRE:
acCounter=getOverheadWire(pLinePoints,vblSaveCounter);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for(j=0;j<vblSaveCounter;j++)
{
//pLinePoints[j]=new POINT2(pOriginalLinePoints[j]);
pLinePoints[j].style=1;
}
//pLinePoints[vblSaveCounter-1].style=5;
for(j=vblSaveCounter;j<2*vblSaveCounter;j++)
{
pLinePoints[j]=new POINT2(pOriginalLinePoints[j-vblSaveCounter]);
pLinePoints[j].style=20;
}
//pLinePoints[2*vblSaveCounter-1].style=5;
acCounter=pLinePoints.length;
break;
case TacticalLines.BOUNDARY:
acCounter=pLinePoints.length;
break;
case TacticalLines.REEF:
vblCounter = GetReefPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ICE_DRIFT:
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-5], pLinePoints[vblCounter - 4], 10, 10,pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RESTRICTED_AREA:
vblCounter=GetRestrictedAreaPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TRAINING_AREA:
for (j = 0; j < vblSaveCounter; j++)
{
pLinePoints[j].style = 1;
}
pLinePoints[vblSaveCounter - 1].style = 5;
pt0 = lineutility.CalcCenterPointDouble(pLinePoints, vblSaveCounter - 1);
lineutility.CalcCircleDouble(pt0, 20, 26, arcPts, 0);
for (j = vblSaveCounter; j < vblSaveCounter + 26; j++)
{
pLinePoints[j] = new POINT2(arcPts[j - vblSaveCounter]);
}
pLinePoints[j-1].style = 5;
//! inside the circle
pt1 = new POINT2(pt0);
pt1.y -= 12;
pt1.style = 0;
pt2 = new POINT2(pt1);
pt2.y += 12;
pt2.style = 5;
pt3 = new POINT2(pt2);
pt3.y += 3;
pt3.style = 0;
pt4 = new POINT2(pt3);
pt4.y += 3;
pLinePoints[j++] = new POINT2(pt1);
pLinePoints[j++] = new POINT2(pt2);
pLinePoints[j++] = new POINT2(pt3);
pt4.style = 5;
pLinePoints[j++] = new POINT2(pt4);
vblCounter = j;
acCounter=vblCounter;
break;
case TacticalLines.PIPE:
vblCounter=GetPipePoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ANCHORAGE_AREA:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 1: //extend left
case 2: //extend below
break;
case 0: //extend right
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 1: //extend left
case 3: //extend above
break;
case 0: //extend right
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 1: //extend left
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 3: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 1: //extend left
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 2: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = GetAnchorageDouble(pLinePoints, vblSaveCounter);
acCounter = lFlotCount;
break;
case TacticalLines.ANCHORAGE_LINE:
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
acCounter=GetAnchorageDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.LRO:
int xCount=countsupport.GetXPointsCount(pOriginalLinePoints, vblSaveCounter);
POINT2 []xPoints2=new POINT2[xCount];
int lvoCount=countsupport.GetLVOCount(pOriginalLinePoints, vblSaveCounter);
POINT2 []lvoPoints=new POINT2[lvoCount];
xCount=GetXPoints(pOriginalLinePoints,xPoints2,vblSaveCounter);
lvoCount=GetLVOPoints(pOriginalLinePoints,lvoPoints,vblSaveCounter);
for(k=0;k<xCount;k++)
{
pLinePoints[k]=new POINT2(xPoints2[k]);
}
pLinePoints[xCount-1].style=5;
for(k=0;k<lvoCount;k++)
{
pLinePoints[xCount+k]=new POINT2(lvoPoints[k]);
}
acCounter=xCount+lvoCount;
break;
case TacticalLines.UNDERCAST:
if(pLinePoints[0].x<pLinePoints[1].x)
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
lFlotCount=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.LVO:
acCounter=GetLVOPoints(pOriginalLinePoints,pLinePoints,vblSaveCounter);
break;
case TacticalLines.ICING:
vblCounter=GetIcingPointsDouble(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.MVFR:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 0: //extend left
case 3: //extend below
break;
case 1: //extend right
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 0: //extend left
case 2: //extend above
break;
case 1: //extend right
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 0: //extend left
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 2: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 0: //extend left
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 3: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = flot.GetFlotDouble(pLinePoints, vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.ITD:
acCounter=GetITDPointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.CONVERGANCE:
acCounter=GetConvergancePointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.RIDGE:
vblCounter=GetRidgePointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TROUGH:
case TacticalLines.INSTABILITY:
case TacticalLines.SHEAR:
//case TacticalLines.SQUALL:
//CELineArrayGlobals.MaxPixels2=saveMaxPixels+100;
vblCounter=GetSquallDouble(pLinePoints,10,6,30,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.SQUALL:
//vblCounter = GetSquallDouble(pLinePoints, 10, 6, 30, vblSaveCounter);
vblCounter=GetSevereSquall(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.USF:
case TacticalLines.SFG:
case TacticalLines.SFY:
vblCounter=flot.GetSFPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.SF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.OFY:
vblCounter=flot.GetOFYPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.OCCLUDED:
case TacticalLines.UOF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.WF:
case TacticalLines.UWF:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter-vblSaveCounter+j]=pOriginalLinePoints[j];
acCounter=lFlotCount+vblSaveCounter;
break;
case TacticalLines.WFG:
case TacticalLines.WFY:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
acCounter=lFlotCount;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.CF:
case TacticalLines.UCF:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
pLinePoints[vblCounter-1].style=5;
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
pLinePoints[vblCounter-1].style=5;
acCounter=vblCounter;
break;
case TacticalLines.IL:
case TacticalLines.PLANNED:
case TacticalLines.ESR1:
case TacticalLines.ESR2:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
d=lineutility.CalcDistanceDouble(pLinePoints[0], pt0);
pt4 = lineutility.ExtendLineDouble(pt0, pLinePoints[0], d);
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt4, pt2, pt3);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
pLinePoints[2] = new POINT2(pt3);
pLinePoints[3] = new POINT2(pt2);
switch (lineType) {
case TacticalLines.IL:
case TacticalLines.ESR2:
pLinePoints[0].style = 0;
pLinePoints[1].style = 5;
pLinePoints[2].style = 0;
break;
case TacticalLines.PLANNED:
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2].style = 1;
break;
case TacticalLines.ESR1:
pLinePoints[1].style = 5;
if (pt0.x <= pt1.x) {
if (pLinePoints[1].y <= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
} else {
if (pLinePoints[1].y >= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
}
break;
default:
break;
}
acCounter=4;
break;
case TacticalLines.FORDSITE:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2] = new POINT2(pt0);
pLinePoints[2].style = 1;
pLinePoints[3] = new POINT2(pt1);
pLinePoints[3].style = 5;
acCounter=4;
break;
case TacticalLines.ROADBLK:
pts = new POINT2[4];
for (j = 0; j < 4; j++) {
pts[j] = new POINT2(pLinePoints[j]);
}
dRadius = lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
d = lineutility.CalcDistanceToLineDouble(pLinePoints[0], pLinePoints[1], pLinePoints[2]);
//first two lines
pLinePoints[0] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], d, 0);
pLinePoints[1] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], d, 5);
pLinePoints[2] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], -d, 0);
pLinePoints[3] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], -d, 5);
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[0], midpt, d);
//the next line
pLinePoints[4] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[5] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[5].style = 5;
//recompute the original midpt because it was moved
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[1], midpt, d);
//the last line
pLinePoints[6] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[7] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[7].style = 5;
acCounter=8;
break;
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
acCounter=vblCounter;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PNO:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DMAF:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
pLinePoints[vblCounter-1].style=5;
FillPoints(pLinePoints,vblCounter,points);
xPoints=lineutility.LineOfXPoints(pOriginalLinePoints);
for(j=0;j<xPoints.size();j++)
{
points.add((POINT2)xPoints.get(j));
}
acCounter=points.size();
break;
case TacticalLines.FOXHOLE:
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical==0) //line is vertical
{
if (pt0.y > pt1.y) {
direction = 0;
} else {
direction = 1;
}
}
if (bolVertical != 0 && m.value[0] <= 1) {
if (pt0.x < pt1.x) {
direction = 3;
} else {
direction = 2;
}
}
if (bolVertical != 0 && m.value[0] > 1) {
if (pt0.x < pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x < pt1.x && pt0.y < pt1.y) {
direction = 0;
}
if (pt0.x > pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x > pt1.x && pt0.y < pt1.y) {
direction = 0;
}
}
//M. Deutch 8-19-04
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<250)
dMBR=250;
if(dMBR>500)
dMBR=500;
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, direction, dMBR / 20);
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, direction, dMBR / 20);
acCounter=4;
break;
case TacticalLines.ISOLATE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.OCCUPY:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=32;
break;
case TacticalLines.RETAIN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=75;
break;
case TacticalLines.SECURE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.TURN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.ENCIRCLE:
//pOriginalLinePoints=null;
//pOriginalLinePoints = new POINT2[vblSaveCounter+2];
//for(j = 0;j<vblSaveCounter;j++)
// pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
//pOriginalLinePoints[vblSaveCounter] = new POINT2(pLinePoints[0]);
//pOriginalLinePoints[vblSaveCounter+1] = new POINT2(pLinePoints[1]);
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
//for(j=0;j<vblSaveCounter+2;j++)
// pLinePoints[pointCounter+j]=new POINT2(pOriginalLinePoints[j]);
//pointCounter += vblSaveCounter+1;
//acCounter=pointCounter;
break;
case TacticalLines.BELT1:
pUpperLinePoints=new POINT2[vblSaveCounter];
pLowerLinePoints=new POINT2[vblSaveCounter];
pUpperLowerLinePoints=new POINT2[2*vblCounter];
for(j=0;j<vblSaveCounter;j++)
pLowerLinePoints[j]=new POINT2(pLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLinePoints[j]=new POINT2(pLinePoints[j]);
pUpperLinePoints = Channels.CoordIL2Double(1,pUpperLinePoints,1,vblSaveCounter,lineType,30);
pLowerLinePoints = Channels.CoordIL2Double(1,pLowerLinePoints,0,vblSaveCounter,lineType,30);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j]=new POINT2(pUpperLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j+vblSaveCounter]=new POINT2(pLowerLinePoints[vblSaveCounter-j-1]);
pUpperLowerLinePoints[2*vblSaveCounter]=new POINT2(pUpperLowerLinePoints[0]);
vblCounter=GetZONEPointsDouble2(pUpperLowerLinePoints,lineType,2*vblSaveCounter+1);
for(j=0;j<vblCounter;j++)
pLinePoints[j]=new POINT2(pUpperLowerLinePoints[j]);
//pLinePoints[j]=pLinePoints[0];
//vblCounter++;
acCounter=vblCounter;
break;
case TacticalLines.BELT: //change 2
case TacticalLines.ZONE:
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.STRONG:
case TacticalLines.FORT:
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.ATWALL:
case TacticalLines.LINE: //7-9-07
acCounter = GetATWallPointsDouble2(pLinePoints, lineType, vblSaveCounter);
break;
// case TacticalLines.ATWALL3D:
// acCounter = GetATWallPointsDouble3D(pLinePoints, lineType, vblSaveCounter);
// break;
case TacticalLines.PLD:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.FEBA:
CoordFEBADouble(pLinePoints,vblCounter);
acCounter=pLinePoints.length;
break;
case TacticalLines.UAV:
case TacticalLines.MRR:
if(rev==RendererSettings.Symbology_2525Bch2_USAS_13_14)
{
dMRR=pOriginalLinePoints[0].style;
if (dMRR <= 0) {
dMRR = 1;//was 14
}
lineutility.GetSAAFRSegment(pLinePoints, lineType, dMRR,rev);
acCounter=6;
}
if(rev==RendererSettings.Symbology_2525C)
{
return GetLineArray2Double(TacticalLines.SAAFR,pLinePoints,vblCounter,vblSaveCounter,shapes,clipBounds,rev);
}
break;
case TacticalLines.MRR_USAS:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR: //added 5-4-07
case TacticalLines.SAAFR: //these have multiple segments
case TacticalLines.AC:
dMRR = dACP;
// if (dMRR <= 0) {
// dMRR = 14;
// }
lineutility.InitializePOINT2Array(acPoints);
lineutility.InitializePOINT2Array(arcPts);
acCounter = 0;
for (j = 0; j < vblSaveCounter;j++)
if(pOriginalLinePoints[j].style<=0)
pOriginalLinePoints[j].style=1; //was 14
//get the SAAFR segments
for (j = 0; j < vblSaveCounter - 1; j++) {
//diagnostic: use style member for dMBR
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRSegment(acPoints, lineType, dMBR,rev);//was dMRR
for (k = 0; k < 6; k++)
{
pLinePoints[acCounter] = new POINT2(acPoints[k]);
acCounter++;
}
}
//get the circles
int nextCircleSize=0,currentCircleSize=0;
for (j = 0; j < vblSaveCounter-1; j++)
{
currentCircleSize=pOriginalLinePoints[j].style;
nextCircleSize=pOriginalLinePoints[j+1].style;
//draw the circle at the segment front end
arcPts[0] = new POINT2(pOriginalLinePoints[j]);
//diagnostic: use style member for dMBR
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
//draw the circle at the segment back end
arcPts[0] = new POINT2(pOriginalLinePoints[j+1]);
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
}
//acPoints = null;
break;
case TacticalLines.MINED:
case TacticalLines.UXO:
acCounter=vblCounter;
break;
case TacticalLines.BEARING:
case TacticalLines.ACOUSTIC:
case TacticalLines.ELECTRO:
case TacticalLines.TORPEDO:
case TacticalLines.OPTICAL:
acCounter=vblCounter;
break;
case TacticalLines.MSDZ:
lineutility.InitializePOINT2Array(circlePoints);
pt3 = new POINT2(pLinePoints[3]);
dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[j] = new POINT2(circlePoints[j]);
}
pLinePoints[99].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt2);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[100 + j] = new POINT2(circlePoints[j]);
}
pLinePoints[199].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt3);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[200 + j] = new POINT2(circlePoints[j]);
}
acCounter=300;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.CONVOY:
d=lineutility.CalcDistanceDouble(pt0, pt1);
if(d<=30)
{
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
pt0 = lineutility.ExtendLine2Double(pt1, pt0, -30, 0);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 30);
lineutility.GetArrowHead4Double(pt0, pt2, 30, 30, pArrowPoints, 0);
d = lineutility.CalcDistanceDouble(pLinePoints[0], pArrowPoints[0]);
d1 = lineutility.CalcDistanceDouble(pLinePoints[3], pArrowPoints[0]);
pLinePoints[3].style = 5;
if (d < d1) {
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[4].style = 0;
pLinePoints[5] = new POINT2(pArrowPoints[0]);
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pArrowPoints[1]);
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pArrowPoints[2]);
pLinePoints[7].style = 0;
pLinePoints[8] = new POINT2(pLinePoints[3]);
} else {
pLinePoints[4] = pLinePoints[3];
pLinePoints[4].style = 0;
pLinePoints[5] = pArrowPoints[0];
pLinePoints[5].style = 0;
pLinePoints[6] = pArrowPoints[1];
pLinePoints[6].style = 0;
pLinePoints[7] = pArrowPoints[2];
pLinePoints[7].style = 0;
pLinePoints[8] = pLinePoints[0];
}
acCounter=9;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.HCONVOY:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
pt2.x = (pt0.x + pt1.x) / 2;
pt2.y = (pt0.y + pt1.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[5] = new POINT2(pt0);
pLinePoints[5].style = 0;
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 50);
lineutility.GetArrowHead4Double(pt2, pt0, 20, 20, pArrowPoints, 0);
// for (j = 0; j < 3; j++)
// {
// pLinePoints[j + 6] = new POINT2(pArrowPoints[j]);
// }
// pLinePoints[8].style = 0;
// pLinePoints[9] = new POINT2(pArrowPoints[0]);
pLinePoints[6]=new POINT2(pArrowPoints[1]);
pLinePoints[7]=new POINT2(pArrowPoints[0]);
pLinePoints[8]=new POINT2(pArrowPoints[2]);
pLinePoints[8].style = 0;
pLinePoints[9] = new POINT2(pArrowPoints[1]);
acCounter=10;
FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.ONEWAY:
case TacticalLines.ALT:
case TacticalLines.TWOWAY:
nCounter = (int) vblSaveCounter;
pLinePoints[vblSaveCounter - 1].style = 5;
for (j = 0; j < vblSaveCounter - 1; j++) {
d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if(d<20) //too short
continue;
pt0 = new POINT2(pLinePoints[j]);
pt1 = new POINT2(pLinePoints[j + 1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1],m);
d=lineutility.CalcDistanceDouble(pLinePoints[j],pLinePoints[j+1]);
pt2 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -3 * d / 4, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -1 * d / 4, 5);
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
d = 10;
if (dMBR / 20 < minLength) {
d = 5;
}
lineutility.GetArrowHead4Double(pt2, pt3, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
if (lineType == (long) TacticalLines.ALT) {
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
if (lineType == (long) TacticalLines.TWOWAY) {
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
}
acCounter=nCounter;
break;
case TacticalLines.CFL:
for(j=0;j<vblCounter;j++) //dashed lines
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKFNT: //extra three for arrow plus extra three for feint
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<20)//was 10
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], 21);//was 11
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], 20); //was 10
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
d = dMBR;
pt0=lineutility.ExtendLineDouble(pLinePoints[vblCounter-8], pLinePoints[vblCounter - 7], 20); //was 10
pt1 = new POINT2(pLinePoints[vblCounter - 8]);
pt2 = new POINT2(pLinePoints[vblCounter - 7]);
if (d / 10 > maxLength) {
d = 10 * maxLength;
}
if (d / 10 < minLength) {
d = 10 * minLength;
}
if(d<250)
d=250;
if(d>500)
d=250;
lineutility.GetArrowHead4Double(pt1, pt2, (int) d / 10, (int) d / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = pArrowPoints[k];
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) d / 10, (int) d / 10,
pArrowPoints,18);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = pArrowPoints[k];
}
acCounter=vblCounter;
break;
case TacticalLines.FORDIF:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2], pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
for (j = 0; j < vblCounter; j++) {
pLinePoints[j].style = 1;
}
//CommandSight section
//comment 2 lines for CS
pt0 = lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
pt1 = lineutility.MidPointDouble(pLinePoints[2], pLinePoints[3], 0);
//uncomment 3 line for CS
//pt0=new POINT2(pt2);
//d=lineutility.CalcDistanceDouble(pt4, pt2);
//pt1=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], d);
//end section
// pts = new POINT2[2];
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// pointCounter = lineutility.BoundPointsCount(pts, 2);
// segments = new int[pointCounter];
// pts = new POINT2[pointCounter];
// lineutility.InitializePOINT2Array(pts);
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// lineutility.BoundPoints(pts, 2, segments);
// for (j = 0; j < pointCounter - 1; j++) {
// if (segments[j] == 1) {
// pt0 = new POINT2(pts[j]);
// pt1 = new POINT2(pts[j + 1]);
// break;
// }
// }
// for (j = 3; j < vblCounter; j++) {
// pLinePoints[j] = new POINT2(pLinePoints[3]);
// pLinePoints[j].style = 5;
// }
// pLinePoints[1].style = 5;
//
//added section 10-27-20
POINT2[]savepoints=null;
Boolean drawJaggies=true;
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints=lineutility.BoundOneSegment(pt0, pt1, ul, lr);
if(savepoints != null && savepoints.length>1)
{
pt0=savepoints[0];
pt1=savepoints[1];
}
midpt=lineutility.MidPointDouble(pt0, pt1, 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
}
else
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
}
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
//end section
}
else
{
midpt=lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
else
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
}
//end section
//calculate start, end points for upper and lower lines
//across the middle
pt2 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, -10, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, -10, 0);
pt4 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, 10, 0);
pt5 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, 10, 0);
dWidth = lineutility.CalcDistanceDouble(pt0, pt1);
pointCounter = 4;
n = 1;
pLinePoints[pointCounter] = new POINT2(pt0);
pLinePoints[pointCounter].style = 0;
pointCounter++;
//while (dExtendLength < dWidth - 20)
if(drawJaggies)
while (dExtendLength < dWidth - 10)
{
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt2, pt3, dExtendLength - dWidth, 0);
pointCounter++;
n++;
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt4, pt5, dExtendLength - dWidth, 0);
pointCounter++;
n++;
}
pLinePoints[pointCounter] = new POINT2(pt1);
pLinePoints[pointCounter].style = 5;
pointCounter++;
acCounter=pointCounter;
break;
case TacticalLines.ATDITCH:
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
break;
case (int)TacticalLines.ATDITCHC: //extra Points were calculated by a function
pLinePoints[0].style=9;
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
pLinePoints[vblCounter-1].style=10;
break;
case TacticalLines.ATDITCHM:
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pLinePoints[0].style = 9;
acCounter = lineutility.GetDitchSpikeDouble(
pLinePoints,
vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style = 20;
break;
case TacticalLines.DIRATKGND:
//reverse the points
//lineutility.ReversePointsDouble2(
//pLinePoints,
//vblSaveCounter);
//was 20
if (dMBR / 30 > maxLength) {
dMBR = 30 * maxLength;
}
if (dMBR / 30 < minLength) {
dMBR = 30 * minLength;
}
//if(dMBR<250)
// dMBR = 250;
if(dMBR<500)
dMBR = 500;
if(dMBR>750)
dMBR = 500;
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<dMBR/40)
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], dMBR/40+1);
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1],dMBR/40);
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pt0 = new POINT2(pLinePoints[vblCounter - 12]);
pt1 = new POINT2(pLinePoints[vblCounter - 11]);
pt2 = lineutility.ExtendLineDouble(pt0, pt1, dMBR / 40);
lineutility.GetArrowHead4Double(pt0, pt1, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 10 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pt0, pt2, (int) (dMBR / 13.33), (int) (dMBR / 13.33),
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 7 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[vblCounter - 10]);
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 7]);
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 5]);
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.MFLANE:
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RAFT: //extra eight Points for hash marks either end
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>200)
dMBR=200;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKAIR:
//added section for click-drag mode
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
for(k=vblSaveCounter-1;k>0;k--)
{
d += lineutility.CalcDistanceDouble(pLinePoints[k],pLinePoints[k-1]);
if(d>60)
break;
}
if(d>60)
{
middleSegment=k;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
else
{
if(vblSaveCounter<=3)
middleSegment=1;
else
middleSegment=2;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
pt0 = new POINT2(pLinePoints[0]);
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<150)
dMBR=150;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pLinePoints[vblCounter - 10], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 9 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 6].x = (pLinePoints[vblCounter - 11].x + pLinePoints[vblCounter - 10].x) / 2;
pLinePoints[vblCounter - 6].y = (pLinePoints[vblCounter - 11].y + pLinePoints[vblCounter - 10].y) / 2;
pt0 = new POINT2(pLinePoints[vblCounter - 6]);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt3, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 6 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 10], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt2, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
//this section was added to remove fill from the bow tie feature
ArrayList<POINT2> airPts=new ArrayList();
pLinePoints[middleSegment-1].style=5;
//pLinePoints[middleSegment].style=14;
if(vblSaveCounter==2)
pLinePoints[1].style=5;
for(j=0;j<vblCounter;j++)
airPts.add(new POINT2(pLinePoints[j]));
midpt=lineutility.MidPointDouble(pLinePoints[middleSegment-1], pLinePoints[middleSegment], 0);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment]);
pt1.style=5;
airPts.add(pt1);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment-1], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment-1]);
pt1.style=5;
airPts.add(pt1);
//re-dimension pLinePoints so that it can hold the
//the additional points required by the shortened middle segment
//which has the bow tie feature
vblCounter=airPts.size();
pLinePoints=new POINT2[airPts.size()];
for(j=0;j<airPts.size();j++)
pLinePoints[j]=new POINT2(airPts.get(j));
//end section
acCounter=vblCounter;
FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PDF:
//reverse pt0 and pt1 8-1-08
pt0 = new POINT2(pLinePoints[1]);
pt1 = new POINT2(pLinePoints[0]);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
//end section
pts2 = new POINT2[3];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts2[2] = new POINT2(pt2);
lineutility.GetPixelsMin(pts2, 3,
offsetX,
offsetY);
if(offsetX.value[0]<0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
pLinePoints[2].style = 5;
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR < minLength) {
dMBR = 20 * minLength;
}
if(dMBR>250)
dMBR=250;
pt2 = lineutility.ExtendLineDouble(pt0, pt1, -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[3] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
pLinePoints[3].style = 0;
pLinePoints[4] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[4].style = 0;
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].y = pt2.y - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].y = pt2.y + 2;
pLinePoints[4].style = 0;
}
if (bolVertical == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].x = pt2.x - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].x = pt2.x + 2;
pLinePoints[4].style = 0;
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, -dMBR / 10);
if (bolVertical != 0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
//get the Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[5] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[5].style = 0;
pLinePoints[6] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].y = pt2.y + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].y = pt2.y - 2;
}
if (bolVertical == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].x = pt2.x + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].x = pt2.x - 2;
}
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pLinePoints[3]);
pLinePoints[7].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[8 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[2], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[11 + j] = new POINT2(pArrowPoints[j]);
pLinePoints[11 + j].style = 0;
}
//FillPoints(pLinePoints,14,points,lineType);
acCounter=14;
break;
case TacticalLines.DIRATKSPT:
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if(dMBR/20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(client.startsWith("cpof"))
{
if(dMBR<250)
dMBR=250;
}
else
{
if(dMBR<150)
dMBR=150;
}
if(dMBR>500)
dMBR=500;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 5], pLinePoints[vblCounter - 4], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - k - 1] = new POINT2(pArrowPoints[k]);
}
acCounter=vblCounter;
break;
case TacticalLines.ABATIS:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
lineutility.GetPixelsMin(pts2, 2,
offsetX,
offsetY);
if(offsetX.value[0]<=0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
if(dMBR>300)
dMBR=300;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
midpt.x=(pt0.x+pLinePoints[0].x) / 2;
midpt.y = (pt0.y + pLinePoints[0].y) / 2;
pLinePoints[vblCounter - 3] = new POINT2(pt0);
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 3].style = 0;
if (bolVertical != 0 && m.value[0] != 0) {
b = midpt.y + (1 / m.value[0]) * midpt.x; //the line equation
//get Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, dMBR / 20);
if (pLinePoints[vblCounter - 2].y >= midpt.y) {
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dMBR / 20);
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].y = midpt.y - dMBR / 20;
}
if (bolVertical == 0) {
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].x = midpt.x - dMBR / 20;
}
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[0]);
//put the abatis feature on the front
// ArrayList<POINT2>abatisPts=new ArrayList();
// for(j=3;j<vblCounter;j++)
// abatisPts.add(new POINT2(pLinePoints[j-3]));
//
// abatisPts.add(0,new POINT2(pLinePoints[vblCounter-3]));
// abatisPts.add(1,new POINT2(pLinePoints[vblCounter-2]));
// abatisPts.add(2,new POINT2(pLinePoints[vblCounter-1]));
//
// for(j=0;j<abatisPts.size();j++)
// pLinePoints[j]=new POINT2(abatisPts.get(j));
//end section
FillPoints(pLinePoints,vblCounter,points);
acCounter=vblCounter;
break;
case TacticalLines.CLUSTER:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
//for some reason occulus puts the points on top of one another
if(Math.abs(pt0.y-pt1.y)<1)
{
pt1.y = pt0.y +1;
}
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts = new POINT2[26];
dRadius = lineutility.CalcDistanceDouble(pt0, pt1) / 2;
midpt.x = (pt1.x + pt0.x) / 2;
midpt.y = (pt1.y + pt0.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical!=0 && m.value[0] != 0) //not vertical or horizontal
{
b = midpt.y + (1 / m.value[0]) * midpt.x; //normal y intercept at x=0
//we want to get the y intercept at x=offsetX
//b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
//ptYIntercept.x = offsetX.value[0];
ptYIntercept.x=0;
//ptYIntercept.y = b1;
ptYIntercept.y = b;
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, dRadius);
if (pLinePoints[0].x <= pLinePoints[1].x) {
if (pt2.y >= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
} else {
if (pt2.y <= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pt2 = midpt;
if (pLinePoints[0].x <= pLinePoints[1].x) {
pt2.y = midpt.y - dRadius;
} else {
pt2.y = midpt.y + dRadius;
}
}
if (bolVertical == 0) //vertical line
{
pt2 = midpt;
if (pLinePoints[0].y <= pLinePoints[1].y) {
pt2.x = midpt.x + dRadius;
} else {
pt2.x = midpt.x - dRadius;
}
}
pt1 = lineutility.ExtendLineDouble(midpt, pt2, 100);
pts[0] = new POINT2(pt2);
pts[1] = new POINT2(pt1);
lineutility.ArcArrayDouble(
pts,
0,dRadius,
lineType);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
for (j = 0; j < 26; j++) {
pLinePoints[2 + j] = new POINT2(pts[j]);
pLinePoints[2 + j].style = 1;
}
acCounter=28;
break;
case TacticalLines.TRIP:
dRadius = lineutility.CalcDistanceToLineDouble(pt0, pt1, pt2);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt1.y + 1 / m.value[0] * pt1.x;
b1 = pt2.y - m.value[0] * pt2.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
b = calcPoint1.y + 1 / m.value[0] * calcPoint1.x;
calcPoint3 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
b = calcPoint2.y + 1 / m.value[0] * calcPoint2.x;
calcPoint4 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
b = pt1.y + 1 / m.value[0] * pt1.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical != 0 && m.value[0] == 0) {
calcPoint0.x = pt1.x;
calcPoint0.y = pt2.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.x = calcPoint0.x + dRadius / 2;
calcPoint3.y = calcPoint0.y;
calcPoint4.x = pt1.x + dRadius;
calcPoint4.y = pt2.y;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical == 0) {
calcPoint0.x = pt2.x;
calcPoint0.y = pt1.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.y = calcPoint0.y + dRadius / 2;
calcPoint3.x = calcPoint0.x;
calcPoint4.y = pt1.y + dRadius;
calcPoint4.x = pt2.x;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
arcPts[0] = new POINT2(calcPoint1);
arcPts[1] = new POINT2(calcPoint3);
lineutility.ArcArrayDouble(
arcPts,
0,dRadius,
lineType);
pLinePoints[0].style = 5;
pLinePoints[1].style = 5;
for (k = 0; k < 26; k++) {
pLinePoints[k] = new POINT2(arcPts[k]);
}
for (k = 25; k < vblCounter; k++) {
pLinePoints[k].style = 5;
}
pLinePoints[26] = new POINT2(pt1);
dRadius = lineutility.CalcDistanceDouble(pt1, pt0);
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 - 7, 0);
pLinePoints[27] = new POINT2(midpt);
pLinePoints[27].style = 0;
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 + 7, 0);
pLinePoints[28] = new POINT2(midpt);
pLinePoints[29] = new POINT2(pt0);
pLinePoints[29].style = 5;
lineutility.GetArrowHead4Double(pt1, pt0, 15, 15, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[30 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 0; k < 3; k++) {
pLinePoints[30 + k].style = 5;
}
midpt = lineutility.MidPointDouble(pt0, pt1, 0);
d = lineutility.CalcDistanceDouble(pt1, calcPoint0);
//diagnostic for CS
//pLinePoints[33] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, d, 0);
//pLinePoints[34] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, -d, 5);
pLinePoints[33]=pt2;
pt3=lineutility.PointRelativeToLine(pt0, pt1, pt0, pt2);
d=lineutility.CalcDistanceDouble(pt3, pt2);
pt4=lineutility.ExtendAlongLineDouble(pt0, pt1, d);
d=lineutility.CalcDistanceDouble(pt2, pt4);
pLinePoints[34]=lineutility.ExtendLineDouble(pt2, pt4, d);
//end section
acCounter=35;
break;
case TacticalLines.FOLLA:
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(client.startsWith("cpof"))
d2=20;
else
d2=30;
if(d<d2)
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>150)
dMBR=150;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -2 * dMBR / 10);
for (k = 0; k < vblCounter - 14; k++) {
pLinePoints[k].style = 18;
}
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], 5 * dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
pLinePoints[vblCounter - 12].style = 0;
pLinePoints[vblCounter - 11] = new POINT2(pArrowPoints[2]);
pLinePoints[vblCounter - 11].style = 0;
pLinePoints[vblCounter - 10] = new POINT2(pArrowPoints[0]);
pLinePoints[vblCounter - 10].style = 0;
pLinePoints[vblCounter - 9] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 9].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 8 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 6].style = 0;
//diagnostic to make first point tip of arrowhead 6-14-12
//pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], 0.75 * dMBR / 10);
pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], -0.75 * dMBR / 10);
pLinePoints[1]=pt3;
pLinePoints[1].style=5;
//lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (1.25 * dMBR / 10), (int) (1.25 * dMBR / 10), pArrowPoints, 0);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (dMBR / 10), (int) (dMBR / 10), pArrowPoints, 0);
//end section
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 5 + k] = new POINT2(pArrowPoints[2 - k]);
}
pLinePoints[vblCounter - 5].style = 0;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 5;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 7]);
acCounter=16;
break;
case TacticalLines.FOLSP:
if(client.startsWith("cpof"))
d2=25;
else
d2=25;
double folspDist=0;
folspDist=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(folspDist<d2) //was 10
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(lineType, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
// else if(folspDist<d2)//was 25
// {
// lineType=TacticalLines.FOLLA;
// GetLineArray2Double(lineType, pLinePoints,16,2,shapes,clipBounds,rev);
// for(k=0;k<pLinePoints.length;k++)
// if(pLinePoints[k].style==18)
// pLinePoints[k].style=0;
//
// //lineType=TacticalLines.FOLSP;
// //acCounter=16;
// break;
// }
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
if(client.startsWith("cpof"))
{
if(folspDist<25)
dMBR=125;
if(folspDist<75)
dMBR=150;
if(folspDist<100)
dMBR=175;
if(folspDist<125)
dMBR=200;
}
else
{
dMBR*=1.5;
}
//make tail larger 6-10-11 m. Deutch
//pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 8.75);
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 4);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(k=0; k < 3; k++)
{
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 12].style = 0;
//make tail larger 6-10-11 m. Deutch
//pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 20);
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 15);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 11 + k] = new POINT2(pArrowPoints[2 - k]);
pLinePoints[vblCounter - 11 + k].style = 0;
}
pLinePoints[vblCounter - 8] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 8].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 20, (int) dMBR / 20,pArrowPoints,9);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 7 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 4; k > 0; k--)
{
pLinePoints[vblCounter - k].style = 5;
}
acCounter=12;
break;
case TacticalLines.FERRY:
lLinestyle=9;
if(dMBR/10>maxLength)
dMBR=10*maxLength;
if(dMBR/10<minLength)
dMBR=10*minLength;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-8],pLinePoints[vblCounter-7],(int)dMBR/10,(int)dMBR/10,pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-6+k]=new POINT2(pArrowPoints[k]);
lineutility.GetArrowHead4Double(pLinePoints[1],pLinePoints[0],(int)dMBR/10,(int)dMBR/10, pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-3+k]=new POINT2(pArrowPoints[k]);
acCounter=8;
break;
case TacticalLines.NAVIGATION:
pt3 = lineutility.ExtendLine2Double(pt1, pt0, -10, 0);
pt4 = lineutility.ExtendLine2Double(pt0, pt1, -10, 0);
pt5 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, 10, 0);
pt6 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, -10, 0);
pt7 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, 10, 0);
pt8 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, -10, 0);
if (pt5.y < pt6.y) {
pLinePoints[0] = new POINT2(pt5);
} else {
pLinePoints[0] = new POINT2(pt6);
}
if (pt7.y > pt8.y) {
pLinePoints[3] = new POINT2(pt7);
} else {
pLinePoints[3] = new POINT2(pt8);
}
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
acCounter=4;
break;
case TacticalLines.FORTL:
acCounter=GetFORTLPointsDouble(pLinePoints,lineType,vblSaveCounter);
break;
// case TacticalLines.HOLD:
// case TacticalLines.BRDGHD:
// lineutility.ReorderPoints(pLinePoints);
// acCounter=pLinePoints.length;
// FillPoints(pLinePoints,acCounter,points);
// break;
case TacticalLines.CANALIZE:
acCounter = DISMSupport.GetDISMCanalizeDouble(pLinePoints,lineType);
break;
case TacticalLines.BREACH:
acCounter=DISMSupport.GetDISMBreachDouble( pLinePoints,lineType);
break;
case TacticalLines.SCREEN:
case TacticalLines.GUARD:
case TacticalLines.COVER:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SCREEN_REVC: //works for 3 or 4 points
case TacticalLines.GUARD_REVC:
case TacticalLines.COVER_REVC:
acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SARA:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=14;
break;
case TacticalLines.DISRUPT:
acCounter=DISMSupport.GetDISMDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.CONTAIN:
acCounter=DISMSupport.GetDISMContainDouble(pLinePoints,lineType);
//FillPoints(pLinePoints,acCounter,points,lineType);
break;
case TacticalLines.PENETRATE:
DISMSupport.GetDISMPenetrateDouble(pLinePoints,lineType);
acCounter=7;
break;
case TacticalLines.MNFLDBLK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.BLOCK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
//FillPoints(pLinePoints,4,points,lineType);
acCounter=4;
break;
case TacticalLines.LINTGT:
case TacticalLines.LINTGTS:
case TacticalLines.FPF:
acCounter=DISMSupport.GetDISMLinearTargetDouble(pLinePoints, lineType, vblCounter);
break;
case TacticalLines.GAP:
case TacticalLines.ASLTXING:
case TacticalLines.BRIDGE: //change 1
DISMSupport.GetDISMGapDouble(
pLinePoints,
lineType);
acCounter=12;
break;
case TacticalLines.MNFLDDIS:
acCounter=DISMSupport.GetDISMMinefieldDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.SPTBYFIRE:
acCounter=DISMSupport.GetDISMSupportByFireDouble(pLinePoints,lineType);
break;
case TacticalLines.ATKBYFIRE:
acCounter=DISMSupport.GetDISMATKBYFIREDouble(pLinePoints,lineType);
break;
case TacticalLines.BYIMP:
acCounter=DISMSupport.GetDISMByImpDouble(pLinePoints,lineType);
break;
case TacticalLines.CLEAR:
acCounter=DISMSupport.GetDISMClearDouble(pLinePoints,lineType);
break;
case TacticalLines.BYDIF:
acCounter=DISMSupport.GetDISMByDifDouble(pLinePoints,lineType,clipBounds);
break;
case TacticalLines.SEIZE:
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,0);
break;
case TacticalLines.SEIZE_REVC: //works for 3 or 4 points
double radius=0;
if(rev==RendererSettings.Symbology_2525C)
{
radius=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
pLinePoints[1]=new POINT2(pLinePoints[3]);
pLinePoints[2]=new POINT2(pLinePoints[2]);
}
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,radius);
break;
case TacticalLines.FIX:
case TacticalLines.MNFLDFIX:
acCounter = DISMSupport.GetDISMFixDouble(pLinePoints, lineType,clipBounds);
break;
case TacticalLines.RIP:
acCounter = DISMSupport.GetDISMRIPDouble(pLinePoints,lineType);
break;
case TacticalLines.DELAY:
case TacticalLines.WITHDRAW:
case TacticalLines.WDRAWUP:
case TacticalLines.RETIRE:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
acCounter=DISMSupport.GetDelayGraphicEtcDouble(pLinePoints);
break;
case TacticalLines.EASY:
acCounter=DISMSupport.GetDISMEasyDouble(pLinePoints,lineType);
break;
case TacticalLines.DECEIVE:
DISMSupport.GetDISMDeceiveDouble(pLinePoints);
acCounter=4;
break;
case TacticalLines. BYPASS:
acCounter=DISMSupport.GetDISMBypassDouble(pLinePoints,lineType);
break;
case TacticalLines.PAA_RECTANGULAR:
DISMSupport.GetDISMPAADouble(pLinePoints,lineType);
acCounter=5;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.AMBUSH:
acCounter=DISMSupport.AmbushPointsDouble(pLinePoints);
break;
case TacticalLines.FLOT:
acCounter=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
break;
default:
acCounter=vblSaveCounter;
break;
}
//diagnostic
//lineutility.WriteFile(Double.toString(pLinePoints[0].x)+" to "+Double.toString(pLinePoints[1].x));
//end diagnostic
//Fill points
//and/or return points if shapes is null
switch(lineType)
{
case TacticalLines.BOUNDARY:
FillPoints(pLinePoints,acCounter,points);
//break;
return points;
case TacticalLines.CONTAIN:
case TacticalLines.BLOCK:
//case TacticalLines.DMAF: //points are already filled for DMAF
case TacticalLines.COVER:
case TacticalLines.SCREEN: //note: screen, cover, guard are getting their modifiers before the call to getlinearray
case TacticalLines.GUARD:
case TacticalLines.COVER_REVC:
case TacticalLines.SCREEN_REVC:
case TacticalLines.GUARD_REVC:
//case TacticalLines.DUMMY: //commented 5-3-10
case TacticalLines.PAA_RECTANGULAR:
case TacticalLines.FOLSP:
case TacticalLines.FOLLA:
//add these for rev c 3-12-12
case TacticalLines.BREACH:
case TacticalLines.BYPASS:
case TacticalLines.CANALIZE:
case TacticalLines.CLEAR:
case TacticalLines.DISRUPT:
case TacticalLines.FIX:
case TacticalLines.ISOLATE:
case TacticalLines.OCCUPY:
case TacticalLines.PENETRATE:
case TacticalLines.RETAIN:
case TacticalLines.SECURE:
case TacticalLines.SEIZE:
case TacticalLines.SEIZE_REVC:
FillPoints(pLinePoints,acCounter,points);
break;
default:
//if shapes is null then it is a non-CPOF client, dependent upon pixels
//instead of shapes
if(shapes==null)
{
FillPoints(pLinePoints,acCounter,points);
return points;
}
break;
}
//the shapes require pLinePoints
//if the shapes are null then it is a non-CPOF client,
if(shapes==null)
return points;
Shape2 shape=null;
Shape gp=null;
Shape2 redShape=null,blueShape=null,paleBlueShape=null,whiteShape=null;
Shape2 redFillShape=null,blueFillShape=null,blackShape=null;
BasicStroke blueStroke,paleBlueStroke;
Area blueArea=null;
Area paleBlueArea=null;
Area whiteArea=null;
boolean beginLine=true;
Polygon poly=null;
//a loop for the outline shapes
switch(lineType)
{
case TacticalLines.DIRATKGND:
//create two shapes. the first shape is for the line
//the second shape is for the arrow
//renderer will know to use a skinny stroke for the arrow shape
//the line shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
shape.moveTo(pLinePoints[0]);
for(j=0;j<acCounter-10;j++)
{
//shape.lineTo(pLinePoints[j].x,pLinePoints[j].y);
shape.lineTo(pLinePoints[j]);
}
shapes.add(shape);
//the arrow shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[acCounter-10].x,pLinePoints[acCounter-10].y);
shape.moveTo(pLinePoints[acCounter-10]);
for(j=9;j>0;j--)
{
if(pLinePoints[acCounter-j-1].style == 5)
{
//shape.moveTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.moveTo(pLinePoints[acCounter-j]);
}
else
{
//shape.lineTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.lineTo(pLinePoints[acCounter-j]);
}
}
//shape.lineTo(pLinePoints[acCounter-1].x,pLinePoints[acCounter-1].y);
shapes.add(shape);
break;
// case TacticalLines.BBS_LINE:
// Shape2 outerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//line color
// Shape2 innerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//fill color
// BasicStroke wideStroke=new BasicStroke(pLinePoints[0].style);
// BasicStroke thinStroke=new BasicStroke(pLinePoints[0].style-1);
// for(k=0;k<vblSaveCounter;k++)
// {
// if(k==0)
// {
// outerShape.moveTo(pLinePoints[k]);
// innerShape.moveTo(pLinePoints[k]);
// }
// else
// {
// outerShape.lineTo(pLinePoints[k]);
// innerShape.lineTo(pLinePoints[k]);
// }
// }
// outerShape.setStroke(wideStroke);
// innerShape.setStroke(thinStroke);
// shapes.add(outerShape);
// shapes.add(innerShape);
// break;
case TacticalLines.DEPTH_AREA:
paleBlueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
paleBlueShape.setFillColor(new Color(153,204,255));
paleBlueStroke=new BasicStroke(28);
blueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
blueShape.setFillColor(new Color(30,144,255));
blueStroke=new BasicStroke(14);
whiteShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
whiteShape.setFillColor(Color.WHITE);
poly=new Polygon();
for(k=0;k<vblSaveCounter;k++)
{
poly.addPoint((int)pLinePoints[k].x, (int)pLinePoints[k].y);
if(k==0)
whiteShape.moveTo(pLinePoints[k]);
else
whiteShape.lineTo(pLinePoints[k]);
}
whiteArea=new Area(poly);
blueArea=new Area(blueStroke.createStrokedShape(poly));
blueArea.intersect(whiteArea);
blueShape.setShape(lineutility.createStrokedShape(blueArea));
paleBlueArea=new Area(paleBlueStroke.createStrokedShape(poly));
paleBlueArea.intersect(whiteArea);
paleBlueShape.setShape(lineutility.createStrokedShape(paleBlueArea));
shapes.add(whiteShape);
shapes.add(paleBlueShape);
shapes.add(blueShape);
break;
case TacticalLines.TRAINING_AREA:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for outline
redShape.set_Style(1);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for symbol
blueShape.set_Style(0);
redShape.moveTo(pLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
redShape.lineTo(pLinePoints[k]);
//blueShape.moveTo(pLinePoints[vblSaveCounter]);
beginLine=true;
for(k=vblSaveCounter;k<acCounter;k++)
{
if(pLinePoints[k].style==0)
{
if(beginLine)
{
blueShape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
blueShape.lineTo(pLinePoints[k]);
}
if(pLinePoints[k].style==5)
{
blueShape.lineTo(pLinePoints[k]);
beginLine=true;
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.ITD:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.GREEN);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFY:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//flots and spikes (triangles)
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
//blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
//blackShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//red and blue short segments (between the flots)
for(k=0;k<vblCounter-1;k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFG:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes red outline
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==22)
{
POINT2[] CirclePoints=new POINT2[8];
redShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
redShape.setFillColor(Color.RED);
if(redShape !=null && redShape.getShape() != null)
shapes.add(redShape);
}
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
blueShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
blueShape.setFillColor(Color.BLUE);
if(blueShape !=null && blueShape.getShape() != null)
shapes.add(blueShape);
}
}
break;
case TacticalLines.USF:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
beginLine=true;
//int color=0;//red
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==19)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==25)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SF:
blackShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blackShape.setLineColor(Color.BLACK);
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23)
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//12-30-11
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
blackShape.lineTo(pLinePoints[l]);
}
redFillShape.lineTo(pLinePoints[k-9]); //12-30-11
shapes.add(redFillShape); //12-30-11
}
if(pLinePoints[k].style==24)
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
blueFillShape.lineTo(pLinePoints[k-2]);
shapes.add(blueFillShape); //12-30-11
blackShape.moveTo(pLinePoints[k-2]);
blackShape.lineTo(pLinePoints[k-1]);
blackShape.lineTo(pLinePoints[k]);
}
}
//the corners
blackShape.moveTo(pOriginalLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
blackShape.lineTo(pOriginalLinePoints[k]);
//shapes.add(redFillShape); //12-30-11
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
shapes.add(blackShape);
break;
case TacticalLines.WFG:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.FOLLA:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1); //dashed line
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(0); //dashed line
//shape.moveTo(pLinePoints[2]);
for(j=2;j<vblCounter;j++)
{
if(pLinePoints[j-1].style != 5)
shape.lineTo(pLinePoints[j]);
else
shape.moveTo(pLinePoints[j]);
}
shapes.add(shape);
break;
case TacticalLines.CFG:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==9)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
d=lineutility.CalcDistanceDouble(pLinePoints[k], pLinePoints[k+1]);
pt0=lineutility.ExtendAlongLineDouble(pLinePoints[k], pLinePoints[k+1], d-5);
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pt0.x,pt0.y);
shape.lineTo(pt0);
}
if(pLinePoints[k].style==0 && k==acCounter-2)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.PIPE:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==1)
{
if(k==0)
{
shape.moveTo(pLinePoints[k]);
}
else
shape.lineTo(pLinePoints[k]);
}
}
shapes.add(shape);
break;
case TacticalLines.ATDITCHM:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 4, 8, CirclePoints, 9);//was 3
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
if(k<acCounter-2)
{
if(pLinePoints[k].style!=0 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==10)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
//use shapes instead of pixels
// if(shape==null)
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//
// if(beginLine)
// {
// if(k==0)
// shape.set_Style(pLinePoints[k].style);
//
// shape.moveTo(pLinePoints[k]);
// beginLine=false;
// }
// else
// {
// //diagnostic 1-8-13
// if(k<acCounter-1)
// {
// if(pLinePoints[k].style==5)
// {
// shape.moveTo(pLinePoints[k]);
// continue;
// }
// }
// //end section
// shape.lineTo(pLinePoints[k]);
// //diagnostic 1-8-13
// //if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
// if(pLinePoints[k].style==10)
// {
// beginLine=true;
// }
// }
// if(pLinePoints[k+1].style==20)
// {
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
// }
if(k<acCounter-2)
{
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
}//end for
break;
case TacticalLines.DIRATKFNT:
//the solid lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18)
continue;
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k>0) //doubled points with linestyle=5
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
continue;//shape.lineTo(pLinePoints[k]);
if(k==0)
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==vblCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
//the dashed lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18 && pLinePoints[k-1].style == 5)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.set_Style(pLinePoints[k].style);
shape.set_Style(1);
shape.moveTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==18 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
}
else
continue;
}
break;
case TacticalLines.ESR1:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[2].style);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
break;
case TacticalLines.DUMMY: //commented 5-3-10
//first shape is the original points
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.set_Style(1);
// shape.moveTo(pLinePoints[acCounter-1]);
// shape.lineTo(pLinePoints[acCounter-2]);
// shape.lineTo(pLinePoints[acCounter-3]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for (k = 0; k < acCounter-3; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k==0)
shape.set_Style(pLinePoints[k].style);
//if(k>0) //doubled points with linestyle=5
// if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
// shape.lineTo(pLinePoints[k]);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-4) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1);
shape.moveTo(pLinePoints[acCounter-1]);
shape.lineTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-3]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMA:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[vblCounter-3]);
shape.set_Style(1);
shape.lineTo(pLinePoints[vblCounter-2]);
shape.lineTo(pLinePoints[vblCounter-1]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.FORDIF:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[4].style);
shape.moveTo(pLinePoints[4]);
for(k=5;k<acCounter;k++)
{
if(pLinePoints[k-1].style != 5)
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMAF:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(points.get(0).style);
shape.moveTo(points.get(0));
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(points.get(k));
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(points.get(vblCounter-3));
shape.set_Style(1);
shape.lineTo(points.get(vblCounter-2));
shape.lineTo(points.get(vblCounter-1));
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for(k=vblCounter;k<points.size();k++)
{
if(beginLine)
{
if(k==0)
shape.set_Style(points.get(k).style);
if(k>0) //doubled points with linestyle=5
if(points.get(k).style==5 && points.get(k-1).style==5)
shape.lineTo(points.get(k));
shape.moveTo(points.get(k));
beginLine=false;
}
else
{
shape.lineTo(points.get(k));
if(points.get(k).style==5 || points.get(k).style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==points.size()-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.AIRFIELD:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for (k = 1; k < acCounter-5; k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[acCounter-4]);
shape.lineTo(pLinePoints[acCounter-3]);
shape.moveTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-1]);
shapes.add(shape);
//we need an extra shape to outline the center feature
//in case there is opaque fill that obliterates it
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.MIN_POINTS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for(k=1;k<pLinePoints.length;k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
break;
default:
for (k = 0; k < acCounter; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
//if(pLinePoints[k].style==5)
// continue;
if(k==0)
shape.set_Style(pLinePoints[k].style);
if(k>0) //doubled points with linestyle=5
{
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5 && k< acCounter-1)
continue;
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==10) //CF
continue;
}
if(k==0 && pLinePoints.length>1)
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==5)
continue;
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
break;
}//end switch
//a loop for arrowheads with fill
//these require a separate shape for fill
switch(lineType)
{
case TacticalLines.BELT1://requires non-decorated fill shape
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pUpperLinePoints[0]);
for(j=1;j<pUpperLinePoints.length;j++)
{
shape.lineTo(pUpperLinePoints[j]);
//lineutility.SegmentLineShape(pUpperLinePoints[j], pUpperLinePoints[j+1], shape);
}
shape.lineTo(pLowerLinePoints[pLowerLinePoints.length-1]);
for(j=pLowerLinePoints.length-1;j>=0;j--)
{
shape.lineTo(pLowerLinePoints[j]);
//lineutility.SegmentLineShape(pLowerLinePoints[j], pLowerLinePoints[j-1], shape);
}
shape.lineTo(pUpperLinePoints[0]);
shapes.add(0,shape);
break;
case TacticalLines.DIRATKAIR:
//added this section to not fill the bow tie and instead
//add a shape to close what had been the bow tie fill areas with
//a line segment for each one
int outLineCounter=0;
POINT2[]ptOutline=new POINT2[4];
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==10)
{
//shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[k-2]);
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(1,shape);
//collect these four points
ptOutline[outLineCounter++]=pLinePoints[k-2];
ptOutline[outLineCounter++]=pLinePoints[k];
}
}//end for
//build a shape from the to use as outline for the feature
//if fill alpha is high
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.moveTo(ptOutline[0]);
// shape.lineTo(ptOutline[1]);
// shape.lineTo(ptOutline[3]);
// shape.lineTo(ptOutline[2]);
// shape.lineTo(ptOutline[0]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(0,shape);
break;
case TacticalLines.OFY:
case TacticalLines.OCCLUDED:
case TacticalLines.WF:
case TacticalLines.WFG:
case TacticalLines.WFY:
case TacticalLines.CF:
case TacticalLines.CFY:
case TacticalLines.CFG:
//case TacticalLines.SF:
//case TacticalLines.SFY:
//case TacticalLines.SFG:
case TacticalLines.SARA:
case TacticalLines.FERRY:
case TacticalLines.EASY:
case TacticalLines.BYDIF:
case TacticalLines.BYIMP:
case TacticalLines.FOLSP:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
case TacticalLines.MNFLDFIX:
case TacticalLines.TURN:
case TacticalLines.MNFLDDIS:
//POINT2 initialFillPt=null;
for (k = 0; k < acCounter; k++)
{
if(k==0)
{
if(pLinePoints[k].style==9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
}
else //k>0
{
if(pLinePoints[k].style==9 && pLinePoints[k-1].style != 9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
if(pLinePoints[k].style==9 && pLinePoints[k-1].style==9) //9,9,...,9,10
{
shape.lineTo(pLinePoints[k]);
}
}
if(pLinePoints[k].style==10)
{
shape.lineTo(pLinePoints[k]);
if(lineType==TacticalLines.SARA)
shape.lineTo(pLinePoints[k-2]);
if(shape !=null && shape.getShape() != null)
{
//must line to the initial fill point to close the shape
//this is a requirement for the java linear ring (map3D java client)
//if(initialFillPt != null)
//shape.lineTo(initialFillPt);
shapes.add(0,shape);
//initialFillPt=null;
}
}
}//end for
break;
default:
break;
}
//CELineArray.add_Shapes(shapes);
//clean up
pArrowPoints=null;
arcPts=null;
circlePoints=null;
pOriginalLinePoints=null;
pts2=null;
pts=null;
segments=null;
pUpperLinePoints=null;
pLowerLinePoints=null;
pUpperLowerLinePoints=null;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetLineArray2Double",
new RendererException("GetLineArray2Dboule " + Integer.toString(lineType), exc));
}
return points;
}
}
| revised BBS_RECTANGLE to display a square.
| core/JavaLineArray/src/main/java/JavaLineArray/arraysupport.java | revised BBS_RECTANGLE to display a square. | <ide><path>ore/JavaLineArray/src/main/java/JavaLineArray/arraysupport.java
<ide> {
<ide> ymax=pLinePoints[1].y;
<ide> ymin=pLinePoints[0].y;
<del> }
<add> }
<add> if(xmax-xmin>ymax-ymin)
<add> ymax=ymin+(xmax-xmin);
<add> else
<add> xmax=xmin+(ymax-ymin);
<add>
<ide> pt0=new POINT2(xmin-buffer,ymin-buffer);
<ide> pt2=new POINT2(xmax+buffer,ymax+buffer);
<ide> pt1=new POINT2(pt0); |
|
Java | mit | 37836ce38fe2de636d11512e57a21ac5413cd65f | 0 | juckele/vivarium,juckele/vivarium,juckele/vivarium | package io.vivarium.experiment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import io.vivarium.audit.ActionFrequencyFunction;
import io.vivarium.audit.AuditFunction;
import io.vivarium.audit.CensusFunction;
import io.vivarium.core.Blueprint;
import io.vivarium.core.Species;
import io.vivarium.scripts.CreateWorld;
import io.vivarium.scripts.RunSimulation;
import io.vivarium.serialization.FileIO;
import io.vivarium.serialization.Format;
import io.vivarium.util.Functions;
import io.vivarium.util.Rand;
import io.vivarium.util.concurrency.ThreadRandAllocator;
public class MutationRateLocal
{
private static final int WORLD_SIZE = 100;
private static final int LIFE_TIMES_PER_SIMULATION = 1000;
private static final int TICKS_PER_SIMULATION = LIFE_TIMES_PER_SIMULATION * 20_000;
private static final int MAX_SIMULATIONS = 101;
private static final int PEAK_THREAD_THROUGHPUT = 4;
private static final int MIN_MUTATION_EXPONENT = -15;
private static final int MAX_MUTATION_EXPONENT = -5;
/**
* Runs the MutationRate experiment.
*
* Hypothesis: There is an optimal mutation rate for population health.
*
* @param args
* @throws InterruptedException
* Not really...
*/
public static void main(String[] args) throws InterruptedException
{
// If we're running multi-threaded code, we need to use a multi-threaded random allocator
Rand.setAllocator(new ThreadRandAllocator());
// Set up thread pool
ExecutorService executorService = Executors.newFixedThreadPool(PEAK_THREAD_THROUGHPUT);
Collection<WorldRunner> tasks = new LinkedList<>();
double[] mutationRates = Functions.generateDitherArray(MIN_MUTATION_EXPONENT, MAX_MUTATION_EXPONENT,
MAX_SIMULATIONS);
for (int i = 0; i < MAX_SIMULATIONS; i++)
{
double mutationRateExponent = Math.round(mutationRates[i] * 100) / 100.0;
// Record the thread name
String name = "mutation=2^" + mutationRateExponent;
// Make a blueprint
Blueprint blueprint = Blueprint.makeDefault();
blueprint.setSize(WORLD_SIZE);
// Set species
ArrayList<Species> speciesList = new ArrayList<>();
Species species = Species.makeDefault();
species.setMutationRateExponent(mutationRateExponent);
species.setNormalizeAfterMutation(Math.sqrt(42));
speciesList.add(species);
blueprint.setSpecies(speciesList);
// Set audit functions
ArrayList<AuditFunction> auditFunctions = new ArrayList<>();
auditFunctions.add(new ActionFrequencyFunction());
auditFunctions.add(new CensusFunction());
blueprint.setAuditFunctions(auditFunctions);
// Save the blueprint
FileIO.saveSerializer(blueprint, name + "_blueprint.viv", Format.JSON);
// Create callable
log("Generating blueprint " + name);
tasks.add(new WorldRunner(name));
}
// Do the work!
executorService.invokeAll(tasks);
log("Awating");
executorService.shutdown();
executorService.awaitTermination(10_000, TimeUnit.DAYS);
log("Completed");
}
private static class WorldRunner implements Callable<Object>
{
private final String _name;
WorldRunner(String name)
{
this._name = name;
}
@Override
public Object call()
{
try
{
// Create a world
{
log("Generating world " + _name);
String[] args = { "-b", _name + "_blueprint.viv", "-o", _name + "_initial.viv" };
CreateWorld.main(args);
}
// Run the world
{
log("Starting simulation of world " + _name);
String[] args = { "-i", _name + "_initial.viv", "-o", _name + "_complete.viv", "-t",
"" + TICKS_PER_SIMULATION };
RunSimulation.main(args);
log("Completeing simulation of world " + _name);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
private synchronized static void log(String event)
{
System.out.println(event);
}
}
| vivarium-scripts/src/main/java/io/vivarium/experiment/MutationRateLocal.java | package io.vivarium.experiment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import io.vivarium.audit.ActionFrequencyFunction;
import io.vivarium.audit.AuditFunction;
import io.vivarium.audit.CensusFunction;
import io.vivarium.core.Blueprint;
import io.vivarium.core.Species;
import io.vivarium.scripts.CreateWorld;
import io.vivarium.scripts.RunSimulation;
import io.vivarium.serialization.FileIO;
import io.vivarium.serialization.Format;
import io.vivarium.util.Functions;
import io.vivarium.util.Rand;
import io.vivarium.util.concurrency.ThreadRandAllocator;
public class MutationRateLocal
{
private static final int WORLD_SIZE = 100;
private static final int LIFE_TIMES_PER_SIMULATION = 1000;
private static final int TICKS_PER_SIMULATION = LIFE_TIMES_PER_SIMULATION * 20_000;
private static final int MAX_SIMULATIONS = 101;
private static final int PEAK_THREAD_THROUGHPUT = 4;
private static final int MIN_MUTATION_EXPONENT = -15;
private static final int MAX_MUTATION_EXPONENT = -5;
/**
* Runs the MutationRate experiment.
*
* Hypothesis: There is an optimal mutation rate for population health.
*
* @param args
* @throws InterruptedException
* Not really...
*/
public static void main(String[] args) throws InterruptedException
{
// If we're running multi-threaded code, we need to use a multi-threaded random allocator
Rand.setAllocator(new ThreadRandAllocator());
// Set up thread pool
ExecutorService executorService = Executors.newFixedThreadPool(PEAK_THREAD_THROUGHPUT);
Collection<WorldRunner> tasks = new LinkedList<>();
double[] mutationRates = Functions.generateDitherArray(MIN_MUTATION_EXPONENT, MAX_MUTATION_EXPONENT,
MAX_SIMULATIONS);
for (int i = 0; i < MAX_SIMULATIONS; i++)
{
double mutationRateExponent = Math.round(mutationRates[i] * 100) / 100.0;
// Record the thread name
String name = "mutation=2^" + mutationRateExponent;
// Make a blueprint
Blueprint blueprint = Blueprint.makeDefault();
blueprint.setSize(WORLD_SIZE);
// Set species
ArrayList<Species> speciesList = new ArrayList<>();
Species species = Species.makeDefault();
species.setMutationRateExponent(mutationRateExponent);
species.setNormalizeAfterMutation(Math.sqrt(42));
speciesList.add(species);
blueprint.setSpecies(speciesList);
// Set audit functions
ArrayList<AuditFunction> auditFunctions = new ArrayList<>();
auditFunctions.add(new ActionFrequencyFunction());
auditFunctions.add(new CensusFunction());
blueprint.setAuditFunctions(auditFunctions);
// Save the blueprint
FileIO.saveSerializer(blueprint, name + "_blueprint.viv", Format.JSON);
// Create callable
log("Generating blueprint " + name);
tasks.add(new WorldRunner(name));
}
// Do the work!
executorService.invokeAll(tasks);
log("Awating");
executorService.shutdown();
executorService.awaitTermination(10_000, TimeUnit.DAYS);
log("Completed");
}
private static class WorldRunner implements Callable<Object>
{
private final String _name;
WorldRunner(String name)
{
this._name = name;
}
@Override
public Object call() throws Exception
{
// Create a world
{
log("Generating world " + _name);
String[] args = { "-b", _name + "_blueprint.viv", "-o", _name + "_initial.viv" };
CreateWorld.main(args);
}
// Run the world
{
log("Starting simulation of world " + _name);
String[] args = { "-i", _name + "_initial.viv", "-o", _name + "_complete.viv", "-t",
"" + TICKS_PER_SIMULATION };
RunSimulation.main(args);
log("Completeing simulation of world " + _name);
}
return null;
}
}
private synchronized static void log(String event)
{
System.out.println(event);
}
}
| Print errors if they happen!
| vivarium-scripts/src/main/java/io/vivarium/experiment/MutationRateLocal.java | Print errors if they happen! | <ide><path>ivarium-scripts/src/main/java/io/vivarium/experiment/MutationRateLocal.java
<ide> }
<ide>
<ide> @Override
<del> public Object call() throws Exception
<add> public Object call()
<ide> {
<del> // Create a world
<add> try
<ide> {
<del> log("Generating world " + _name);
<del> String[] args = { "-b", _name + "_blueprint.viv", "-o", _name + "_initial.viv" };
<del> CreateWorld.main(args);
<add> // Create a world
<add> {
<add> log("Generating world " + _name);
<add> String[] args = { "-b", _name + "_blueprint.viv", "-o", _name + "_initial.viv" };
<add> CreateWorld.main(args);
<add> }
<add>
<add> // Run the world
<add> {
<add> log("Starting simulation of world " + _name);
<add> String[] args = { "-i", _name + "_initial.viv", "-o", _name + "_complete.viv", "-t",
<add> "" + TICKS_PER_SIMULATION };
<add> RunSimulation.main(args);
<add> log("Completeing simulation of world " + _name);
<add> }
<ide> }
<del>
<del> // Run the world
<add> catch (Exception e)
<ide> {
<del> log("Starting simulation of world " + _name);
<del> String[] args = { "-i", _name + "_initial.viv", "-o", _name + "_complete.viv", "-t",
<del> "" + TICKS_PER_SIMULATION };
<del> RunSimulation.main(args);
<del> log("Completeing simulation of world " + _name);
<add> e.printStackTrace();
<ide> }
<ide>
<ide> return null; |
|
Java | agpl-3.0 | e5f7b0e157d6dc119f2eef3e2160b83527f3ef76 | 0 | rpsl4j/rpsl4j-parser,rpsl4j/rpsl4j-parser,rpsl4j/rpsl4j-parser | package net.ripe.db.whois.common.rpsl;
import com.google.common.base.Splitter;
import net.ripe.db.whois.common.generated.AggrBndryParser;
import net.ripe.db.whois.common.generated.AggrMtdParser;
import net.ripe.db.whois.common.generated.ComponentsParser;
import net.ripe.db.whois.common.generated.ComponentsR6Parser;
import net.ripe.db.whois.common.generated.DefaultParser;
import net.ripe.db.whois.common.generated.ExportParser;
import net.ripe.db.whois.common.generated.ExportViaParser;
import net.ripe.db.whois.common.generated.FilterParser;
import net.ripe.db.whois.common.generated.IfaddrParser;
import net.ripe.db.whois.common.generated.ImportParser;
import net.ripe.db.whois.common.generated.ImportViaParser;
import net.ripe.db.whois.common.generated.InjectParser;
import net.ripe.db.whois.common.generated.InjectR6Parser;
import net.ripe.db.whois.common.generated.InterfaceParser;
import net.ripe.db.whois.common.generated.MpDefaultParser;
import net.ripe.db.whois.common.generated.MpExportParser;
import net.ripe.db.whois.common.generated.MpFilterParser;
import net.ripe.db.whois.common.generated.MpImportParser;
import net.ripe.db.whois.common.generated.MpPeerParser;
import net.ripe.db.whois.common.generated.MpPeeringParser;
import net.ripe.db.whois.common.generated.PeerParser;
import net.ripe.db.whois.common.generated.PeeringParser;
import net.ripe.db.whois.common.generated.V6FilterParser;
import net.ripe.db.whois.common.ip.Ipv4Resource;
import net.ripe.db.whois.common.ip.Ipv6Resource;
import net.ripe.db.whois.common.rpsl.attrs.AddressPrefixRange;
import net.ripe.db.whois.common.rpsl.attrs.AutnumStatus;
import net.ripe.db.whois.common.rpsl.attrs.Inet6numStatus;
import net.ripe.db.whois.common.rpsl.attrs.InetnumStatus;
import net.ripe.db.whois.common.rpsl.attrs.OrgType;
import net.ripe.db.whois.common.rpsl.attrs.RangeOperation;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.ripe.db.whois.common.domain.CIString.ciString;
// TODO: [AH] queries should NOT match AUTO- versions of keys, we should remove the AUTO- patterns from here
// TODO: [AH] fix capture groups (add '?:' where capture is not needed)
public interface AttributeSyntax extends Documented {
AttributeSyntax ANY_SYNTAX = new AnySyntax();
AttributeSyntax ADDRESS_PREFIX_RANGE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AddressPrefixRangeParser());
AttributeSyntax ALIAS_SYNTAX = new AttributeSyntaxRegexp(254,
Pattern.compile("(?i)^[A-Z0-9]([-A-Z0-9]*[A-Z0-9])?(\\.[A-Z0-9]([-A-Z0-9]*[A-Z0-9])?)*(\\.)?$"), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n"
);
AttributeSyntax AS_BLOCK_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AsBlockParser(), "" +
"<as-number> - <as-number>\n");
AttributeSyntax AS_NUMBER_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AutNumParser(), "" +
"An \"AS\" string followed by an integer in the range\n" +
"from 0 to 4294967295\n");
AttributeSyntax AS_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AsSetParser(), "" +
"An as-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"as-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"An as-set name can also be hierarchical. A hierarchical set\n" +
"name is a sequence of set names and AS numbers separated by\n" +
"colons \":\". At least one component of such a name must be\n" +
"an actual set name (i.e. start with \"as-\"). All the set\n" +
"name components of a hierarchical as-name have to be as-set\n" +
"names.\n");
AttributeSyntax AGGR_BNDRY_SYNTAX = new AttributeSyntaxParser(new AggrBndryParser(), "" +
"[<as-expression>]\n");
AttributeSyntax AGGR_MTD_SYNTAX = new AttributeSyntaxParser(new AggrMtdParser(), "" +
"inbound | outbound [<as-expression>]\n");
AttributeSyntax AUTH_SCHEME_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^(MD5-PW \\$1\\$[A-Z0-9./]{1,8}\\$[A-Z0-9./]{22}|PGPKEY-[A-F0-9]{8}|SSO [-@.\\w]{1,90}|X509-[1-9][0-9]{0,19}|AUTO-[1-9][0-9]*)$"), "" +
"<auth-scheme> <scheme-info> Description\n" +
"\n" +
"MD5-PW encrypted We strongly advise phrases longer\n" +
" password, produced than 8 characters to be used,\n" +
" using the FreeBSD avoiding the use of words or\n" +
" crypt_md5 combinations of words found in any\n" +
" algorithm dictionary of any language.\n" +
"\n" +
"PGPKEY-<id> Strong scheme of authentication.\n" +
" <id> is the PGP key ID to be\n" +
" used for authentication. This string\n" +
" is the same one that is used in the\n" +
" corresponding key-cert object's\n" +
" \"key-cert:\" attribute.\n" +
"\n" +
"X509-<nnn> Strong scheme of authentication.\n" +
" <nnn> is the index number of the\n" +
" corresponding key-cert object's\n" +
" \"key-cert:\" attribute (X509-nnn).\n" +
"\n" +
"SSO username The username is the same as one used \n" +
" for a RIPE NCC Access account. This must \n" +
" be a valid username and is checked \n" +
" against the RIPE NCC Access user list.\n"
);
AttributeSyntax CERTIF_SYNTAX = new AnySyntax("" +
"The value of the public key should be supplied either using\n" +
"multiple \"certif:\" attributes, or in one \"certif:\"\n" +
"attribute. In the first case, this is easily done by\n" +
"exporting the key from your local key ring in ASCII armored\n" +
"format and prepending each line of the key with the string\n" +
"\"certif:\". In the second case, line continuation should be\n" +
"used to represent an ASCII armored format of the key. All\n" +
"the lines of the exported key must be included; also the\n" +
"begin and end markers and the empty line which separates the\n" +
"header from the key body.\n");
AttributeSyntax CHANGED_SYNTAX = new AttributeSyntaxParser(new AttributeParser.ChangedParser(), "" +
"An e-mail address as defined in RFC 2822, followed by a date\n" +
"in the format YYYYMMDD.\n");
AttributeSyntax COUNTRY_CODE_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^[a-z]{2}$"),
"Valid two-letter ISO 3166 country code.");
AttributeSyntax COMPONENTS_SYNTAX = new ComponentsSyntax();
AttributeSyntax DEFAULT_SYNTAX = new AttributeSyntaxParser(new DefaultParser(), "" +
"to <peering> [action <action>] [networks <filter>]");
AttributeSyntax DOMAIN_SYNTAX = new AttributeSyntaxParser(new AttributeParser.DomainParser(), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n");
AttributeSyntax DS_RDATA_SYNTAX = new AttributeSyntaxParser(new AttributeParser.DsRdataParser(), "" +
"<Keytag> <Algorithm> <Digest type> <Digest>\n" +
"\n" +
"Keytag is represented by an unsigned decimal integer (0-65535).\n" +
"\n" +
"Algorithm is represented by an unsigned decimal integer (0-255).\n" +
"\n" +
"Digest type is represented by a unsigned decimal integer (0-255).\n" +
"\n" +
"Digest is a digest in hexadecimal representation (case insensitive). Its length varies for various digest types.\n" +
"For digest type SHA-1 digest is represented by 20 octets (40 characters, plus possible spaces).\n" +
"\n" +
"For more details, see RFC4034.\n");
AttributeSyntax EMAIL_SYNTAX = new AttributeSyntaxRegexp(80, Pattern.compile("(?i)^.+@([^.]+[.])+[^.]+$"),
"An e-mail address as defined in RFC 2822.\n");
AttributeSyntax EXPORT_COMPS_SYNTAX = new ExportCompsSyntax();
AttributeSyntax EXPORT_SYNTAX = new AttributeSyntaxParser(new ExportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"to <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"to <peering-N> [action <action-N>]\n" +
"announce <filter>\n");
AttributeSyntax FILTER_SYNTAX = new AttributeSyntaxParser(new FilterParser(), "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"for more information.\n");
AttributeSyntax FILTER_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.FilterSetParser(), "" +
"A filter-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"fltr-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A filter-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"fltr-\"). All the\n" +
"set name components of a hierarchical filter-name have to be\n" +
"filter-set names.\n");
AttributeSyntax FREE_FORM_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?s)^.*$"), "" +
"A sequence of ASCII characters.\n");
AttributeSyntax GENERATED_SYNTAX = new AnySyntax("" +
"Attribute generated by server.");
AttributeSyntax GEOLOC_SYNTAX = new GeolocSyntax();
AttributeSyntax HOLES_SYNTAX = new RoutePrefixSyntax();
AttributeSyntax IMPORT_SYNTAX = new AttributeSyntaxParser(new ImportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"from <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"from <peering-N> [action <action-N>]\n" +
"accept <filter>\n");
AttributeSyntax INET_RTR_SYNTAX = new AttributeSyntaxRegexp(254,
Pattern.compile("(?i)^[A-Z0-9]([-_A-Z0-9]*[A-Z0-9])?(\\.[A-Z0-9]([-_A-Z0-9]*[A-Z0-9])?)*(\\.)?$"), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n"
);
AttributeSyntax IFADDR_SYNTAX = new AttributeSyntaxParser(new IfaddrParser(), "" +
"<ipv4-address> masklen <integer> [action <action>]");
AttributeSyntax INJECT_SYNTAX = new InjectSyntax();
AttributeSyntax INTERFACE_SYNTAX = new AttributeSyntaxParser(new InterfaceParser(), "" +
"afi <afi> <ipv4-address> masklen <integer> [action <action>]\n" +
"afi <afi> <ipv6-address> masklen <integer> [action <action>]\n" +
" [tunnel <remote-endpoint-address>,<encapsulation>]\n");
AttributeSyntax IPV4_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Ipv4ResourceParser(), "" +
"<ipv4-address> - <ipv4-address>");
AttributeSyntax IPV6_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Ipv6ResourceParser(), "" +
"<ipv6-address>/<prefix>");
AttributeSyntax IRT_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^irt-[A-Z0-9_-]*[A-Z0-9]$"), "" +
"An irt name is made up of letters, digits, the character\n" +
"underscore \"_\", and the character hyphen \"-\"; it must start\n" +
"with \"irt-\", and the last character of a name must be a\n" +
"letter or a digit.\n");
AttributeSyntax KEY_CERT_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^(PGPKEY-[A-F0-9]{8})|(X509-[1-9][0-9]*)|(AUTO-[1-9][0-9]*)$"), "" +
"PGPKEY-<id>\n" +
"\n" +
"<id> is the PGP key ID of the public key in 8-digit\n" +
"hexadecimal format without \"0x\" prefix."
);
AttributeSyntax LANGUAGE_CODE_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^[a-z]{2}$"), "" +
"Valid two-letter ISO 639-1 language code.\n");
AttributeSyntax MBRS_BY_REF_SYNTAX = new AnySyntax("" +
"<mntner-name> | ANY\n");
AttributeSyntax MEMBER_OF_SYNTAX = new MemberOfSyntax();
AttributeSyntax MEMBERS_SYNTAX = new MembersSyntax(false);
AttributeSyntax METHOD_SYNTAX = new AnySyntax("" +
"Currently, only PGP keys are supported.\n");
AttributeSyntax MNT_ROUTES_SYNTAX = new AttributeSyntaxParser(new AttributeParser.MntRoutesParser(), new Multiple(new HashMap<ObjectType, String>() {{
put(ObjectType.AUT_NUM, "<mnt-name> [ { list of (<ipv4-address>/<prefix> or <ipv6-address>/<prefix>) } | ANY ]\n");
put(ObjectType.INET6NUM, "<mnt-name> [ { list of <ipv6-address>/<prefix> } | ANY ]\n");
put(ObjectType.INETNUM, "<mnt-name> [ { list of <address-prefix-range> } | ANY ]\n");
put(ObjectType.ROUTE, "<mnt-name> [ { list of <address-prefix-range> } | ANY ]\n");
put(ObjectType.ROUTE6, "<mnt-name> [ { list of <ipv6-address>/<prefix> } | ANY ]\n");
}}));
AttributeSyntax MP_DEFAULT_SYNTAX = new AttributeSyntaxParser(new MpDefaultParser(), "" +
"to <peering> [action <action>] [networks <filter>]\n");
AttributeSyntax MP_EXPORT_SYNTAX = new AttributeSyntaxParser(new MpExportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"afi <afi-list>\n" +
"to <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"to <peering-N> [action <action-N>]\n" +
"announce <filter>\n");
AttributeSyntax EXPORT_VIA_SYNTAX = new AttributeSyntaxParser(new ExportViaParser(), "" +
"[protocol <protocol-1>] [into <protocol-2>] \n" +
"afi <afi-list>\n" +
"<peering-1>\n" +
"to <peering-2> [action <action-1>; <action-2>; ... <action-N>;]\n" +
" .\n" +
" .\n" +
" .\n" +
"<peering-3>\n" +
"to <peering-M> [action <action-1>; <action-2>; ... <action-N>;]\n" +
"announce <filter>\n");
AttributeSyntax MP_FILTER_SYNTAX = new AttributeSyntaxParser(new MpFilterParser(), "" +
"Logical expression which when applied to a set of multiprotocol\n" +
"routes returns a subset of these routes. Please refer to RPSLng\n" +
"Internet Draft for more information.\n");
AttributeSyntax MP_IMPORT_SYNTAX = new AttributeSyntaxParser(new MpImportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"afi <afi-list>\n" +
"from <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"from <peering-N> [action <action-N>]\n" +
"accept (<filter>|<filter> except <importexpression>|\n" +
" <filter> refine <importexpression>)\n");
AttributeSyntax IMPORT_VIA_SYNTAX = new AttributeSyntaxParser(new ImportViaParser(), "" +
"[protocol <protocol-1>] [into <protocol-2>]\n" +
"afi <afi-list>\n" +
"<peering-1>\n" +
"from <peering-2> [action <action-1>; <action-2>; ... <action-N>;]\n" +
" .\n" +
" .\n" +
" .\n" +
"<peering-3>\n" +
"from <peering-M> [action <action-1>; <action-2>; ... <action-N>;]\n" +
"accept (<filter>|<filter> except <importexpression>|\n" +
" <filter> refine <importexpression>)\n");
AttributeSyntax MP_MEMBERS_SYNTAX = new MembersSyntax(true);
AttributeSyntax MP_PEER_SYNTAX = new AttributeSyntaxParser(new MpPeerParser(), new Multiple(new HashMap<ObjectType, String>() {{
put(ObjectType.INET_RTR, "" +
"<protocol> afi <afi> <ipv4- or ipv6- address> <options>\n" +
"| <protocol> <inet-rtr-name> <options>\n" +
"| <protocol> <rtr-set-name> <options>\n" +
"| <protocol> <peering-set-name> <options>\n");
put(ObjectType.PEERING_SET, "" +
"afi <afi> <peering>\n");
}}));
AttributeSyntax MP_PEERING_SYNTAX = new AttributeSyntaxParser(new MpPeeringParser(), "" +
"afi <afi> <peering>\n");
AttributeSyntax NETNAME_SYNTAX = new AttributeSyntaxRegexp(80, Pattern.compile("(?i)^[A-Z]([A-Z0-9_-]*[A-Z0-9])?$"), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a name\n" +
"must be a letter, and the last character of a name must be a\n" +
"letter or a digit.\n");
AttributeSyntax NIC_HANDLE_SYNTAX = new AttributeSyntaxRegexp(30, Pattern.compile("(?i)^([A-Z]{2,4}([1-9][0-9]{0,5})?(-[A-Z]{2,10})?|AUTO-[1-9][0-9]*([A-Z]{2,4})?)$"), "" +
"From 2 to 4 characters optionally followed by up to 6 digits\n" +
"optionally followed by a source specification. The first digit\n" +
"must not be \"0\". Source specification starts with \"-\" followed\n" +
"by source name up to 9-character length.\n");
AttributeSyntax NSERVER_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NServerParser(), "" +
"Nameserver name as specified in RFC 1034 with or without\n" +
"trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n" +
"\n" +
"The nameserver name may be optionally followed by IPv4 address\n" +
"in decimal dotted quad form (e.g. 192.0.2.1) or IPv6 address\n" +
"in lowercase canonical form (Section 2.2.1, RFC 4291).\n" +
"\n" +
"The nameserver name may be followed by an IP address only when\n" +
"the name is inside of the domain being delegated.\n");
AttributeSyntax NUMBER_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("^[0-9]+$"), "" +
"Specifies a numeric value.\n");
AttributeSyntax OBJECT_NAME_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NameParser(), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a name\n" +
"must be a letter, and the last character of a name must be a\n" +
"letter or a digit. The following words are reserved by\n" +
"RPSL, and they can not be used as names:\n" +
"\n" +
" any as-any rs-any peeras and or not atomic from to at\n" +
" action accept announce except refine networks into inbound\n" +
" outbound\n" +
"\n" +
"Names starting with certain prefixes are reserved for\n" + // TODO: [ES] implement per type
"certain object types. Names starting with \"as-\" are\n" +
"reserved for as set names. Names starting with \"rs-\" are\n" +
"reserved for route set names. Names starting with \"rtrs-\"\n" +
"are reserved for router set names. Names starting with\n" +
"\"fltr-\" are reserved for filter set names. Names starting\n" +
"with \"prng-\" are reserved for peering set names. Names\n" +
"starting with \"irt-\" are reserved for irt names.\n");
AttributeSyntax REFERRAL_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NameParser());
AttributeSyntax SOURCE_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^[A-Z][A-Z0-9_-]*[A-Z0-9]$"), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a\n" +
"registry name must be a letter, and the last character of a\n" +
"registry name must be a letter or a digit."
);
AttributeSyntax ORGANISATION_SYNTAX = new AttributeSyntaxRegexp(30,
Pattern.compile("(?i)^(ORG-[A-Z]{2,4}([1-9][0-9]{0,5})?-[A-Z][A-Z0-9_-]*[A-Z0-9]|AUTO-[1-9][0-9]*([A-Z]{2,4})?)$"), "" +
"The 'ORG-' string followed by 2 to 4 characters, followed by up to 5 digits\n" +
"followed by a source specification. The first digit must not be \"0\".\n" +
"Source specification starts with \"-\" followed by source name up to\n" +
"9-character length.\n"
);
AttributeSyntax ORG_NAME_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^[\\]\\[A-Z0-9._\"*()@,&:!'`+\\/-]{1,64}( [\\]\\[A-Z0-9._\"*()@,&:!'`+\\/-]{1,64}){0,29}$"), "" +
"A list of words separated by white space. A word is made up of letters,\n" +
"digits, the character underscore \"_\", and the character hyphen \"-\";\n" +
"the first character of a word must be a letter or digit; the last\n" +
"character of a word must be a letter, digit or a dot.\n"
);
AttributeSyntax ORG_TYPE_SYNTAX = new OrgTypeSyntax();
AttributeSyntax PEER_SYNTAX = new AttributeSyntaxParser(new PeerParser(), "" +
"<protocol> <ipv4-address> <options>\n" +
"| <protocol> <inet-rtr-name> <options>\n" +
"| <protocol> <rtr-set-name> <options>\n" +
"| <protocol> <peering-set-name> <options>\n");
AttributeSyntax PEERING_SYNTAX = new AttributeSyntaxParser(new PeeringParser(), "" +
"<peering>\n");
AttributeSyntax PERSON_ROLE_NAME_SYNTAX = new PersonRoleSyntax();
AttributeSyntax POEM_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^POEM-[A-Z0-9][A-Z0-9_-]*$"), "" +
"POEM-<string>\n" +
"\n" +
"<string> can include alphanumeric characters, and \"_\" and\n" +
"\"-\" characters.\n"
);
AttributeSyntax POETIC_FORM_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^FORM-[A-Z0-9][A-Z0-9_-]*$"), "" +
"FORM-<string>\n" +
"\n" +
"<string> can include alphanumeric characters, and \"_\" and\n" +
"\"-\" characters.\n"
);
AttributeSyntax PINGABLE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.IPAddressParser());
AttributeSyntax PHONE_SYNTAX = new AttributeSyntaxRegexp(30,
Pattern.compile("" +
"(?i)^" +
"[+][0-9. -]+" + // "normal" phone numbers
"(?:[(][0-9. -]+[)][0-9. -]+)?" + // a possible '(123)' at the end
"(?:ext[.][0-9. -]+)?" + // a possible 'ext. 123' at the end
"$"), "" +
"Contact telephone number. Can take one of the forms:\n" +
"\n" +
"'+' <integer-list>\n" +
"'+' <integer-list> \"(\" <integer-list> \")\" <integer-list>\n" +
"'+' <integer-list> ext. <integer list>\n" +
"'+' <integer-list> \"(\" integer list \")\" <integer-list> ext. <integer-list>\n"
);
AttributeSyntax ROUTE_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RouteSetParser(), "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n");
AttributeSyntax RTR_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RtrSetParser(), "" +
"A router-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rtrs-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A router-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rtrs-\"). All the\n" +
"set name components of a hierarchical router-set name have\n" +
"to be router-set names.\n");
AttributeSyntax PEERING_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.PeeringSetParser(), "" +
"A peering-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"prng-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A peering-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"prng-\"). All the\n" +
"set name components of a hierarchical peering-set name have\n" +
"to be peering-set names.\n");
AttributeSyntax ROUTE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RouteResourceParser(), "" +
"An address prefix is represented as an IPv4 address followed\n" +
"by the character slash \"/\" followed by an integer in the\n" +
"range from 0 to 32. The following are valid address\n" +
"prefixes: 128.9.128.5/32, 128.9.0.0/16, 0.0.0.0/0; and the\n" +
"following address prefixes are invalid: 0/0, 128.9/16 since\n" +
"0 or 128.9 are not strings containing four integers.\n");
AttributeSyntax ROUTE6_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Route6ResourceParser(), "" +
"<ipv6-address>/<prefix>\n");
AttributeSyntax STATUS_SYNTAX = new StatusSyntax();
class AttributeSyntaxRegexp implements AttributeSyntax {
private final Integer maxLength;
private final Pattern matchPattern;
private final String description;
AttributeSyntaxRegexp(final Pattern matchPattern, final String description) {
this(null, matchPattern, description);
}
AttributeSyntaxRegexp(final Integer maxLength, final Pattern matchPattern, final String description) {
this.maxLength = maxLength;
this.matchPattern = matchPattern;
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
final boolean lengthOk = maxLength == null || value.length() <= maxLength;
final boolean matches = matchPattern.matcher(value).matches();
return lengthOk && matches;
}
@Override
public String getDescription(final ObjectType objectType) {
return description;
}
}
class AnySyntax implements AttributeSyntax {
private final String description;
public AnySyntax() {
this("");
}
public AnySyntax(final String description) {
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
return true;
}
@Override
public String getDescription(final ObjectType objectType) {
return description;
}
}
class RoutePrefixSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return IPV4_SYNTAX.matches(objectType, value);
case ROUTE6:
return IPV6_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case ROUTE:
return "" +
"An address prefix is represented as an IPv4 address followed\n" +
"by the character slash \"/\" followed by an integer in the\n" +
"range from 0 to 32. The following are valid address\n" +
"prefixes: 128.9.128.5/32, 128.9.0.0/16, 0.0.0.0/0; and the\n" +
"following address prefixes are invalid: 0/0, 128.9/16 since\n" +
"0 or 128.9 are not strings containing four integers.";
case ROUTE6:
return "" +
"<ipv6-address>/<prefix>";
default:
return "";
}
}
}
class GeolocSyntax implements AttributeSyntax {
private static final Pattern GEOLOC_PATTERN = Pattern.compile("^[+-]?(\\d*\\.?\\d+)\\s+[+-]?(\\d*\\.?\\d+)$");
private static final double LATITUDE_RANGE = 90.0;
private static final double LONGITUDE_RANGE = 180.0;
@Override
public boolean matches(final ObjectType objectType, final String value) {
final Matcher matcher = GEOLOC_PATTERN.matcher(value);
if (!matcher.matches()) {
return false;
}
if (Double.compare(LATITUDE_RANGE, Double.parseDouble(matcher.group(1))) < 0) {
return false;
}
if (Double.compare(LONGITUDE_RANGE, Double.parseDouble(matcher.group(2))) < 0) {
return false;
}
return true;
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"Location coordinates of the resource. Can take one of the following forms:\n" +
"\n" +
"[-90,90][-180,180]\n";
}
}
class MemberOfSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case AUT_NUM:
return AS_SET_SYNTAX.matches(objectType, value);
case ROUTE:
case ROUTE6:
return ROUTE_SET_SYNTAX.matches(objectType, value);
case INET_RTR:
return RTR_SET_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case AUT_NUM:
return "" +
"An as-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"as-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"An as-set name can also be hierarchical. A hierarchical set\n" +
"name is a sequence of set names and AS numbers separated by\n" +
"colons \":\". At least one component of such a name must be\n" +
"an actual set name (i.e. start with \"as-\"). All the set\n" +
"name components of a hierarchical as-name have to be as-set\n" +
"names.\n";
case ROUTE:
return "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n";
case ROUTE6:
return "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n";
case INET_RTR:
return "" +
"A router-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rtrs-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A router-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rtrs-\"). All the\n" +
"set name components of a hierarchical router-set name have\n" +
"to be router-set names.\n";
default:
return "";
}
}
}
class MembersSyntax implements AttributeSyntax {
private final boolean allowIpv6;
MembersSyntax(final boolean allowIpv6) {
this.allowIpv6 = allowIpv6;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case AS_SET:
final boolean asNumberSyntax = AS_NUMBER_SYNTAX.matches(objectType, value);
final boolean asSetSyntax = AS_SET_SYNTAX.matches(objectType, value);
return asNumberSyntax || asSetSyntax;
case ROUTE_SET:
if (ROUTE_SET_SYNTAX.matches(objectType, value)) {
return true;
}
if (AS_NUMBER_SYNTAX.matches(objectType, value) || AS_SET_SYNTAX.matches(objectType, value)) {
return true;
}
if (ADDRESS_PREFIX_RANGE_SYNTAX.matches(objectType, value)) {
final AddressPrefixRange apr = AddressPrefixRange.parse(value);
if ((apr.getIpInterval() instanceof Ipv4Resource) || (allowIpv6 && apr.getIpInterval() instanceof Ipv6Resource)) {
return true;
}
}
return validateRouteSetWithRange(objectType, value);
case RTR_SET:
return allowIpv6 && IPV6_SYNTAX.matches(objectType, value) ||
INET_RTR_SYNTAX.matches(objectType, value) ||
RTR_SET_SYNTAX.matches(objectType, value) ||
IPV4_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case AS_SET:
return "" +
"list of\n" +
"<as-number> or\n" +
"<as-set-name>\n";
case ROUTE_SET:
if (allowIpv6) {
return "" +
"list of\n" +
"<address-prefix-range> or\n" +
"<route-set-name> or\n" +
"<route-set-name><range-operator>.\n";
} else {
return "" +
"list of\n" +
"<ipv4-address-prefix-range> or\n" +
"<route-set-name> or\n" +
"<route-set-name><range-operator>.\n";
}
case RTR_SET:
return allowIpv6 ? "" +
"list of\n" +
"<inet-rtr-name> or\n" +
"<rtr-set-name> or\n" +
"<ipv4-address> or\n" +
"<ipv6-address>\n"
: "" +
"list of\n" +
"<inet-rtr-name> or\n" +
"<rtr-set-name> or\n" +
"<ipv4-address>\n";
default:
return "";
}
}
private boolean validateRouteSetWithRange(ObjectType objectType, String value) {
final int rangeOperationIdx = value.lastIndexOf('^');
if (rangeOperationIdx == -1) {
return false;
}
final String routeSet = value.substring(0, rangeOperationIdx);
final boolean routeSetSyntaxResult = ROUTE_SET_SYNTAX.matches(objectType, routeSet);
if (!routeSetSyntaxResult) {
return routeSetSyntaxResult;
}
final String rangeOperation = value.substring(rangeOperationIdx);
try {
RangeOperation.parse(rangeOperation, 0, 128);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
class OrgTypeSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
return OrgType.getFor(value) != null;
}
@Override
public String getDescription(final ObjectType objectType) {
final StringBuilder builder = new StringBuilder();
builder.append("org-type can have one of these values:\n\n");
for (final OrgType orgType : OrgType.values()) {
builder.append("o '")
.append(orgType)
.append("' ")
.append(orgType.getInfo())
.append("\n");
}
builder.append("\n");
return builder.toString();
}
}
class PersonRoleSyntax implements AttributeSyntax {
private static final Pattern PATTERN = Pattern.compile("(?i)^[A-Z][A-Z0-9\\\\.`'_-]{0,63}(?: [A-Z0-9\\\\.`'_-]{1,64}){0,9}$");
private static final Splitter SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();
@Override
public boolean matches(final ObjectType objectType, final String value) {
if (!PATTERN.matcher(value).matches()) {
return false;
}
int nrNamesStartingWithLetter = 0;
for (final String name : SPLITTER.split(value)) {
if (Character.isLetter(name.charAt(0))) {
nrNamesStartingWithLetter++;
if (nrNamesStartingWithLetter == 2) {
return true;
}
}
}
return false;
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"It should contain 2 to 10 words.\n" +
"Each word consists of letters, digits or the following symbols:\n" +
".`'_-\n" +
"The first word should begin with a letter.\n" +
"Max 64 characters can be used in each word.";
}
}
class StatusSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case INETNUM:
try {
InetnumStatus.getStatusFor(ciString(value));
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
case INET6NUM:
try {
Inet6numStatus.getStatusFor(ciString(value));
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
case AUT_NUM:
try {
AutnumStatus.valueOf(value.toUpperCase());
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
final StringBuilder descriptionBuilder = new StringBuilder();
descriptionBuilder.append("Status can have one of these values:\n\n");
switch (objectType) {
case INETNUM:
for (final InetnumStatus status : InetnumStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
case INET6NUM:
for (final Inet6numStatus status : Inet6numStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
case AUT_NUM:
for (final AutnumStatus status : AutnumStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
default:
return "";
}
}
}
class ComponentsSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new ComponentsParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new ComponentsR6Parser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"[ATOMIC] [[<filter>] [protocol <protocol> <filter> ...]]\n" +
"\n" +
"<protocol> is a routing routing protocol name such as\n" +
"BGP4, OSPF or RIP\n" +
"\n" +
"<filter> is a policy expression\n";
}
}
class ExportCompsSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new FilterParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new V6FilterParser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case ROUTE:
return "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"for more information.";
case ROUTE6:
return "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"and RPSLng I-D for more information.";
default:
return "";
}
}
}
class InjectSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new InjectParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new InjectR6Parser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"[at <router-expression>]\n" +
"[action <action>]\n" +
"[upon <condition>]\n";
}
}
class AttributeSyntaxParser implements AttributeSyntax {
private final AttributeParser attributeParser;
private final Documented description;
public AttributeSyntaxParser(final AttributeParser attributeParser) {
this(attributeParser, "");
}
public AttributeSyntaxParser(final AttributeParser attributeParser, final String description) {
this(attributeParser, new Single(description));
}
public AttributeSyntaxParser(final AttributeParser attributeParser, final Documented description) {
this.attributeParser = attributeParser;
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
try {
attributeParser.parse(value);
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return description.getDescription(objectType);
}
}
boolean matches(ObjectType objectType, String value);
}
| src/main/java/net/ripe/db/whois/common/rpsl/AttributeSyntax.java | package net.ripe.db.whois.common.rpsl;
import com.google.common.base.Splitter;
import net.ripe.db.whois.common.generated.AggrBndryParser;
import net.ripe.db.whois.common.generated.AggrMtdParser;
import net.ripe.db.whois.common.generated.ComponentsParser;
import net.ripe.db.whois.common.generated.ComponentsR6Parser;
import net.ripe.db.whois.common.generated.DefaultParser;
import net.ripe.db.whois.common.generated.ExportParser;
import net.ripe.db.whois.common.generated.ExportViaParser;
import net.ripe.db.whois.common.generated.FilterParser;
import net.ripe.db.whois.common.generated.IfaddrParser;
import net.ripe.db.whois.common.generated.ImportParser;
import net.ripe.db.whois.common.generated.ImportViaParser;
import net.ripe.db.whois.common.generated.InjectParser;
import net.ripe.db.whois.common.generated.InjectR6Parser;
import net.ripe.db.whois.common.generated.InterfaceParser;
import net.ripe.db.whois.common.generated.MpDefaultParser;
import net.ripe.db.whois.common.generated.MpExportParser;
import net.ripe.db.whois.common.generated.MpFilterParser;
import net.ripe.db.whois.common.generated.MpImportParser;
import net.ripe.db.whois.common.generated.MpPeerParser;
import net.ripe.db.whois.common.generated.MpPeeringParser;
import net.ripe.db.whois.common.generated.PeerParser;
import net.ripe.db.whois.common.generated.PeeringParser;
import net.ripe.db.whois.common.generated.V6FilterParser;
import net.ripe.db.whois.common.ip.Ipv4Resource;
import net.ripe.db.whois.common.ip.Ipv6Resource;
import net.ripe.db.whois.common.rpsl.attrs.AddressPrefixRange;
import net.ripe.db.whois.common.rpsl.attrs.AutnumStatus;
import net.ripe.db.whois.common.rpsl.attrs.Inet6numStatus;
import net.ripe.db.whois.common.rpsl.attrs.InetnumStatus;
import net.ripe.db.whois.common.rpsl.attrs.OrgType;
import net.ripe.db.whois.common.rpsl.attrs.RangeOperation;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.ripe.db.whois.common.domain.CIString.ciString;
// TODO: [AH] queries should NOT match AUTO- versions of keys, we should remove the AUTO- patterns from here
// TODO: [AH] fix capture groups (add '?:' where capture is not needed)
public interface AttributeSyntax extends Documented {
AttributeSyntax ANY_SYNTAX = new AnySyntax();
AttributeSyntax ADDRESS_PREFIX_RANGE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AddressPrefixRangeParser());
AttributeSyntax ALIAS_SYNTAX = new AttributeSyntaxRegexp(254,
Pattern.compile("(?i)^[A-Z0-9]([-A-Z0-9]*[A-Z0-9])?(\\.[A-Z0-9]([-A-Z0-9]*[A-Z0-9])?)*(\\.)?$"), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n"
);
AttributeSyntax AS_BLOCK_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AsBlockParser(), "" +
"<as-number> - <as-number>\n");
AttributeSyntax AS_NUMBER_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AutNumParser(), "" +
"An \"AS\" string followed by an integer in the range\n" +
"from 0 to 4294967295\n");
AttributeSyntax AS_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.AsSetParser(), "" +
"An as-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"as-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"An as-set name can also be hierarchical. A hierarchical set\n" +
"name is a sequence of set names and AS numbers separated by\n" +
"colons \":\". At least one component of such a name must be\n" +
"an actual set name (i.e. start with \"as-\"). All the set\n" +
"name components of a hierarchical as-name have to be as-set\n" +
"names.\n");
AttributeSyntax AGGR_BNDRY_SYNTAX = new AttributeSyntaxParser(new AggrBndryParser(), "" +
"[<as-expression>]\n");
AttributeSyntax AGGR_MTD_SYNTAX = new AttributeSyntaxParser(new AggrMtdParser(), "" +
"inbound | outbound [<as-expression>]\n");
AttributeSyntax AUTH_SCHEME_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^(MD5-PW \\$1\\$[A-Z0-9./]{1,8}\\$[A-Z0-9./]{22}|PGPKEY-[A-F0-9]{8}|SSO [-@.\\w]{1,90}|X509-[1-9][0-9]{0,19}|AUTO-[1-9][0-9]*)$"), "" +
"<auth-scheme> <scheme-info> Description\n" +
"\n" +
"MD5-PW encrypted We strongly advise phrases longer\n" +
" password, produced than 8 characters to be used,\n" +
" using the FreeBSD avoiding the use of words or\n" +
" crypt_md5 combinations of words found in any\n" +
" algorithm dictionary of any language.\n" +
"\n" +
"PGPKEY-<id> Strong scheme of authentication.\n" +
" <id> is the PGP key ID to be\n" +
" used for authentication. This string\n" +
" is the same one that is used in the\n" +
" corresponding key-cert object's\n" +
" \"key-cert:\" attribute.\n" +
"\n" +
"X509-<nnn> Strong scheme of authentication.\n" +
" <nnn> is the index number of the\n" +
" corresponding key-cert object's\n" +
" \"key-cert:\" attribute (X509-nnn).\n" +
"\n" +
"SSO username The username is the same as one used \n" +
" for a RIPE NCC Access account. This must \n" +
" be a valid username and is checked \n" +
" against the RIPE NCC Access user list.\n"
);
AttributeSyntax CERTIF_SYNTAX = new AnySyntax("" +
"The value of the public key should be supplied either using\n" +
"multiple \"certif:\" attributes, or in one \"certif:\"\n" +
"attribute. In the first case, this is easily done by\n" +
"exporting the key from your local key ring in ASCII armored\n" +
"format and prepending each line of the key with the string\n" +
"\"certif:\". In the second case, line continuation should be\n" +
"used to represent an ASCII armored format of the key. All\n" +
"the lines of the exported key must be included; also the\n" +
"begin and end markers and the empty line which separates the\n" +
"header from the key body.\n");
AttributeSyntax CHANGED_SYNTAX = new AttributeSyntaxParser(new AttributeParser.ChangedParser(), "" +
"An e-mail address as defined in RFC 2822, followed by a date\n" +
"in the format YYYYMMDD.\n");
AttributeSyntax COUNTRY_CODE_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^[a-z]{2}$"),
"Valid two-letter ISO 3166 country code.");
AttributeSyntax COMPONENTS_SYNTAX = new ComponentsSyntax();
AttributeSyntax DEFAULT_SYNTAX = new AttributeSyntaxParser(new DefaultParser(), "" +
"to <peering> [action <action>] [networks <filter>]");
AttributeSyntax DOMAIN_SYNTAX = new AttributeSyntaxParser(new AttributeParser.DomainParser(), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n");
AttributeSyntax DS_RDATA_SYNTAX = new AttributeSyntaxParser(new AttributeParser.DsRdataParser(), "" +
"<Keytag> <Algorithm> <Digest type> <Digest>\n" +
"\n" +
"Keytag is represented by an unsigned decimal integer (0-65535).\n" +
"\n" +
"Algorithm is represented by an unsigned decimal integer (0-255).\n" +
"\n" +
"Digest type is represented by a unsigned decimal integer (0-255).\n" +
"\n" +
"Digest is a digest in hexadecimal representation (case insensitive). Its length varies for various digest types.\n" +
"For digest type SHA-1 digest is represented by 20 octets (40 characters, plus possible spaces).\n" +
"\n" +
"For more details, see RFC4034.\n");
AttributeSyntax EMAIL_SYNTAX = new AttributeSyntaxRegexp(80, Pattern.compile("(?i)^.+@([^.]+[.])+[^.]+$"),
"An e-mail address as defined in RFC 2822.\n");
AttributeSyntax EXPORT_COMPS_SYNTAX = new ExportCompsSyntax();
AttributeSyntax EXPORT_SYNTAX = new AttributeSyntaxParser(new ExportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"to <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"to <peering-N> [action <action-N>]\n" +
"announce <filter>\n");
AttributeSyntax FILTER_SYNTAX = new AttributeSyntaxParser(new FilterParser(), "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"for more information.\n");
AttributeSyntax FILTER_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.FilterSetParser(), "" +
"A filter-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"fltr-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A filter-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"fltr-\"). All the\n" +
"set name components of a hierarchical filter-name have to be\n" +
"filter-set names.\n");
AttributeSyntax FREE_FORM_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?s)^.*$"), "" +
"A sequence of ASCII characters.\n");
AttributeSyntax GENERATED_SYNTAX = new AnySyntax("" +
"Attribute generated by server.");
AttributeSyntax GEOLOC_SYNTAX = new GeolocSyntax();
AttributeSyntax HOLES_SYNTAX = new RoutePrefixSyntax();
AttributeSyntax IMPORT_SYNTAX = new AttributeSyntaxParser(new ImportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"from <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"from <peering-N> [action <action-N>]\n" +
"accept <filter>\n");
AttributeSyntax INET_RTR_SYNTAX = new AttributeSyntaxRegexp(254,
Pattern.compile("(?i)^[A-Z0-9]([-_A-Z0-9]*[A-Z0-9])?(\\.[A-Z0-9]([-_A-Z0-9]*[A-Z0-9])?)*(\\.)?$"), "" +
"Domain name as specified in RFC 1034 (point 5.2.1.2) with or\n" +
"without trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n"
);
AttributeSyntax IFADDR_SYNTAX = new AttributeSyntaxParser(new IfaddrParser(), "" +
"<ipv4-address> masklen <integer> [action <action>]");
AttributeSyntax INJECT_SYNTAX = new InjectSyntax();
AttributeSyntax INTERFACE_SYNTAX = new AttributeSyntaxParser(new InterfaceParser(), "" +
"afi <afi> <ipv4-address> masklen <integer> [action <action>]\n" +
"afi <afi> <ipv6-address> masklen <integer> [action <action>]\n" +
" [tunnel <remote-endpoint-address>,<encapsulation>]\n");
AttributeSyntax IPV4_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Ipv4ResourceParser(), "" +
"<ipv4-address> - <ipv4-address>");
AttributeSyntax IPV6_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Ipv6ResourceParser(), "" +
"<ipv6-address>/<prefix>");
AttributeSyntax IRT_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^irt-[A-Z0-9_-]*[A-Z0-9]$"), "" +
"An irt name is made up of letters, digits, the character\n" +
"underscore \"_\", and the character hyphen \"-\"; it must start\n" +
"with \"irt-\", and the last character of a name must be a\n" +
"letter or a digit.\n");
AttributeSyntax KEY_CERT_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^(PGPKEY-[A-F0-9]{8})|(X509-[1-9][0-9]*)|(AUTO-[1-9][0-9]*)$"), "" +
"PGPKEY-<id>\n" +
"\n" +
"<id> is the PGP key ID of the public key in 8-digit\n" +
"hexadecimal format without \"0x\" prefix."
);
AttributeSyntax LANGUAGE_CODE_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("(?i)^[a-z]{2}$"), "" +
"Valid two-letter ISO 639-1 language code.\n");
AttributeSyntax MBRS_BY_REF_SYNTAX = new AnySyntax("" +
"<mntner-name> | ANY\n");
AttributeSyntax MEMBER_OF_SYNTAX = new MemberOfSyntax();
AttributeSyntax MEMBERS_SYNTAX = new MembersSyntax(false);
AttributeSyntax METHOD_SYNTAX = new AnySyntax("" +
"Currently, only PGP keys are supported.\n");
AttributeSyntax MNT_ROUTES_SYNTAX = new AttributeSyntaxParser(new AttributeParser.MntRoutesParser(), new Multiple(new HashMap<ObjectType, String>() {{
put(ObjectType.AUT_NUM, "<mnt-name> [ { list of (<ipv4-address>/<prefix> or <ipv6-address>/<prefix>) } | ANY ]\n");
put(ObjectType.INET6NUM, "<mnt-name> [ { list of <ipv6-address>/<prefix> } | ANY ]\n");
put(ObjectType.INETNUM, "<mnt-name> [ { list of <address-prefix-range> } | ANY ]\n");
put(ObjectType.ROUTE, "<mnt-name> [ { list of <address-prefix-range> } | ANY ]\n");
put(ObjectType.ROUTE6, "<mnt-name> [ { list of <ipv6-address>/<prefix> } | ANY ]\n");
}}));
AttributeSyntax MP_DEFAULT_SYNTAX = new AttributeSyntaxParser(new MpDefaultParser(), "" +
"to <peering> [action <action>] [networks <filter>]\n");
AttributeSyntax MP_EXPORT_SYNTAX = new AttributeSyntaxParser(new MpExportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"afi <afi-list>\n" +
"to <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"to <peering-N> [action <action-N>]\n" +
"announce <filter>\n");
AttributeSyntax EXPORT_VIA_SYNTAX = new AttributeSyntaxParser(new ExportViaParser(), "" +
"[protocol <protocol-1>] [into <protocol-2>] \n" +
"afi <afi-list>\n" +
"<peering-1>\n" +
"to <peering-2> [action <action-1>; <action-2>; ... <action-N>;]\n" +
" .\n" +
" .\n" +
" .\n" +
"<peering-3>\n" +
"to <peering-M> [action <action-1>; <action-2>; ... <action-N>;]\n" +
"announce <filter>\n");
AttributeSyntax MP_FILTER_SYNTAX = new AttributeSyntaxParser(new MpFilterParser(), "" +
"Logical expression which when applied to a set of multiprotocol\n" +
"routes returns a subset of these routes. Please refer to RPSLng\n" +
"Internet Draft for more information.\n");
AttributeSyntax MP_IMPORT_SYNTAX = new AttributeSyntaxParser(new MpImportParser(), "" +
"[protocol <protocol-1>] [into <protocol-1>]\n" +
"afi <afi-list>\n" +
"from <peering-1> [action <action-1>]\n" +
" .\n" +
" .\n" +
" .\n" +
"from <peering-N> [action <action-N>]\n" +
"accept (<filter>|<filter> except <importexpression>|\n" +
" <filter> refine <importexpression>)\n");
AttributeSyntax IMPORT_VIA_SYNTAX = new AttributeSyntaxParser(new ImportViaParser(), "" +
"[protocol <protocol-1>] [into <protocol-2>]\n" +
"afi <afi-list>\n" +
"<peering-1>\n" +
"from <peering-2> [action <action-1>; <action-2>; ... <action-N>;]\n" +
" .\n" +
" .\n" +
" .\n" +
"<peering-3>\n" +
"from <peering-M> [action <action-1>; <action-2>; ... <action-N>;]\n" +
"accept (<filter>|<filter> except <importexpression>|\n" +
" <filter> refine <importexpression>)\n");
AttributeSyntax MP_MEMBERS_SYNTAX = new MembersSyntax(true);
AttributeSyntax MP_PEER_SYNTAX = new AttributeSyntaxParser(new MpPeerParser(), new Multiple(new HashMap<ObjectType, String>() {{
put(ObjectType.INET_RTR, "" +
"<protocol> afi <afi> <ipv4- or ipv6- address> <options>\n" +
"| <protocol> <inet-rtr-name> <options>\n" +
"| <protocol> <rtr-set-name> <options>\n" +
"| <protocol> <peering-set-name> <options>\n");
put(ObjectType.PEERING_SET, "" +
"afi <afi> <peering>\n");
}}));
AttributeSyntax MP_PEERING_SYNTAX = new AttributeSyntaxParser(new MpPeeringParser(), "" +
"afi <afi> <peering>\n");
AttributeSyntax NETNAME_SYNTAX = new AttributeSyntaxRegexp(80, Pattern.compile("(?i)^[A-Z]([A-Z0-9_-]*[A-Z0-9])?$"), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a name\n" +
"must be a letter, and the last character of a name must be a\n" +
"letter or a digit.\n");
AttributeSyntax NIC_HANDLE_SYNTAX = new AttributeSyntaxRegexp(30, Pattern.compile("(?i)^([A-Z]{2,4}([1-9][0-9]{0,5})?(-[A-Z]{2,10})?|AUTO-[1-9][0-9]*([A-Z]{2,4})?)$"), "" +
"From 2 to 4 characters optionally followed by up to 6 digits\n" +
"optionally followed by a source specification. The first digit\n" +
"must not be \"0\". Source specification starts with \"-\" followed\n" +
"by source name up to 9-character length.\n");
AttributeSyntax NSERVER_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NServerParser(), "" +
"Nameserver name as specified in RFC 1034 with or without\n" +
"trailing dot (\".\"). The total length should not exceed\n" +
"254 characters (octets).\n" +
"\n" +
"The nameserver name may be optionally followed by IPv4 address\n" +
"in decimal dotted quad form (e.g. 192.0.2.1) or IPv6 address\n" +
"in lowercase canonical form (Section 2.2.1, RFC 4291).\n" +
"\n" +
"The nameserver name may be followed by an IP address only when\n" +
"the name is inside of the domain being delegated.\n");
AttributeSyntax NUMBER_SYNTAX = new AttributeSyntaxRegexp(Pattern.compile("^[0-9]+$"), "" +
"Specifies a numeric value.\n");
AttributeSyntax OBJECT_NAME_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NameParser(), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a name\n" +
"must be a letter, and the last character of a name must be a\n" +
"letter or a digit. The following words are reserved by\n" +
"RPSL, and they can not be used as names:\n" +
"\n" +
" any as-any rs-any peeras and or not atomic from to at\n" +
" action accept announce except refine networks into inbound\n" +
" outbound\n" +
"\n" +
"Names starting with certain prefixes are reserved for\n" + // TODO: [ES] implement per type
"certain object types. Names starting with \"as-\" are\n" +
"reserved for as set names. Names starting with \"rs-\" are\n" +
"reserved for route set names. Names starting with \"rtrs-\"\n" +
"are reserved for router set names. Names starting with\n" +
"\"fltr-\" are reserved for filter set names. Names starting\n" +
"with \"prng-\" are reserved for peering set names. Names\n" +
"starting with \"irt-\" are reserved for irt names.\n");
AttributeSyntax REFERRAL_SYNTAX = new AttributeSyntaxParser(new AttributeParser.NameParser());
AttributeSyntax SOURCE_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^[A-Z][A-Z0-9_-]*[A-Z0-9]$"), "" +
"Made up of letters, digits, the character underscore \"_\",\n" +
"and the character hyphen \"-\"; the first character of a\n" +
"registry name must be a letter, and the last character of a\n" +
"registry name must be a letter or a digit."
);
AttributeSyntax ORGANISATION_SYNTAX = new AttributeSyntaxRegexp(30,
Pattern.compile("(?i)^(ORG-[A-Z]{2,4}([1-9][0-9]{0,5})?-[A-Z][A-Z0-9_-]*[A-Z0-9]|AUTO-[1-9][0-9]*([A-Z]{2,4})?)$"), "" +
"The 'ORG-' string followed by 2 to 4 characters, followed by up to 5 digits\n" +
"followed by a source specification. The first digit must not be \"0\".\n" +
"Source specification starts with \"-\" followed by source name up to\n" +
"9-character length.\n"
);
AttributeSyntax ORG_NAME_SYNTAX = new AttributeSyntaxRegexp(
Pattern.compile("(?i)^[\\]\\[A-Z0-9._\"*()@,&:!'`+\\/-]{1,64}( [\\]\\[A-Z0-9._\"*()@,&:!'`+\\/-]{1,64}){0,29}$"), "" +
"A list of words separated by white space. A word is made up of letters,\n" +
"digits, the character underscore \"_\", and the character hyphen \"-\";\n" +
"the first character of a word must be a letter or digit; the last\n" +
"character of a word must be a letter, digit or a dot.\n"
);
AttributeSyntax ORG_TYPE_SYNTAX = new OrgTypeSyntax();
AttributeSyntax PEER_SYNTAX = new AttributeSyntaxParser(new PeerParser(), "" +
"<protocol> <ipv4-address> <options>\n" +
"| <protocol> <inet-rtr-name> <options>\n" +
"| <protocol> <rtr-set-name> <options>\n" +
"| <protocol> <peering-set-name> <options>\n");
AttributeSyntax PEERING_SYNTAX = new AttributeSyntaxParser(new PeeringParser(), "" +
"<peering>\n");
AttributeSyntax PERSON_ROLE_NAME_SYNTAX = new PersonRoleSyntax();
AttributeSyntax POEM_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^POEM-[A-Z0-9][A-Z0-9_-]*$"), "" +
"POEM-<string>\n" +
"\n" +
"<string> can include alphanumeric characters, and \"_\" and\n" +
"\"-\" characters.\n"
);
AttributeSyntax POETIC_FORM_SYNTAX = new AttributeSyntaxRegexp(80,
Pattern.compile("(?i)^FORM-[A-Z0-9][A-Z0-9_-]*$"), "" +
"FORM-<string>\n" +
"\n" +
"<string> can include alphanumeric characters, and \"_\" and\n" +
"\"-\" characters.\n"
);
AttributeSyntax PINGABLE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.IPAddressParser());
AttributeSyntax PHONE_SYNTAX = new AttributeSyntaxRegexp(30,
Pattern.compile("" +
"(?i)^" +
"[+][0-9. -]+" + // "normal" phone numbers
"(?:[(][0-9. -]+[)][0-9. -]+)?" + // a possible '(123)' at the end
"(?:ext[.][0-9. -]+)?" + // a possible 'ext. 123' at the end
"$"), "" +
"Contact telephone number. Can take one of the forms:\n" +
"\n" +
"'+' <integer-list>\n" +
"'+' <integer-list> \"(\" <integer-list> \")\" <integer-list>\n" +
"'+' <integer-list> ext. <integer list>\n" +
"'+' <integer-list> \"(\" integer list \")\" <integer-list> ext. <integer-list>\n"
);
AttributeSyntax ROUTE_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RouteSetParser(), "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n");
AttributeSyntax RTR_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RtrSetParser(), "" +
"A router-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rtrs-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A router-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rtrs-\"). All the\n" +
"set name components of a hierarchical router-set name have\n" +
"to be router-set names.\n");
AttributeSyntax PEERING_SET_SYNTAX = new AttributeSyntaxParser(new AttributeParser.PeeringSetParser(), "" +
"A peering-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"prng-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A peering-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"prng-\"). All the\n" +
"set name components of a hierarchical peering-set name have\n" +
"to be peering-set names.\n");
AttributeSyntax ROUTE_SYNTAX = new AttributeSyntaxParser(new AttributeParser.RouteResourceParser(), "" +
"An address prefix is represented as an IPv4 address followed\n" +
"by the character slash \"/\" followed by an integer in the\n" +
"range from 0 to 32. The following are valid address\n" +
"prefixes: 128.9.128.5/32, 128.9.0.0/16, 0.0.0.0/0; and the\n" +
"following address prefixes are invalid: 0/0, 128.9/16 since\n" +
"0 or 128.9 are not strings containing four integers.\n");
AttributeSyntax ROUTE6_SYNTAX = new AttributeSyntaxParser(new AttributeParser.Route6ResourceParser(), "" +
"<ipv6-address>/<prefix>\n");
AttributeSyntax STATUS_SYNTAX = new StatusSyntax();
class AttributeSyntaxRegexp implements AttributeSyntax {
private final Integer maxLength;
private final Pattern matchPattern;
private final String description;
AttributeSyntaxRegexp(final Pattern matchPattern, final String description) {
this(null, matchPattern, description);
}
AttributeSyntaxRegexp(final Integer maxLength, final Pattern matchPattern, final String description) {
this.maxLength = maxLength;
this.matchPattern = matchPattern;
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
final boolean lengthOk = maxLength == null || value.length() <= maxLength;
final boolean matches = matchPattern.matcher(value).matches();
return lengthOk && matches;
}
@Override
public String getDescription(final ObjectType objectType) {
return description;
}
}
class AnySyntax implements AttributeSyntax {
private final String description;
public AnySyntax() {
this("");
}
public AnySyntax(final String description) {
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
return true;
}
@Override
public String getDescription(final ObjectType objectType) {
return description;
}
}
class RoutePrefixSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return IPV4_SYNTAX.matches(objectType, value);
case ROUTE6:
return IPV6_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case ROUTE:
return "" +
"An address prefix is represented as an IPv4 address followed\n" +
"by the character slash \"/\" followed by an integer in the\n" +
"range from 0 to 32. The following are valid address\n" +
"prefixes: 128.9.128.5/32, 128.9.0.0/16, 0.0.0.0/0; and the\n" +
"following address prefixes are invalid: 0/0, 128.9/16 since\n" +
"0 or 128.9 are not strings containing four integers.";
case ROUTE6:
return "" +
"<ipv6-address>/<prefix>";
default:
return "";
}
}
}
class GeolocSyntax implements AttributeSyntax {
private static final Pattern GEOLOC_PATTERN = Pattern.compile("^[+-]?(\\d*\\.?\\d+)\\s+[+-]?(\\d*\\.?\\d+)$");
private static final double LATITUDE_RANGE = 90.0;
private static final double LONGITUDE_RANGE = 180.0;
@Override
public boolean matches(final ObjectType objectType, final String value) {
final Matcher matcher = GEOLOC_PATTERN.matcher(value);
if (!matcher.matches()) {
return false;
}
if (Double.compare(LATITUDE_RANGE, Double.parseDouble(matcher.group(1))) < 0) {
return false;
}
if (Double.compare(LONGITUDE_RANGE, Double.parseDouble(matcher.group(2))) < 0) {
return false;
}
return true;
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"Location coordinates of the resource. Can take one of the following forms:\n" +
"\n" +
"[-90,90][-180,180]\n";
}
}
class MemberOfSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case AUT_NUM:
return AS_SET_SYNTAX.matches(objectType, value);
case ROUTE:
case ROUTE6:
return ROUTE_SET_SYNTAX.matches(objectType, value);
case INET_RTR:
return RTR_SET_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case AUT_NUM:
return "" +
"An as-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"as-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"An as-set name can also be hierarchical. A hierarchical set\n" +
"name is a sequence of set names and AS numbers separated by\n" +
"colons \":\". At least one component of such a name must be\n" +
"an actual set name (i.e. start with \"as-\"). All the set\n" +
"name components of a hierarchical as-name have to be as-set\n" +
"names.\n";
case ROUTE:
return "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n";
case ROUTE6:
return "" +
"An route-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rs-\", and the last character of a name must\n" +
"be a letter or a digit.\n" +
"\n" +
"A route-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rs-\"). All the set\n" +
"name components of a hierarchical route-name have to be\n" +
"route-set names.\n";
case INET_RTR:
return "" +
"A router-set name is made up of letters, digits, the\n" +
"character underscore \"_\", and the character hyphen \"-\"; it\n" +
"must start with \"rtrs-\", and the last character of a name\n" +
"must be a letter or a digit.\n" +
"\n" +
"A router-set name can also be hierarchical. A hierarchical\n" +
"set name is a sequence of set names and AS numbers separated\n" +
"by colons \":\". At least one component of such a name must\n" +
"be an actual set name (i.e. start with \"rtrs-\"). All the\n" +
"set name components of a hierarchical router-set name have\n" +
"to be router-set names.\n";
default:
return "";
}
}
}
class MembersSyntax implements AttributeSyntax {
private final boolean allowIpv6;
MembersSyntax(final boolean allowIpv6) {
this.allowIpv6 = allowIpv6;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case AS_SET:
final boolean asNumberSyntax = AS_NUMBER_SYNTAX.matches(objectType, value);
final boolean asSetSyntax = AS_SET_SYNTAX.matches(objectType, value);
return asNumberSyntax || asSetSyntax;
case ROUTE_SET:
if (ROUTE_SET_SYNTAX.matches(objectType, value)) {
return true;
}
if (AS_NUMBER_SYNTAX.matches(objectType, value) || AS_SET_SYNTAX.matches(objectType, value)) {
return true;
}
if (ADDRESS_PREFIX_RANGE_SYNTAX.matches(objectType, value)) {
final AddressPrefixRange apr = AddressPrefixRange.parse(value);
if ((apr.getIpInterval() instanceof Ipv4Resource) || (allowIpv6 && apr.getIpInterval() instanceof Ipv6Resource)) {
return true;
}
}
return validateRouteSetWithRange(objectType, value);
case RTR_SET:
return allowIpv6 && IPV6_SYNTAX.matches(objectType, value) ||
INET_RTR_SYNTAX.matches(objectType, value) ||
RTR_SET_SYNTAX.matches(objectType, value) ||
IPV4_SYNTAX.matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case AS_SET:
return "" +
"list of\n" +
"<as-number> or\n" +
"<as-set-name>\n";
case ROUTE_SET:
if (allowIpv6) {
return "" +
"list of\n" +
"<address-prefix-range> or\n" +
"<route-set-name> or\n" +
"<route-set-name><range-operator>.\n";
} else {
return "" +
"list of\n" +
"<ipv4-address-prefix-range> or\n" +
"<route-set-name> or\n" +
"<route-set-name><range-operator>.\n";
}
case RTR_SET:
return allowIpv6 ? "" +
"list of\n" +
"<inet-rtr-name> or\n" +
"<rtr-set-name> or\n" +
"<ipv4-address> or\n" +
"<ipv6-address>\n"
: "" +
"list of\n" +
"<inet-rtr-name> or\n" +
"<rtr-set-name> or\n" +
"<ipv4-address>\n";
default:
return "";
}
}
private boolean validateRouteSetWithRange(ObjectType objectType, String value) {
final int rangeOperationIdx = value.lastIndexOf('^');
if (rangeOperationIdx == -1) {
return false;
}
final String routeSet = value.substring(0, rangeOperationIdx);
final boolean routeSetSyntaxResult = ROUTE_SET_SYNTAX.matches(objectType, routeSet);
if (!routeSetSyntaxResult) {
return routeSetSyntaxResult;
}
final String rangeOperation = value.substring(rangeOperationIdx);
try {
RangeOperation.parse(rangeOperation, 0, 128);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
class OrgTypeSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
return OrgType.getFor(value) != null;
}
@Override
public String getDescription(final ObjectType objectType) {
final StringBuilder builder = new StringBuilder();
builder.append("org-type can have one of these values:\n\n");
for (final OrgType orgType : OrgType.values()) {
builder.append("o '")
.append(orgType)
.append("' ")
.append(orgType.getInfo())
.append("\n");
}
builder.append("\n");
return builder.toString();
}
}
class PersonRoleSyntax implements AttributeSyntax {
private static final Pattern PATTERN = Pattern.compile("(?i)^[A-Z][A-Z0-9\\\\.`'_-]{0,63}(?: [A-Z0-9\\\\.`'_-]{1,64}){0,9}$");
private static final Splitter SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();
@Override
public boolean matches(final ObjectType objectType, final String value) {
if (!PATTERN.matcher(value).matches()) {
return false;
}
int nrNamesStartingWithLetter = 0;
for (final String name : SPLITTER.split(value)) {
if (Character.isLetter(name.charAt(0))) {
nrNamesStartingWithLetter++;
if (nrNamesStartingWithLetter == 2) {
return true;
}
}
}
return false;
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"Must have at least 2 words beginning with a letter.\n" +
"Each word consists of letters, digits and the following symbols:\n" +
" .`'_-\n" +
"The first word should begin with a letter.\n" +
"Max 64 characters can be used in each word.";
}
}
class StatusSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case INETNUM:
try {
InetnumStatus.getStatusFor(ciString(value));
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
case INET6NUM:
try {
Inet6numStatus.getStatusFor(ciString(value));
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
case AUT_NUM:
try {
AutnumStatus.valueOf(value.toUpperCase());
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
final StringBuilder descriptionBuilder = new StringBuilder();
descriptionBuilder.append("Status can have one of these values:\n\n");
switch (objectType) {
case INETNUM:
for (final InetnumStatus status : InetnumStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
case INET6NUM:
for (final Inet6numStatus status : Inet6numStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
case AUT_NUM:
for (final AutnumStatus status : AutnumStatus.values()) {
descriptionBuilder.append("o ").append(status).append('\n');
}
return descriptionBuilder.toString();
default:
return "";
}
}
}
class ComponentsSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new ComponentsParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new ComponentsR6Parser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"[ATOMIC] [[<filter>] [protocol <protocol> <filter> ...]]\n" +
"\n" +
"<protocol> is a routing routing protocol name such as\n" +
"BGP4, OSPF or RIP\n" +
"\n" +
"<filter> is a policy expression\n";
}
}
class ExportCompsSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new FilterParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new V6FilterParser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
switch (objectType) {
case ROUTE:
return "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"for more information.";
case ROUTE6:
return "" +
"Logical expression which when applied to a set of routes\n" +
"returns a subset of these routes. Please refer to RFC 2622\n" +
"and RPSLng I-D for more information.";
default:
return "";
}
}
}
class InjectSyntax implements AttributeSyntax {
@Override
public boolean matches(final ObjectType objectType, final String value) {
switch (objectType) {
case ROUTE:
return new AttributeSyntaxParser(new InjectParser()).matches(objectType, value);
case ROUTE6:
return new AttributeSyntaxParser(new InjectR6Parser()).matches(objectType, value);
default:
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return "" +
"[at <router-expression>]\n" +
"[action <action>]\n" +
"[upon <condition>]\n";
}
}
class AttributeSyntaxParser implements AttributeSyntax {
private final AttributeParser attributeParser;
private final Documented description;
public AttributeSyntaxParser(final AttributeParser attributeParser) {
this(attributeParser, "");
}
public AttributeSyntaxParser(final AttributeParser attributeParser, final String description) {
this(attributeParser, new Single(description));
}
public AttributeSyntaxParser(final AttributeParser attributeParser, final Documented description) {
this.attributeParser = attributeParser;
this.description = description;
}
@Override
public boolean matches(final ObjectType objectType, final String value) {
try {
attributeParser.parse(value);
return true;
} catch (IllegalArgumentException ignored) {
return false;
}
}
@Override
public String getDescription(final ObjectType objectType) {
return description.getDescription(objectType);
}
}
boolean matches(ObjectType objectType, String value);
}
| updated person, role syntax
| src/main/java/net/ripe/db/whois/common/rpsl/AttributeSyntax.java | updated person, role syntax | <ide><path>rc/main/java/net/ripe/db/whois/common/rpsl/AttributeSyntax.java
<ide> @Override
<ide> public String getDescription(final ObjectType objectType) {
<ide> return "" +
<del> "Must have at least 2 words beginning with a letter.\n" +
<del> "Each word consists of letters, digits and the following symbols:\n" +
<del> " .`'_-\n" +
<add> "It should contain 2 to 10 words.\n" +
<add> "Each word consists of letters, digits or the following symbols:\n" +
<add> ".`'_-\n" +
<ide> "The first word should begin with a letter.\n" +
<ide> "Max 64 characters can be used in each word.";
<del>
<ide> }
<ide> }
<ide> |
|
Java | agpl-3.0 | 8b032063654790675814be44f8cec2adb76a9ab7 | 0 | kuali/kc,geothomasp/kcmit,mukadder/kc,iu-uits-es/kc,iu-uits-es/kc,ColostateResearchServices/kc,mukadder/kc,geothomasp/kcmit,kuali/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,kuali/kc,ColostateResearchServices/kc,jwillia/kc-old1,jwillia/kc-old1,UniversityOfHawaiiORS/kc,jwillia/kc-old1,geothomasp/kcmit,mukadder/kc,geothomasp/kcmit,geothomasp/kcmit,iu-uits-es/kc,ColostateResearchServices/kc,UniversityOfHawaiiORS/kc | /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.questionnaire;
import static org.kuali.kra.infrastructure.Constants.MAPPING_BASIC;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.kra.bo.CoeusSubModule;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.printing.util.PrintingUtils;
import org.kuali.kra.proposaldevelopment.bo.AttachmentDataSource;
import org.kuali.kra.questionnaire.print.QuestionnairePrintingService;
import org.kuali.kra.questionnaire.question.Question;
import org.kuali.kra.service.VersioningService;
import org.kuali.kra.service.impl.VersioningServiceImpl;
import org.kuali.rice.kns.document.MaintenanceDocumentBase;
import org.kuali.rice.kns.web.struts.action.KualiMaintenanceDocumentAction;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.krad.exception.AuthorizationException;
import org.kuali.rice.krad.service.SequenceAccessorService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;
/*
* Big issue is that questionnairequestions and usages can't be included in xmldoccontent because maintframework - questions &
* usages are not defined in maint DD's 'maintsections'. Current work around is using KraMaintenanceDocument to make rice
* maintenance framework to think that QnQuestions & QnUsages are defined in maintenance section. So, they will be saved in
* xmldoccontent.
*
* The hierarchical nature of data and heavily depending on js also needs some manipulation, so make these a little
* complicated..
*/
/**
* This is the maintenance action class is for questionnaire.
*/
public class QuestionnaireMaintenanceDocumentAction extends KualiMaintenanceDocumentAction {
private static final Log LOG = LogFactory.getLog(QuestionnaireMaintenanceDocumentAction.class);
private static final String PCP = "#;#";
private static final String PQP = "#q#";
private static final String PUP = "#u#";
private static final String PFP = "#f#";
private static final ActionForward RESPONSE_ALREADY_HANDLED = null;
private static final String DOCUMENT_NUMBER = "documentNumber";
@Override
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject();
if (newQuestionnaire.getSequenceNumber() == null) {
newQuestionnaire.setSequenceNumber(1);
}
setupQuestionAndUsage(form);
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
newQuestionnaire.setFileName(qnForm.getTemplateFile().getFileName());
newQuestionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
}
qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
newQuestionnaire.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
ActionForward forward = super.save(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* set up question and usage data for JS to parse and create QnQuestion tree nodes and usage list items
*/
private void setupQuestionAndUsage(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject());
String questions = assembleQuestions(qnForm);
String usages = assembleUsages(questionnaire);
qnForm.setEditData(questions + PCP + usages);
}
private void checkAndSetAllQuestionsAreUpToDate(QuestionnaireMaintenanceForm qnForm) {
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject());
qnForm.setAllQuestionsAreUpToDate(checkIfAllQuestionsAreUpToDate(questionnaire));
}
private boolean checkIfAllQuestionsAreUpToDate(Questionnaire questionnaire) {
boolean retVal = true;
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (question.getQuestion() == null || !question.getQuestionRefIdFk().equals(question.getQuestion().getQuestionRefId())) {
question.refreshReferenceObject("question");
}
if( !("N".equals(getVersionedQuestion(question))) ) {
retVal = false;
break;
}
}
return retVal;
}
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
permissionCheckForDocHandler(form);
ActionForward forward = super.docHandler(mapping, form, request, response);
setupQuestionAndUsage(form);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* check if user has modify or view questionnaire permission.
*/
private void permissionCheckForDocHandler(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (!getQuestionnaireAuthorizationService().hasPermission(PermissionConstants.MODIFY_QUESTIONNAIRE)) {
if (!getQuestionnaireAuthorizationService().hasPermission(PermissionConstants.VIEW_QUESTIONNAIRE)) {
throw new AuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), "Edit/View", "Questionnaire");
}
else {
if (!qnForm.isReadOnly()) {
// if user only has VIEW_QUESTIONNAIRE permission
qnForm.setReadOnly(true);
}
}
}
}
/*
* loop thru qnquestion and assemble results. Also find the max questionnumber.
*/
private String getQuestionReturnResult(QuestionnaireMaintenanceForm questionnaireForm, Questionnaire questionnaire) {
Collections.sort(questionnaire.getQuestionnaireQuestions(), new QuestionnaireQuestionComparator());
String result = "parent-0";
List<QuestionnaireQuestion> remainQuestions = new ArrayList<QuestionnaireQuestion>();
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (!question.getParentQuestionNumber().equals(0)) {
remainQuestions.add((QuestionnaireQuestion) ObjectUtils.deepCopy(question));
}
}
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (question.getQuestionNumber() > questionnaireForm.getQuestionNumber()) {
questionnaireForm.setQuestionNumber(question.getQuestionNumber());
}
if (question.getParentQuestionNumber().equals(0)) {
result = result + PQP + getQnReturnfields(question);
String childrenResult = getChildrenQuestions(question, remainQuestions);
if (StringUtils.isNotBlank(childrenResult)) {
result = result + childrenResult;
}
}
}
questionnaireForm.setQuestionNumber(questionnaireForm.getQuestionNumber() + 1);
return result;
}
/*
* get all the questions data needed for JS to manipulate.
*/
private String assembleQuestions(QuestionnaireMaintenanceForm questionnaireForm) {
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) questionnaireForm.getDocument())
.getNewMaintainableObject().getDataObject();
questionnaireForm.setQuestionNumber(0);
return getQuestionReturnResult(questionnaireForm, questionnaire);
}
/*
* get the question properties related to response
*/
private String getQeustionResponse(Question question) {
// for 'lookup', there is no maxlength set up. so, use this field for lookup return type
String retString = "";
if (question.getQuestionTypeId().equals(new Integer(6))) {
String className = question.getLookupClass();
if(className!=null){
className = className.substring(className.lastIndexOf(".") + 1);
retString = className + PFP + question.getMaxAnswers() + PFP + getLookupReturnType(question.getLookupClass(), question.getLookupReturn()) ;
}
}
else {
retString = question.getDisplayedAnswers() + PFP + question.getMaxAnswers() + PFP + question.getAnswerMaxLength();
}
return retString;
}
/*
* get the lookup return field type if possible
* This will be passed in the 'maxlength' field, and js will use this to validate branching condition
*/
private String getLookupReturnType(String className, String lookReturn) {
String retVal = "0";
String lookupReturnType = "";
try {
lookupReturnType = Class.forName(className).getDeclaredField(lookReturn).getType().getSimpleName();
} catch (Exception e) {
}
if ("String".equals(lookupReturnType)) {
retVal= "5";
} else if ("Date".equals(lookupReturnType)) {
retVal= "4";
} else if ("Integer".equals(lookupReturnType) || "Long".equals(lookupReturnType)) {
retVal= "3";
}
return retVal;
}
/*
* get the children questions data
*/
private String getChildrenQuestions(QuestionnaireQuestion questionnaireQuestion, List<QuestionnaireQuestion> questionnaireQuestions) {
String result = "";
List<QuestionnaireQuestion> remainQuestions = new ArrayList<QuestionnaireQuestion>();
for (QuestionnaireQuestion question : questionnaireQuestions) {
if (question.getParentQuestionNumber().equals(questionnaireQuestion.getQuestionNumber())) {
result = result + PQP + getQnReturnfields(question);
String childrenResult = getChildrenQuestions(question, questionnaireQuestions);
if (StringUtils.isNotBlank(childrenResult)) {
result = result + childrenResult;
}
}
}
return result;
}
/*
* this method is to get the property from questionnairequestion and question and concatenate them with "#f#" as separator. This
* will be parsed by js to construct question node
*/
private String getQnReturnfields(QuestionnaireQuestion question) {
if (question.getQuestion() == null || !question.getQuestionRefIdFk().equals(question.getQuestion().getQuestionRefId())) {
question.refreshReferenceObject("question");
}
String desc = question.getQuestion().getQuestion();
if (desc.indexOf("\"") > 0) {
desc = desc.replace("\"", """);
}
return question.getQuestionnaireQuestionsId() + PFP + question.getQuestionRefIdFk() + PFP + question.getQuestionSeqNumber()
+ PFP + desc + PFP + question.getQuestion().getQuestionTypeId() + PFP + question.getQuestionNumber() + PFP
+ question.getCondition() + PFP + question.getConditionValue() + PFP + question.getParentQuestionNumber() + PFP
+ question.getQuestion().getSequenceNumber() + PFP + getQeustionResponse(question.getQuestion()) + PFP
+ question.getVersionNumber() + PFP + (question.getConditionFlag() ? "Y" : "N") + PFP + getVersionedQuestion(question)+
PFP+question.getRuleId();
}
@SuppressWarnings("unchecked")
private String getVersionedQuestion(QuestionnaireQuestion qnQuestion) {
String results = "N";
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("questionId", qnQuestion.getQuestion().getQuestionId());
Question question = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, fieldValues, "sequenceNumber", false)).get(0);
if (!question.getSequenceNumber().equals(qnQuestion.getQuestion().getSequenceNumber())) {
results = question.getQuestionRefId().toString();
}
return results;
}
/*
* Create a concatenated usage properties string.
*/
private String assembleUsages(Questionnaire questionnaire) {
String result = "";
for (QuestionnaireUsage questionnaireUsage : questionnaire.getQuestionnaireUsages()) {
// get the module description
questionnaireUsage.refresh();
String moduleDescription = questionnaireUsage.getCoeusModule() != null ? questionnaireUsage.getCoeusModule().getDescription() : "";
// get the sub module description
CoeusSubModule subModule = getSubModule(questionnaireUsage.getModuleItemCode(), questionnaireUsage.getModuleSubItemCode());
String subModuleDescription = subModule != null ? subModule.getDescription() : "";
result = result + questionnaireUsage.getQuestionnaireUsageId() + PFP + questionnaireUsage.getModuleItemCode() + PFP
+ questionnaireUsage.getQuestionnaireLabel() + PFP + questionnaireUsage.getQuestionnaireSequenceNumber() + PFP
+ questionnaireUsage.getModuleSubItemCode() + PFP + questionnaireUsage.getRuleId() + PFP
+ questionnaireUsage.getVersionNumber() + PFP + (questionnaireUsage.isMandatory() ? "Y" : "N") + PFP
+ moduleDescription + PFP + subModuleDescription + PUP;
}
if (StringUtils.isNotBlank(result)) {
result = result.substring(0, result.length() - 3);
}
return result;
}
private CoeusSubModule getSubModule(String moduleCode, String subModuleCode) {
CoeusSubModule retVal = null;
List<CoeusSubModule> subModules = new ArrayList<CoeusSubModule>();
Map<String, Object> fieldValues = new HashMap<String, Object>();
fieldValues.put("moduleCode", moduleCode);
fieldValues.put("subModuleCode", subModuleCode);
subModules.addAll(getBusinessObjectService().findMatching(CoeusSubModule.class, fieldValues));
if(!subModules.isEmpty()) {
retVal = subModules.get(0);
}
return retVal;
}
@Override
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = super.edit(mapping, form, request, response);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (qnForm.isReadOnly()) {
// if (!(qnnrs.isEmpty()) && !KraServiceLocator.getService(DocumentService.class).documentExists(request.getParameter("docId"))) {
// we are responding to a 'view' action for an approved questionnaire
// qnForm.getDocInfo().get(1).setDisplayValue("Final");
//docStatus.setDisplayValue("Final");
qnForm.getDocument().getDocumentHeader().setDocumentDescription("questionnaire - bootstrap data");
}
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
Questionnaire oldQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getOldMaintainableObject().getDataObject();
versionQuestionnaire(questionnaire, oldQuestionnaire);
Long questionnaireRefId = KraServiceLocator.getService(SequenceAccessorService.class).getNextAvailableSequenceNumber(
"SEQ_QUESTIONNAIRE_REF_ID");
questionnaire.setQuestionnaireRefIdFromLong(questionnaireRefId);
// inherit from previous version when start editing
// questionnaire.setIsFinal(false);
oldQuestionnaire.setQuestionnaireRefIdFromLong(questionnaireRefId);
String questions = assembleQuestions(qnForm);
String usages = assembleUsages(((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject()));
qnForm.setEditData(questions + PCP + usages);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getMaintenanceAction().equals(
KRADConstants.MAINTENANCE_COPY_ACTION)) {
preRouteCopy(form);
}
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
// ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
// .setIsFinal(true);
setupQuestionAndUsage(form);
qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
ActionForward forward = super.route(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getMaintenanceAction().equals(
KRADConstants.MAINTENANCE_COPY_ACTION)) {
preRouteCopy(form);
}
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
// ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
// .setIsFinal(true);
setupQuestionAndUsage(form);
ActionForward forward = super.blanketApprove(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* For 'copy' action : create the copied questionnaire
*/
private void preRouteCopy(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Map fieldValues = new HashMap<String, Object>();
fieldValues.put("questionnaireRefId", ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getOldMaintainableObject().getDataObject()).getQuestionnaireRefId());
Questionnaire oldQuestionnaire = (Questionnaire) getBusinessObjectService().findByPrimaryKey(Questionnaire.class,
fieldValues);
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
KraServiceLocator.getService(QuestionnaireService.class).copyQuestionnaire(oldQuestionnaire, questionnaire);
questionnaire.setSequenceNumber(1); // just in case
}
/*
* Create new version of questionnaire
*/
private void versionQuestionnaire(Questionnaire questionnaire, Questionnaire oldQuestionnaire) {
try {
VersioningService versionService = new VersioningServiceImpl();
Questionnaire newQuestionnaire = (Questionnaire) versionService.createNewVersion(oldQuestionnaire);
questionnaire.setQuestionnaireRefId(null);
questionnaire.setSequenceNumber(newQuestionnaire.getSequenceNumber());
for (QuestionnaireQuestion qnaireQuestion : questionnaire.getQuestionnaireQuestions()) {
qnaireQuestion.setQuestionnaireRefIdFk(null);
qnaireQuestion.setQuestionnaireQuestionsId(null);
}
for (QuestionnaireUsage qnaireUsage : questionnaire.getQuestionnaireUsages()) {
qnaireUsage.setQuestionnaireUsageId(null);
qnaireUsage.setQuestionnaireRefIdFk(null);
}
questionnaire.setDocumentNumber("");
}
catch (Exception e) {
}
}
@Override
public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = super.start(mapping, form, request, response);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (qnForm.getMaintenanceAction().equals(KRADConstants.MAINTENANCE_NEW_ACTION)
&& ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.getSequenceNumber() == null) {
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setSequenceNumber(1);
}
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward close(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
if (buttonClicked != null && ConfirmationQuestion.YES.equals(buttonClicked)) {
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject());
questionnaire.setQuestionnaireUsages(qnForm.getQuestionnaireUsages());
setupQuestionAndUsage(qnForm);
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
questionnaire.setFileName(qnForm.getTemplateFile().getFileName());
questionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
}
}
forward = super.close(mapping, form, request, response);
if (buttonClicked == null || ConfirmationQuestion.NO.equals(buttonClicked)) {
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject();
qnForm.setQuestionnaireUsages(questionnaire.getQuestionnaireUsages());
// also need to save usages data in form to be restored if 'yes' is clicked
// this is processed twice, so questionnaireUsage will be reset in qnform.reset
// that's why we need to save this for restoration later
questionnaire.setQuestionnaireUsages(new ArrayList<QuestionnaireUsage>());
}
return forward;
}
/**
*
* This method is to print Questionnaire
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward printQuestionnaire(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO : this is only available after questionnaire is saved ?
ActionForward forward = mapping.findForward(MAPPING_BASIC);
Map<String, Object> reportParameters = new HashMap<String, Object>();
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
reportParameters.put("documentNumber", qnForm.getDocument().getDocumentNumber());
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject());
reportParameters.put("questionnaireId", questionnaire.getQuestionnaireIdAsInteger());
if (qnForm.getTemplateFile() != null && qnForm.getTemplateFile().getFileData().length > 0) {
reportParameters.put("template", qnForm.getTemplateFile().getFileData());
} else {
reportParameters.put("template", questionnaire.getTemplate());
}
// TODO : this is not a transaction document, so set to null ?
AttachmentDataSource dataStream = getQuestionnairePrintingService().printQuestionnaire(null, reportParameters);
if (dataStream.getContent() != null) {
PrintingUtils.streamToResponse(dataStream, response);
forward = null;
}
return forward;
}
public ActionForward addTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
questionnaire.setFileName(qnForm.getTemplateFile().getFileName());
questionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward viewTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
this.streamToResponse(qnForm.getTemplateFile().getFileData(), qnForm.getTemplateFile().getFileName(),
Constants.CORRESPONDENCE_TEMPLATE_CONTENT_TYPE_1, response);
} else {
this.streamToResponse(questionnaire.getTemplate(), questionnaire.getFileName(),
Constants.CORRESPONDENCE_TEMPLATE_CONTENT_TYPE_1, response);
}
return RESPONSE_ALREADY_HANDLED;
}
public ActionForward deleteTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
questionnaire.setFileName(null);
questionnaire.setTemplate(null);
qnForm.setTemplateFile(null);
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward getSubModuleCodeList(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward("ajaxQuestionnaire");
}
public ActionForward getQuestionMaintainTable(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (StringUtils.isNotBlank(qnForm.getQuestionId())) {
Map pkMap = new HashMap();
pkMap.put("questionRefId", qnForm.getQuestionId());
qnForm.setQuestion((Question)getBusinessObjectService().findByPrimaryKey(Question.class, pkMap));
//lets check for a more current version
pkMap.clear();
pkMap.put("questionId", qnForm.getQuestion().getQuestionId());
List<Question> questions = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, pkMap, "sequenceNumber", false));
if (CollectionUtils.isNotEmpty(questions)) {
if (!StringUtils.equals(questions.get(0).getQuestionRefId().toString(), qnForm.getQuestionId())) {
qnForm.setQuestionCurrentVersion(false);
}
}
}
return mapping.findForward("ajaxQuestionMaintainTable");
}
public ActionForward getQuestionCurrentVersion(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (StringUtils.isNotBlank(qnForm.getQuestionId())) {
Map pkMap = new HashMap();
pkMap.put("questionRefId", qnForm.getQuestionId());
Question oldQ = (Question)getBusinessObjectService().findByPrimaryKey(Question.class, pkMap);
if (oldQ != null) {
pkMap.clear();
pkMap.put("questionId", oldQ.getQuestionId());
List<Question> questions = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, pkMap, "sequenceNumber", false));
if (CollectionUtils.isNotEmpty(questions)) {
qnForm.setQuestion(questions.get(0));
}
}
}
return mapping.findForward("ajaxQuestionCurrentVersion");
}
private QuestionnaireAuthorizationService getQuestionnaireAuthorizationService() {
return KraServiceLocator.getService(QuestionnaireAuthorizationService.class);
}
private QuestionnairePrintingService getQuestionnairePrintingService() {
return KraServiceLocator.getService(QuestionnairePrintingService.class);
}
@Override
protected void populateAuthorizationFields(KualiDocumentFormBase formBase){
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) formBase;
// for 'view' questionnaire. which is using 'edit.
boolean isReadOnly = qnForm.isReadOnly();
// populateAuthorizationFields will override the isReadOnly property of the form. if it is 'view'
super.populateAuthorizationFields(formBase);
if (isReadOnly && StringUtils.equals(qnForm.getMethodToCall(), "edit")) {
qnForm.setReadOnly(isReadOnly);
}
if (qnForm.isReadOnly() && formBase.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_CAN_CLOSE)) {
Map<String, String> documentActions = new HashMap<String, String>();
documentActions.put(KRADConstants.KUALI_ACTION_CAN_CLOSE, "TRUE");
qnForm.setDocumentActions(documentActions);
}
}
}
| src/main/java/org/kuali/kra/questionnaire/QuestionnaireMaintenanceDocumentAction.java | /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.questionnaire;
import static org.kuali.kra.infrastructure.Constants.MAPPING_BASIC;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.kra.bo.CoeusSubModule;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.printing.util.PrintingUtils;
import org.kuali.kra.proposaldevelopment.bo.AttachmentDataSource;
import org.kuali.kra.questionnaire.print.QuestionnairePrintingService;
import org.kuali.kra.questionnaire.question.Question;
import org.kuali.kra.service.VersioningService;
import org.kuali.kra.service.impl.VersioningServiceImpl;
import org.kuali.rice.kns.document.MaintenanceDocumentBase;
import org.kuali.rice.kns.web.struts.action.KualiMaintenanceDocumentAction;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.krad.exception.AuthorizationException;
import org.kuali.rice.krad.service.SequenceAccessorService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;
/*
* Big issue is that questionnairequestions and usages can't be included in xmldoccontent because maintframework - questions &
* usages are not defined in maint DD's 'maintsections'. Current work around is using KraMaintenanceDocument to make rice
* maintenance framework to think that QnQuestions & QnUsages are defined in maintenance section. So, they will be saved in
* xmldoccontent.
*
* The hierarchical nature of data and heavily depending on js also needs some manipulation, so make these a little
* complicated..
*/
/**
* This is the maintenance action class is for questionnaire.
*/
public class QuestionnaireMaintenanceDocumentAction extends KualiMaintenanceDocumentAction {
private static final Log LOG = LogFactory.getLog(QuestionnaireMaintenanceDocumentAction.class);
private static final String PCP = "#;#";
private static final String PQP = "#q#";
private static final String PUP = "#u#";
private static final String PFP = "#f#";
private static final ActionForward RESPONSE_ALREADY_HANDLED = null;
private static final String DOCUMENT_NUMBER = "documentNumber";
@Override
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject();
if (newQuestionnaire.getSequenceNumber() == null) {
newQuestionnaire.setSequenceNumber(1);
}
setupQuestionAndUsage(form);
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
newQuestionnaire.setFileName(qnForm.getTemplateFile().getFileName());
newQuestionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
}
qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
newQuestionnaire.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
ActionForward forward = super.save(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* set up question and usage data for JS to parse and create QnQuestion tree nodes and usage list items
*/
private void setupQuestionAndUsage(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject());
String questions = assembleQuestions(qnForm);
String usages = assembleUsages(questionnaire);
qnForm.setEditData(questions + PCP + usages);
}
private void checkAndSetAllQuestionsAreUpToDate(QuestionnaireMaintenanceForm qnForm) {
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject());
qnForm.setAllQuestionsAreUpToDate(checkIfAllQuestionsAreUpToDate(questionnaire));
}
private boolean checkIfAllQuestionsAreUpToDate(Questionnaire questionnaire) {
boolean retVal = true;
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (question.getQuestion() == null || !question.getQuestionRefIdFk().equals(question.getQuestion().getQuestionRefId())) {
question.refreshReferenceObject("question");
}
if( !("N".equals(getVersionedQuestion(question))) ) {
retVal = false;
break;
}
}
return retVal;
}
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
permissionCheckForDocHandler(form);
ActionForward forward = super.docHandler(mapping, form, request, response);
setupQuestionAndUsage(form);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* check if user has modify or view questionnaire permission.
*/
private void permissionCheckForDocHandler(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (!getQuestionnaireAuthorizationService().hasPermission(PermissionConstants.MODIFY_QUESTIONNAIRE)) {
if (!getQuestionnaireAuthorizationService().hasPermission(PermissionConstants.VIEW_QUESTIONNAIRE)) {
throw new AuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), "Edit/View", "Questionnaire");
}
else {
if (!qnForm.isReadOnly()) {
// if user only has VIEW_QUESTIONNAIRE permission
qnForm.setReadOnly(true);
}
}
}
}
/*
* loop thru qnquestion and assemble results. Also find the max questionnumber.
*/
private String getQuestionReturnResult(QuestionnaireMaintenanceForm questionnaireForm, Questionnaire questionnaire) {
Collections.sort(questionnaire.getQuestionnaireQuestions(), new QuestionnaireQuestionComparator());
String result = "parent-0";
List<QuestionnaireQuestion> remainQuestions = new ArrayList<QuestionnaireQuestion>();
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (!question.getParentQuestionNumber().equals(0)) {
remainQuestions.add((QuestionnaireQuestion) ObjectUtils.deepCopy(question));
}
}
for (QuestionnaireQuestion question : questionnaire.getQuestionnaireQuestions()) {
if (question.getQuestionNumber() > questionnaireForm.getQuestionNumber()) {
questionnaireForm.setQuestionNumber(question.getQuestionNumber());
}
if (question.getParentQuestionNumber().equals(0)) {
result = result + PQP + getQnReturnfields(question);
String childrenResult = getChildrenQuestions(question, remainQuestions);
if (StringUtils.isNotBlank(childrenResult)) {
result = result + childrenResult;
}
}
}
questionnaireForm.setQuestionNumber(questionnaireForm.getQuestionNumber() + 1);
return result;
}
/*
* get all the questions data needed for JS to manipulate.
*/
private String assembleQuestions(QuestionnaireMaintenanceForm questionnaireForm) {
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) questionnaireForm.getDocument())
.getNewMaintainableObject().getDataObject();
questionnaireForm.setQuestionNumber(0);
return getQuestionReturnResult(questionnaireForm, questionnaire);
}
/*
* get the question properties related to response
*/
private String getQeustionResponse(Question question) {
// for 'lookup', there is no maxlength set up. so, use this field for lookup return type
String retString = "";
if (question.getQuestionTypeId().equals(new Integer(6))) {
String className = question.getLookupClass();
if(className!=null){
className = className.substring(className.lastIndexOf(".") + 1);
retString = className + PFP + question.getMaxAnswers() + PFP + getLookupReturnType(question.getLookupClass(), question.getLookupReturn()) ;
}
}
else {
retString = question.getDisplayedAnswers() + PFP + question.getMaxAnswers() + PFP + question.getAnswerMaxLength();
}
return retString;
}
/*
* get the lookup return field type if possible
* This will be passed in the 'maxlength' field, and js will use this to validate branching condition
*/
private String getLookupReturnType(String className, String lookReturn) {
String retVal = "0";
String lookupReturnType = "";
try {
lookupReturnType = Class.forName(className).getDeclaredField(lookReturn).getType().getSimpleName();
} catch (Exception e) {
}
if ("String".equals(lookupReturnType)) {
retVal= "5";
} else if ("Date".equals(lookupReturnType)) {
retVal= "4";
} else if ("Integer".equals(lookupReturnType) || "Long".equals(lookupReturnType)) {
retVal= "3";
}
return retVal;
}
/*
* get the children questions data
*/
private String getChildrenQuestions(QuestionnaireQuestion questionnaireQuestion, List<QuestionnaireQuestion> questionnaireQuestions) {
String result = "";
List<QuestionnaireQuestion> remainQuestions = new ArrayList<QuestionnaireQuestion>();
for (QuestionnaireQuestion question : questionnaireQuestions) {
if (question.getParentQuestionNumber().equals(questionnaireQuestion.getQuestionNumber())) {
result = result + PQP + getQnReturnfields(question);
String childrenResult = getChildrenQuestions(question, questionnaireQuestions);
if (StringUtils.isNotBlank(childrenResult)) {
result = result + childrenResult;
}
}
}
return result;
}
/*
* this method is to get the property from questionnairequestion and question and concatenate them with "#f#" as separator. This
* will be parsed by js to construct question node
*/
private String getQnReturnfields(QuestionnaireQuestion question) {
if (question.getQuestion() == null || !question.getQuestionRefIdFk().equals(question.getQuestion().getQuestionRefId())) {
question.refreshReferenceObject("question");
}
String desc = question.getQuestion().getQuestion();
if (desc.indexOf("\"") > 0) {
desc = desc.replace("\"", """);
}
return question.getQuestionnaireQuestionsId() + PFP + question.getQuestionRefIdFk() + PFP + question.getQuestionSeqNumber()
+ PFP + desc + PFP + question.getQuestion().getQuestionTypeId() + PFP + question.getQuestionNumber() + PFP
+ question.getCondition() + PFP + question.getConditionValue() + PFP + question.getParentQuestionNumber() + PFP
+ question.getQuestion().getSequenceNumber() + PFP + getQeustionResponse(question.getQuestion()) + PFP
+ question.getVersionNumber() + PFP + (question.getConditionFlag() ? "Y" : "N") + PFP + getVersionedQuestion(question)+
PFP+question.getRuleId();
}
@SuppressWarnings("unchecked")
private String getVersionedQuestion(QuestionnaireQuestion qnQuestion) {
String results = "N";
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("questionId", qnQuestion.getQuestion().getQuestionId());
Question question = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, fieldValues, "sequenceNumber", false)).get(0);
if (!question.getSequenceNumber().equals(qnQuestion.getQuestion().getSequenceNumber())) {
results = question.getQuestionRefId().toString();
}
return results;
}
/*
* Create a concatenated usage properties string.
*/
private String assembleUsages(Questionnaire questionnaire) {
String result = "";
for (QuestionnaireUsage questionnaireUsage : questionnaire.getQuestionnaireUsages()) {
// get the module description
questionnaireUsage.refresh();
String moduleDescription = questionnaireUsage.getCoeusModule() != null ? questionnaireUsage.getCoeusModule().getDescription() : "";
// get the sub module description
CoeusSubModule subModule = getSubModule(questionnaireUsage.getModuleItemCode(), questionnaireUsage.getModuleSubItemCode());
String subModuleDescription = subModule != null ? subModule.getDescription() : "";
result = result + questionnaireUsage.getQuestionnaireUsageId() + PFP + questionnaireUsage.getModuleItemCode() + PFP
+ questionnaireUsage.getQuestionnaireLabel() + PFP + questionnaireUsage.getQuestionnaireSequenceNumber() + PFP
+ questionnaireUsage.getModuleSubItemCode() + PFP + questionnaireUsage.getRuleId() + PFP
+ questionnaireUsage.getVersionNumber() + PFP + (questionnaireUsage.isMandatory() ? "Y" : "N") + PFP
+ moduleDescription + PFP + subModuleDescription + PUP;
}
if (StringUtils.isNotBlank(result)) {
result = result.substring(0, result.length() - 3);
}
return result;
}
private CoeusSubModule getSubModule(String moduleCode, String subModuleCode) {
CoeusSubModule retVal = null;
List<CoeusSubModule> subModules = new ArrayList<CoeusSubModule>();
Map<String, Object> fieldValues = new HashMap<String, Object>();
fieldValues.put("moduleCode", moduleCode);
fieldValues.put("subModuleCode", subModuleCode);
subModules.addAll(getBusinessObjectService().findMatching(CoeusSubModule.class, fieldValues));
if(!subModules.isEmpty()) {
retVal = subModules.get(0);
}
return retVal;
}
@Override
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = super.edit(mapping, form, request, response);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (qnForm.isReadOnly()) {
// if (!(qnnrs.isEmpty()) && !KraServiceLocator.getService(DocumentService.class).documentExists(request.getParameter("docId"))) {
// we are responding to a 'view' action for an approved questionnaire
// qnForm.getDocInfo().get(1).setDisplayValue("Final");
//docStatus.setDisplayValue("Final");
qnForm.getDocument().getDocumentHeader().setDocumentDescription("questionnaire - bootstrap data");
}
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
Questionnaire oldQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getOldMaintainableObject().getDataObject();
versionQuestionnaire(questionnaire, oldQuestionnaire);
Long questionnaireRefId = KraServiceLocator.getService(SequenceAccessorService.class).getNextAvailableSequenceNumber(
"SEQ_QUESTIONNAIRE_REF_ID");
questionnaire.setQuestionnaireRefIdFromLong(questionnaireRefId);
// inherit from previous version when start editing
// questionnaire.setIsFinal(false);
oldQuestionnaire.setQuestionnaireRefIdFromLong(questionnaireRefId);
String questions = assembleQuestions(qnForm);
String usages = assembleUsages(((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject()));
qnForm.setEditData(questions + PCP + usages);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getMaintenanceAction().equals(
KRADConstants.MAINTENANCE_COPY_ACTION)) {
preRouteCopy(form);
}
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
// ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
// .setIsFinal(true);
setupQuestionAndUsage(form);
qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
ActionForward forward = super.route(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getMaintenanceAction().equals(
KRADConstants.MAINTENANCE_COPY_ACTION)) {
preRouteCopy(form);
}
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
// ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
// .setIsFinal(true);
setupQuestionAndUsage(form);
ActionForward forward = super.blanketApprove(mapping, form, request, response);
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
/*
* For 'copy' action : create the copied questionnaire
*/
private void preRouteCopy(ActionForm form) {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Map fieldValues = new HashMap<String, Object>();
fieldValues.put("questionnaireRefId", ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getOldMaintainableObject().getDataObject()).getQuestionnaireRefId());
Questionnaire oldQuestionnaire = (Questionnaire) getBusinessObjectService().findByPrimaryKey(Questionnaire.class,
fieldValues);
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
KraServiceLocator.getService(QuestionnaireService.class).copyQuestionnaire(oldQuestionnaire, questionnaire);
questionnaire.setSequenceNumber(1); // just in case
}
/*
* Create new version of questionnaire
*/
private void versionQuestionnaire(Questionnaire questionnaire, Questionnaire oldQuestionnaire) {
try {
VersioningService versionService = new VersioningServiceImpl();
Questionnaire newQuestionnaire = (Questionnaire) versionService.createNewVersion(oldQuestionnaire);
questionnaire.setQuestionnaireRefId(null);
questionnaire.setSequenceNumber(newQuestionnaire.getSequenceNumber());
for (QuestionnaireQuestion qnaireQuestion : questionnaire.getQuestionnaireQuestions()) {
qnaireQuestion.setQuestionnaireRefIdFk(null);
qnaireQuestion.setQuestionnaireQuestionsId(null);
}
for (QuestionnaireUsage qnaireUsage : questionnaire.getQuestionnaireUsages()) {
qnaireUsage.setQuestionnaireUsageId(null);
qnaireUsage.setQuestionnaireRefIdFk(null);
}
questionnaire.setDocumentNumber("");
}
catch (Exception e) {
}
}
@Override
public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = super.start(mapping, form, request, response);
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (qnForm.getMaintenanceAction().equals(KRADConstants.MAINTENANCE_NEW_ACTION)
&& ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.getSequenceNumber() == null) {
((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject().getDataObject())
.setSequenceNumber(1);
}
checkAndSetAllQuestionsAreUpToDate(qnForm);
return forward;
}
@Override
public ActionForward close(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
if (buttonClicked != null && ConfirmationQuestion.YES.equals(buttonClicked)) {
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject());
questionnaire.setQuestionnaireUsages(qnForm.getQuestionnaireUsages());
setupQuestionAndUsage(qnForm);
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
questionnaire.setFileName(qnForm.getTemplateFile().getFileName());
questionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
}
}
forward = super.close(mapping, form, request, response);
if (buttonClicked == null || ConfirmationQuestion.NO.equals(buttonClicked)) {
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject();
qnForm.setQuestionnaireUsages(questionnaire.getQuestionnaireUsages());
// also need to save usages data in form to be restored if 'yes' is clicked
// this is processed twice, so questionnaireUsage will be reset in qnform.reset
// that's why we need to save this for restoration later
questionnaire.setQuestionnaireUsages(new ArrayList<QuestionnaireUsage>());
}
return forward;
}
/**
*
* This method is to print Questionnaire
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward printQuestionnaire(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO : this is only available after questionnaire is saved ?
ActionForward forward = mapping.findForward(MAPPING_BASIC);
Map<String, Object> reportParameters = new HashMap<String, Object>();
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
reportParameters.put("documentNumber", qnForm.getDocument().getDocumentNumber());
Questionnaire questionnaire = ((Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
.getNewMaintainableObject().getDataObject());
reportParameters.put("questionnaireId", questionnaire.getQuestionnaireIdAsInteger());
if (qnForm.getTemplateFile() != null && qnForm.getTemplateFile().getFileData().length > 0) {
reportParameters.put("template", qnForm.getTemplateFile().getFileData());
} else {
reportParameters.put("template", questionnaire.getTemplate());
}
// TODO : this is not a transaction document, so set to null ?
AttachmentDataSource dataStream = getQuestionnairePrintingService().printQuestionnaire(null, reportParameters);
if (dataStream.getContent() != null) {
PrintingUtils.streamToResponse(dataStream, response);
forward = null;
}
return forward;
}
public ActionForward addTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
questionnaire.setFileName(qnForm.getTemplateFile().getFileName());
questionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward viewTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
this.streamToResponse(qnForm.getTemplateFile().getFileData(), qnForm.getTemplateFile().getFileName(),
Constants.CORRESPONDENCE_TEMPLATE_CONTENT_TYPE_1, response);
} else {
this.streamToResponse(questionnaire.getTemplate(), questionnaire.getFileName(),
Constants.CORRESPONDENCE_TEMPLATE_CONTENT_TYPE_1, response);
}
return RESPONSE_ALREADY_HANDLED;
}
public ActionForward deleteTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
Questionnaire questionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject()
.getBusinessObject();
questionnaire.setFileName(null);
questionnaire.setTemplate(null);
qnForm.setTemplateFile(null);
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward getSubModuleCodeList(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward("ajaxQuestionnaire");
}
public ActionForward getQuestionMaintainTable(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (StringUtils.isNotBlank(qnForm.getQuestionId())) {
Map pkMap = new HashMap();
pkMap.put("questionRefId", qnForm.getQuestionId());
qnForm.setQuestion((Question)getBusinessObjectService().findByPrimaryKey(Question.class, pkMap));
//lets check for a more current version
pkMap.clear();
pkMap.put("questionId", qnForm.getQuestion().getQuestionId());
List<Question> questions = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, pkMap, "sequenceNumber", false));
if (CollectionUtils.isNotEmpty(questions)) {
if (!StringUtils.equals(questions.get(0).getQuestionRefId().toString(), qnForm.getQuestionId())) {
qnForm.setQuestionCurrentVersion(false);
}
}
}
return mapping.findForward("ajaxQuestionMaintainTable");
}
public ActionForward getQuestionCurrentVersion(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
if (StringUtils.isNotBlank(qnForm.getQuestionId())) {
Map pkMap = new HashMap();
pkMap.put("questionRefId", qnForm.getQuestionId());
Question oldQ = (Question)getBusinessObjectService().findByPrimaryKey(Question.class, pkMap);
if (oldQ != null) {
pkMap.clear();
pkMap.put("questionId", oldQ.getQuestionId());
List<Question> questions = ((List<Question>)getBusinessObjectService().findMatchingOrderBy(Question.class, pkMap, "sequenceNumber", false));
if (CollectionUtils.isNotEmpty(questions)) {
qnForm.setQuestion(questions.get(0));
}
}
}
return mapping.findForward("ajaxQuestionCurrentVersion");
}
private QuestionnaireAuthorizationService getQuestionnaireAuthorizationService() {
return KraServiceLocator.getService(QuestionnaireAuthorizationService.class);
}
private QuestionnairePrintingService getQuestionnairePrintingService() {
return KraServiceLocator.getService(QuestionnairePrintingService.class);
}
@Override
protected void populateAuthorizationFields(KualiDocumentFormBase formBase){
QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) formBase;
// for 'view' questionnaire. which is using 'edit.
boolean isReadOnly = qnForm.isReadOnly();
// populateAuthorizationFields will override the isReadOnly property of the form. if it is 'view'
super.populateAuthorizationFields(formBase);
if (isReadOnly && StringUtils.equals(qnForm.getMethodToCall(), "edit")) {
qnForm.setReadOnly(isReadOnly);
}
if (qnForm.isReadOnly() && formBase.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_CAN_CLOSE)) {
Map<String, String> documentActions = new HashMap<String, String>();
documentActions.put(KRADConstants.KUALI_ACTION_CAN_CLOSE, "TRUE");
qnForm.setDocumentActions(documentActions);
}
}
}
| Jira#KRACOEUS_5493
| src/main/java/org/kuali/kra/questionnaire/QuestionnaireMaintenanceDocumentAction.java | Jira#KRACOEUS_5493 | <ide><path>rc/main/java/org/kuali/kra/questionnaire/QuestionnaireMaintenanceDocumentAction.java
<ide> .getOldMaintainableObject().getDataObject();
<ide> versionQuestionnaire(questionnaire, oldQuestionnaire);
<ide> Long questionnaireRefId = KraServiceLocator.getService(SequenceAccessorService.class).getNextAvailableSequenceNumber(
<del> "SEQ_QUESTIONNAIRE_REF_ID");
<add> "SEQ_QUESTIONNAIRE_REF_ID");
<ide> questionnaire.setQuestionnaireRefIdFromLong(questionnaireRefId);
<ide> // inherit from previous version when start editing
<ide> // questionnaire.setIsFinal(false); |
|
Java | apache-2.0 | 06d002b938b9b06e3522f449d747b929bb65275f | 0 | catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/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.exercise.security.authorization.models.simplifiedroles;
import java.io.ByteArrayInputStream;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlManager;
import com.google.common.collect.ImmutableList;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.commons.PropertiesUtil;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.plugins.name.NamespaceEditorProvider;
import org.apache.jackrabbit.oak.plugins.nodetype.ReadOnlyNodeTypeManager;
import org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider;
import org.apache.jackrabbit.oak.plugins.nodetype.write.NodeTypeRegistry;
import org.apache.jackrabbit.oak.plugins.tree.TreeLocation;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider;
import org.apache.jackrabbit.oak.spi.commit.EditorHook;
import org.apache.jackrabbit.oak.spi.commit.MoveTracker;
import org.apache.jackrabbit.oak.spi.commit.Validator;
import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider;
import org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer;
import org.apache.jackrabbit.oak.spi.security.CompositeConfiguration;
import org.apache.jackrabbit.oak.spi.security.ConfigurationBase;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.Context;
import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration;
import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.EmptyPermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
import org.apache.jackrabbit.oak.spi.state.ApplyDiff;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.spi.xml.ProtectedItemImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.spi.security.RegistrationConstants.OAK_SECURITY_NAME;
@Component(metatype = true, immediate = true, policy = org.apache.felix.scr.annotations.ConfigurationPolicy.REQUIRE)
@Service({AuthorizationConfiguration.class, org.apache.jackrabbit.oak.spi.security.SecurityConfiguration.class})
@Properties({
@Property(name = "supportedPath",
label = "Supported Path"),
@Property(name = CompositeConfiguration.PARAM_RANKING,
label = "Ranking",
description = "Ranking of this configuration in a setup with multiple authorization configurations.",
intValue = 10),
@Property(name = OAK_SECURITY_NAME,
propertyPrivate = true,
value = "org.apache.jackrabbit.oak.exercise.security.authorization.models.simplifiedroles.ThreeRolesAuthorizationConfiguration")
})
public class ThreeRolesAuthorizationConfiguration extends ConfigurationBase implements AuthorizationConfiguration, ThreeRolesConstants {
private static final Logger log = LoggerFactory.getLogger(ThreeRolesAuthorizationConfiguration.class);
private String supportedPath;
@org.apache.felix.scr.annotations.Activate
private void activate(Map<String, Object> properties) {
supportedPath = PropertiesUtil.toString(properties.get("supportedPath"), (String) null);
}
@Modified
private void modified(Map<String, Object> properties) {
supportedPath = PropertiesUtil.toString(properties.get("supportedPath"), (String) null);
}
@Deactivate
private void deactivate(Map<String, Object> properties) {
supportedPath = null;
}
@Nonnull
@Override
public AccessControlManager getAccessControlManager(@Nonnull Root root, @Nonnull NamePathMapper namePathMapper) {
return new ThreeRolesAccessControlManager(root, supportedPath, getSecurityProvider());
}
@Nonnull
@Override
public RestrictionProvider getRestrictionProvider() {
return RestrictionProvider.EMPTY;
}
@Nonnull
@Override
public PermissionProvider getPermissionProvider(@Nonnull Root root, @Nonnull String workspaceName, @Nonnull Set<Principal> principals) {
if (supportedPath == null) {
return EmptyPermissionProvider.getInstance();
} else {
return new ThreeRolesPermissionProvider(root, principals, supportedPath, getContext(), getRootProvider());
}
}
@Nonnull
@Override
public String getName() {
return AuthorizationConfiguration.NAME;
}
@Nonnull
@Override
public RepositoryInitializer getRepositoryInitializer() {
String cnd = "<rep='internal'>\n" +
"["+MIX_REP_THREE_ROLES_POLICY+"] \n mixin\n " +
" +"+REP_3_ROLES_POLICY+" ("+NT_REP_THREE_ROLES_POLICY+") protected IGNORE\n\n" +
"["+NT_REP_THREE_ROLES_POLICY+"] > "+ AccessControlConstants.NT_REP_POLICY+"\n" +
" - "+REP_READERS +" (STRING) multiple protected IGNORE\n" +
" - "+REP_EDITORS+" (STRING) multiple protected IGNORE\n" +
" - "+REP_OWNERS+" (STRING) multiple protected IGNORE";
System.out.println(cnd);
return builder -> {
NodeState base = builder.getNodeState();
NodeStore store = new MemoryNodeStore(base);
Root root = getRootProvider().createSystemRoot(store,
new EditorHook(new CompositeEditorProvider(new NamespaceEditorProvider(), new TypeEditorProvider())));
try {
if (!ReadOnlyNodeTypeManager.getInstance(root, NamePathMapper.DEFAULT).hasNodeType(MIX_REP_THREE_ROLES_POLICY)) {
NodeTypeRegistry.register(root, new ByteArrayInputStream(cnd.getBytes()), "oak exercise");
NodeState target = store.getRoot();
target.compareAgainstBaseState(base, new ApplyDiff(builder));
}
} catch (RepositoryException e) {
log.error(e.getMessage());
}
};
}
@Nonnull
@Override
public List<? extends ValidatorProvider> getValidators(@Nonnull String workspaceName, @Nonnull Set<Principal> principals, @Nonnull MoveTracker moveTracker) {
return ImmutableList.of(new ValidatorProvider() {
@Override
protected Validator getRootValidator(NodeState before, NodeState after, CommitInfo info) {
// EXERCISE: write a validator that meets the following requirements:
// 1. check that the item names defined with the node types are only used within the scope of the 2 node types
// 2. check that the policies are never nested.
// NOTE: having this validator allows to rely on item names in
// Context implementation and simplify the permission evaluation
// i.e. preventing expensive effective node type calculation/verification
// and checks for nested policies in time critical evaluation steps.
return null;
}
});
}
@Nonnull
@Override
public List<ProtectedItemImporter> getProtectedItemImporters() {
// EXERCISE
return ImmutableList.of();
}
@Nonnull
@Override
public Context getContext() {
/**
* Simplified implementation of the Context interface that just tests
* item names without every evaluating node type information.
* See {@link #getValidators(String, Set, MoveTracker)} above.
*/
return new Context() {
@Override
public boolean definesProperty(@Nonnull Tree parent, @Nonnull PropertyState property) {
return definesTree(parent) && NAMES.contains(property.getName());
}
@Override
public boolean definesContextRoot(@Nonnull Tree tree) {
return definesTree(tree);
}
@Override
public boolean definesTree(@Nonnull Tree tree) {
return REP_3_ROLES_POLICY.equals(tree.getName());
}
@Override
public boolean definesLocation(@Nonnull TreeLocation location) {
String name = location.getName();
return NAMES.contains(name);
}
@Override
public boolean definesInternal(@Nonnull Tree tree) {
return false;
}
};
}
@Override
public void setParameters(@Nonnull ConfigurationParameters config) {
super.setParameters(config);
supportedPath = config.getConfigValue("supportedPath", null);
}
} | oak-exercise/src/main/java/org/apache/jackrabbit/oak/exercise/security/authorization/models/simplifiedroles/ThreeRolesAuthorizationConfiguration.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.exercise.security.authorization.models.simplifiedroles;
import java.io.ByteArrayInputStream;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlManager;
import com.google.common.collect.ImmutableList;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.commons.PropertiesUtil;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.plugins.name.NamespaceEditorProvider;
import org.apache.jackrabbit.oak.plugins.nodetype.ReadOnlyNodeTypeManager;
import org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider;
import org.apache.jackrabbit.oak.plugins.nodetype.write.NodeTypeRegistry;
import org.apache.jackrabbit.oak.plugins.tree.TreeLocation;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider;
import org.apache.jackrabbit.oak.spi.commit.EditorHook;
import org.apache.jackrabbit.oak.spi.commit.MoveTracker;
import org.apache.jackrabbit.oak.spi.commit.Validator;
import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider;
import org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer;
import org.apache.jackrabbit.oak.spi.security.CompositeConfiguration;
import org.apache.jackrabbit.oak.spi.security.ConfigurationBase;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.Context;
import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration;
import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.EmptyPermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionProvider;
import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
import org.apache.jackrabbit.oak.spi.security.principal.AdminPrincipal;
import org.apache.jackrabbit.oak.spi.security.principal.SystemPrincipal;
import org.apache.jackrabbit.oak.spi.state.ApplyDiff;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.spi.xml.ProtectedItemImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.spi.security.RegistrationConstants.OAK_SECURITY_NAME;
@Component(metatype = true, policy = org.apache.felix.scr.annotations.ConfigurationPolicy.REQUIRE)
@Service({AuthorizationConfiguration.class, org.apache.jackrabbit.oak.spi.security.SecurityConfiguration.class})
@Properties({
@Property(name = "supportedPath",
label = "Supported Path"),
@Property(name = CompositeConfiguration.PARAM_RANKING,
label = "Ranking",
description = "Ranking of this configuration in a setup with multiple authorization configurations.",
intValue = 10),
@Property(name = OAK_SECURITY_NAME,
propertyPrivate = true,
value = "org.apache.jackrabbit.oak.exercise.security.authorization.models.simplifiedroles.ThreeRolesAuthorizationConfiguration")
})
public class ThreeRolesAuthorizationConfiguration extends ConfigurationBase implements AuthorizationConfiguration, ThreeRolesConstants {
private static final Logger log = LoggerFactory.getLogger(ThreeRolesAuthorizationConfiguration.class);
private String supportedPath;
@org.apache.felix.scr.annotations.Activate
private void activate(Map<String, Object> properties) {
supportedPath = PropertiesUtil.toString(properties.get("supportedPath"), (String) null);
}
@Modified
private void modified(Map<String, Object> properties) {
supportedPath = PropertiesUtil.toString(properties.get("supportedPath"), (String) null);
}
@Deactivate
private void deactivate(Map<String, Object> properties) {
supportedPath = null;
}
@Nonnull
@Override
public AccessControlManager getAccessControlManager(@Nonnull Root root, @Nonnull NamePathMapper namePathMapper) {
return new ThreeRolesAccessControlManager(root, supportedPath, getSecurityProvider());
}
@Nonnull
@Override
public RestrictionProvider getRestrictionProvider() {
return RestrictionProvider.EMPTY;
}
@Nonnull
@Override
public PermissionProvider getPermissionProvider(@Nonnull Root root, @Nonnull String workspaceName, @Nonnull Set<Principal> principals) {
if (supportedPath == null || isAdminOrSystem(principals)) {
return EmptyPermissionProvider.getInstance();
} else {
return new ThreeRolesPermissionProvider(root, principals, supportedPath, getContext(), getRootProvider());
}
}
@Nonnull
@Override
public String getName() {
return AuthorizationConfiguration.NAME;
}
@Nonnull
@Override
public RepositoryInitializer getRepositoryInitializer() {
String cnd = "<rep='internal'>\n" +
"["+MIX_REP_THREE_ROLES_POLICY+"] \n mixin\n " +
" +"+REP_3_ROLES_POLICY+" ("+NT_REP_THREE_ROLES_POLICY+") protected IGNORE\n\n" +
"["+NT_REP_THREE_ROLES_POLICY+"] > "+ AccessControlConstants.NT_REP_POLICY+"\n" +
" - "+REP_READERS +" (STRING) multiple protected IGNORE\n" +
" - "+REP_EDITORS+" (STRING) multiple protected IGNORE\n" +
" - "+REP_OWNERS+" (STRING) multiple protected IGNORE";
System.out.println(cnd);
return builder -> {
NodeState base = builder.getNodeState();
NodeStore store = new MemoryNodeStore(base);
Root root = getRootProvider().createSystemRoot(store,
new EditorHook(new CompositeEditorProvider(new NamespaceEditorProvider(), new TypeEditorProvider())));
try {
if (!ReadOnlyNodeTypeManager.getInstance(root, NamePathMapper.DEFAULT).hasNodeType(MIX_REP_THREE_ROLES_POLICY)) {
NodeTypeRegistry.register(root, new ByteArrayInputStream(cnd.getBytes()), "oak exercise");
NodeState target = store.getRoot();
target.compareAgainstBaseState(base, new ApplyDiff(builder));
}
} catch (RepositoryException e) {
log.error(e.getMessage());
}
};
}
@Nonnull
@Override
public List<? extends ValidatorProvider> getValidators(@Nonnull String workspaceName, @Nonnull Set<Principal> principals, @Nonnull MoveTracker moveTracker) {
return ImmutableList.of(new ValidatorProvider() {
@Override
protected Validator getRootValidator(NodeState before, NodeState after, CommitInfo info) {
// EXERCISE: write a validator that meets the following requirements:
// 1. check that the item names defined with the node types are only used within the scope of the 2 node types
// 2. check that the policies are never nested.
// NOTE: having this validator allows to rely on item names in
// Context implementation and simplify the permission evaluation
// i.e. preventing expensive effective node type calculation/verification
// and checks for nested policies in time critical evaluation steps.
return null;
}
});
}
@Nonnull
@Override
public List<ProtectedItemImporter> getProtectedItemImporters() {
// EXERCISE
return ImmutableList.of();
}
@Nonnull
@Override
public Context getContext() {
/**
* Simplified implementation of the Context interface that just tests
* item names without every evaluating node type information.
* See {@link #getValidators(String, Set, MoveTracker)} above.
*/
return new Context() {
@Override
public boolean definesProperty(@Nonnull Tree parent, @Nonnull PropertyState property) {
return definesTree(parent) && NAMES.contains(property.getName());
}
@Override
public boolean definesContextRoot(@Nonnull Tree tree) {
return definesTree(tree);
}
@Override
public boolean definesTree(@Nonnull Tree tree) {
return REP_3_ROLES_POLICY.equals(tree.getName());
}
@Override
public boolean definesLocation(@Nonnull TreeLocation location) {
String name = location.getName();
return NAMES.contains(name);
}
@Override
public boolean definesInternal(@Nonnull Tree tree) {
return false;
}
};
}
private static boolean isAdminOrSystem(@Nonnull Set<Principal> principals) {
if (principals.contains(SystemPrincipal.INSTANCE)) {
return true;
} else {
for (Principal principal : principals) {
if (principal instanceof AdminPrincipal) {
return true;
}
}
return false;
}
}
@Override
public void setParameters(@Nonnull ConfigurationParameters config) {
super.setParameters(config);
supportedPath = config.getConfigValue("supportedPath", null);
}
} | minor improvement to exercise code
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1833119 13f79535-47bb-0310-9956-ffa450edef68
| oak-exercise/src/main/java/org/apache/jackrabbit/oak/exercise/security/authorization/models/simplifiedroles/ThreeRolesAuthorizationConfiguration.java | minor improvement to exercise code | <ide><path>ak-exercise/src/main/java/org/apache/jackrabbit/oak/exercise/security/authorization/models/simplifiedroles/ThreeRolesAuthorizationConfiguration.java
<ide> import org.apache.jackrabbit.oak.spi.security.authorization.permission.EmptyPermissionProvider;
<ide> import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionProvider;
<ide> import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
<del>import org.apache.jackrabbit.oak.spi.security.principal.AdminPrincipal;
<del>import org.apache.jackrabbit.oak.spi.security.principal.SystemPrincipal;
<ide> import org.apache.jackrabbit.oak.spi.state.ApplyDiff;
<ide> import org.apache.jackrabbit.oak.spi.state.NodeState;
<ide> import org.apache.jackrabbit.oak.spi.state.NodeStore;
<ide>
<ide> import static org.apache.jackrabbit.oak.spi.security.RegistrationConstants.OAK_SECURITY_NAME;
<ide>
<del>@Component(metatype = true, policy = org.apache.felix.scr.annotations.ConfigurationPolicy.REQUIRE)
<add>@Component(metatype = true, immediate = true, policy = org.apache.felix.scr.annotations.ConfigurationPolicy.REQUIRE)
<ide> @Service({AuthorizationConfiguration.class, org.apache.jackrabbit.oak.spi.security.SecurityConfiguration.class})
<ide> @Properties({
<ide> @Property(name = "supportedPath",
<ide> @Nonnull
<ide> @Override
<ide> public PermissionProvider getPermissionProvider(@Nonnull Root root, @Nonnull String workspaceName, @Nonnull Set<Principal> principals) {
<del> if (supportedPath == null || isAdminOrSystem(principals)) {
<add> if (supportedPath == null) {
<ide> return EmptyPermissionProvider.getInstance();
<ide> } else {
<ide> return new ThreeRolesPermissionProvider(root, principals, supportedPath, getContext(), getRootProvider());
<ide> };
<ide> }
<ide>
<del> private static boolean isAdminOrSystem(@Nonnull Set<Principal> principals) {
<del> if (principals.contains(SystemPrincipal.INSTANCE)) {
<del> return true;
<del> } else {
<del> for (Principal principal : principals) {
<del> if (principal instanceof AdminPrincipal) {
<del> return true;
<del> }
<del> }
<del> return false;
<del> }
<del> }
<del>
<ide> @Override
<ide> public void setParameters(@Nonnull ConfigurationParameters config) {
<ide> super.setParameters(config); |
|
Java | bsd-3-clause | error: pathspec 'src/edu/wpi/first/wpilibj/templates/Climber.java' did not match any file(s) known to git
| 36c1250941ec323f82a4f20a1979bada96755c65 | 1 | RobotCasserole1736/robotcasserole2013 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
/**
*
* @author Kristen Dunne
*/
public class Climber {
CANJaguar tilt, lift;
XBoxC joy;
double lift_speed = .8;
double tilt_speed = .8;
public Climber(int tilt_id, int lift_id, XBoxC joy)
{
try {
tilt = new CANJaguar(tilt_id);
lift = new CANJaguar(lift_id);
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
this.joy = joy;
}
public void tilt(boolean activated)
{
try {
if (joy.getRawButton(3)){
tilt.setX(tilt_speed);
}
else if (joy.getRawButton(4)){
tilt.setX(-tilt_speed);
}
else {
tilt.setX(0);
}
}
catch (CANTimeoutException ex) {
ex.printStackTrace();
}
}
public void lift(boolean activated)
{
try {
if (joy.getRawButton(5)){
lift.setX(lift_speed);
}
else if (joy.getRawButton(6)){
lift.setX(-lift_speed);
}
else {
lift.setX(0);
}
}
catch (CANTimeoutException ex) {
ex.printStackTrace();
}
}
}
| src/edu/wpi/first/wpilibj/templates/Climber.java | Many bug fixes in code found while testing | src/edu/wpi/first/wpilibj/templates/Climber.java | Many bug fixes in code found while testing | <ide><path>rc/edu/wpi/first/wpilibj/templates/Climber.java
<add>/*
<add> * To change this template, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>package edu.wpi.first.wpilibj.templates;
<add>
<add>import edu.wpi.first.wpilibj.CANJaguar;
<add>import edu.wpi.first.wpilibj.Joystick;
<add>import edu.wpi.first.wpilibj.can.CANTimeoutException;
<add>
<add>/**
<add> *
<add> * @author Kristen Dunne
<add> */
<add>public class Climber {
<add>
<add> CANJaguar tilt, lift;
<add> XBoxC joy;
<add> double lift_speed = .8;
<add> double tilt_speed = .8;
<add>
<add> public Climber(int tilt_id, int lift_id, XBoxC joy)
<add> {
<add> try {
<add> tilt = new CANJaguar(tilt_id);
<add> lift = new CANJaguar(lift_id);
<add> } catch (CANTimeoutException ex) {
<add> ex.printStackTrace();
<add> }
<add> this.joy = joy;
<add> }
<add>
<add> public void tilt(boolean activated)
<add> {
<add> try {
<add> if (joy.getRawButton(3)){
<add> tilt.setX(tilt_speed);
<add> }
<add> else if (joy.getRawButton(4)){
<add> tilt.setX(-tilt_speed);
<add> }
<add> else {
<add> tilt.setX(0);
<add> }
<add> }
<add> catch (CANTimeoutException ex) {
<add> ex.printStackTrace();
<add> }
<add>
<add> }
<add> public void lift(boolean activated)
<add> {
<add> try {
<add> if (joy.getRawButton(5)){
<add> lift.setX(lift_speed);
<add> }
<add> else if (joy.getRawButton(6)){
<add> lift.setX(-lift_speed);
<add> }
<add> else {
<add> lift.setX(0);
<add> }
<add> }
<add> catch (CANTimeoutException ex) {
<add> ex.printStackTrace();
<add> }
<add>
<add> }
<add>
<add>
<add>} |
|
JavaScript | mit | 32afef7a00691e5076d73c8d22cbeac74616f7ca | 0 | Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc | // @flow
import {createSelector} from 'reselect'
import fromPairs from 'lodash/fromPairs'
import {namesSelector} from './names'
import toPairs from 'lodash/toPairs'
import type {PlayerMap} from '../../../types'
/**
* PlayerName structure to be passed into name-input-list component.
* This represent one player in the system.
* First string is the ID. Second string is the name.
*/
export type PlayerName = [string, string]
export function revert(data: PlayerName[]): PlayerMap<string> {
return fromPairs(data)
}
/**
* Select names source used for name-input-list component for usage in settings view.
*/
export const nameInputListSourceSelector = createSelector(
namesSelector,
(names: PlayerMap<string>): PlayerName[] => (
toPairs(names)
)
)
| src/selectors/ui/settings/name-input-list-source.js | // @flow
import {createSelector} from 'reselect'
import {namesSelector} from './names'
import toPairs from 'lodash/toPairs'
import type {PlayerMap} from '../../../types'
/**
* Select names source used for name-input-list component for usage in settings view.
*/
export const nameInputListSourceSelector = createSelector(
namesSelector,
(names: PlayerMap<string>) => (
toPairs(names)
)
)
| Add type annotation to name-input-list-source selector
| src/selectors/ui/settings/name-input-list-source.js | Add type annotation to name-input-list-source selector | <ide><path>rc/selectors/ui/settings/name-input-list-source.js
<ide> // @flow
<ide> import {createSelector} from 'reselect'
<add>import fromPairs from 'lodash/fromPairs'
<ide> import {namesSelector} from './names'
<ide> import toPairs from 'lodash/toPairs'
<ide>
<ide> import type {PlayerMap} from '../../../types'
<ide>
<ide> /**
<add> * PlayerName structure to be passed into name-input-list component.
<add> * This represent one player in the system.
<add> * First string is the ID. Second string is the name.
<add> */
<add>export type PlayerName = [string, string]
<add>
<add>export function revert(data: PlayerName[]): PlayerMap<string> {
<add> return fromPairs(data)
<add>}
<add>
<add>/**
<ide> * Select names source used for name-input-list component for usage in settings view.
<ide> */
<ide> export const nameInputListSourceSelector = createSelector(
<ide> namesSelector,
<del> (names: PlayerMap<string>) => (
<add> (names: PlayerMap<string>): PlayerName[] => (
<ide> toPairs(names)
<ide> )
<ide> ) |
|
Java | apache-2.0 | error: pathspec 'chapter_002/src/main/java/ru/job4j/chess/model/Cell.java' did not match any file(s) known to git
| 38277cb0bf95bf6e2e073bde370aaeb2e3b776c2 | 1 | Basil135/vkucyh | package ru.job4j.chess.model;
/**
* This class describes a cell of board of chess.
*
* @author Kucykh Vasily (mailto:[email protected])
* @version $Id$
* @since 20.04.2017
*/
public class Cell {
/**
* parameter describes row of board of chess.
*/
private final int x;
/**
* parameter describes column of board of chess.
*/
private final int y;
/**
* constructor of Cell class.
*
* @param x is set point at row on the board
* @param y is set point at column on the board
*/
public Cell(final int x, final int y) {
this.x = x;
this.y = y;
}
/**
* method return row on the board.
*
* @return x as row on the board of chess
*/
public int getX() {
return this.x;
}
/**
* method return column on the board of chess.
*
* @return y as column on the board of chess
*/
public int getY() {
return this.y;
}
} | chapter_002/src/main/java/ru/job4j/chess/model/Cell.java | Added Cell.java to chess application
| chapter_002/src/main/java/ru/job4j/chess/model/Cell.java | Added Cell.java to chess application | <ide><path>hapter_002/src/main/java/ru/job4j/chess/model/Cell.java
<add>package ru.job4j.chess.model;
<add>
<add>/**
<add> * This class describes a cell of board of chess.
<add> *
<add> * @author Kucykh Vasily (mailto:[email protected])
<add> * @version $Id$
<add> * @since 20.04.2017
<add> */
<add>public class Cell {
<add>
<add> /**
<add> * parameter describes row of board of chess.
<add> */
<add> private final int x;
<add> /**
<add> * parameter describes column of board of chess.
<add> */
<add> private final int y;
<add>
<add> /**
<add> * constructor of Cell class.
<add> *
<add> * @param x is set point at row on the board
<add> * @param y is set point at column on the board
<add> */
<add> public Cell(final int x, final int y) {
<add> this.x = x;
<add> this.y = y;
<add> }
<add>
<add> /**
<add> * method return row on the board.
<add> *
<add> * @return x as row on the board of chess
<add> */
<add> public int getX() {
<add> return this.x;
<add> }
<add>
<add> /**
<add> * method return column on the board of chess.
<add> *
<add> * @return y as column on the board of chess
<add> */
<add> public int getY() {
<add> return this.y;
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 31bec9d1566c30080b7d63caccebf7b2a60ae523 | 0 | crnk-project/crnk-framework,crnk-project/crnk-framework,crnk-project/crnk-framework,crnk-project/crnk-framework,crnk-project/crnk-framework | package io.crnk.gen.openapi.internal.annotations;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.crnk.gen.openapi.internal.OASGenerator;
import io.crnk.gen.openapi.internal.OASMergeUtil;
import io.crnk.meta.model.MetaAttribute;
import io.crnk.meta.model.resource.MetaResource;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public class OASAnnotations {
private static final Logger LOGGER = LoggerFactory.getLogger(OASGenerator.class);
private static Map<Type, Map<String, Schema>> cache;
private static Set<Type> failed;
private OASAnnotations() {
cache = new HashMap<>();
failed = new HashSet<>();
// Hack to support ObjectNode: When an Object has two setters with the same number
// of parameters the parser blows up.
ObjectMapper mapper = Json.mapper();
mapper.addMixIn(ObjectNode.class, IgnoreObjectNodeSetAllIntMixIn.class);
}
private static class SingletonHelper {
private static final OASAnnotations INSTANCE = new OASAnnotations();
}
abstract static class IgnoreObjectNodeSetAllIntMixIn
{
@JsonIgnore
public abstract void setAll(ObjectNode other);
}
public static OASAnnotations getInstance() {
return SingletonHelper.INSTANCE;
}
public void applyFromModel(Schema schema, MetaResource metaResource, MetaAttribute metaAttribute) {
Type type = metaResource.getImplementationType();
if (failed.contains(type)) {
return;
}
Map<String, Schema> model = cache.get(type);
if (model == null) {
try {
model = ModelConverters.getInstance().read(type);
cache.put(type, model);
} catch (Exception e) {
failed.add(type);
LOGGER.warn("Unable to parse model" + metaResource.getName());
return;
}
}
String[] words = metaResource.getImplementationClassName().split(Pattern.quote("."));
Schema derivedSchema = model.get(words[words.length - 1]);
derivedSchema = (Schema) derivedSchema.getProperties().get(metaAttribute.getUnderlyingName());
OASMergeUtil.mergeSchema(schema, derivedSchema);
}
}
| crnk-gen/crnk-gen-openapi/src/main/java/io/crnk/gen/openapi/internal/annotations/OASAnnotations.java | package io.crnk.gen.openapi.internal.annotations;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.crnk.gen.openapi.internal.OASGenerator;
import io.crnk.gen.openapi.internal.OASMergeUtil;
import io.crnk.meta.model.MetaAttribute;
import io.crnk.meta.model.resource.MetaResource;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public class OASAnnotations {
private static final Logger LOGGER = LoggerFactory.getLogger(OASGenerator.class);
private static Map<Type, Map<String, Schema>> cache;
private static Set<Type> failed;
private OASAnnotations() {
cache = new HashMap<>();
failed = new HashSet<>();
// Hack to support ObjectNode: When an Object has two setters with the same number
// of parameters the parser blows up.
ObjectMapper mapper = Json.mapper();
mapper.addMixIn(ObjectNode.class, IgnoreObjectNodeSetAllIntMixIn.class);
}
private static class SingletonHelper {
private static final OASAnnotations INSTANCE = new OASAnnotations();
}
abstract static class IgnoreObjectNodeSetAllIntMixIn
{
@JsonIgnore
public abstract void setAll(ObjectNode other);
}
public static OASAnnotations getInstance() {
return SingletonHelper.INSTANCE;
}
public void applyFromModel(Schema schema, MetaResource metaResource, MetaAttribute metaAttribute) {
Type type = metaResource.getImplementationType();
if (failed.contains(type)) {
return;
}
Map<String, Schema> model = cache.get(type);
if (model == null) {
try {
model = ModelConverters.getInstance().read(type);
cache.put(type, model);
} catch (Exception e) {
failed.add(type);
LOGGER.error("Unable to parse model" + metaResource.getName(), e);
return;
}
}
String[] words = metaResource.getImplementationClassName().split(Pattern.quote("."));
Schema derivedSchema = model.get(words[words.length - 1]);
derivedSchema = (Schema) derivedSchema.getProperties().get(metaAttribute.getUnderlyingName());
OASMergeUtil.mergeSchema(schema, derivedSchema);
}
}
| Change error to a warning for openapi annotation model parsing failure
| crnk-gen/crnk-gen-openapi/src/main/java/io/crnk/gen/openapi/internal/annotations/OASAnnotations.java | Change error to a warning for openapi annotation model parsing failure | <ide><path>rnk-gen/crnk-gen-openapi/src/main/java/io/crnk/gen/openapi/internal/annotations/OASAnnotations.java
<ide> cache.put(type, model);
<ide> } catch (Exception e) {
<ide> failed.add(type);
<del> LOGGER.error("Unable to parse model" + metaResource.getName(), e);
<add> LOGGER.warn("Unable to parse model" + metaResource.getName());
<ide> return;
<ide> }
<ide> } |
|
Java | mit | 8815e3edf9193fa72a1af68dfbe5cb56e7fea118 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.application.team.controller;
import org.innovateuk.ifs.BaseUnitTest;
import org.innovateuk.ifs.filter.CookieFlashMessageFilter;
import org.innovateuk.ifs.registration.controller.AcceptInviteController;
import org.innovateuk.ifs.registration.model.AcceptRejectApplicationInviteModelPopulator;
import org.innovateuk.ifs.registration.service.RegistrationCookieService;
import org.innovateuk.ifs.registration.service.RegistrationService;
import org.innovateuk.ifs.registration.viewmodel.AcceptRejectApplicationInviteViewModel;
import org.innovateuk.ifs.registration.viewmodel.ConfirmOrganisationInviteOrganisationViewModel;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.Validator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import static org.innovateuk.ifs.BaseControllerMockMVCTest.setupMockMvc;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.invite.builder.ApplicationInviteResourceBuilder.newApplicationInviteResource;
import static org.innovateuk.ifs.invite.builder.InviteOrganisationResourceBuilder.newInviteOrganisationResource;
import static org.innovateuk.ifs.invite.constant.InviteStatus.SENT;
import static org.innovateuk.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "classpath:application.properties")
public class AcceptInviteControllerTest extends BaseUnitTest {
@InjectMocks
private AcceptInviteController acceptInviteController;
@Mock
private Validator validator;
@Mock
private CookieFlashMessageFilter cookieFlashMessageFilter;
@Mock
private RegistrationService registrationService;
@Mock
private RegistrationCookieService registrationCookieService;
@Spy
@InjectMocks
private AcceptRejectApplicationInviteModelPopulator acceptRejectApplicationInviteModelPopulator;
@Before
public void setUp() throws Exception {
// Process mock annotations
MockitoAnnotations.initMocks(this);
super.setup();
mockMvc = setupMockMvc(acceptInviteController, () -> null, env, messageSource);
this.setupCompetition();
this.setupApplicationWithRoles();
this.setupApplicationResponses();
this.setupFinances();
this.setupInvites();
this.setupCookieUtil();
}
@Test
public void testInviteEntryPage() throws Exception {
when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(null);
MvcResult result = mockMvc.perform(get(String.format("/accept-invite/%s", INVITE_HASH)))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration/accept-invite-new-user"))
.andReturn();
assertTrue(result.getModelAndView().getModel().containsKey("model"));
Object viewModel = result.getModelAndView().getModel().get("model");
assertTrue(viewModel.getClass().equals(AcceptRejectApplicationInviteViewModel.class));
verify(registrationCookieService, times(1)).deleteAllRegistrationJourneyCookies(any(HttpServletResponse.class));
verify(registrationCookieService, times(1)).saveToInviteHashCookie(eq(INVITE_HASH), any());
}
@Test
public void testConfirmInvitedOrganisation() throws Exception {
final Long organisationId = 3L;
when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(newUserResource().withEmail("[email protected]").build());
when(inviteRestService.getInviteByHash(anyString())).thenReturn(restSuccess(newApplicationInviteResource()
.withStatus(SENT)
.withEmail("[email protected]")
.withInviteOrganisation(organisationId)
.build()));
when(inviteRestService.getInviteOrganisationByHash(anyString())).thenReturn(restSuccess(newInviteOrganisationResource().withOrganisation(organisationId).build()));
when(organisationService.getOrganisationByIdForAnonymousUserFlow(organisationId)).thenReturn(newOrganisationResource().withId(organisationId).build());
when(registrationCookieService.getInviteHashCookieValue(any())).thenReturn(Optional.of(INVITE_HASH));
MvcResult result = mockMvc.perform(get(String.format("/accept-invite/confirm-invited-organisation")))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration/confirm-invited-organisation"))
.andReturn();
assertTrue(result.getModelAndView().getModel().containsKey("model"));
Object viewModel = result.getModelAndView().getModel().get("model");
assertTrue(viewModel.getClass().equals(ConfirmOrganisationInviteOrganisationViewModel.class));
verify(registrationCookieService, times(1)).saveToOrganisationIdCookie(eq(organisationId), any());
}
@Test
public void testInviteEntryPageInvalid() throws Exception {
mockMvc.perform(get(String.format("/accept-invite/%s", INVALID_INVITE_HASH)))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("url-hash-invalid"));
verify(registrationCookieService, times(1)).deleteOrganisationCreationCookie(any());
verify(registrationCookieService, times(1)).deleteOrganisationIdCookie(any());
verify(registrationCookieService, times(1)).deleteInviteHashCookie(any());
}
@Test
public void testInviteEntryPageAccepted() throws Exception {
when(inviteRestService.getInviteOrganisationByHash(ACCEPTED_INVITE_HASH)).thenReturn(restSuccess(newInviteOrganisationResource().build()));
mockMvc.perform(get(String.format("/accept-invite/%s", ACCEPTED_INVITE_HASH)))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/login"));
verify(registrationCookieService, times(1)).deleteOrganisationCreationCookie(any());
verify(registrationCookieService, times(1)).deleteOrganisationIdCookie(any());
verify(registrationCookieService, times(1)).deleteInviteHashCookie(any());
}
} | ifs-web-service/ifs-application-service/src/test/java/org/innovateuk/ifs/application/team/controller/AcceptInviteControllerTest.java | package org.innovateuk.ifs.application.team.controller;
import org.innovateuk.ifs.BaseUnitTest;
import org.innovateuk.ifs.filter.CookieFlashMessageFilter;
import org.innovateuk.ifs.registration.controller.AcceptInviteController;
import org.innovateuk.ifs.registration.model.AcceptRejectApplicationInviteModelPopulator;
import org.innovateuk.ifs.registration.service.RegistrationCookieService;
import org.innovateuk.ifs.registration.service.RegistrationService;
import org.innovateuk.ifs.registration.viewmodel.AcceptRejectApplicationInviteViewModel;
import org.innovateuk.ifs.registration.viewmodel.ConfirmOrganisationInviteOrganisationViewModel;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.Validator;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import static org.innovateuk.ifs.BaseControllerMockMVCTest.setupMockMvc;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.invite.builder.ApplicationInviteResourceBuilder.newApplicationInviteResource;
import static org.innovateuk.ifs.invite.builder.InviteOrganisationResourceBuilder.newInviteOrganisationResource;
import static org.innovateuk.ifs.invite.constant.InviteStatus.SENT;
import static org.innovateuk.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "classpath:application.properties")
public class AcceptInviteControllerTest extends BaseUnitTest {
@InjectMocks
private AcceptInviteController acceptInviteController;
@Mock
private Validator validator;
@Mock
private CookieFlashMessageFilter cookieFlashMessageFilter;
@Mock
private RegistrationService registrationService;
@Mock
private RegistrationCookieService registrationCookieService;
@Spy
@InjectMocks
private AcceptRejectApplicationInviteModelPopulator acceptRejectApplicationInviteModelPopulator;
@Before
public void setUp() throws Exception {
// Process mock annotations
MockitoAnnotations.initMocks(this);
super.setup();
mockMvc = setupMockMvc(acceptInviteController, () -> null, env, messageSource);
this.setupCompetition();
this.setupApplicationWithRoles();
this.setupApplicationResponses();
this.setupFinances();
this.setupInvites();
this.setupCookieUtil();
}
@Test
public void testInviteEntryPage() throws Exception {
when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(null);
MvcResult result = mockMvc.perform(get(String.format("/accept-invite/%s", INVITE_HASH)))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration/accept-invite-new-user"))
.andReturn();
assertTrue(result.getModelAndView().getModel().containsKey("model"));
Object viewModel = result.getModelAndView().getModel().get("model");
assertTrue(viewModel.getClass().equals(AcceptRejectApplicationInviteViewModel.class));
verify(registrationCookieService, times(1)).saveToInviteHashCookie(eq(INVITE_HASH), any());
}
@Test
public void testConfirmInvitedOrganisation() throws Exception {
final Long organisationId = 3L;
when(userAuthenticationService.getAuthenticatedUser(any(HttpServletRequest.class))).thenReturn(newUserResource().withEmail("[email protected]").build());
when(inviteRestService.getInviteByHash(anyString())).thenReturn(restSuccess(newApplicationInviteResource()
.withStatus(SENT)
.withEmail("[email protected]")
.withInviteOrganisation(organisationId)
.build()));
when(inviteRestService.getInviteOrganisationByHash(anyString())).thenReturn(restSuccess(newInviteOrganisationResource().withOrganisation(organisationId).build()));
when(organisationService.getOrganisationByIdForAnonymousUserFlow(organisationId)).thenReturn(newOrganisationResource().withId(organisationId).build());
when(registrationCookieService.getInviteHashCookieValue(any())).thenReturn(Optional.of(INVITE_HASH));
MvcResult result = mockMvc.perform(get(String.format("/accept-invite/confirm-invited-organisation")))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration/confirm-invited-organisation"))
.andReturn();
assertTrue(result.getModelAndView().getModel().containsKey("model"));
Object viewModel = result.getModelAndView().getModel().get("model");
assertTrue(viewModel.getClass().equals(ConfirmOrganisationInviteOrganisationViewModel.class));
verify(registrationCookieService, times(1)).saveToOrganisationIdCookie(eq(organisationId), any());
}
@Test
public void testInviteEntryPageInvalid() throws Exception {
mockMvc.perform(get(String.format("/accept-invite/%s", INVALID_INVITE_HASH)))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("url-hash-invalid"));
verify(registrationCookieService, times(1)).deleteOrganisationCreationCookie(any());
verify(registrationCookieService, times(1)).deleteOrganisationIdCookie(any());
verify(registrationCookieService, times(1)).deleteInviteHashCookie(any());
}
@Test
public void testInviteEntryPageAccepted() throws Exception {
when(inviteRestService.getInviteOrganisationByHash(ACCEPTED_INVITE_HASH)).thenReturn(restSuccess(newInviteOrganisationResource().build()));
mockMvc.perform(get(String.format("/accept-invite/%s", ACCEPTED_INVITE_HASH)))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/login"));
verify(registrationCookieService, times(1)).deleteOrganisationCreationCookie(any());
verify(registrationCookieService, times(1)).deleteOrganisationIdCookie(any());
verify(registrationCookieService, times(1)).deleteInviteHashCookie(any());
}
} | IFS-1300 Add unit test to cover service call
| ifs-web-service/ifs-application-service/src/test/java/org/innovateuk/ifs/application/team/controller/AcceptInviteControllerTest.java | IFS-1300 Add unit test to cover service call | <ide><path>fs-web-service/ifs-application-service/src/test/java/org/innovateuk/ifs/application/team/controller/AcceptInviteControllerTest.java
<ide> import org.springframework.validation.Validator;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<add>import javax.servlet.http.HttpServletResponse;
<ide> import java.util.Optional;
<ide>
<ide> import static org.innovateuk.ifs.BaseControllerMockMVCTest.setupMockMvc;
<ide>
<ide> assertTrue(viewModel.getClass().equals(AcceptRejectApplicationInviteViewModel.class));
<ide>
<add> verify(registrationCookieService, times(1)).deleteAllRegistrationJourneyCookies(any(HttpServletResponse.class));
<ide> verify(registrationCookieService, times(1)).saveToInviteHashCookie(eq(INVITE_HASH), any());
<ide> }
<ide> |
|
JavaScript | mit | 4f2323294acfd0c4c87f61c4c851ec01889db65b | 0 | clehner/wave-cards | /*
Wave-Cards
A Google Wave Gadget for playing cards
v1.0
Copyright (c) 2009 Charles Lehner
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.
*/
(function () {
var
cardsContainer, // #cards
cardsWindow, // #cardsWindow
decksContainer, // #decks
rotation = 0, // angle the card container is rotated.
transitionDuration = 250, // length (ms) of a transition/animation
peekLockMode = false, // to allow cards to be peeked at indefinitely
dragUnderMode = false, // to slide cards over or above other cards
drag, // object being currently dragged
players = [], // wave participants
highestId = 0, // highest card id
highestZ = 0, // highest z-index of a card
hasFocus, // whether the window has the user's focus
me, // the participant whose client renders the gadget
things = {}, // objects (cards and decks) encoded in the wave state
waveState, // the wave gadget state
waveStateKeys = [], // the keys of the gadget state
waveStateValues = {}, // the values of the gadget state
playersLoaded = false,
stateLoaded = false,
gadgetLoaded = false;
/*
#cardsWindow
#hostButtons
#addDeck
#rotate
#cards
*/
/* -------------- State stuff -------------- */
function gadgetLoad() {
// run once
if (gadgetLoaded) return;
// Get dom references
cardsContainer = document.getElementById("cards");
cardsWindow = document.getElementById("cardsWindow");
decksContainer = document.getElementById("decks");
// Wait for cardsContainer to be available
if (!cardsContainer) {
return setTimeout(arguments.callee, 20);
}
// Attach the listeners
addEventListener("keydown", onKeyDown, false);
addEventListener("keyup", onKeyUp, false);
addEventListener("blur", onBlur, false);
addEventListener("focus", onFocus, false);
cardsContainer.addEventListener("mousedown", onMouseDown, false);
document.getElementById("rotateBtn").addEventListener("click",
rotateTable, false);
document.getElementById("addDeckBtn").addEventListener("click",
addDeck, false);
// Set up wave callbacks
if (wave && wave.isInWaveContainer()) {
wave.setStateCallback(stateUpdated);
wave.setParticipantCallback(participantsUpdated);
}
gadgetLoaded = true;
}
gadgets.util.registerOnLoadHandler(gadgetLoad);
// called when the wave state is updated
function stateUpdated() {
var keys, i, key, value, thing;
// we must wait for the players list before loading the cards
if (!playersLoaded) {
return;
}
waveState = wave.getState();
if (!waveState) {
return;
}
keys = waveState.getKeys();
waveStateValues = {};
// Update stuff
for (i = 0; (key=keys[i]); i++) {
value = waveState.get(key);
if (value) {
waveStateValues[key] = value;
thing = getThing(key);
thing.updateState(value);
}
}
// Check for deleted values
// Look for keys that were in the state before but now are not.
for (i = waveStateKeys.length; i--;) {
key = waveStateKeys[i];
if (!(key in waveStateValues)) {
thing = getThing(key);
thing.remove();
}
}
waveStateKeys = keys;
stateLoaded = true;
}
function participantsUpdated() {
players = wave.getParticipants();
if (!playersLoaded) {
// This is the first participant update
me = wave.getViewer();
if (me) {
playersLoaded = true;
stateUpdated();
}
}
}
function onMouseDown(e) {
// start mouse drag
addEventListener("mousemove", onDrag, false);
addEventListener("mouseup", onMouseUp, false);
if (e.target && e.target.object && e.target.object instanceof Card) {
// mousedown on a card
drag = CardSelection;
var card = e.target.object;
if (!card.selected && !e.shiftKey) {
CardSelection.clear();
}
CardSelection.add(card);
if (hasFocus) {
// prevent dragging the images in firefox
if (e.preventDefault) e.preventDefault();
}
} else {
// mousedown on empty space, create a selection box.
// clear the selection unless shift is held
if (!e.shiftKey) {
CardSelection.clear();
}
drag = SelectionBox;
}
var rot = rotatePoint(e.clientX, e.clientY, rotation,
cardsContainer.offsetWidth, cardsContainer.offsetHeight);
drag.dragStart(rot.x, rot.y, e);
}
function onMouseUp() {
// release the drag
drag.dragEnd();
drag = null;
removeEventListener("mouseup", onMouseUp, false);
removeEventListener("mousemove", onDrag, false);
}
function onDrag(e) {
var rot = rotatePoint(e.clientX, e.clientY, rotation,
cardsContainer.offsetWidth, cardsContainer.offsetHeight);
drag.drag(rot.x, rot.y);
}
// Hotkeys
var keydowns = {};
function onKeyDown(e) {
var key = e.keyCode;
if (keydowns[key]) {
return true;
}
keydowns[key] = true;
switch(key) {
// U - drag cards under other cards
case 85:
dragUnderMode = true;
CardSelection.detectOverlaps();
break;
// S - Shuffle the selected cards
case 83:
CardSelection.shuffle();
break;
// G - Group
case 72:
// TODO
break;
// F - Flip
case 70:
CardSelection.flip();
break;
// P - peek start
case 80:
CardSelection.peekStart();
break;
// L - peek lock on
case 76:
peekLockMode = true;
CardSelection.peekLock();
}
}
function onKeyUp(e) {
var key = e.keyCode;
keydowns[key] = false;
switch(key) {
// U - slide cards above other cards
case 85:
dragUnderMode = false;
CardSelection.detectOverlaps();
break;
// P - peek stop
case 80:
CardSelection.peekStop();
break;
// L - peek lock off
case 76:
peekLockMode = false;
}
}
function onFocus() {
hasFocus = true;
}
// stop dragging cards when the window loses focus
function onBlur() {
hasFocus = false;
if (drag) {
onMouseUp();
}
}
// get a stateful object (card or deck) by its key in the wave state
function getThing(key) {
if (things[key]) {
return things[key];
}
var key2 = key.split("_");
var type = key2[0];
var id = ~~key2[1];
highestId = Math.max(highestId, id);
var thing =
type == "card" ? new Card(id, key) :
type == "deck" ? new Deck(id, key) :
new Stateful(id, key);
things[key] = thing;
return thing;
}
// create a deck of cards
function addDeck() {
var newDeck, cards, card, i, s, r;
newDeck = getThing("deck_"+(++highestId));
cards = newDeck.cards;
i = 0;
for (s = 0; s < 4; s++) {
for (r = 0; r < 13; r++) {
with(cards[i++] = getThing("card_"+(++highestId))) {
suit = s;
rank = r;
stateX = stateY = 30 + ~~(i/3);
z = ++highestZ;
deck = newDeck;
queueUpdate();
}
}
}
newDeck.sendUpdate();
}
// rotate the cards container 90 degrees
function rotateTable() {
var oldRotation = rotation;
rotation += 90;
var rotater = function (n) {
return "rotate(" + (oldRotation + 90 * n) + "deg)";
};
var t = {};
t[Transition.cssTransformType] = rotater;
Transition(cardsContainer, t, transitionDuration);
}
// get the coordinates of a point rotated around another point a certain angle
function rotatePoint(x, y, a, w, h) {
//a %= 360;
a = a % 360 + (a < 0 ? 360 : 0);
switch (a) {
case 0:
return {x: x, y: y};
case 90:
return {x: y, y: h-x};
case 180:
return {x: w-x, y: h-y};
case 270:
return {x: w-y, y: x};
default:
// TODO: fancy matrix stuff
}
}
// Return whether or not an element has a class.
function hasClass(ele, cls) {
if (!ele) throw new Error("not an element, can't add class name.");
if (ele.className) {
return new RegExp("(\\s|^)" + cls + "(\\s|$)").test(ele.className);
}
}
// Add a class to an element.
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
// Remove a class from an element.
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
ele.className = ele.className.replace(reg, " ");
}
}
// Add or remove a class from an element
function toggleClass(ele, cls, yes) {
if (yes) addClass(ele, cls);
else removeClass(ele, cls);
}
/* -------------- Stateful -------------- */
// an object that maintains its state in a node of the wave state.
Stateful = Classy({
id: "",
key: "",
stateNames: [],
_stateString: "",
_state: [],
removed: false,
loaded: false, // has it recieved a state update yet, or is it a placeholder
delta: {}, // delta is shared with all instances
constructor: function (id, key) {
this.id = id;
this.key = key;
},
// convert the state to a string.
// this should be overridden or augmented.
makeState: function () {
return {};
},
// update the state of the item
updateState: function (newStateString) {
if (!newStateString && this.removed) this.remove();
if (this.removed) return; // don't wake the dead
// first compare state by string to see if it is different at all.
if (newStateString == this._stateString) return;
// convert state to array
var newStateArray = newStateString.split(",");
// build an object of the new state
var newStateObject = {};
var changes = {};
// and find which properties are changed in the new state
for (var i = this.stateNames.length; i--;) {
var stateName = this.stateNames[i];
newStateObject[stateName] = newStateArray[i];
if (this._state[stateName] !== newStateArray[i]) {
// this property is changed
changes[stateName] = true;
}
}
// notify the object of the state change and updated properties
this.update(changes, newStateObject);
this._state = newStateObject;
this._stateString = newStateString;
this.loaded = true;
},
// encode the state into string format
makeStateString: function () {
if (this.removed) return null;
var stateObject = this.makeState();
var len = this.stateNames.length;
var stateArray = new Array(len);
for (var i = len; i--;) {
stateArray[i] = stateObject[this.stateNames[i]];
}
return stateArray.join(",");
},
// send the wave an update of this item's state
sendUpdate: function (local) {
this.queueUpdate(local);
this.flushUpdates();
},
// queue the item to be updated later.
queueUpdate: function (local) {
var stateString = this.makeStateString();
this.delta[this.key] = stateString;
if (local) {
this.updateState(stateString);
}
},
// send queued deltas
flushUpdates: function (local) {
waveState.submitDelta(this.delta);
Stateful.prototype.delta = {};
},
// send the update soon
asyncUpdate: function (local) {
this.queueUpdate(local);
if (!Stateful.updateTimeout) {
Stateful.updateTimeout = setTimeout(function () {
Stateful.prototype.flushUpdates();
delete Stateful.updateTimeout;
}, 10);
}
},
// delete this object
remove: function () {
this.removed = true;
},
markForRemoval: function () {
this.makeStateString = function () {
return null;
};
},
// Deal with a state change. Should be overridden
update: function () {}
});
/* -------------- Deck -------------- */
Deck = Classy(Stateful, {
stateNames: ["color", "cards"],
colors: ["blue", "red", "green"],
color: "",
colorId: 0,
decksByColor: [],
cards: [],
icon: null,
constructor: function () {
Stateful.apply(this, arguments);
this.cards = [];
this.icon = document.createElement("li");
// use first unused color id
for (var i = 0; this.decksByColor[i]; i++) {}
this.colorId = i;
this.renderColor();
var $this = this;
this.icon.onclick = function () {
if (confirm("Delete this deck?")) {
$this.markForRemoval();
$this.sendUpdate();
}
};
decksContainer.appendChild(this.icon);
},
makeState: function () {
return {
color: this.colorId,
cards: this.cards.map(function (item) {
return item.id;
}).join(";")
};
},
markForRemoval: function () {
this.cards.forEach(function (card) {
card.markForRemoval();
card.queueUpdate();
});
//this.remove();
Stateful.prototype.markForRemoval.call(this);
},
remove: function () {
if (this.removed) return;
Stateful.prototype.remove.call(this);
delete this.cards;
delete this.decksByColor[this.colorId];
decksContainer.removeChild(this.icon);
},
update: function (changes, newState) {
if (changes.cards) {
var cardIds = newState.cards.split(";");
var len = cardIds.length;
this.cards = new Array(len);
for (var i = len; i--;) {
this.cards[i] = getThing("card_" + cardIds[i]);
}
}
if (changes.color) {
delete this.decksByColor[this.colorId];
this.colorId = ~~newState.color;
this.renderColor();
}
},
renderColor: function () {
this.decksByColor[this.colorId] = this;
this.color = this.colors[this.colorId % 3];
this.icon.className = this.color;
this.icon.title = "Delete the " + this.color + " deck";
},
});
/* -------------- Card -------------- */
Card = Classy(Stateful, {
suits: ["diamonds", "spades", "hearts", "clubs"],
ranks: ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"],//, "joker"],
dom: (function () {
var wrapper, label, card, front, back;
// Create "prototype" DOM elements
(wrapper = document.createElement("div")) .className = "cardWrapper";
(card = document.createElement("div")) .className = "card";
(label = document.createElement("span")).className = "label";
(front = document.createElement("div")) .className = "front";
(back = document.createElement("div")) .className = "back";
wrapper.appendChild(card);
wrapper.appendChild(label);
card.appendChild(front);
card.appendChild(back);
return {
wrapper: wrapper
};
})(),
all: [], // all cards, by id. shared
x: 0,
y: 0,
z: 0,
suit: 0,
rank: 0,
width: 73,
height: 97,
title: "",
stateX: 0,
stateY: 0,
renderedZ: NaN,
oldX: 0,
oldY: 0,
oldZ: 0,
user: null, // wave user last to touch it
userClass: "", // css class representing the user
deck: null, // the deck this card is apart of
deckClass: "", // css class for the deck color
moving: false, // a wave user is holding or dragging the card
movingNow: false, // animating a move. not necessarily being held
selected: false, // is in the selection
dragging: false, // is being dragged by the mouse
faceup: false, // which side is up
flipping: false, // animating a flip
peeking: false, // we are peeking at the card
peeked: false, // someone else is peeking at the card
peekLock: false, // we are staying peeking at the card
overlaps: {}, // other movables that are overlapping this one.
stateNames: ["deck", "suit", "rank", "flip", "peeked", "moving",
"x", "y", "z", "user"],
makeState: function () {
with(this) {
return {
deck: deck ? deck.id : "",
suit: suit,
rank: rank,
x: ~~stateX,
y: ~~stateY,
z: ~~z,
flip: faceup ? "f" : "",
moving: moving ? "m" : "",
peeked: peeking ? "p" : "",
user: me ? me.getId() : null
};
}
},
constructor: function (id) {
Stateful.apply(this, arguments);
this.all[id] = this;
this.overlaps = [];
// Clone the dom elements for this instance
var wrapper, card;
this.dom = {
wrapper: (wrapper = this.dom.wrapper.cloneNode(1)),
card: (card = wrapper.childNodes[0]),
label: wrapper.childNodes[1],
front: card.childNodes[0],
back: card.childNodes[1]
};
// Give the dom elements references to this card object
for (var node in this.dom) {
this.dom[node].object = this;
}
},
remove: function () {
if (this.removed) return; // beat not the bones of the buried
Stateful.prototype.remove.call(this);
delete this.all[this.id];
// stop dragging
//if (captured == this) captured = null;
// remove from z-index cache
ZIndexCache.remove(this);
// deselect
if (this.selected) {
CardSelection.remove(this);
}
//if (this.selected) delete selection[selection.indexOf(this.selected)];
// stop any running transitions
Transition.stopAll(this.dom.card);
cardsContainer.removeChild(this.dom.wrapper);
// Remove DOM<->JS connections.
for (var node in this.dom) {
delete this.dom[node].object;
}
delete this.dom;
//deleteAll(this, ["wrapper", "card", "label", "front", "back"], ["object"]);
},
update: function (changes, newState) {
if (!this.loaded) {
// then this is the first state update.
// Insert the card into the page.
cardsContainer.appendChild(this.dom.wrapper);
}
if (changes.suit || changes.rank) {
if (changes.suit) this.suit = newState.suit;
if (changes.rank) this.rank = newState.rank;
this.renderFace();
}
if (changes.deck) {
this.deck = getThing("deck_" + newState.deck);
this.renderDeck();
// if the deck is not yet loaded, wait until it is.
if (!this.deck.loaded) {
var $this = this;
setTimeout(function () {
if ($this.deck.loaded) {
$this.renderDeck();
}
}, 1);
}
}
// if a card moves while it is selected and being dragged,
// refresh the selection's bounds
if (this.dragging && this.selected && (changes.x || changes.y || changes.z)) {
CardSelection.refreshBounds();
}
if (changes.x || changes.y) {
this.stateX = ~~newState.x;
this.stateY = ~~newState.y;
this.renderPosition(true);
}
if (changes.z) {
this.z = ~~newState.z;
this.renderZ();
}
if (changes.moving) {
// someone is holding or dragging the card
this.moving = (newState.moving=="m");
this.renderHighlight();
}
if (changes.user) {
// the user who last touched the card
this.user = wave.getParticipantById(newState.user);
this.renderUserLabel();
}
if (changes.flip) {
// Flip the card
this.faceup = !!newState.flip;
this.renderFlip();
} else if (changes.peeked) {
// a user is peeking at the card.
this.peeked = newState.peeked;
if (this.peeking && this.user != me) {
// we were peeking at the card but now someone else has taken it,
// so now we have to stop peeking at it.
this.peeking = false;
}
this.renderPeek();
this.renderHighlight();
}
},
flip: function (queue) {
this.faceup = !this.faceup;
this.asyncUpdate();
},
peekStart: function () {
with(this) {
if (!peeking) {
peeking = true;
if (peekLockMode) {
this.peekLock = true;
}
renderPeek();
asyncUpdate();
}
}
},
peekStop: function () {
// delay so that other clients have time to notice the peek
var $this = this;
setTimeout(function () {
// if this card's peek lock is on, then we stay peeking at it.
if (!$this.peekLock) {
$this.peeking = false;
$this.peeked = false;
$this.renderPeek();
$this.renderHighlight();
$this.asyncUpdate();
}
}, transitionDuration);
},
// return whether an object is overlapping another.
isOverlapping: function (thing) {
if (this === thing) return false; // can't overlap itself
var xDelta = thing.x - this.x;
var yDelta = thing.y - this.y;
return ((xDelta < this.width) && (-xDelta < thing.width) &&
(yDelta < this.height) && (-yDelta < thing.height));
},
// return id map of all cards overlapping this one.
getOverlappingObjects: function () {
var overlappingObjects = {};
var all = Card.prototype.all;
for (var i in all) {
var item = all[i];
if (this.isOverlapping(item)) {
overlappingObjects[i] = item;
}
}
return overlappingObjects;
},
// detect and process cards that overlap with this one.
detectOverlaps: function () {
var overlaps = this.getOverlappingObjects();
for (var i in overlaps) {
if (!this.overlaps[i]) this.onOverlap(overlaps[i]);
}
this.overlaps = overlaps;
},
dragStart: function (x, y, e) {
//captured = this;
this.user = me;
// stop the card if it is moving.
if (this.movingNow) {
this.x = this.dom.wrapper.offsetLeft;
this.y = this.dom.wrapper.offsetTop;
this.renderPositionStatic();
}
this.startX = x - this.x;
this.startY = y - this.y;
// the viewer is holding the card
this.user = me;
this.moving = true;
this.asyncUpdate();
return false;
},
drag: function (x, y) {
this.oldX = this.x;
this.oldY = this.y;
this.x = x - this.startX;
this.y = y - this.startY;
this.renderPositionStatic();
},
dragEnd: function () {
this.stateX = this.x;
this.stateY = this.y;
this.moving = false;
// when the user lets go of a card, they stop peeking at it
// unless in peek lock mode
if (this.peeking && !this.peekLock) {
this.peekStop();
}
this.asyncUpdate();
this.renderHighlight();
},
/* About the layering modes:
The goal is for moving the cards around to feel as realistic as possible. There are two layering modes: drag-under mode and drag-over mode, represented by the boolean var dragUnderMode. They are toggled by holding the "u" key. In drag-under mode, dragged cards should slide under the other cards. In drag-over mode, they should be able to be placed above the other cards. This all has to be done while maintaining the layering so that you cannot move a card up "through" another card.
The way it is done is this:
The selection is being dragged.
A card (A) in the selection is being detected to be overlapping an outside card (B).
If in drag-under mode, raise every card in the selection above card B.
Else, raise card A above card B.
Also raise every card that is above the card being raised,
unless one of them is the card being raised over,
in which case do nothing.
*/
// Raise a group of cards and every card overlapping above them,
// above the current card.
raise: function (cardsToRaise) {
cardsToRaise = Array.prototype.concat.call(cardsToRaise);
var numCardsToRaise = cardsToRaise.length;
if (!numCardsToRaise) {
// nothing to raise
return;
}
// Get the minimum z of the cards to be raised.
var lowestCard = cardsToRaise[0];
var lowestZ = lowestCard.z;
for (var i = numCardsToRaise - 1; i--;) {
var card = cardsToRaise[i];
if (card.z < lowestZ) {
lowestCard = card;
lowestZ = card.z;
}
}
// Get the cards that overlap above this card (recursively).
// Get cards with z >= the lowest base cardthis card's z.
var cardsAbove = ZIndexCache.getAbove(lowestZ);
// Ones of these that overlap with this card (or with one that does, etc),
// will need to be raised along with this one.
// for each card with z >= this card
for (i = cardsAbove.length; i--;) {
var cardAbove = cardsAbove[i];
// check if card overlaps with any of the cards to be raised
for (var j = 0; j < numCardsToRaise; j++) {
var cardToRaise = cardsToRaise[j];
if (cardToRaise.isOverlapping(cardAbove)) {
// It overlaps.
// Make sure it is not a knot.
if (cardAbove === this) {
// This would mean raising a card above itself,
// which is not possible. Abort!
//if (window.console) console.log('knot');
return false;
} else {
// it overlaps, therefore it will be raised too.
cardsToRaise[numCardsToRaise++] = cardAbove;
break;
}
}
}
}
// Raise the cards while maintaining the stacking order.
// Minimizing the distances between them, without lowering them
var raiseAmount = this.z - lowestZ + 1;
var zPrev = Infinity;
for (i = 0; i < numCardsToRaise; i++) {
var card = cardsToRaise[i];
zDelta = card.z - zPrev;
zPrev = card.z;
if (zDelta > 1) {
raiseAmount -= zDelta - 1;
if (raiseAmount < 1) {
// can't do lowering yet. (TODO)
break;
}
}
card.z += raiseAmount;
card.renderZ();
card.queueUpdate();
}
return true;
},
/* -------------- Card View functions -------------- */
// Set the card's classes and title to its suit and rank.
renderFace: function () {
// to do: change this so that it doesn't overwrite other classNames.
var rank = this.ranks[this.rank];
var suit = this.suits[this.suit];
addClass(this.dom.front, rank);
addClass(this.dom.front, suit);
this.title = rank + " of " + suit;
this.dom.front.setAttribute("title", this.title);
},
renderUserLabel: function () {
var playerNum = players.indexOf(this.user)+1;
// replace old class with new one
if (this.userClass) {
removeClass(this.dom.wrapper, this.userClass);
}
this.userClass = "p" + ((playerNum % 8) + 1);
addClass(this.dom.wrapper, this.userClass);
//timeout?
if (this.user) {
// Set the label to the player's first name,
// or blank if they are the viewer.
var userLabel = (this.user == me) ? "" :
this.user.getDisplayName().match(/^[^ ]+/, '')[0];
this.dom.label.innerHTML = userLabel;
}
},
// If the user wants to peek at the card, show a corner of the back through the front.
renderPeek: function () {
toggleClass(this.dom.wrapper, "peeked", this.peeked || this.peeking);
toggleClass(this.dom.wrapper, "peeking", this.peeking);
},
// determine whether the card should have a highlight or not
needsHighlight: function () {
return this.flipping || this.peeking || this.peeked || this.moving || this.movingNow;
},
// set whether the card is selected or not
renderSelected: function () {
toggleClass(this.dom.wrapper, "selected", this.selected);
this.renderHighlight();
},
// Display or hide the card's highlight and player label.
renderHighlight: function () {
var needsHighlight = this.needsHighlight();
if (needsHighlight == this.highlighted) {
return;
}
this.highlighted = needsHighlight;
toggleClass(this.dom.wrapper, "highlight", needsHighlight);
// Fade hiding the label, but show it immediately
if (needsHighlight) {
if (this.dom.label._transitions && this.dom.label._transitions.opacity) {
this.dom.label._transitions.opacity.stop();
}
this.dom.label.style.opacity = 1;
this.dom.label.style.visibility = "visible";
} else {
Transition(
this.dom.label,
{opacity: 0},
transitionDuration*(this.user == me ? .5 : 3),
function (n) {
// Hide the label when the animation is done so it doesn't get in the way of other things
if (this.style.opacity == 0) {
this.style.visibility = "hidden";
}
}
);
}
},
// move the card to its x and y.
renderPosition: function (transition) {
if ((this.x == this.stateX) && (this.y == this.stateY)) {
// no change
return;
}
var oldX = this.x;
this.x = ~~this.stateX;
this.y = ~~this.stateY;
if (transition && !isNaN(this.x)) {
var $this = this;
this.movingNow = true;
this.renderHighlight();
Transition(this.dom.wrapper, {
left: this.x + "px",
top: this.y + "px"
}, transitionDuration, function (n) {
$this.movingNow = false;
$this.renderHighlight();
});
} else {
this.renderPositionStatic();
}
},
renderPositionStatic: function () {
this.movingNow = false;
this.dom.wrapper.style.left = this.x + "px";
this.dom.wrapper.style.top = this.y + "px";
},
// set the z-index of the element to the z of the object.
renderZ: function () {
if (this.z === this.renderedZ) {
return false;
}
if (this.z > 100000) {
// problem: the z-index shouldn't get this high in the first place.
this.z = 0;
throw new Error("z-index is too high!");
}
ZIndexCache.remove(this, this.renderedZ);
ZIndexCache.add(this);
this.renderedZ = this.z;
this.dom.card.style.zIndex = this.z;
if (this.z > highestZ) highestZ = this.z;
},
// helper functions for renderFlip
removeFlipClass: function () {
removeClass(this.dom.wrapper, this.faceup ? "facedown" : "faceup");
},
flipClasses: function () {
this.removeFlipClass();
addClass(this.dom.wrapper, this.faceup ? "faceup" : "facedown");
},
renderFlip: function () {
var $this, faceup, a, halfWay, t, rotater;
faceup = this.faceup;
$this = this;
if (this.isFaceup === undefined) {
this.isFaceup = faceup;
return this.flipClasses();
}
this.flipping = true;
this.renderHighlight();
// Animate the flip with the transform property if it is supported, otherwise opacity.
var cssTransform = Transition.cssTransformType;
if (cssTransform) {
/*
Safari 3 and Mozilla 3.5 support CSS Transformations. Safari 4
and Chrome support rotateY, a 3D transformation. So we use
rotateY if it is supported, otherwise a matrix "stretch".
Fall back on opacity if transforms are not supported.
*/
if (window.WebKitCSSMatrix) {
this.dom[faceup ? "back" : "front"].style[cssTransform] = "rotateY(180deg)"
// rotate to 0 from 180 or -180
a = faceup ? -1 : 1;
rotater = function (n) {
return "rotateY(" + 180*(a + -a*n) + "deg)";
};
halfWay = 3; // 3 not 2 because of the easing function i think
} else {
//
this.dom[faceup ? "back" : "front"].style[cssTransform] = "matrix(-1, 0, 0, 1, 0, 0)";
// flip from -1 to 1, reverse to front
rotater = function (n) {
return "matrix(" + (-1 + 2*n) + ", 0, 0, 1, 0, 0)";
};
halfWay = 2;
}
this.dom.card.style[cssTransform] = rotater(0);
t = {};
t[cssTransform] = rotater;
Transition(this.dom.card, t, transitionDuration, function () {
$this.dom.card.style[cssTransform] = "";
$this.dom.front.style[cssTransform] = "";
$this.dom.back.style[cssTransform] = "";
$this.flipping = false;
$this.renderHighlight();
$this.removeFlipClass();
});
setTimeout(function () {
$this.flipClasses();
}, transitionDuration / halfWay);
} else {
// no transforms; use opacity.
this.dom.back.style.opacity = ~~faceup;
this.removeFlipClass();
Transition(this.dom.back, {opacity: ~~!this.faceup}, transitionDuration, function () {
$this.flipClasses();
$this.flipping = false;
$this.renderHighlight();
});
}
},
renderDeck: function () {
if (this.deckClass) {
removeClass(this.dom.card, this.deckClass);
}
this.deckClass = this.deck.color;
addClass(this.dom.card, this.deckClass);
}
});
// source: http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
// Cards Selection
var CardSelection = {
cards: [],
x: 0,
y: 0,
startX: 0,
startY: 0,
width: 0,
height: 0,
z: 0, // highest z
z1: 0, // lowest z
overlappers: [], // cards that overlap a card in the selection
overlappees: {}, // Cards in the selection that have an overlapper,
// by the id of their overlapper
// Clear the selection
clear: function () {
this.cards.forEach(function (card) {
card.selected = false;
card.renderSelected();
});
this.cards = [];
},
// add a card to the selection
add: function (card) {
if (!card.selected) {
this.cards.push(card);
card.selected = true;
card.renderSelected();
}
},
// remove a card from the selection
remove: function (card) {
this.cards.splice(this.cards.indexOf(card), 1);
},
// compute the dimensions and coordinates of the selection as a whole
refreshBounds: function () {
var cards = this.cards,
x1 = Infinity,
x2 = -Infinity,
y1 = Infinity,
y2 = -Infinity,
z1 = Infinity,
z2 = -Infinity;
for (i = cards.length; i--;) {
with(cards[i]) {
var x3 = x + width;
var y3 = y + height;
if (x < x1) x1 = x;
if (x3 > x2) x2 = x3;
if (y < y1) y1 = y;
if (y3 > y2) y2 = y3;
if (z < z1) z1 = z;
if (z > z2) z2 = z;
}
}
this.x = x1;
this.width = x2 - x1;
this.y = y1;
this.height = y2 - y1;
this.z = z2;
this.z1 = z1;
},
// Collision detection.
// Detect what cards are in the way of the selection
detectOverlaps: function () {
var cardsNear, i, j, len, overlappers, overlappees, card, overlappee;
// find cards that might be in the way.
if (dragUnderMode) {
cardsNear = ZIndexCache.getBelow(this.z);
} else {
cardsNear = ZIndexCache.getAbove(this.z1);
}
len = cardsNear.length;
j = 0;
overlappers = new Array(len);
overlappees = {};
for (i = 0; i < len; i++) {
card = cardsNear[i];
// don't test for collision with self
if (!card.selected) {
overlappee = this.nowOverlaps(card);
if (overlappee) {
// Collision!
// Overlappee is the card in the selection that is
// being overlapped by the overlapper, card.
overlappees[card.id] = overlappee;
overlappers[j++] = card;
}
}
}
this.overlappees = overlappees;
this.overlappers = overlappers;
},
// start dragging the selected cards
dragStart: function (x, y) {
this.cards.forEach(function (card) {
card.dragStart(x, y);
});
this.refreshBounds();
this.detectOverlaps();
this.startX = x - this.x;
this.startY = y - this.y;
},
drag: function (x, y) {
var cards, overlapper, i, oldOverlappees, overlappers, overlappee, oldOverlappee;
// update the position of each card
cards = this.cards;
for (i = cards.length; i--;) {
cards[i].drag(x, y);
}
// update the position of the selection as a whole
this.x = x - this.startX;
this.y = y - this.startY;
oldOverlappees = this.overlappees;
this.detectOverlaps();
overlappers = this.overlappers; // cards that overlap a card in the selection
for (i = 0; overlapper = overlappers[i]; i++) {
oldOverlappee = oldOverlappees[overlapper.id];
overlappee = this.overlappees[overlapper.id];
if (overlappee != oldOverlappee) {
// The overlap is new, or with a different card than before.
// Temporarily move back the overlappee to before it was
// overlapping, so it doesn't get in the way of itself.
with(overlappee) {
var realX = x;
var realY = y;
x = oldX;
y = oldY;
}
// Raise the Z of one pile over one card.
if (dragUnderMode) {
overlappee.raise(overlapper);
} else {
overlapper.raise(CardSelection.cards);
}
// Restore overlappee position.
overlappee.x = realX;
overlappee.y = realY;
overlappee.sendUpdate(true);
// Because the selection's Z has changed, recalculate its
// bounds.
this.refreshBounds();
// don't need to test for any more collisions, because
// the overlaps are ordered by significance
break;
}
}
},
dragEnd: function () {
this.cards.forEach(function (card) {
card.dragEnd();
});
},
// If a card overlaps the selection now, return the card in the selection
// that it overlaps with.
nowOverlaps: function (card) {
if (card.isOverlapping(this)) {
// Now find exactly which card in the selection is overlapping.
// In drag-under mode, find the highest card in the selection
// that overlaps with the given card. In drag-over mode, find
// the lowest.
var zStart, zEnd, zInc
if (dragUnderMode) {
zStart = this.z;
zEnd = this.z1;
zInc = -1;
} else {
zStart = this.z1;
zEnd = this.z;
zInc = 1;
}
var buckets = ZIndexCache.buckets;
for (var z = zStart; z != (zEnd + zInc); z += zInc) {
var bucket = buckets[z];
if (bucket) {
for (var i = 0, l = bucket.length; i < l; i++) {
var card2 = bucket[i];
if (card2.selected && card2.isOverlapping(card)) {
return card2;
}
}
}
}
}
return false;
},
peekStart: function () {
this.cards.forEach(function (card) {
card.peekStart();
});
},
peekStop: function () {
this.cards.forEach(function (card) {
card.peekStop();
});
},
peekLock: function () {
this.cards.forEach(function (card) {
card.peekLock ^= 1;
});
},
// flip the positions of the cards, not just the faces.
flip: function () {
this.refreshBounds();
var xx = 2 * this.x + this.width,
zz = this.z + this.z1;
this.cards.forEach(function (card) {
card.stateX = xx - (card.x + card.width);
card.z = zz - card.z;
//card.flip();
card.faceup = !card.faceup;
card.queueUpdate();
});
Stateful.prototype.flushUpdates();
},
// shuffle the positions of the selected cards
shuffle: function () {
var cards = this.cards;
// randomly reassign the position properties of each card
var positions = cards.map(function (card) {
return {
x: card.x,
y: card.y,
z: card.z,
faceup: card.faceup
};
});
shuffle(positions);
positions.forEach(function (pos, i) {
with(cards[i]) {
stateX = pos.x;
stateY = pos.y;
z = pos.z;
faceup = pos.faceup;
queueUpdate();
}
});
Stateful.prototype.flushUpdates();
}
};
var ZIndexCache = {
buckets: [], // array of "buckets" of each card with a particular z value
aboveCache: {}, // cache for getAbove()
belowCache: {}, // cache for getBelow()
hasCaches: false, // are aboveCache and belowCache useful
// add a card into the z-index cache
add: function (card) {
if (this.hasCaches) {
this.aboveCache = {};
this.belowCache = {};
this.hasCaches = false;
}
var z = card.z;
var bucket = this.buckets[z];
if (bucket) {
bucket[bucket.length] = card;
} else {
this.buckets[z] = [card];
}
},
// remove a card from the z-index cache, optionally from a particular bucket
remove: function (card, z) {
if (this.hasCaches) {
this.aboveCache = {};
this.belowCache = {};
this.hasCaches = false;
}
if (z === undefined) z = card.z;
var bucket = this.buckets[z];
if (bucket) {
var index = bucket.indexOf(card);
if (index != -1) {
bucket.splice(index, 1);
}
}
},
// get cards with z >= a given amount, starting from max
getAbove: function (zMin) {
var cards, i, j, z, buckets, bucket, cache;
// check cache first
if (cache = this.aboveCache[zMin]) {
return cache;
}
cards = [];
j = 0;
buckets = this.buckets;
for (z = buckets.length-1; z >= zMin; z--) {
if (bucket = buckets[z]) {
// add each card in this bucket
for (i = bucket.length; i--;) {
cards[j++] = bucket[i];
}
}
}
this.aboveCache[zMin] = cards;
this.hasCaches = true;
return cards;
},
// get cards with z <= a given amount, starting from 0
getBelow: function (zMax) {
var cards, i, j, z, buckets, bucket, cache;
// check cache first
if (cache = this.belowCache[zMax]) {
return cache;
}
cards = [];
j = 0;
buckets = this.buckets;
for (z = 0; z <= zMax; z++) {
if (bucket = buckets[z]) {
// add each card in this bucket
for (i = bucket.length; i--;) {
cards[j++] = bucket[i];
}
}
}
this.belowCache[zMax] = cards;
this.hasCaches = true;
return cards;
}
};
// Drag Selection Box
var SelectionBox = {
div: (function () {
var div = document.createElement("div");
div.id = "selectionBox";
return div;
})(),
firstMove: false,
startX: 0,
startY: 0,
x: 0,
y: 0,
width: 0,
height: 0,
overlaps: {},
getOverlappingObjects: Card.prototype.getOverlappingObjects,
isOverlapping: Card.prototype.isOverlapping,
detectOverlaps: function () {
var overlaps = this.getOverlappingObjects();
for (var i in overlaps) {
if (!this.overlaps[i]) this.onOverlap(overlaps[i]);
}
for (var i in this.overlaps) {
if (!overlaps[i]) this.onUnOverlap(this.overlaps[i]);
}
this.overlaps = overlaps;
},
onOverlap: function (card) {
CardSelection.add(card);
},
onUnOverlap: function (card) {
CardSelection.remove(card);
card.selected = false;
card.renderSelected();
},
// start a selection box
dragStart: function (x, y) {
this.dragging = true;
this.startX = x;
this.startY = y;
this.firstMove = true;
},
drag: function (endX, endY) {
with(this) {
x = Math.min(startX, endX) +
(document.documentElement.scrollLeft + document.body.scrollLeft +
cardsWindow.scrollLeft - cardsWindow.offsetLeft);
y = Math.min(startY, endY) +
(document.documentElement.scrollTop + document.body.scrollTop +
cardsWindow.scrollTop - cardsWindow.offsetTop);
width = Math.abs(startX - endX);
height = Math.abs(startY - endY);
with(div.style) {
left = x + "px";
top = y + "px";
width = this.width + "px";
height = this.height + "px";
}
detectOverlaps();
if (firstMove) {
cardsContainer.appendChild(div);
firstMove = false;
}
}
},
dragEnd: function () {
if (!this.firstMove) {
this.dragging = false;
cardsContainer.removeChild(this.div);
}
}
};
})(); | cards.js | /*
Wave-Cards
A Google Wave Gadget for playing cards
v1.0
Copyright (c) 2009 Charles Lehner
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.
*/
(function () {
var
cardsContainer, // #cards
cardsWindow, // #cardsWindow
decksContainer, // #decks
rotation = 0, // angle the card container is rotated.
transitionDuration = 250, // length (ms) of a transition/animation
peekLockMode = false, // to allow cards to be peeked at indefinitely
dragUnderMode = false, // to slide cards over or above other cards
drag, // object being currently dragged
players = [], // wave participants
highestId = 0, // highest card id
highestZ = 0, // highest z-index of a card
hasFocus, // whether the window has the user's focus
me, // the participant whose client renders the gadget
things = {}, // objects (cards and decks) encoded in the wave state
waveState, // the wave gadget state
waveStateKeys = [], // the keys of the gadget state
waveStateValues = {}, // the values of the gadget state
playersLoaded = false,
stateLoaded = false,
gadgetLoaded = false;
/*
#cardsWindow
#hostButtons
#addDeck
#rotate
#cards
*/
/* -------------- State stuff -------------- */
function gadgetLoad() {
// run once
if (gadgetLoaded) return;
// Get dom references
cardsContainer = document.getElementById("cards");
cardsWindow = document.getElementById("cardsWindow");
decksContainer = document.getElementById("decks");
// Wait for cardsContainer to be available
if (!cardsContainer) {
return setTimeout(arguments.callee, 20);
}
// Attach the listeners
addEventListener("keydown", onKeyDown, false);
addEventListener("keyup", onKeyUp, false);
addEventListener("blur", onBlur, false);
addEventListener("focus", onFocus, false);
cardsContainer.addEventListener("mousedown", onMouseDown, false);
document.getElementById("rotateBtn").addEventListener("click",
rotateTable, false);
document.getElementById("addDeckBtn").addEventListener("click",
addDeck, false);
// Set up wave callbacks
if (wave && wave.isInWaveContainer()) {
wave.setStateCallback(stateUpdated);
wave.setParticipantCallback(participantsUpdated);
}
gadgetLoaded = true;
}
gadgets.util.registerOnLoadHandler(gadgetLoad);
// called when the wave state is updated
function stateUpdated() {
var keys, i, key, value, thing;
// we must wait for the players list before loading the cards
if (!playersLoaded) {
return;
}
waveState = wave.getState();
if (!waveState) {
return;
}
keys = waveState.getKeys();
waveStateValues = {};
// Update stuff
for (i=0; (key=keys[i]); i++) {
value = waveState.get(key);
waveStateValues[key] = value;
thing = getThing(key);
thing.updateState(value);
}
// Check for deleted values
// Look for keys that were in the state before but now are not.
for (i=waveStateKeys.length; i--;) {
if (!(waveStateKeys[i] in waveStateValues)) {
thing = getThing(waveStateKeys[i]);
thing.remove();
}
}
waveStateKeys = keys;
stateLoaded = true;
}
function participantsUpdated() {
players = wave.getParticipants();
if (!playersLoaded) {
// This is the first participant update
me = wave.getViewer();
if (me) {
playersLoaded = true;
stateUpdated();
}
}
}
function onMouseDown(e) {
// start mouse drag
addEventListener("mousemove", onDrag, false);
addEventListener("mouseup", onMouseUp, false);
if (e.target && e.target.object && e.target.object instanceof Card) {
// mousedown on a card
drag = CardSelection;
var card = e.target.object;
if (!card.selected && !e.shiftKey) {
CardSelection.clear();
}
CardSelection.add(card);
if (hasFocus) {
// prevent dragging the images in firefox
if (e.preventDefault) e.preventDefault();
}
} else {
// mousedown on empty space, create a selection box.
// clear the selection unless shift is held
if (!e.shiftKey) {
CardSelection.clear();
}
drag = SelectionBox;
}
var rot = rotatePoint(e.clientX, e.clientY, rotation,
cardsContainer.offsetWidth, cardsContainer.offsetHeight);
drag.dragStart(rot.x, rot.y, e);
}
function onMouseUp() {
// release the drag
drag.dragEnd();
drag = null;
removeEventListener("mouseup", onMouseUp, false);
removeEventListener("mousemove", onDrag, false);
}
function onDrag(e) {
var rot = rotatePoint(e.clientX, e.clientY, rotation,
cardsContainer.offsetWidth, cardsContainer.offsetHeight);
drag.drag(rot.x, rot.y);
}
// Hotkeys
var keydowns = {};
function onKeyDown(e) {
var key = e.keyCode;
if (keydowns[key]) {
return true;
}
keydowns[key] = true;
switch(key) {
// U - drag cards under other cards
case 85:
dragUnderMode = true;
CardSelection.detectOverlaps();
break;
// S - Shuffle the selected cards
case 83:
CardSelection.shuffle();
break;
// G - Group
case 72:
// TODO
break;
// F - Flip
case 70:
CardSelection.flip();
break;
// P - peek start
case 80:
CardSelection.peekStart();
break;
// L - peek lock on
case 76:
peekLockMode = true;
CardSelection.peekLock();
}
}
function onKeyUp(e) {
var key = e.keyCode;
keydowns[key] = false;
switch(key) {
// U - slide cards above other cards
case 85:
dragUnderMode = false;
CardSelection.detectOverlaps();
break;
// P - peek stop
case 80:
CardSelection.peekStop();
break;
// L - peek lock off
case 76:
peekLockMode = false;
}
}
function onFocus() {
hasFocus = true;
}
// stop dragging cards when the window loses focus
function onBlur() {
hasFocus = false;
if (drag) {
onMouseUp();
}
}
// get a stateful object (card or deck) by its key in the wave state
function getThing(key) {
if (things[key]) {
return things[key];
}
var key2 = key.split("_");
var type = key2[0];
var id = ~~key2[1];
highestId = Math.max(highestId, id);
var thing =
type == "card" ? new Card(id, key) :
type == "deck" ? new Deck(id, key) :
new Stateful(id, key);
things[key] = thing;
return thing;
}
// create a deck of cards
function addDeck() {
var newDeck, cards, card, i, s, r;
newDeck = getThing("deck_"+(++highestId));
cards = newDeck.cards;
i = 0;
for (s = 0; s < 4; s++) {
for (r = 0; r < 13; r++) {
with(cards[i++] = getThing("card_"+(++highestId))) {
suit = s;
rank = r;
stateX = stateY = 30 + ~~(i/3);
z = ++highestZ;
deck = newDeck;
queueUpdate();
}
}
}
newDeck.sendUpdate();
}
// rotate the cards container 90 degrees
function rotateTable() {
var oldRotation = rotation;
rotation += 90;
var rotater = function (n) {
return "rotate(" + (oldRotation + 90 * n) + "deg)";
};
var t = {};
t[Transition.cssTransformType] = rotater;
Transition(cardsContainer, t, transitionDuration);
}
// get the coordinates of a point rotated around another point a certain angle
function rotatePoint(x, y, a, w, h) {
//a %= 360;
a = a % 360 + (a < 0 ? 360 : 0);
switch (a) {
case 0:
return {x: x, y: y};
case 90:
return {x: y, y: h-x};
case 180:
return {x: w-x, y: h-y};
case 270:
return {x: w-y, y: x};
default:
// TODO: fancy matrix stuff
}
}
// Return whether or not an element has a class.
function hasClass(ele, cls) {
if (!ele) throw new Error("not an element, can't add class name.");
if (ele.className) {
return new RegExp("(\\s|^)" + cls + "(\\s|$)").test(ele.className);
}
}
// Add a class to an element.
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
// Remove a class from an element.
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
ele.className = ele.className.replace(reg, " ");
}
}
// Add or remove a class from an element
function toggleClass(ele, cls, yes) {
if (yes) addClass(ele, cls);
else removeClass(ele, cls);
}
/* -------------- Stateful -------------- */
// an object that maintains its state in a node of the wave state.
Stateful = Classy({
id: "",
key: "",
stateNames: [],
_stateString: "",
_state: [],
removed: false,
loaded: false, // has it recieved a state update yet, or is it a placeholder
delta: {}, // delta is shared with all instances
constructor: function (id, key) {
this.id = id;
this.key = key;
},
// convert the state to a string.
// this should be overridden or augmented.
makeState: function () {
return {};
},
// update the state of the item
updateState: function (newStateString) {
if (!newStateString) this.remove();
if (this.removed) return; // don't wake the dead
// first compare state by string to see if it is different at all.
if (newStateString == this._stateString) return;
// convert state to array
var newStateArray = newStateString.split(",");
// build an object of the new state
var newStateObject = {};
var changes = {};
// and find which properties are changed in the new state
for (var i = this.stateNames.length; i--;) {
var stateName = this.stateNames[i];
newStateObject[stateName] = newStateArray[i];
if (this._state[stateName] !== newStateArray[i]) {
// this property is changed
changes[stateName] = true;
}
}
// notify the object of the state change and updated properties
this.update(changes, newStateObject);
this._state = newStateObject;
this._stateString = newStateString;
this.loaded = true;
},
// encode the state into string format
makeStateString: function () {
if (this.removed) return null;
var stateObject = this.makeState();
var len = this.stateNames.length;
var stateArray = new Array(len);
for (var i = len; i--;) {
stateArray[i] = stateObject[this.stateNames[i]];
}
return stateArray.join(",");
},
// send the wave an update of this item's state
sendUpdate: function (local) {
this.queueUpdate(local);
this.flushUpdates();
},
// queue the item to be updated later.
queueUpdate: function (local) {
var stateString = this.makeStateString();
this.delta[this.key] = stateString;
if (local) {
this.updateState(stateString);
}
},
// send queued deltas
flushUpdates: function (local) {
waveState.submitDelta(this.delta);
Stateful.prototype.delta = {};
},
// send the update soon
asyncUpdate: function (local) {
this.queueUpdate(local);
if (!Stateful.updateTimeout) {
Stateful.updateTimeout = setTimeout(function () {
Stateful.prototype.flushUpdates();
delete Stateful.updateTimeout;
}, 10);
}
},
// delete this object
remove: function () {
this.removed = true;
delete things[this.key];
},
markForRemoval: function () {
this.makeStateString = function () {
return null;
};
},
// Deal with a state change. Should be overridden
update: function () {}
});
/* -------------- Deck -------------- */
Deck = Classy(Stateful, {
stateNames: ["color", "cards"],
colors: ["blue", "red", "green"],
color: "",
colorId: 0,
decksByColor: [],
cards: [],
icon: null,
constructor: function () {
Stateful.apply(this, arguments);
this.cards = [];
this.icon = document.createElement("li");
// use first unused color id
for (var i = 0; this.decksByColor[i]; i++) {}
this.colorId = i;
this.renderColor();
var $this = this;
this.icon.onclick = function () {
if (confirm("Delete this deck?")) {
$this.markForRemoval();
$this.sendUpdate();
}
};
decksContainer.appendChild(this.icon);
},
makeState: function () {
return {
color: this.colorId,
cards: this.cards.map(function (item) {
return item.id;
}).join(";")
};
},
markForRemoval: function () {
this.cards.forEach(function (card) {
card.markForRemoval();
card.queueUpdate();
});
this.remove();
Stateful.prototype.markForRemoval.call(this);
},
remove: function () {
if (this.removed) return;
Stateful.prototype.remove.call(this);
delete this.cards;
delete this.decksByColor[this.colorId];
decksContainer.removeChild(this.icon);
},
update: function (changes, newState) {
if (changes.cards) {
var cardIds = newState.cards.split(";");
var len = cardIds.length;
this.cards = new Array(len);
for (var i = len; i--;) {
this.cards[i] = getThing("card_" + cardIds[i]);
}
}
if (changes.color) {
delete this.decksByColor[this.colorId];
this.colorId = ~~newState.color;
this.renderColor();
}
},
renderColor: function () {
this.decksByColor[this.colorId] = this;
this.color = this.colors[this.colorId % 3];
this.icon.className = this.color;
this.icon.title = "Delete the " + this.color + " deck";
},
});
/* -------------- Card -------------- */
Card = Classy(Stateful, {
suits: ["diamonds", "spades", "hearts", "clubs"],
ranks: ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"],//, "joker"],
dom: (function () {
var wrapper, label, card, front, back;
// Create "prototype" DOM elements
(wrapper = document.createElement("div")) .className = "cardWrapper";
(card = document.createElement("div")) .className = "card";
(label = document.createElement("span")).className = "label";
(front = document.createElement("div")) .className = "front";
(back = document.createElement("div")) .className = "back";
wrapper.appendChild(card);
wrapper.appendChild(label);
card.appendChild(front);
card.appendChild(back);
return {
wrapper: wrapper
};
})(),
all: [], // all cards, by id. shared
x: 0,
y: 0,
z: 0,
suit: 0,
rank: 0,
width: 73,
height: 97,
title: "",
stateX: 0,
stateY: 0,
renderedZ: NaN,
oldX: 0,
oldY: 0,
oldZ: 0,
user: null, // wave user last to touch it
userClass: "", // css class representing the user
deck: null, // the deck this card is apart of
deckClass: "", // css class for the deck color
moving: false, // a wave user is holding or dragging the card
movingNow: false, // animating a move. not necessarily being held
selected: false, // is in the selection
dragging: false, // is being dragged by the mouse
faceup: false, // which side is up
flipping: false, // animating a flip
peeking: false, // we are peeking at the card
peeked: false, // someone else is peeking at the card
peekLock: false, // we are staying peeking at the card
overlaps: {}, // other movables that are overlapping this one.
stateNames: ["deck", "suit", "rank", "flip", "peeked", "moving",
"x", "y", "z", "user"],
makeState: function () {
with(this) {
return {
deck: deck ? deck.id : "",
suit: suit,
rank: rank,
x: ~~stateX,
y: ~~stateY,
z: ~~z,
flip: faceup ? "f" : "",
moving: moving ? "m" : "",
peeked: peeking ? "p" : "",
user: me ? me.getId() : null
};
}
},
constructor: function (id) {
Stateful.apply(this, arguments);
this.all[id] = this;
this.overlaps = [];
// Clone the dom elements for this instance
var wrapper, card;
this.dom = {
wrapper: (wrapper = this.dom.wrapper.cloneNode(1)),
card: (card = wrapper.childNodes[0]),
label: wrapper.childNodes[1],
front: card.childNodes[0],
back: card.childNodes[1]
};
// Give the dom elements references to this card object
for (var node in this.dom) {
this.dom[node].object = this;
}
},
remove: function () {
if (this.removed) return; // beat not the bones of the buried
Stateful.prototype.remove.call(this);
delete this.all[this.id];
// stop dragging
//if (captured == this) captured = null;
// remove from z-index cache
ZIndexCache.remove(this);
// deselect
if (this.selected) {
CardSelection.remove(this);
}
//if (this.selected) delete selection[selection.indexOf(this.selected)];
// stop any running transitions
Transition.stopAll(this.dom.card);
cardsContainer.removeChild(this.dom.wrapper);
// Remove DOM<->JS connections.
for (var node in this.dom) {
delete this.dom[node].object;
}
delete this.dom;
//deleteAll(this, ["wrapper", "card", "label", "front", "back"], ["object"]);
},
update: function (changes, newState) {
if (!this.loaded) {
// then this is the first state update.
// Insert the card into the page.
cardsContainer.appendChild(this.dom.wrapper);
}
if (changes.suit || changes.rank) {
if (changes.suit) this.suit = newState.suit;
if (changes.rank) this.rank = newState.rank;
this.renderFace();
}
if (changes.deck) {
this.deck = getThing("deck_" + newState.deck);
this.renderDeck();
// if the deck is not yet loaded, wait until it is.
if (!this.deck.loaded) {
var $this = this;
setTimeout(function () {
if ($this.deck.loaded) {
$this.renderDeck();
}
}, 1);
}
}
// if a card moves while it is selected and being dragged,
// refresh the selection's bounds
if (this.dragging && this.selected && (changes.x || changes.y || changes.z)) {
CardSelection.refreshBounds();
}
if (changes.x || changes.y) {
this.stateX = ~~newState.x;
this.stateY = ~~newState.y;
this.renderPosition(true);
}
if (changes.z) {
this.z = ~~newState.z;
this.renderZ();
}
if (changes.moving) {
// someone is holding or dragging the card
this.moving = (newState.moving=="m");
this.renderHighlight();
}
if (changes.user) {
// the user who last touched the card
this.user = wave.getParticipantById(newState.user);
this.renderUserLabel();
}
if (changes.flip) {
// Flip the card
this.faceup = !!newState.flip;
this.renderFlip();
} else if (changes.peeked) {
// a user is peeking at the card.
this.peeked = newState.peeked;
if (this.peeking && this.user != me) {
// we were peeking at the card but now someone else has taken it,
// so now we have to stop peeking at it.
this.peeking = false;
}
this.renderPeek();
this.renderHighlight();
}
},
flip: function (queue) {
this.faceup = !this.faceup;
this.asyncUpdate();
},
peekStart: function () {
with(this) {
if (!peeking) {
peeking = true;
if (peekLockMode) {
this.peekLock = true;
}
renderPeek();
asyncUpdate();
}
}
},
peekStop: function () {
// delay so that other clients have time to notice the peek
var $this = this;
setTimeout(function () {
// if this card's peek lock is on, then we stay peeking at it.
if (!$this.peekLock) {
$this.peeking = false;
$this.peeked = false;
$this.renderPeek();
$this.renderHighlight();
$this.asyncUpdate();
}
}, transitionDuration);
},
// return whether an object is overlapping another.
isOverlapping: function (thing) {
if (this === thing) return false; // can't overlap itself
var xDelta = thing.x - this.x;
var yDelta = thing.y - this.y;
return ((xDelta < this.width) && (-xDelta < thing.width) &&
(yDelta < this.height) && (-yDelta < thing.height));
},
// return id map of all cards overlapping this one.
getOverlappingObjects: function () {
var overlappingObjects = {};
var all = Card.prototype.all;
for (var i in all) {
var item = all[i];
if (this.isOverlapping(item)) {
overlappingObjects[i] = item;
}
}
return overlappingObjects;
},
// detect and process cards that overlap with this one.
detectOverlaps: function () {
var overlaps = this.getOverlappingObjects();
for (var i in overlaps) {
if (!this.overlaps[i]) this.onOverlap(overlaps[i]);
}
this.overlaps = overlaps;
},
dragStart: function (x, y, e) {
//captured = this;
this.user = me;
// stop the card if it is moving.
if (this.movingNow) {
this.x = this.dom.wrapper.offsetLeft;
this.y = this.dom.wrapper.offsetTop;
this.renderPositionStatic();
}
this.startX = x - this.x;
this.startY = y - this.y;
// the viewer is holding the card
this.user = me;
this.moving = true;
this.asyncUpdate();
return false;
},
drag: function (x, y) {
this.oldX = this.x;
this.oldY = this.y;
this.x = x - this.startX;
this.y = y - this.startY;
this.renderPositionStatic();
},
dragEnd: function () {
this.stateX = this.x;
this.stateY = this.y;
this.moving = false;
// when the user lets go of a card, they stop peeking at it
// unless in peek lock mode
if (this.peeking && !this.peekLock) {
this.peekStop();
}
this.asyncUpdate();
this.renderHighlight();
},
/* About the layering modes:
The goal is for moving the cards around to feel as realistic as possible. There are two layering modes: drag-under mode and drag-over mode, represented by the boolean var dragUnderMode. They are toggled by holding the "u" key. In drag-under mode, dragged cards should slide under the other cards. In drag-over mode, they should be able to be placed above the other cards. This all has to be done while maintaining the layering so that you cannot move a card up "through" another card.
The way it is done is this:
The selection is being dragged.
A card (A) in the selection is being detected to be overlapping an outside card (B).
If in drag-under mode, raise every card in the selection above card B.
Else, raise card A above card B.
Also raise every card that is above the card being raised,
unless one of them is the card being raised over,
in which case do nothing.
*/
// Raise a group of cards and every card overlapping above them,
// above the current card.
raise: function (cardsToRaise) {
cardsToRaise = Array.prototype.concat.call(cardsToRaise);
var numCardsToRaise = cardsToRaise.length;
if (!numCardsToRaise) {
// nothing to raise
return;
}
// Get the minimum z of the cards to be raised.
var lowestCard = cardsToRaise[0];
var lowestZ = lowestCard.z;
for (var i = numCardsToRaise - 1; i--;) {
var card = cardsToRaise[i];
if (card.z < lowestZ) {
lowestCard = card;
lowestZ = card.z;
}
}
// Get the cards that overlap above this card (recursively).
// Get cards with z >= the lowest base cardthis card's z.
var cardsAbove = ZIndexCache.getAbove(lowestZ);
// Ones of these that overlap with this card (or with one that does, etc),
// will need to be raised along with this one.
// for each card with z >= this card
for (i = cardsAbove.length; i--;) {
var cardAbove = cardsAbove[i];
// check if card overlaps with any of the cards to be raised
for (var j = 0; j < numCardsToRaise; j++) {
var cardToRaise = cardsToRaise[j];
if (cardToRaise.isOverlapping(cardAbove)) {
// It overlaps.
// Make sure it is not a knot.
if (cardAbove === this) {
// This would mean raising a card above itself,
// which is not possible. Abort!
//console.log('knot');
return false;
} else {
// it overlaps, therefore it will be raised too.
cardsToRaise[numCardsToRaise++] = cardAbove;
break;
}
}
}
}
// Raise the cards while maintaining the stacking order.
// Minimizing the distances between them, without lowering them
var raiseAmount = this.z - lowestZ + 1;
var zPrev = Infinity;
for (i = 0; i < numCardsToRaise; i++) {
var card = cardsToRaise[i];
zDelta = card.z - zPrev;
zPrev = card.z;
if (zDelta > 1) {
raiseAmount -= zDelta - 1;
if (raiseAmount < 1) {
// can't do lowering yet. (TODO)
break;
}
}
card.z += raiseAmount;
card.renderZ();
card.queueUpdate();
}
return true;
},
/* -------------- Card View functions -------------- */
// Set the card's classes and title to its suit and rank.
renderFace: function () {
// to do: change this so that it doesn't overwrite other classNames.
var rank = this.ranks[this.rank];
var suit = this.suits[this.suit];
addClass(this.dom.front, rank);
addClass(this.dom.front, suit);
this.title = rank + " of " + suit;
this.dom.front.setAttribute("title", this.title);
},
renderUserLabel: function () {
var playerNum = players.indexOf(this.user)+1;
// replace old class with new one
if (this.userClass) {
removeClass(this.dom.wrapper, this.userClass);
}
this.userClass = "p" + ((playerNum % 8) + 1);
addClass(this.dom.wrapper, this.userClass);
//timeout?
if (this.user) {
// Set the label to the player's first name,
// or blank if they are the viewer.
var userLabel = (this.user == me) ? "" :
this.user.getDisplayName().match(/^[^ ]+/, '')[0];
this.dom.label.innerHTML = userLabel;
}
},
// If the user wants to peek at the card, show a corner of the back through the front.
renderPeek: function () {
toggleClass(this.dom.wrapper, "peeked", this.peeked || this.peeking);
toggleClass(this.dom.wrapper, "peeking", this.peeking);
},
// determine whether the card should have a highlight or not
needsHighlight: function () {
return this.flipping || this.peeking || this.peeked || this.moving || this.movingNow;
},
// set whether the card is selected or not
renderSelected: function () {
toggleClass(this.dom.wrapper, "selected", this.selected);
this.renderHighlight();
},
// Display or hide the card's highlight and player label.
renderHighlight: function () {
var needsHighlight = this.needsHighlight();
if (needsHighlight == this.highlighted) {
return;
}
this.highlighted = needsHighlight;
toggleClass(this.dom.wrapper, "highlight", needsHighlight);
// Fade hiding the label, but show it immediately
if (needsHighlight) {
if (this.dom.label._transitions && this.dom.label._transitions.opacity) {
this.dom.label._transitions.opacity.stop();
}
this.dom.label.style.opacity = 1;
this.dom.label.style.visibility = "visible";
} else {
Transition(
this.dom.label,
{opacity: 0},
transitionDuration*(this.user == me ? .5 : 3),
function (n) {
// Hide the label when the animation is done so it doesn't get in the way of other things
if (this.style.opacity == 0) {
this.style.visibility = "hidden";
}
}
);
}
},
// move the card to its x and y.
renderPosition: function (transition) {
if ((this.x == this.stateX) && (this.y == this.stateY)) {
// no change
return;
}
var oldX = this.x;
this.x = ~~this.stateX;
this.y = ~~this.stateY;
if (transition && !isNaN(this.x)) {
var $this = this;
this.movingNow = true;
this.renderHighlight();
Transition(this.dom.wrapper, {
left: this.x + "px",
top: this.y + "px"
}, transitionDuration, function (n) {
$this.movingNow = false;
$this.renderHighlight();
});
} else {
this.renderPositionStatic();
}
},
renderPositionStatic: function () {
this.movingNow = false;
this.dom.wrapper.style.left = this.x + "px";
this.dom.wrapper.style.top = this.y + "px";
},
// set the z-index of the element to the z of the object.
renderZ: function () {
if (this.z === this.renderedZ) {
return false;
}
if (this.z > 100000) {
// problem: the z-index shouldn't get this high in the first place.
this.z = 0;
throw new Error("z-index is too high!");
}
ZIndexCache.remove(this, this.renderedZ);
ZIndexCache.add(this);
this.renderedZ = this.z;
this.dom.card.style.zIndex = this.z;
if (this.z > highestZ) highestZ = this.z;
},
// helper functions for renderFlip
removeFlipClass: function () {
removeClass(this.dom.wrapper, this.faceup ? "facedown" : "faceup");
},
flipClasses: function () {
this.removeFlipClass();
addClass(this.dom.wrapper, this.faceup ? "faceup" : "facedown");
},
renderFlip: function () {
var $this, faceup, a, halfWay, t, rotater;
faceup = this.faceup;
$this = this;
if (this.isFaceup === undefined) {
this.isFaceup = faceup;
return this.flipClasses();
}
this.flipping = true;
this.renderHighlight();
// Animate the flip with the transform property if it is supported, otherwise opacity.
var cssTransform = Transition.cssTransformType;
if (cssTransform) {
/*
Safari 3 and Mozilla 3.5 support CSS Transformations. Safari 4
and Chrome support rotateY, a 3D transformation. So we use
rotateY if it is supported, otherwise a matrix "stretch".
Fall back on opacity if transforms are not supported.
*/
if (window.WebKitCSSMatrix) {
this.dom[faceup ? "back" : "front"].style[cssTransform] = "rotateY(180deg)"
// rotate to 0 from 180 or -180
a = faceup ? -1 : 1;
rotater = function (n) {
return "rotateY(" + 180*(a + -a*n) + "deg)";
};
halfWay = 3; // 3 not 2 because of the easing function i think
} else {
//
this.dom[faceup ? "back" : "front"].style[cssTransform] = "matrix(-1, 0, 0, 1, 0, 0)";
// flip from -1 to 1, reverse to front
rotater = function (n) {
return "matrix(" + (-1 + 2*n) + ", 0, 0, 1, 0, 0)";
};
halfWay = 2;
}
this.dom.card.style[cssTransform] = rotater(0);
t = {};
t[cssTransform] = rotater;
Transition(this.dom.card, t, transitionDuration, function () {
$this.dom.card.style[cssTransform] = "";
$this.dom.front.style[cssTransform] = "";
$this.dom.back.style[cssTransform] = "";
$this.flipping = false;
$this.renderHighlight();
$this.removeFlipClass();
});
setTimeout(function () {
$this.flipClasses();
}, transitionDuration / halfWay);
} else {
// no transforms; use opacity.
this.dom.back.style.opacity = ~~faceup;
this.removeFlipClass();
Transition(this.dom.back, {opacity: ~~!this.faceup}, transitionDuration, function () {
$this.flipClasses();
$this.flipping = false;
$this.renderHighlight();
});
}
},
renderDeck: function () {
if (this.deckClass) {
removeClass(this.dom.card, this.deckClass);
}
this.deckClass = this.deck.color;
addClass(this.dom.card, this.deckClass);
}
});
// source: http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
// Cards Selection
var CardSelection = {
cards: [],
x: 0,
y: 0,
startX: 0,
startY: 0,
width: 0,
height: 0,
z: 0, // highest z
z1: 0, // lowest z
overlappers: [], // cards that overlap a card in the selection
overlappees: {}, // Cards in the selection that have an overlapper,
// by the id of their overlapper
// Clear the selection
clear: function () {
this.cards.forEach(function (card) {
card.selected = false;
card.renderSelected();
});
this.cards = [];
},
// add a card to the selection
add: function (card) {
if (!card.selected) {
this.cards.push(card);
card.selected = true;
card.renderSelected();
}
},
// remove a card from the selection
remove: function (card) {
this.cards.splice(this.cards.indexOf(card), 1);
},
// compute the dimensions and coordinates of the selection as a whole
refreshBounds: function () {
var cards = this.cards,
x1 = Infinity,
x2 = -Infinity,
y1 = Infinity,
y2 = -Infinity,
z1 = Infinity,
z2 = -Infinity;
for (i = cards.length; i--;) {
with(cards[i]) {
var x3 = x + width;
var y3 = y + height;
if (x < x1) x1 = x;
if (x3 > x2) x2 = x3;
if (y < y1) y1 = y;
if (y3 > y2) y2 = y3;
if (z < z1) z1 = z;
if (z > z2) z2 = z;
}
}
this.x = x1;
this.width = x2 - x1;
this.y = y1;
this.height = y2 - y1;
this.z = z2;
this.z1 = z1;
},
// Collision detection.
// Detect what cards are in the way of the selection
detectOverlaps: function () {
var cardsNear, i, j, len, overlappers, overlappees, card, overlappee;
// find cards that might be in the way.
if (dragUnderMode) {
cardsNear = ZIndexCache.getBelow(this.z);
} else {
cardsNear = ZIndexCache.getAbove(this.z1);
}
len = cardsNear.length;
j = 0;
overlappers = new Array(len);
overlappees = {};
for (i = 0; i < len; i++) {
card = cardsNear[i];
// don't test for collision with self
if (!card.selected) {
overlappee = this.nowOverlaps(card);
if (overlappee) {
// Collision!
overlappees[card.id] = overlappee;
overlappers[j++] = card;
}
}
}
this.overlappees = overlappees;
this.overlappers = overlappers;
},
// start dragging the selected cards
dragStart: function (x, y) {
this.cards.forEach(function (card) {
card.dragStart(x, y);
});
this.refreshBounds();
this.detectOverlaps();
this.startX = x - this.x;
this.startY = y - this.y;
},
drag: function (x, y) {
var cards, overlapper, i, oldOverlappees, overlappers, overlappee;
// update the position of each card
cards = this.cards;
for (i = cards.length; i--;) {
cards[i].drag(x, y);
}
// update the position of the selection as a whole
this.x = x - this.startX;
this.y = y - this.startY;
oldOverlappees = this.overlappees;
this.detectOverlaps();
overlappers = this.overlappers; // cards that overlap a card in the selection
for (i = 0; overlapper = overlappers[i]; i++) {
overlappee = oldOverlappees[overlapper.id]; // in the selection
if (!overlappee) {
overlappee = this.overlappees[overlapper.id];
// New overlap.
// Temporarily move back the overlappee before it was overlapping.
with(overlappee) {
var realX = x;
var realY = y;
x = oldX;
y = oldY;
}
// Raise the Z of one pile over one card.
if (dragUnderMode) {
overlappee.raise(overlapper);
} else {
overlapper.raise(CardSelection.cards);
}
// Restore overlappee position.
overlappee.x = realX;
overlappee.y = realY;
overlappee.sendUpdate(true);
// Because the selection's Z has changed, recalculate its
// bounds.
this.refreshBounds();
// don't need to test for any more collisions, because
// "overlaps" is ordered by significance
break;
}
}
},
dragEnd: function () {
this.cards.forEach(function (card) {
card.dragEnd();
});
},
// If a card overlaps the selection now, return the card in the selection
// that it overlaps with.
nowOverlaps: function (card) {
if (card.isOverlapping(this)) {
// Now find exactly which card in the selection is overlapping.
// In drag-under mode, find the highest card in the selection
// that overlaps with the given card. In drag-over mode, find
// the lowest.
var zStart, zEnd, zInc
if (dragUnderMode) {
zStart = this.z;
zEnd = this.z1;
zInc = -1;
} else {
zStart = this.z1;
zEnd = this.z;
zInc = 1;
}
var buckets = ZIndexCache.buckets;
for (var z = zStart; z != (zEnd + zInc); z += zInc) {
var bucket = buckets[z];
if (bucket) {
for (var i = 0, l = bucket.length; i < l; i++) {
var card2 = bucket[i];
if (card2.selected && card2.isOverlapping(card)) {
return card2;
}
}
}
}
}
return false;
},
peekStart: function () {
this.cards.forEach(function (card) {
card.peekStart();
});
},
peekStop: function () {
this.cards.forEach(function (card) {
card.peekStop();
});
},
peekLock: function () {
this.cards.forEach(function (card) {
card.peekLock ^= 1;
});
},
// flip the positions of the cards, not just the faces.
flip: function () {
this.refreshBounds();
var xx = 2 * this.x + this.width,
zz = this.z + this.z1;
this.cards.forEach(function (card) {
card.stateX = xx - (card.x + card.width);
card.z = zz - card.z;
//card.flip();
card.faceup = !card.faceup;
card.queueUpdate();
});
Stateful.prototype.flushUpdates();
},
// shuffle the positions of the selected cards
shuffle: function () {
var cards = this.cards;
// randomly reassign the position properties of each card
var positions = cards.map(function (card) {
return {
x: card.x,
y: card.y,
z: card.z,
faceup: card.faceup
};
});
shuffle(positions);
positions.forEach(function (pos, i) {
with(cards[i]) {
stateX = pos.x;
stateY = pos.y;
z = pos.z;
faceup = pos.faceup;
queueUpdate();
}
});
Stateful.prototype.flushUpdates();
}
};
var ZIndexCache = {
buckets: [], // array of "buckets" of each card with a particular z value
aboveCache: {}, // cache for getAbove()
belowCache: {}, // cache for getBelow()
hasCaches: false, // are aboveCache and belowCache useful
// add a card into the z-index cache
add: function (card) {
if (this.hasCaches) {
this.aboveCache = {};
this.belowCache = {};
this.hasCaches = false;
}
var z = card.z;
var bucket = this.buckets[z];
if (bucket) {
bucket[bucket.length] = card;
} else {
this.buckets[z] = [card];
}
},
// remove a card from the z-index cache, optionally from a particular bucket
remove: function (card, z) {
if (this.hasCaches) {
this.aboveCache = {};
this.belowCache = {};
this.hasCaches = false;
}
if (z === undefined) z = card.z;
var bucket = this.buckets[z];
if (bucket) {
var index = bucket.indexOf(card);
if (index != -1) {
bucket.splice(index, 1);
}
}
},
// get cards with z >= a given amount, starting from max
getAbove: function (zMin) {
var cards, i, j, z, buckets, bucket, cache;
// check cache first
if (cache = this.aboveCache[zMin]) {
return cache;
}
cards = [];
j = 0;
buckets = this.buckets;
for (z = buckets.length-1; z >= zMin; z--) {
if (bucket = buckets[z]) {
// add each card in this bucket
for (i = bucket.length; i--;) {
cards[j++] = bucket[i];
}
}
}
this.aboveCache[zMin] = cards;
this.hasCaches = true;
return cards;
},
// get cards with z <= a given amount, starting from 0
getBelow: function (zMax) {
var cards, i, j, z, buckets, bucket, cache;
// check cache first
if (cache = this.belowCache[zMax]) {
return cache;
}
cards = [];
j = 0;
buckets = this.buckets;
for (z = 0; z <= zMax; z++) {
if (bucket = buckets[z]) {
// add each card in this bucket
for (i = bucket.length; i--;) {
cards[j++] = bucket[i];
}
}
}
this.belowCache[zMax] = cards;
this.hasCaches = true;
return cards;
}
};
// Drag Selection Box
var SelectionBox = {
div: (function () {
var div = document.createElement("div");
div.id = "selectionBox";
return div;
})(),
firstMove: false,
startX: 0,
startY: 0,
x: 0,
y: 0,
width: 0,
height: 0,
overlaps: {},
getOverlappingObjects: Card.prototype.getOverlappingObjects,
isOverlapping: Card.prototype.isOverlapping,
detectOverlaps: function () {
var overlaps = this.getOverlappingObjects();
for (var i in overlaps) {
if (!this.overlaps[i]) this.onOverlap(overlaps[i]);
}
for (var i in this.overlaps) {
if (!overlaps[i]) this.onUnOverlap(this.overlaps[i]);
}
this.overlaps = overlaps;
},
onOverlap: function (card) {
CardSelection.add(card);
},
onUnOverlap: function (card) {
CardSelection.remove(card);
card.selected = false;
card.renderSelected();
},
// start a selection box
dragStart: function (x, y) {
this.dragging = true;
this.startX = x;
this.startY = y;
this.firstMove = true;
},
drag: function (endX, endY) {
with(this) {
x = Math.min(startX, endX) +
(document.documentElement.scrollLeft + document.body.scrollLeft +
cardsWindow.scrollLeft - cardsWindow.offsetLeft);
y = Math.min(startY, endY) +
(document.documentElement.scrollTop + document.body.scrollTop +
cardsWindow.scrollTop - cardsWindow.offsetTop);
width = Math.abs(startX - endX);
height = Math.abs(startY - endY);
with(div.style) {
left = x + "px";
top = y + "px";
width = this.width + "px";
height = this.height + "px";
}
detectOverlaps();
if (firstMove) {
cardsContainer.appendChild(div);
firstMove = false;
}
}
},
dragEnd: function () {
if (!this.firstMove) {
this.dragging = false;
cardsContainer.removeChild(this.div);
}
}
};
})(); | Fixed dealing with deleted state items.
Improved overlap detection. | cards.js | Fixed dealing with deleted state items. Improved overlap detection. | <ide><path>ards.js
<ide> waveStateValues = {};
<ide>
<ide> // Update stuff
<del> for (i=0; (key=keys[i]); i++) {
<add> for (i = 0; (key=keys[i]); i++) {
<ide> value = waveState.get(key);
<del> waveStateValues[key] = value;
<del>
<del> thing = getThing(key);
<del> thing.updateState(value);
<add> if (value) {
<add> waveStateValues[key] = value;
<add>
<add> thing = getThing(key);
<add> thing.updateState(value);
<add> }
<ide> }
<ide>
<ide> // Check for deleted values
<ide> // Look for keys that were in the state before but now are not.
<del> for (i=waveStateKeys.length; i--;) {
<del> if (!(waveStateKeys[i] in waveStateValues)) {
<del> thing = getThing(waveStateKeys[i]);
<add> for (i = waveStateKeys.length; i--;) {
<add> key = waveStateKeys[i];
<add> if (!(key in waveStateValues)) {
<add> thing = getThing(key);
<ide> thing.remove();
<ide> }
<ide> }
<ide>
<ide> // update the state of the item
<ide> updateState: function (newStateString) {
<del> if (!newStateString) this.remove();
<add> if (!newStateString && this.removed) this.remove();
<ide> if (this.removed) return; // don't wake the dead
<ide>
<ide> // first compare state by string to see if it is different at all.
<ide> // delete this object
<ide> remove: function () {
<ide> this.removed = true;
<del> delete things[this.key];
<ide> },
<ide>
<ide> markForRemoval: function () {
<ide> card.markForRemoval();
<ide> card.queueUpdate();
<ide> });
<del> this.remove();
<add> //this.remove();
<ide> Stateful.prototype.markForRemoval.call(this);
<ide> },
<ide>
<ide>
<ide> // This would mean raising a card above itself,
<ide> // which is not possible. Abort!
<del> //console.log('knot');
<add> //if (window.console) console.log('knot');
<ide> return false;
<ide> } else {
<ide>
<ide> if (overlappee) {
<ide> // Collision!
<ide>
<add> // Overlappee is the card in the selection that is
<add> // being overlapped by the overlapper, card.
<add>
<ide> overlappees[card.id] = overlappee;
<ide> overlappers[j++] = card;
<ide> }
<ide> },
<ide>
<ide> drag: function (x, y) {
<del> var cards, overlapper, i, oldOverlappees, overlappers, overlappee;
<add> var cards, overlapper, i, oldOverlappees, overlappers, overlappee, oldOverlappee;
<ide>
<ide> // update the position of each card
<ide> cards = this.cards;
<ide>
<ide> for (i = 0; overlapper = overlappers[i]; i++) {
<ide>
<del> overlappee = oldOverlappees[overlapper.id]; // in the selection
<del> if (!overlappee) {
<del> overlappee = this.overlappees[overlapper.id];
<del>
<del> // New overlap.
<add> oldOverlappee = oldOverlappees[overlapper.id];
<add> overlappee = this.overlappees[overlapper.id];
<add> if (overlappee != oldOverlappee) {
<add> // The overlap is new, or with a different card than before.
<ide>
<del> // Temporarily move back the overlappee before it was overlapping.
<add> // Temporarily move back the overlappee to before it was
<add> // overlapping, so it doesn't get in the way of itself.
<ide> with(overlappee) {
<ide> var realX = x;
<ide> var realY = y;
<ide> this.refreshBounds();
<ide>
<ide> // don't need to test for any more collisions, because
<del> // "overlaps" is ordered by significance
<add> // the overlaps are ordered by significance
<ide> break;
<ide> }
<ide> } |
|
Java | apache-2.0 | 2f91acfc7ab01d7ac50dafd7ad8ff1b445863448 | 0 | Cognifide/APM,Cognifide/APM,Cognifide/APM,Cognifide/APM | /*-
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.ui.models;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import com.cognifide.apm.api.scripts.Script;
import com.cognifide.apm.core.history.History;
import com.cognifide.apm.core.history.HistoryEntry;
import com.cognifide.apm.core.history.ScriptHistory;
import com.cognifide.apm.core.scripts.ScriptModel;
import com.cognifide.apm.core.utils.CalendarUtils;
import com.day.cq.commons.jcr.JcrConstants;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.jetbrains.annotations.NotNull;
@Model(adaptables = Resource.class)
public final class ScriptsRowModel {
private static final Set<String> FOLDER_TYPES = ImmutableSet
.of(JcrConstants.NT_FOLDER, "sling:OrderedFolder", "sling:Folder");
public static final String SCRIPTS_ROW_RESOURCE_TYPE = "apm/components/scriptsRow";
@Self
private Resource resource;
@Inject
private History history;
@Getter
private String scriptName;
@Getter
private boolean isFolder;
@Getter
private boolean isValid;
@Getter
private String author;
@Getter
private Calendar lastModified;
@Getter
private final List<ScriptRun> runs = new ArrayList<>();
@Getter
private String launchMode;
@Getter
private String launchEnvironment;
@Getter
private boolean isLaunchEnabled;
@PostConstruct
protected void afterCreated() {
this.isFolder = isFolder(resource);
this.scriptName = defaultIfEmpty(getProperty(resource, JcrConstants.JCR_TITLE), resource.getName());
if (!isFolder) {
Optional.ofNullable(resource.adaptTo(ScriptModel.class)).ifPresent(script -> {
ScriptHistory scriptHistory = history.findScriptHistory(resource.getResourceResolver(), script);
this.author = script.getAuthor();
this.isValid = script.isValid();
this.lastModified = CalendarUtils.asCalendar(script.getLastModified());
this.runs.add(createScriptRun("dryRun", script, scriptHistory.getLastLocalDryRun()));
this.runs.add(createScriptRun("runOnAuthor", script, scriptHistory.getLastLocalRun()));
this.runs.add(createScriptRun("runOnPublish", script, scriptHistory.getLastRemoteRun()));
this.launchMode = label(script.getLaunchMode());
this.launchEnvironment = label(script.getLaunchEnvironment());
this.isLaunchEnabled = script.isLaunchEnabled();
});
}
}
public String label(Object object) {
String words = object.toString().replace('_', ' ');
words = WordUtils.capitalizeFully(words.toLowerCase());
return words;
}
@NotNull
private ScriptRun createScriptRun(String name, Script script, HistoryEntry historyEntry) {
if (historyEntry != null && StringUtils.equals(historyEntry.getChecksum(), script.getChecksum())) {
return new ScriptRun(name, historyEntry);
} else {
return new ScriptRun(name);
}
}
public static boolean isFolder(Resource resource) {
return FOLDER_TYPES.contains(getProperty(resource, JcrConstants.JCR_PRIMARYTYPE));
}
private static String getProperty(Resource resource, String name) {
return resource.getValueMap().get(name, StringUtils.EMPTY);
}
public String getResourceType() {
return SCRIPTS_ROW_RESOURCE_TYPE;
}
@Getter
public static class ScriptRun {
private final String type;
private final String summary;
private final boolean success;
private final Calendar time;
public ScriptRun(String type) {
this.type = type;
this.summary = null;
this.success = false;
this.time = null;
}
public ScriptRun(String type, HistoryEntry historyEntry) {
this.type = type;
this.summary = historyEntry.getPath();
this.success = historyEntry.isRunSuccessful();
this.time = CalendarUtils.asCalendar(historyEntry.getExecutionTime());
}
}
}
| app/aem/core/src/main/java/com/cognifide/apm/core/ui/models/ScriptsRowModel.java | /*-
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.ui.models;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import com.cognifide.apm.api.scripts.Script;
import com.cognifide.apm.core.history.History;
import com.cognifide.apm.core.history.HistoryEntry;
import com.cognifide.apm.core.history.ScriptHistory;
import com.cognifide.apm.core.scripts.ScriptModel;
import com.cognifide.apm.core.utils.CalendarUtils;
import com.day.cq.commons.jcr.JcrConstants;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.jetbrains.annotations.NotNull;
@Model(adaptables = Resource.class)
public final class ScriptsRowModel {
private static final Set<String> FOLDER_TYPES = ImmutableSet
.of(JcrConstants.NT_FOLDER, "sling:OrderedFolder", "sling:Folder");
public static final String SCRIPTS_ROW_RESOURCE_TYPE = "apm/components/scriptsRow";
@Self
private Resource resource;
@Inject
private History history;
@Getter
private String scriptName;
@Getter
private boolean isFolder;
@Getter
private boolean isValid;
@Getter
private String author;
@Getter
private Calendar lastModified;
@Getter
private final List<ScriptRun> runs = new ArrayList<>();
@Getter
private String launchMode;
@Getter
private String launchEnvironment;
@Getter
private boolean isLaunchEnabled;
@PostConstruct
protected void afterCreated() {
this.isFolder = isFolder(resource);
this.scriptName = defaultIfEmpty(getProperty(resource, JcrConstants.JCR_TITLE), resource.getName());
if (!isFolder) {
Optional.ofNullable(resource.adaptTo(ScriptModel.class)).ifPresent(script -> {
ScriptHistory scriptHistory = history.findScriptHistory(resource.getResourceResolver(), script);
this.author = script.getAuthor();
this.isValid = script.isValid();
this.lastModified = CalendarUtils.asCalendar(script.getLastModified());
this.runs.add(createScriptRun("runOnAuthor", script, scriptHistory.getLastLocalRun()));
this.runs.add(createScriptRun("runOnPublish", script, scriptHistory.getLastRemoteRun()));
this.runs.add(createScriptRun("dryRun", script, scriptHistory.getLastLocalDryRun()));
this.launchMode = label(script.getLaunchMode());
this.launchEnvironment = label(script.getLaunchEnvironment());
this.isLaunchEnabled = script.isLaunchEnabled();
});
}
}
public String label(Object object) {
String words = object.toString().replace('_', ' ');
words = WordUtils.capitalizeFully(words.toLowerCase());
return words;
}
@NotNull
private ScriptRun createScriptRun(String name, Script script, HistoryEntry historyEntry) {
if (historyEntry != null && StringUtils.equals(historyEntry.getChecksum(), script.getChecksum())) {
return new ScriptRun(name, historyEntry);
} else {
return new ScriptRun(name);
}
}
public static boolean isFolder(Resource resource) {
return FOLDER_TYPES.contains(getProperty(resource, JcrConstants.JCR_PRIMARYTYPE));
}
private static String getProperty(Resource resource, String name) {
return resource.getValueMap().get(name, StringUtils.EMPTY);
}
public String getResourceType() {
return SCRIPTS_ROW_RESOURCE_TYPE;
}
@Getter
public static class ScriptRun {
private final String type;
private final String summary;
private final boolean success;
private final Calendar time;
public ScriptRun(String type) {
this.type = type;
this.summary = null;
this.success = false;
this.time = null;
}
public ScriptRun(String type, HistoryEntry historyEntry) {
this.type = type;
this.summary = historyEntry.getPath();
this.success = historyEntry.isRunSuccessful();
this.time = CalendarUtils.asCalendar(historyEntry.getExecutionTime());
}
}
}
| small fix
| app/aem/core/src/main/java/com/cognifide/apm/core/ui/models/ScriptsRowModel.java | small fix | <ide><path>pp/aem/core/src/main/java/com/cognifide/apm/core/ui/models/ScriptsRowModel.java
<ide> this.author = script.getAuthor();
<ide> this.isValid = script.isValid();
<ide> this.lastModified = CalendarUtils.asCalendar(script.getLastModified());
<add> this.runs.add(createScriptRun("dryRun", script, scriptHistory.getLastLocalDryRun()));
<ide> this.runs.add(createScriptRun("runOnAuthor", script, scriptHistory.getLastLocalRun()));
<ide> this.runs.add(createScriptRun("runOnPublish", script, scriptHistory.getLastRemoteRun()));
<del> this.runs.add(createScriptRun("dryRun", script, scriptHistory.getLastLocalDryRun()));
<ide> this.launchMode = label(script.getLaunchMode());
<ide> this.launchEnvironment = label(script.getLaunchEnvironment());
<ide> this.isLaunchEnabled = script.isLaunchEnabled(); |
|
Java | unlicense | 522fdb75a02c956c718a100f8bdd8bc674710b5c | 0 | skeeto/Feedback,skeeto/Feedback,skeeto/Feedback | package feedback;
import java.io.File;
import java.util.Random;
import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.FontMetrics;
import java.awt.RenderingHints;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsConfiguration;
import java.awt.geom.AffineTransform;
import java.awt.image.Kernel;
import java.awt.image.RescaleOp;
import java.awt.image.ColorModel;
import java.awt.image.ConvolveOp;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.awt.image.BufferedImageOp;
import java.awt.image.AffineTransformOp;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Feedback extends JPanel implements Runnable {
private static final long serialVersionUID = 328407319480529736L;
public static int WIDTH = 640; /* Display width */
public static int HEIGHT = 640; /* Display height */
public static int SPEED = 30; /* Animation delay (ms) */
public static double ANGLE = 2.5; /* Rotate op (radians) */
public static double SCALE = 0.99; /* Resize op */
public static int BLUR = 1; /* Guassian filter radius */
public static int INIT_DISTURB = 50; /* Initial number of disturbs */
public static int REINIT = 200; /* Reinitize period (steps) */
public static int M_SIZE = 50; /* Mouse pointer size */
public static int COLOR_SPEED = 15; /* Mouse color change speed */
public static float ENHANCE = 1.5f; /* Display color enhancement */
private ArrayList<BufferedImageOp> ops;
private RescaleOp display; /* Display purpose only. */
/* State */
private BufferedImage image, workA, workB;
private int counter = 1;
private Random rng;
private boolean mouse;
private int mX, mY;
private int mR, mG, mB, mA;
/* GUI */
public static JFrame frame;
/* Config */
private boolean pause = false;
private boolean random = true;
private boolean help = false;
private double angle = ANGLE;
private double scale = SCALE;
private volatile double speed = SPEED;
public static void main(final String[] args) {
frame = new JFrame("Feedback");
Feedback feedback = new Feedback();
frame.add(feedback);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
(new Thread(feedback)).start();
}
public Feedback() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
display = new RescaleOp(ENHANCE, 0.0f, null);
createOps();
rng = new Random();
GraphicsEnvironment ge;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getScreenDevices()[0];
GraphicsConfiguration gc = gd.getConfigurations()[0];
image = gc.createCompatibleImage(WIDTH, HEIGHT);
workA = gc.createCompatibleImage(WIDTH, HEIGHT);
workB = gc.createCompatibleImage(WIDTH, HEIGHT);
Graphics2D g = image.createGraphics();
g.setBackground(Color.BLACK);
g.clearRect(0, 0, WIDTH, HEIGHT);
/* Set up mouse interaction. */
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
mX = e.getX();
mY = e.getY();
if (!pause)
mouse(false);
}
});
this.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
mouse = true;
}
public void mouseExited(MouseEvent e) {
mouse = false;
}
public void mouseClicked(MouseEvent e) {
requestFocusInWindow();
requestFocus();
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
/* Set up keyboard interaction. */
this.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case 's':
screenshot();
break;
case 'n':
random ^= true;
break;
/* Rotation*/
case 'r':
angle /= 1.01;
createOps();
break;
case 'R':
angle *= 1.01;
createOps();
break;
/* Scale */
case 'g':
scale /= 1.01;
createOps();
break;
case 'G':
scale *= 1.01;
scale = Math.min(scale, SCALE);
createOps();
break;
/* Pause/play */
case 'p':
pause(null);
break;
/* Animation speed */
case '+':
speed /= 1.1;
break;
case '-':
speed *= 1.1;
break;
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F1) {
help = true;
repaint();
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F1) {
help = false;
repaint();
}
}
});
requestFocusInWindow();
requestFocus();
mR = rng.nextInt(256);
mG = rng.nextInt(256);
mB = rng.nextInt(256);
mA = 255;
initDisturb();
}
public synchronized void pause(Boolean pause) {
if (pause != null && this.pause == pause)
return;
synchronized (image) {
image.notifyAll();
}
this.pause ^= true;
}
private synchronized void createOps() {
ArrayList<BufferedImageOp> ops = new ArrayList<BufferedImageOp>();
AffineTransform affine = new AffineTransform();
affine.rotate(angle, WIDTH / 2, HEIGHT / 2);
affine.scale(scale, scale);
ops.add(new AffineTransformOp(affine, AffineTransformOp.TYPE_BILINEAR));
this.ops = ops;
}
private void mouse(boolean change) {
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(mR, mG, mB, mA));
g.fillOval(mX - M_SIZE / 2, mY - M_SIZE / 2, M_SIZE, M_SIZE);
if (change) {
mR += rng.nextGaussian() * COLOR_SPEED;
mG += rng.nextGaussian() * COLOR_SPEED;
mB += rng.nextGaussian() * COLOR_SPEED;
mA += rng.nextGaussian();
mR = Math.max(0, Math.min(mR, 255));
mG = Math.max(0, Math.min(mG, 255));
mB = Math.max(0, Math.min(mB, 255));
mA = Math.max(128, Math.min(mA, 255));
}
repaint();
}
private void screenshot() {
boolean state = pause;
pause(true);
try {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter
= new FileNameExtensionFilter("PNG Images", "png");
fc.setFileFilter(filter);
int rc = fc.showDialog(frame, "Save Screenshot");
if (rc == JFileChooser.APPROVE_OPTION) {
save(fc.getSelectedFile());
}
} catch (java.security.AccessControlException ec) {
/* We're in the applet. */
System.out.println("Cannot save screenshot now.");
}
pause(state);
}
private void save(File file) {
try {
ImageIO.write(display.filter(image, null), "PNG", file);
} catch (Exception e) {
JOptionPane.showMessageDialog(frame,
"Unable to write " + file,
"Save failed",
JOptionPane.ERROR_MESSAGE);
}
}
private void message(String msg) {
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
FontMetrics fm = g.getFontMetrics();
int w = fm.stringWidth(msg);
g.drawString(msg, WIDTH / 2 - w / 2, HEIGHT - fm.getAscent() * 2);
}
private void iterate() {
if (!mouse)
counter++;
/* Apply "camera" effects to the image. */
ops.get(0).filter(image, workA);
for (int i = 1; i < ops.size(); i++) {
ops.get(i).filter(workA, workB);
BufferedImage swap = workA;
workA = workB;
workB = swap;
}
/* Mix back into the original image. */
BufferedImage last = workA;
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
int a = last.getRGB(x, y);
int b = image.getRGB(x, y);
int r = 0;
for (int i = 0; i < 32; i += 8) {
int va = (a >> i) & 0xFF;
int vb = (b >> i) & 0xFF;
/* screen */
//int vr = 255 - ((255 - va) * (255 - vb)) / 255;
/* average */
int vr = (va + vb) / 2;
r = r | (vr << i);
}
image.setRGB(x, y, r);
}
}
/* Apply mouse input. */
if (mouse) {
mouse(true);
}
/* Disturb at random. */
if (random) {
if (rng.nextInt(5) == 0) {
disturb();
} else if (rng.nextInt(counter) > REINIT) {
initDisturb();
counter = 1;
}
}
}
private void disturb() {
Graphics g = image.getGraphics();
int r = (int) Math.abs(rng.nextGaussian() * 100);
int y = rng.nextInt(WIDTH);
int x = rng.nextInt(HEIGHT);
g.setColor(new Color(rng.nextInt(256), rng.nextInt(256),
rng.nextInt(256), rng.nextInt(127) + 128));
switch (rng.nextInt(2)) {
case 0:
g.fillRect(x, y, r, r);
break;
case 1:
g.fillOval(x, y, r, r);
break;
}
}
private void initDisturb() {
for (int i = 0; i < INIT_DISTURB; i++) {
disturb();
}
}
public void run() {
while (true) {
try {
Thread.sleep((int) speed);
if (pause) {
synchronized (image) {
image.wait();
}
}
iterate();
repaint();
} catch (InterruptedException e) {
/* Nothing. */
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(display.filter(image, null), 0, 0, this);
if (help) {
/* Print some help information. */
FontMetrics fm = g.getFontMetrics();
int h = fm.getAscent() + fm.getDescent();
g.setColor(Color.WHITE);
int x1 = 10;
int x2 = 50;
int y = h;
g.drawString("Shortcut keys:", x1, y);
y += h * 2;
g.drawString("n", x1, y);
g.drawString("Toggle automated noise", x2, y);
y += h;
g.drawString("g/G", x1, y);
g.drawString("Increase/decrease gravity", x2, y);
y += h;
g.drawString("r/R", x1, y);
g.drawString("Increase/decrease rotation", x2, y);
y += h;
g.drawString("+/-", x1, y);
g.drawString("Increase/decrease animation speed", x2, y);
y += h;
g.drawString("p", x1, y);
g.drawString("Toggle pause/play", x2, y);
y += h;
g.drawString("s", x1, y);
g.drawString("Save a screenshot", x2, y);
y += h;
}
}
public static ConvolveOp getGaussianBlurFilter(int radius,
boolean horizontal) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be >= 1");
}
int size = radius * 2 + 1;
float[] data = new float[size];
float sigma = radius / 3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
float total = 0.0f;
for (int i = -radius; i <= radius; i++) {
float distance = i * i;
int index = i + radius;
data[index] = (float) Math.exp(-distance / twoSigmaSquare)
/ sigmaRoot;
total += data[index];
}
for (int i = 0; i < data.length; i++) {
data[i] /= total;
}
Kernel kernel = null;
if (horizontal) {
kernel = new Kernel(size, 1, data);
} else {
kernel = new Kernel(1, size, data);
}
return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
}
}
| src/feedback/Feedback.java | package feedback;
import java.io.File;
import java.util.Random;
import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.FontMetrics;
import java.awt.RenderingHints;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsConfiguration;
import java.awt.geom.AffineTransform;
import java.awt.image.Kernel;
import java.awt.image.RescaleOp;
import java.awt.image.ColorModel;
import java.awt.image.ConvolveOp;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.awt.image.BufferedImageOp;
import java.awt.image.AffineTransformOp;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Feedback extends JPanel implements Runnable {
private static final long serialVersionUID = 328407319480529736L;
public static int WIDTH = 640; /* Display width */
public static int HEIGHT = 640; /* Display height */
public static int SPEED = 30; /* Animation delay (ms) */
public static double ANGLE = 2.5; /* Rotate op (radians) */
public static double SCALE = 0.99; /* Resize op */
public static int BLUR = 1; /* Guassian filter radius */
public static int INIT_DISTURB = 50; /* Initial number of disturbs */
public static int REINIT = 200; /* Reinitize period (steps) */
public static int M_SIZE = 50; /* Mouse pointer size */
public static int COLOR_SPEED = 15; /* Mouse color change speed */
public static float ENHANCE = 1.5f; /* Display color enhancement */
private ArrayList<BufferedImageOp> ops;
private RescaleOp display; /* Display purpose only. */
/* State */
private BufferedImage image, workA, workB;
private int counter = 1;
private Random rng;
private boolean mouse;
private int mX, mY;
private int mR, mG, mB, mA;
/* GUI */
public static JFrame frame;
/* Config */
private boolean pause = false;
private boolean random = true;
private boolean help = false;
private double angle = ANGLE;
private double scale = SCALE;
private volatile double speed = SPEED;
public static void main(final String[] args) {
frame = new JFrame("Feedback");
Feedback feedback = new Feedback();
frame.add(feedback);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
(new Thread(feedback)).start();
}
public Feedback() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
display = new RescaleOp(ENHANCE, 0.0f, null);
createOps();
rng = new Random();
GraphicsEnvironment ge;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getScreenDevices()[0];
GraphicsConfiguration gc = gd.getConfigurations()[0];
image = gc.createCompatibleImage(WIDTH, HEIGHT);
workA = gc.createCompatibleImage(WIDTH, HEIGHT);
workB = gc.createCompatibleImage(WIDTH, HEIGHT);
Graphics2D g = image.createGraphics();
g.setBackground(Color.BLACK);
g.clearRect(0, 0, WIDTH, HEIGHT);
/* Set up mouse interaction. */
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
mX = e.getX();
mY = e.getY();
if (!pause)
mouse(false);
}
});
this.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
mouse = true;
}
public void mouseExited(MouseEvent e) {
mouse = false;
}
public void mouseClicked(MouseEvent e) {
requestFocusInWindow();
requestFocus();
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
/* Set up keyboard interaction. */
this.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case 's':
screenshot();
break;
case 'n':
random ^= true;
break;
/* Rotation*/
case 'r':
angle /= 1.01;
createOps();
break;
case 'R':
angle *= 1.01;
createOps();
break;
/* Scale */
case 'g':
scale /= 1.01;
createOps();
break;
case 'G':
scale *= 1.01;
scale = Math.min(scale, SCALE);
createOps();
break;
/* Pause/play */
case 'p':
pause(null);
break;
/* Animation speed */
case '+':
speed /= 1.1;
break;
case '-':
speed *= 1.1;
break;
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F1) {
help = true;
repaint();
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F1) {
help = false;
repaint();
}
}
});
requestFocusInWindow();
requestFocus();
mR = rng.nextInt(256);
mG = rng.nextInt(256);
mB = rng.nextInt(256);
mA = 255;
initDisturb();
}
public synchronized void pause(Boolean pause) {
if (pause != null && this.pause == pause)
return;
synchronized (image) {
image.notifyAll();
}
this.pause ^= true;
}
private synchronized void createOps() {
ArrayList<BufferedImageOp> ops = new ArrayList<BufferedImageOp>();
AffineTransform affine = new AffineTransform();
affine.rotate(angle, WIDTH / 2, HEIGHT / 2);
affine.scale(scale, scale);
ops.add(new AffineTransformOp(affine, AffineTransformOp.TYPE_BILINEAR));
this.ops = ops;
}
private void mouse(boolean change) {
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(mR, mG, mB, mA));
g.fillOval(mX - M_SIZE / 2, mY - M_SIZE / 2, M_SIZE, M_SIZE);
if (change) {
mR += rng.nextGaussian() * COLOR_SPEED;
mG += rng.nextGaussian() * COLOR_SPEED;
mB += rng.nextGaussian() * COLOR_SPEED;
mA += rng.nextGaussian();
mR = Math.max(0, Math.min(mR, 255));
mG = Math.max(0, Math.min(mG, 255));
mB = Math.max(0, Math.min(mB, 255));
mA = Math.max(128, Math.min(mA, 255));
}
repaint();
}
private void screenshot() {
boolean state = pause;
pause(true);
try {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter
= new FileNameExtensionFilter("PNG Images", "png");
fc.setFileFilter(filter);
int rc = fc.showDialog(frame, "Save Screenshot");
if (rc == JFileChooser.APPROVE_OPTION) {
save(fc.getSelectedFile());
}
} catch (java.security.AccessControlException ec) {
/* We're in the applet. */
System.out.println("Cannot save screenshot now.");
}
pause(state);
}
private void save(File file) {
try {
ImageIO.write(display.filter(image, null), "PNG", file);
} catch (Exception e) {
JOptionPane.showMessageDialog(frame,
"Unable to write " + file,
"Save failed",
JOptionPane.ERROR_MESSAGE);
}
}
private void iterate() {
if (!mouse)
counter++;
/* Apply "camera" effects to the image. */
ops.get(0).filter(image, workA);
for (int i = 1; i < ops.size(); i++) {
ops.get(i).filter(workA, workB);
BufferedImage swap = workA;
workA = workB;
workB = swap;
}
/* Mix back into the original image. */
BufferedImage last = workA;
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
int a = last.getRGB(x, y);
int b = image.getRGB(x, y);
int r = 0;
for (int i = 0; i < 32; i += 8) {
int va = (a >> i) & 0xFF;
int vb = (b >> i) & 0xFF;
/* screen */
//int vr = 255 - ((255 - va) * (255 - vb)) / 255;
/* average */
int vr = (va + vb) / 2;
r = r | (vr << i);
}
image.setRGB(x, y, r);
}
}
/* Apply mouse input. */
if (mouse) {
mouse(true);
}
/* Disturb at random. */
if (random) {
if (rng.nextInt(5) == 0) {
disturb();
} else if (rng.nextInt(counter) > REINIT) {
initDisturb();
counter = 1;
}
}
}
private void disturb() {
Graphics g = image.getGraphics();
int r = (int) Math.abs(rng.nextGaussian() * 100);
int y = rng.nextInt(WIDTH);
int x = rng.nextInt(HEIGHT);
g.setColor(new Color(rng.nextInt(256), rng.nextInt(256),
rng.nextInt(256), rng.nextInt(127) + 128));
switch (rng.nextInt(2)) {
case 0:
g.fillRect(x, y, r, r);
break;
case 1:
g.fillOval(x, y, r, r);
break;
}
}
private void initDisturb() {
for (int i = 0; i < INIT_DISTURB; i++) {
disturb();
}
}
public void run() {
while (true) {
try {
Thread.sleep((int) speed);
if (pause) {
synchronized (image) {
image.wait();
}
}
iterate();
repaint();
} catch (InterruptedException e) {
/* Nothing. */
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(display.filter(image, null), 0, 0, this);
if (help) {
/* Print some help information. */
FontMetrics fm = g.getFontMetrics();
int h = fm.getAscent() + fm.getDescent();
g.setColor(Color.WHITE);
int x1 = 10;
int x2 = 50;
int y = h;
g.drawString("Shortcut keys:", x1, y);
y += h * 2;
g.drawString("n", x1, y);
g.drawString("Toggle automated noise", x2, y);
y += h;
g.drawString("g/G", x1, y);
g.drawString("Increase/decrease gravity", x2, y);
y += h;
g.drawString("r/R", x1, y);
g.drawString("Increase/decrease rotation", x2, y);
y += h;
g.drawString("+/-", x1, y);
g.drawString("Increase/decrease animation speed", x2, y);
y += h;
g.drawString("p", x1, y);
g.drawString("Toggle pause/play", x2, y);
y += h;
g.drawString("s", x1, y);
g.drawString("Save a screenshot", x2, y);
y += h;
}
}
public static ConvolveOp getGaussianBlurFilter(int radius,
boolean horizontal) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be >= 1");
}
int size = radius * 2 + 1;
float[] data = new float[size];
float sigma = radius / 3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
float total = 0.0f;
for (int i = -radius; i <= radius; i++) {
float distance = i * i;
int index = i + radius;
data[index] = (float) Math.exp(-distance / twoSigmaSquare)
/ sigmaRoot;
total += data[index];
}
for (int i = 0; i < data.length; i++) {
data[i] /= total;
}
Kernel kernel = null;
if (horizontal) {
kernel = new Kernel(size, 1, data);
} else {
kernel = new Kernel(1, size, data);
}
return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
}
}
| Add message system.
| src/feedback/Feedback.java | Add message system. | <ide><path>rc/feedback/Feedback.java
<ide> }
<ide> }
<ide>
<add> private void message(String msg) {
<add> Graphics2D g = image.createGraphics();
<add> g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
<add> RenderingHints.VALUE_ANTIALIAS_ON);
<add> g.setColor(Color.WHITE);
<add> FontMetrics fm = g.getFontMetrics();
<add> int w = fm.stringWidth(msg);
<add> g.drawString(msg, WIDTH / 2 - w / 2, HEIGHT - fm.getAscent() * 2);
<add> }
<add>
<ide> private void iterate() {
<ide> if (!mouse)
<ide> counter++; |
|
Java | bsd-3-clause | edcc3ca48af5160827d4b73e9addb9ff8988f0e1 | 0 | lrytz/asm,lrytz/asm | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* 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. Neither the name of the copyright holders 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 OWNER 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 org.objectweb.asm.commons;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* A {@link org.objectweb.asm.MethodAdapter} with convenient methods to generate
* code. For example, using this adapter, the class below
*
* <pre>
* public class Example {
* public static void main(String[] args) {
* System.out.println("Hello world!");
* }
* }
* </pre>
*
* can be generated as follows:
*
* <pre>
* ClassWriter cw = new ClassWriter(true);
* cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
*
* Method m = Method.getMethod("void <init> ()");
* GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw);
* mg.loadThis();
* mg.invokeConstructor(Type.getType(Object.class), m);
* mg.returnValue();
* mg.endMethod();
*
* m = Method.getMethod("void main (String[])");
* mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
* mg.getStatic(Type.getType(System.class), "out", Type.getType(PrintStream.class));
* mg.push("Hello world!");
* mg.invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println (String)"));
* mg.returnValue();
* mg.endMethod();
*
* cw.visitEnd();
* </pre>
*
* @author Juozas Baliuka
* @author Chris Nokleberg
* @author Eric Bruneton
*/
public class GeneratorAdapter extends LocalVariablesSorter {
private static final String CLDESC = "Ljava/lang/Class;";
private final static Type BYTE_TYPE = Type.getObjectType("java/lang/Byte");
private final static Type BOOLEAN_TYPE = Type.getObjectType("java/lang/Boolean");
private final static Type SHORT_TYPE = Type.getObjectType("java/lang/Short");
private final static Type CHARACTER_TYPE = Type.getObjectType("java/lang/Character");
private final static Type INTEGER_TYPE = Type.getObjectType("java/lang/Integer");
private final static Type FLOAT_TYPE = Type.getObjectType("java/lang/Float");
private final static Type LONG_TYPE = Type.getObjectType("java/lang/Long");
private final static Type DOUBLE_TYPE = Type.getObjectType("java/lang/Double");
private final static Type NUMBER_TYPE = Type.getObjectType("java/lang/Number");
private final static Type OBJECT_TYPE = Type.getObjectType("java/lang/Object");
private final static Method BOOLEAN_VALUE = Method.getMethod("boolean booleanValue()");
private final static Method CHAR_VALUE = Method.getMethod("char charValue()");
private final static Method INT_VALUE = Method.getMethod("int intValue()");
private final static Method FLOAT_VALUE = Method.getMethod("float floatValue()");
private final static Method LONG_VALUE = Method.getMethod("long longValue()");
private final static Method DOUBLE_VALUE = Method.getMethod("double doubleValue()");
/**
* Constant for the {@link #math math} method.
*/
public final static int ADD = Opcodes.IADD;
/**
* Constant for the {@link #math math} method.
*/
public final static int SUB = Opcodes.ISUB;
/**
* Constant for the {@link #math math} method.
*/
public final static int MUL = Opcodes.IMUL;
/**
* Constant for the {@link #math math} method.
*/
public final static int DIV = Opcodes.IDIV;
/**
* Constant for the {@link #math math} method.
*/
public final static int REM = Opcodes.IREM;
/**
* Constant for the {@link #math math} method.
*/
public final static int NEG = Opcodes.INEG;
/**
* Constant for the {@link #math math} method.
*/
public final static int SHL = Opcodes.ISHL;
/**
* Constant for the {@link #math math} method.
*/
public final static int SHR = Opcodes.ISHR;
/**
* Constant for the {@link #math math} method.
*/
public final static int USHR = Opcodes.IUSHR;
/**
* Constant for the {@link #math math} method.
*/
public final static int AND = Opcodes.IAND;
/**
* Constant for the {@link #math math} method.
*/
public final static int OR = Opcodes.IOR;
/**
* Constant for the {@link #math math} method.
*/
public final static int XOR = Opcodes.IXOR;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int EQ = Opcodes.IFEQ;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int NE = Opcodes.IFNE;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int LT = Opcodes.IFLT;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int GE = Opcodes.IFGE;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int GT = Opcodes.IFGT;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int LE = Opcodes.IFLE;
/**
* Access flags of the method visited by this adapter.
*/
private final int access;
/**
* Return type of the method visited by this adapter.
*/
private final Type returnType;
/**
* Argument types of the method visited by this adapter.
*/
private final Type[] argumentTypes;
/**
* Types of the local variables of the method visited by this adapter.
*/
private final List localTypes = new ArrayList();
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param mv the method visitor to which this adapter delegates calls.
* @param access the method's access flags (see {@link Opcodes}).
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
*/
public GeneratorAdapter(
final MethodVisitor mv,
final int access,
final String name,
final String desc)
{
super(access, desc, mv);
this.access = access;
this.returnType = Type.getReturnType(desc);
this.argumentTypes = Type.getArgumentTypes(desc);
}
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param access access flags of the adapted method.
* @param method the adapted method.
* @param mv the method visitor to which this adapter delegates calls.
*/
public GeneratorAdapter(
final int access,
final Method method,
final MethodVisitor mv)
{
super(access, method.getDescriptor(), mv);
this.access = access;
this.returnType = method.getReturnType();
this.argumentTypes = method.getArgumentTypes();
}
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param access access flags of the adapted method.
* @param method the adapted method.
* @param signature the signature of the adapted method (may be
* <tt>null</tt>).
* @param exceptions the exceptions thrown by the adapted method (may be
* <tt>null</tt>).
* @param cv the class visitor to which this adapter delegates calls.
*/
public GeneratorAdapter(
final int access,
final Method method,
final String signature,
final Type[] exceptions,
final ClassVisitor cv)
{
this(access, method, cv.visitMethod(access,
method.getName(),
method.getDescriptor(),
signature,
getInternalNames(exceptions)));
}
/**
* Returns the internal names of the given types.
*
* @param types a set of types.
* @return the internal names of the given types.
*/
private static String[] getInternalNames(final Type[] types) {
if (types == null) {
return null;
}
String[] names = new String[types.length];
for (int i = 0; i < names.length; ++i) {
names[i] = types[i].getInternalName();
}
return names;
}
// ------------------------------------------------------------------------
// Instructions to push constants on the stack
// ------------------------------------------------------------------------
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final boolean value) {
push(value ? 1 : 0);
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final int value) {
if (value >= -1 && value <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + value);
} else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
mv.visitIntInsn(Opcodes.BIPUSH, value);
} else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
mv.visitIntInsn(Opcodes.SIPUSH, value);
} else {
mv.visitLdcInsn(new Integer(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final long value) {
if (value == 0L || value == 1L) {
mv.visitInsn(Opcodes.LCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Long(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final float value) {
int bits = Float.floatToIntBits(value);
if (bits == 0L || bits == 0x3f800000 || bits == 0x40000000) { // 0..2
mv.visitInsn(Opcodes.FCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Float(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final double value) {
long bits = Double.doubleToLongBits(value);
if (bits == 0L || bits == 0x3ff0000000000000L) { // +0.0d and 1.0d
mv.visitInsn(Opcodes.DCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Double(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack. May be <tt>null</tt>.
*/
public void push(final String value) {
if (value == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
} else {
mv.visitLdcInsn(value);
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final Type value) {
if (value == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
} else {
switch (value.getSort()) {
case Type.BOOLEAN:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Boolean",
"TYPE",
CLDESC);
break;
case Type.CHAR:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Char",
"TYPE",
CLDESC);
break;
case Type.BYTE:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Byte",
"TYPE",
CLDESC);
break;
case Type.SHORT:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Short",
"TYPE",
CLDESC);
break;
case Type.INT:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Integer",
"TYPE",
CLDESC);
break;
case Type.FLOAT:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Float",
"TYPE",
CLDESC);
break;
case Type.LONG:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Long",
"TYPE",
CLDESC);
break;
case Type.DOUBLE:
mv.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/Double",
"TYPE",
CLDESC);
break;
default:
mv.visitLdcInsn(value);
}
}
}
// ------------------------------------------------------------------------
// Instructions to load and store method arguments
// ------------------------------------------------------------------------
/**
* Returns the index of the given method argument in the frame's local
* variables array.
*
* @param arg the index of a method argument.
* @return the index of the given method argument in the frame's local
* variables array.
*/
private int getArgIndex(final int arg) {
int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0;
for (int i = 0; i < arg; i++) {
index += argumentTypes[i].getSize();
}
return index;
}
/**
* Generates the instruction to push a local variable on the stack.
*
* @param type the type of the local variable to be loaded.
* @param index an index in the frame's local variables array.
*/
private void loadInsn(final Type type, final int index) {
mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index);
}
/**
* Generates the instruction to store the top stack value in a local
* variable.
*
* @param type the type of the local variable to be stored.
* @param index an index in the frame's local variables array.
*/
private void storeInsn(final Type type, final int index) {
mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), index);
}
/**
* Generates the instruction to load 'this' on the stack.
*/
public void loadThis() {
if ((access & Opcodes.ACC_STATIC) != 0) {
throw new IllegalStateException("no 'this' pointer within static method");
}
mv.visitVarInsn(Opcodes.ALOAD, 0);
}
/**
* Generates the instruction to load the given method argument on the stack.
*
* @param arg the index of a method argument.
*/
public void loadArg(final int arg) {
loadInsn(argumentTypes[arg], getArgIndex(arg));
}
/**
* Generates the instructions to load the given method arguments on the
* stack.
*
* @param arg the index of the first method argument to be loaded.
* @param count the number of method arguments to be loaded.
*/
public void loadArgs(final int arg, final int count) {
int index = getArgIndex(arg);
for (int i = 0; i < count; ++i) {
Type t = argumentTypes[arg + i];
loadInsn(t, index);
index += t.getSize();
}
}
/**
* Generates the instructions to load all the method arguments on the stack.
*/
public void loadArgs() {
loadArgs(0, argumentTypes.length);
}
/**
* Generates the instructions to load all the method arguments on the stack,
* as a single object array.
*/
public void loadArgArray() {
push(argumentTypes.length);
newArray(OBJECT_TYPE);
for (int i = 0; i < argumentTypes.length; i++) {
dup();
push(i);
loadArg(i);
box(argumentTypes[i]);
arrayStore(OBJECT_TYPE);
}
}
/**
* Generates the instruction to store the top stack value in the given
* method argument.
*
* @param arg the index of a method argument.
*/
public void storeArg(final int arg) {
storeInsn(argumentTypes[arg], getArgIndex(arg));
}
// ------------------------------------------------------------------------
// Instructions to load and store local variables
// ------------------------------------------------------------------------
/**
* Returns the type of the given local variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @return the type of the given local variable.
*/
public Type getLocalType(final int local) {
return (Type) localTypes.get(local - firstLocal);
}
protected void setLocalType(final int local, final Type type) {
int index = local - firstLocal;
while (localTypes.size() < index + 1) {
localTypes.add(null);
}
localTypes.set(index, type);
}
/**
* Generates the instruction to load the given local variable on the stack.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void loadLocal(final int local) {
loadInsn(getLocalType(local), local);
}
/**
* Generates the instruction to load the given local variable on the stack.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @param type the type of this local variable.
*/
public void loadLocal(final int local, final Type type) {
setLocalType(local, type);
loadInsn(type, local);
}
/**
* Generates the instruction to store the top stack value in the given local
* variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void storeLocal(final int local) {
storeInsn(getLocalType(local), local);
}
/**
* Generates the instruction to store the top stack value in the given local
* variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @param type the type of this local variable.
*/
public void storeLocal(final int local, final Type type) {
setLocalType(local, type);
storeInsn(type, local);
}
/**
* Generates the instruction to load an element from an array.
*
* @param type the type of the array element to be loaded.
*/
public void arrayLoad(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IALOAD));
}
/**
* Generates the instruction to store an element in an array.
*
* @param type the type of the array element to be stored.
*/
public void arrayStore(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IASTORE));
}
// ------------------------------------------------------------------------
// Instructions to manage the stack
// ------------------------------------------------------------------------
/**
* Generates a POP instruction.
*/
public void pop() {
mv.visitInsn(Opcodes.POP);
}
/**
* Generates a POP2 instruction.
*/
public void pop2() {
mv.visitInsn(Opcodes.POP2);
}
/**
* Generates a DUP instruction.
*/
public void dup() {
mv.visitInsn(Opcodes.DUP);
}
/**
* Generates a DUP2 instruction.
*/
public void dup2() {
mv.visitInsn(Opcodes.DUP2);
}
/**
* Generates a DUP_X1 instruction.
*/
public void dupX1() {
mv.visitInsn(Opcodes.DUP_X1);
}
/**
* Generates a DUP_X2 instruction.
*/
public void dupX2() {
mv.visitInsn(Opcodes.DUP_X2);
}
/**
* Generates a DUP2_X1 instruction.
*/
public void dup2X1() {
mv.visitInsn(Opcodes.DUP2_X1);
}
/**
* Generates a DUP2_X2 instruction.
*/
public void dup2X2() {
mv.visitInsn(Opcodes.DUP2_X2);
}
/**
* Generates a SWAP instruction.
*/
public void swap() {
mv.visitInsn(Opcodes.SWAP);
}
/**
* Generates the instructions to swap the top two stack values.
*
* @param prev type of the top - 1 stack value.
* @param type type of the top stack value.
*/
public void swap(final Type prev, final Type type) {
if (type.getSize() == 1) {
if (prev.getSize() == 1) {
swap(); // same as dupX1(), pop();
} else {
dupX2();
pop();
}
} else {
if (prev.getSize() == 1) {
dup2X1();
pop2();
} else {
dup2X2();
pop2();
}
}
}
// ------------------------------------------------------------------------
// Instructions to do mathematical and logical operations
// ------------------------------------------------------------------------
/**
* Generates the instruction to do the specified mathematical or logical
* operation.
*
* @param op a mathematical or logical operation. Must be one of ADD, SUB,
* MUL, DIV, REM, NEG, SHL, SHR, USHR, AND, OR, XOR.
* @param type the type of the operand(s) for this operation.
*/
public void math(final int op, final Type type) {
mv.visitInsn(type.getOpcode(op));
}
/**
* Generates the instructions to compute the bitwise negation of the top
* stack value.
*/
public void not() {
mv.visitInsn(Opcodes.ICONST_1);
mv.visitInsn(Opcodes.IXOR);
}
/**
* Generates the instruction to increment the given local variable.
*
* @param local the local variable to be incremented.
* @param amount the amount by which the local variable must be incremented.
*/
public void iinc(final int local, final int amount) {
mv.visitIincInsn(local, amount);
}
/**
* Generates the instructions to cast a numerical value from one type to
* another.
*
* @param from the type of the top stack value
* @param to the type into which this value must be cast.
*/
public void cast(final Type from, final Type to) {
if (from != to) {
if (from == Type.DOUBLE_TYPE) {
if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.D2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.D2L);
} else {
mv.visitInsn(Opcodes.D2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.FLOAT_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.F2D);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.F2L);
} else {
mv.visitInsn(Opcodes.F2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.LONG_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.L2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.L2F);
} else {
mv.visitInsn(Opcodes.L2I);
cast(Type.INT_TYPE, to);
}
} else {
if (to == Type.BYTE_TYPE) {
mv.visitInsn(Opcodes.I2B);
} else if (to == Type.CHAR_TYPE) {
mv.visitInsn(Opcodes.I2C);
} else if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.I2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.I2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.I2L);
} else if (to == Type.SHORT_TYPE) {
mv.visitInsn(Opcodes.I2S);
}
}
}
}
// ------------------------------------------------------------------------
// Instructions to do boxing and unboxing operations
// ------------------------------------------------------------------------
/**
* Generates the instructions to box the top stack value. This value is
* replaced by its boxed equivalent on top of the stack.
*
* @param type the type of the top stack value.
*/
public void box(final Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return;
}
if (type == Type.VOID_TYPE) {
push((String) null);
} else {
Type boxed = type;
switch (type.getSort()) {
case Type.BYTE:
boxed = BYTE_TYPE;
break;
case Type.BOOLEAN:
boxed = BOOLEAN_TYPE;
break;
case Type.SHORT:
boxed = SHORT_TYPE;
break;
case Type.CHAR:
boxed = CHARACTER_TYPE;
break;
case Type.INT:
boxed = INTEGER_TYPE;
break;
case Type.FLOAT:
boxed = FLOAT_TYPE;
break;
case Type.LONG:
boxed = LONG_TYPE;
break;
case Type.DOUBLE:
boxed = DOUBLE_TYPE;
break;
}
newInstance(boxed);
if (type.getSize() == 2) {
// Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o
dupX2();
dupX2();
pop();
} else {
// p -> po -> opo -> oop -> o
dupX1();
swap();
}
invokeConstructor(boxed, new Method("<init>",
Type.VOID_TYPE,
new Type[] { type }));
}
}
/**
* Generates the instructions to unbox the top stack value. This value is
* replaced by its unboxed equivalent on top of the stack.
*
* @param type the type of the top stack value.
*/
public void unbox(final Type type) {
Type t = NUMBER_TYPE;
Method sig = null;
switch (type.getSort()) {
case Type.VOID:
return;
case Type.CHAR:
t = CHARACTER_TYPE;
sig = CHAR_VALUE;
break;
case Type.BOOLEAN:
t = BOOLEAN_TYPE;
sig = BOOLEAN_VALUE;
break;
case Type.DOUBLE:
sig = DOUBLE_VALUE;
break;
case Type.FLOAT:
sig = FLOAT_VALUE;
break;
case Type.LONG:
sig = LONG_VALUE;
break;
case Type.INT:
case Type.SHORT:
case Type.BYTE:
sig = INT_VALUE;
}
if (sig == null) {
checkCast(type);
} else {
checkCast(t);
invokeVirtual(t, sig);
}
}
// ------------------------------------------------------------------------
// Instructions to jump to other instructions
// ------------------------------------------------------------------------
/**
* Creates a new {@link Label}.
*
* @return a new {@link Label}.
*/
public Label newLabel() {
return new Label();
}
/**
* Marks the current code position with the given label.
*
* @param label a label.
*/
public void mark(final Label label) {
mv.visitLabel(label);
}
/**
* Marks the current code position with a new label.
*
* @return the label that was created to mark the current code position.
*/
public Label mark() {
Label label = new Label();
mv.visitLabel(label);
return label;
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top two stack values.
*
* @param type the type of the top two stack values.
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifCmp(final Type type, final int mode, final Label label) {
int intOp = -1;
switch (type.getSort()) {
case Type.LONG:
mv.visitInsn(Opcodes.LCMP);
break;
case Type.DOUBLE:
mv.visitInsn(Opcodes.DCMPG);
break;
case Type.FLOAT:
mv.visitInsn(Opcodes.FCMPG);
break;
case Type.ARRAY:
case Type.OBJECT:
switch (mode) {
case EQ:
mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label);
return;
case NE:
mv.visitJumpInsn(Opcodes.IF_ACMPNE, label);
return;
}
throw new IllegalArgumentException("Bad comparison for type "
+ type);
default:
switch (mode) {
case EQ:
intOp = Opcodes.IF_ICMPEQ;
break;
case NE:
intOp = Opcodes.IF_ICMPNE;
break;
case GE:
intOp = Opcodes.IF_ICMPGE;
break;
case LT:
intOp = Opcodes.IF_ICMPLT;
break;
case LE:
intOp = Opcodes.IF_ICMPLE;
break;
case GT:
intOp = Opcodes.IF_ICMPGT;
break;
}
mv.visitJumpInsn(intOp, label);
return;
}
int jumpMode = mode;
switch (mode) {
case GE:
jumpMode = LT;
break;
case LE:
jumpMode = GT;
break;
}
mv.visitJumpInsn(jumpMode, label);
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top two integer stack values.
*
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifICmp(final int mode, final Label label) {
ifCmp(Type.INT_TYPE, mode, label);
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top integer stack value with zero.
*
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifZCmp(final int mode, final Label label) {
mv.visitJumpInsn(mode, label);
}
/**
* Generates the instruction to jump to the given label if the top stack
* value is null.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void ifNull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNULL, label);
}
/**
* Generates the instruction to jump to the given label if the top stack
* value is not null.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void ifNonNull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNONNULL, label);
}
/**
* Generates the instruction to jump to the given label.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void goTo(final Label label) {
mv.visitJumpInsn(Opcodes.GOTO, label);
}
/**
* Generates a RET instruction.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void ret(final int local) {
mv.visitVarInsn(Opcodes.RET, local);
}
/**
* Generates the instructions for a switch statement.
*
* @param keys the switch case keys.
* @param generator a generator to generate the code for the switch cases.
*/
public void tableSwitch(
final int[] keys,
final TableSwitchGenerator generator)
{
float density;
if (keys.length == 0) {
density = 0;
} else {
density = (float) keys.length
/ (keys[keys.length - 1] - keys[0] + 1);
}
tableSwitch(keys, generator, density >= 0.5f);
}
/**
* Generates the instructions for a switch statement.
*
* @param keys the switch case keys.
* @param generator a generator to generate the code for the switch cases.
* @param useTable <tt>true</tt> to use a TABLESWITCH instruction, or
* <tt>false</tt> to use a LOOKUPSWITCH instruction.
*/
public void tableSwitch(
final int[] keys,
final TableSwitchGenerator generator,
final boolean useTable)
{
for (int i = 1; i < keys.length; ++i) {
if (keys[i] < keys[i - 1]) {
throw new IllegalArgumentException("keys must be sorted ascending");
}
}
Label def = newLabel();
Label end = newLabel();
if (keys.length > 0) {
int len = keys.length;
int min = keys[0];
int max = keys[len - 1];
int range = max - min + 1;
if (useTable) {
Label[] labels = new Label[range];
Arrays.fill(labels, def);
for (int i = 0; i < len; ++i) {
labels[keys[i] - min] = newLabel();
}
mv.visitTableSwitchInsn(min, max, def, labels);
for (int i = 0; i < range; ++i) {
Label label = labels[i];
if (label != def) {
mark(label);
generator.generateCase(i + min, end);
}
}
} else {
Label[] labels = new Label[len];
for (int i = 0; i < len; ++i) {
labels[i] = newLabel();
}
mv.visitLookupSwitchInsn(def, keys, labels);
for (int i = 0; i < len; ++i) {
mark(labels[i]);
generator.generateCase(keys[i], end);
}
}
}
mark(def);
generator.generateDefault();
mark(end);
}
/**
* Generates the instruction to return the top stack value to the caller.
*/
public void returnValue() {
mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
}
// ------------------------------------------------------------------------
// Instructions to load and store fields
// ------------------------------------------------------------------------
/**
* Generates a get field or set field instruction.
*
* @param opcode the instruction's opcode.
* @param ownerType the class in which the field is defined.
* @param name the name of the field.
* @param fieldType the type of the field.
*/
private void fieldInsn(
final int opcode,
final Type ownerType,
final String name,
final Type fieldType)
{
mv.visitFieldInsn(opcode,
ownerType.getInternalName(),
name,
fieldType.getDescriptor());
}
/**
* Generates the instruction to push the value of a static field on the
* stack.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void getStatic(final Type owner, final String name, final Type type)
{
fieldInsn(Opcodes.GETSTATIC, owner, name, type);
}
/**
* Generates the instruction to store the top stack value in a static field.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void putStatic(final Type owner, final String name, final Type type)
{
fieldInsn(Opcodes.PUTSTATIC, owner, name, type);
}
/**
* Generates the instruction to push the value of a non static field on the
* stack.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void getField(final Type owner, final String name, final Type type) {
fieldInsn(Opcodes.GETFIELD, owner, name, type);
}
/**
* Generates the instruction to store the top stack value in a non static
* field.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void putField(final Type owner, final String name, final Type type) {
fieldInsn(Opcodes.PUTFIELD, owner, name, type);
}
// ------------------------------------------------------------------------
// Instructions to invoke methods
// ------------------------------------------------------------------------
/**
* Generates an invoke method instruction.
*
* @param opcode the instruction's opcode.
* @param type the class in which the method is defined.
* @param method the method to be invoked.
*/
private void invokeInsn(
final int opcode,
final Type type,
final Method method)
{
String owner = type.getSort() == Type.ARRAY
? type.getDescriptor()
: type.getInternalName();
mv.visitMethodInsn(opcode,
owner,
method.getName(),
method.getDescriptor());
}
/**
* Generates the instruction to invoke a normal method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeVirtual(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKEVIRTUAL, owner, method);
}
/**
* Generates the instruction to invoke a constructor.
*
* @param type the class in which the constructor is defined.
* @param method the constructor to be invoked.
*/
public void invokeConstructor(final Type type, final Method method) {
invokeInsn(Opcodes.INVOKESPECIAL, type, method);
}
/**
* Generates the instruction to invoke a static method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeStatic(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKESTATIC, owner, method);
}
/**
* Generates the instruction to invoke an interface method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeInterface(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKEINTERFACE, owner, method);
}
// ------------------------------------------------------------------------
// Instructions to create objects and arrays
// ------------------------------------------------------------------------
/**
* Generates a type dependent instruction.
*
* @param opcode the instruction's opcode.
* @param type the instruction's operand.
*/
private void typeInsn(final int opcode, final Type type) {
mv.visitTypeInsn(opcode, type.getInternalName());
}
/**
* Generates the instruction to create a new object.
*
* @param type the class of the object to be created.
*/
public void newInstance(final Type type) {
typeInsn(Opcodes.NEW, type);
}
/**
* Generates the instruction to create a new array.
*
* @param type the type of the array elements.
*/
public void newArray(final Type type) {
int typ;
switch (type.getSort()) {
case Type.BOOLEAN:
typ = Opcodes.T_BOOLEAN;
break;
case Type.CHAR:
typ = Opcodes.T_CHAR;
break;
case Type.BYTE:
typ = Opcodes.T_BYTE;
break;
case Type.SHORT:
typ = Opcodes.T_SHORT;
break;
case Type.INT:
typ = Opcodes.T_INT;
break;
case Type.FLOAT:
typ = Opcodes.T_FLOAT;
break;
case Type.LONG:
typ = Opcodes.T_LONG;
break;
case Type.DOUBLE:
typ = Opcodes.T_DOUBLE;
break;
default:
typeInsn(Opcodes.ANEWARRAY, type);
return;
}
mv.visitIntInsn(Opcodes.NEWARRAY, typ);
}
// ------------------------------------------------------------------------
// Miscelaneous instructions
// ------------------------------------------------------------------------
/**
* Generates the instruction to compute the length of an array.
*/
public void arrayLength() {
mv.visitInsn(Opcodes.ARRAYLENGTH);
}
/**
* Generates the instruction to throw an exception.
*/
public void throwException() {
mv.visitInsn(Opcodes.ATHROW);
}
/**
* Generates the instructions to create and throw an exception. The
* exception class must have a constructor with a single String argument.
*
* @param type the class of the exception to be thrown.
* @param msg the detailed message of the exception.
*/
public void throwException(final Type type, final String msg) {
newInstance(type);
dup();
push(msg);
invokeConstructor(type, Method.getMethod("void <init> (String)"));
throwException();
}
/**
* Generates the instruction to check that the top stack value is of the
* given type.
*
* @param type a class or interface type.
*/
public void checkCast(final Type type) {
if (!type.equals(OBJECT_TYPE)) {
typeInsn(Opcodes.CHECKCAST, type);
}
}
/**
* Generates the instruction to test if the top stack value is of the given
* type.
*
* @param type a class or interface type.
*/
public void instanceOf(final Type type) {
typeInsn(Opcodes.INSTANCEOF, type);
}
/**
* Generates the instruction to get the monitor of the top stack value.
*/
public void monitorEnter() {
mv.visitInsn(Opcodes.MONITORENTER);
}
/**
* Generates the instruction to release the monitor of the top stack value.
*/
public void monitorExit() {
mv.visitInsn(Opcodes.MONITOREXIT);
}
// ------------------------------------------------------------------------
// Non instructions
// ------------------------------------------------------------------------
/**
* Marks the end of the visited method.
*/
public void endMethod() {
if ((access & Opcodes.ACC_ABSTRACT) == 0) {
mv.visitMaxs(0, 0);
}
mv.visitEnd();
}
/**
* Marks the start of an exception handler.
*
* @param start beginning of the exception handler's scope (inclusive).
* @param end end of the exception handler's scope (exclusive).
* @param exception internal name of the type of exceptions handled by the
* handler.
*/
public void catchException(
final Label start,
final Label end,
final Type exception)
{
mv.visitTryCatchBlock(start, end, mark(), exception.getInternalName());
}
}
| src/org/objectweb/asm/commons/GeneratorAdapter.java | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* 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. Neither the name of the copyright holders 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 OWNER 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 org.objectweb.asm.commons;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* A {@link org.objectweb.asm.MethodAdapter} with convenient methods to generate
* code. For example, using this adapter, the class below
*
* <pre>
* public class Example {
* public static void main(String[] args) {
* System.out.println("Hello world!");
* }
* }
* </pre>
*
* can be generated as follows:
*
* <pre>
* ClassWriter cw = new ClassWriter(true);
* cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
*
* Method m = Method.getMethod("void <init> ()");
* GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw);
* mg.loadThis();
* mg.invokeConstructor(Type.getType(Object.class), m);
* mg.returnValue();
* mg.endMethod();
*
* m = Method.getMethod("void main (String[])");
* mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
* mg.getStatic(Type.getType(System.class), "out", Type.getType(PrintStream.class));
* mg.push("Hello world!");
* mg.invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println (String)"));
* mg.returnValue();
* mg.endMethod();
*
* cw.visitEnd();
* </pre>
*
* @author Juozas Baliuka
* @author Chris Nokleberg
* @author Eric Bruneton
*/
public class GeneratorAdapter extends LocalVariablesSorter {
private final static Type BYTE_TYPE = Type.getObjectType("java/lang/Byte");
private final static Type BOOLEAN_TYPE = Type.getObjectType("java/lang/Boolean");
private final static Type SHORT_TYPE = Type.getObjectType("java/lang/Short");
private final static Type CHARACTER_TYPE = Type.getObjectType("java/lang/Character");
private final static Type INTEGER_TYPE = Type.getObjectType("java/lang/Integer");
private final static Type FLOAT_TYPE = Type.getObjectType("java/lang/Float");
private final static Type LONG_TYPE = Type.getObjectType("java/lang/Long");
private final static Type DOUBLE_TYPE = Type.getObjectType("java/lang/Double");
private final static Type NUMBER_TYPE = Type.getObjectType("java/lang/Number");
private final static Type OBJECT_TYPE = Type.getObjectType("java/lang/Object");
private final static Method BOOLEAN_VALUE = Method.getMethod("boolean booleanValue()");
private final static Method CHAR_VALUE = Method.getMethod("char charValue()");
private final static Method INT_VALUE = Method.getMethod("int intValue()");
private final static Method FLOAT_VALUE = Method.getMethod("float floatValue()");
private final static Method LONG_VALUE = Method.getMethod("long longValue()");
private final static Method DOUBLE_VALUE = Method.getMethod("double doubleValue()");
/**
* Constant for the {@link #math math} method.
*/
public final static int ADD = Opcodes.IADD;
/**
* Constant for the {@link #math math} method.
*/
public final static int SUB = Opcodes.ISUB;
/**
* Constant for the {@link #math math} method.
*/
public final static int MUL = Opcodes.IMUL;
/**
* Constant for the {@link #math math} method.
*/
public final static int DIV = Opcodes.IDIV;
/**
* Constant for the {@link #math math} method.
*/
public final static int REM = Opcodes.IREM;
/**
* Constant for the {@link #math math} method.
*/
public final static int NEG = Opcodes.INEG;
/**
* Constant for the {@link #math math} method.
*/
public final static int SHL = Opcodes.ISHL;
/**
* Constant for the {@link #math math} method.
*/
public final static int SHR = Opcodes.ISHR;
/**
* Constant for the {@link #math math} method.
*/
public final static int USHR = Opcodes.IUSHR;
/**
* Constant for the {@link #math math} method.
*/
public final static int AND = Opcodes.IAND;
/**
* Constant for the {@link #math math} method.
*/
public final static int OR = Opcodes.IOR;
/**
* Constant for the {@link #math math} method.
*/
public final static int XOR = Opcodes.IXOR;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int EQ = Opcodes.IFEQ;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int NE = Opcodes.IFNE;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int LT = Opcodes.IFLT;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int GE = Opcodes.IFGE;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int GT = Opcodes.IFGT;
/**
* Constant for the {@link #ifCmp ifCmp} method.
*/
public final static int LE = Opcodes.IFLE;
/**
* Access flags of the method visited by this adapter.
*/
private final int access;
/**
* Return type of the method visited by this adapter.
*/
private final Type returnType;
/**
* Argument types of the method visited by this adapter.
*/
private final Type[] argumentTypes;
/**
* Types of the local variables of the method visited by this adapter.
*/
private final List localTypes = new ArrayList();
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param mv the method visitor to which this adapter delegates calls.
* @param access the method's access flags (see {@link Opcodes}).
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
*/
public GeneratorAdapter(
final MethodVisitor mv,
final int access,
final String name,
final String desc)
{
super(access, desc, mv);
this.access = access;
this.returnType = Type.getReturnType(desc);
this.argumentTypes = Type.getArgumentTypes(desc);
}
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param access access flags of the adapted method.
* @param method the adapted method.
* @param mv the method visitor to which this adapter delegates calls.
*/
public GeneratorAdapter(
final int access,
final Method method,
final MethodVisitor mv)
{
super(access, method.getDescriptor(), mv);
this.access = access;
this.returnType = method.getReturnType();
this.argumentTypes = method.getArgumentTypes();
}
/**
* Creates a new {@link GeneratorAdapter}.
*
* @param access access flags of the adapted method.
* @param method the adapted method.
* @param signature the signature of the adapted method (may be
* <tt>null</tt>).
* @param exceptions the exceptions thrown by the adapted method (may be
* <tt>null</tt>).
* @param cv the class visitor to which this adapter delegates calls.
*/
public GeneratorAdapter(
final int access,
final Method method,
final String signature,
final Type[] exceptions,
final ClassVisitor cv)
{
this(access, method, cv.visitMethod(access,
method.getName(),
method.getDescriptor(),
signature,
getInternalNames(exceptions)));
}
/**
* Returns the internal names of the given types.
*
* @param types a set of types.
* @return the internal names of the given types.
*/
private static String[] getInternalNames(final Type[] types) {
if (types == null) {
return null;
}
String[] names = new String[types.length];
for (int i = 0; i < names.length; ++i) {
names[i] = types[i].getInternalName();
}
return names;
}
// ------------------------------------------------------------------------
// Instructions to push constants on the stack
// ------------------------------------------------------------------------
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final boolean value) {
push(value ? 1 : 0);
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final int value) {
if (value >= -1 && value <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + value);
} else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
mv.visitIntInsn(Opcodes.BIPUSH, value);
} else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
mv.visitIntInsn(Opcodes.SIPUSH, value);
} else {
mv.visitLdcInsn(new Integer(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final long value) {
if (value == 0L || value == 1L) {
mv.visitInsn(Opcodes.LCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Long(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final float value) {
int bits = Float.floatToIntBits(value);
if (bits == 0L || bits == 0x3f800000 || bits == 0x40000000) { // 0..2
mv.visitInsn(Opcodes.FCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Float(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final double value) {
long bits = Double.doubleToLongBits(value);
if (bits == 0L || bits == 0x3ff0000000000000L) { // +0.0d and 1.0d
mv.visitInsn(Opcodes.DCONST_0 + (int) value);
} else {
mv.visitLdcInsn(new Double(value));
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack. May be <tt>null</tt>.
*/
public void push(final String value) {
if (value == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
} else {
mv.visitLdcInsn(value);
}
}
/**
* Generates the instruction to push the given value on the stack.
*
* @param value the value to be pushed on the stack.
*/
public void push(final Type value) {
if (value == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
} else {
mv.visitLdcInsn(value);
}
}
// ------------------------------------------------------------------------
// Instructions to load and store method arguments
// ------------------------------------------------------------------------
/**
* Returns the index of the given method argument in the frame's local
* variables array.
*
* @param arg the index of a method argument.
* @return the index of the given method argument in the frame's local
* variables array.
*/
private int getArgIndex(final int arg) {
int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0;
for (int i = 0; i < arg; i++) {
index += argumentTypes[i].getSize();
}
return index;
}
/**
* Generates the instruction to push a local variable on the stack.
*
* @param type the type of the local variable to be loaded.
* @param index an index in the frame's local variables array.
*/
private void loadInsn(final Type type, final int index) {
mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index);
}
/**
* Generates the instruction to store the top stack value in a local
* variable.
*
* @param type the type of the local variable to be stored.
* @param index an index in the frame's local variables array.
*/
private void storeInsn(final Type type, final int index) {
mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), index);
}
/**
* Generates the instruction to load 'this' on the stack.
*/
public void loadThis() {
if ((access & Opcodes.ACC_STATIC) != 0) {
throw new IllegalStateException("no 'this' pointer within static method");
}
mv.visitVarInsn(Opcodes.ALOAD, 0);
}
/**
* Generates the instruction to load the given method argument on the stack.
*
* @param arg the index of a method argument.
*/
public void loadArg(final int arg) {
loadInsn(argumentTypes[arg], getArgIndex(arg));
}
/**
* Generates the instructions to load the given method arguments on the
* stack.
*
* @param arg the index of the first method argument to be loaded.
* @param count the number of method arguments to be loaded.
*/
public void loadArgs(final int arg, final int count) {
int index = getArgIndex(arg);
for (int i = 0; i < count; ++i) {
Type t = argumentTypes[arg + i];
loadInsn(t, index);
index += t.getSize();
}
}
/**
* Generates the instructions to load all the method arguments on the stack.
*/
public void loadArgs() {
loadArgs(0, argumentTypes.length);
}
/**
* Generates the instructions to load all the method arguments on the stack,
* as a single object array.
*/
public void loadArgArray() {
push(argumentTypes.length);
newArray(OBJECT_TYPE);
for (int i = 0; i < argumentTypes.length; i++) {
dup();
push(i);
loadArg(i);
box(argumentTypes[i]);
arrayStore(OBJECT_TYPE);
}
}
/**
* Generates the instruction to store the top stack value in the given
* method argument.
*
* @param arg the index of a method argument.
*/
public void storeArg(final int arg) {
storeInsn(argumentTypes[arg], getArgIndex(arg));
}
// ------------------------------------------------------------------------
// Instructions to load and store local variables
// ------------------------------------------------------------------------
/**
* Returns the type of the given local variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @return the type of the given local variable.
*/
public Type getLocalType(final int local) {
return (Type) localTypes.get(local - firstLocal);
}
protected void setLocalType(final int local, final Type type) {
int index = local - firstLocal;
while (localTypes.size() < index + 1) {
localTypes.add(null);
}
localTypes.set(index, type);
}
/**
* Generates the instruction to load the given local variable on the stack.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void loadLocal(final int local) {
loadInsn(getLocalType(local), local);
}
/**
* Generates the instruction to load the given local variable on the stack.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @param type the type of this local variable.
*/
public void loadLocal(final int local, final Type type) {
setLocalType(local, type);
loadInsn(type, local);
}
/**
* Generates the instruction to store the top stack value in the given local
* variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void storeLocal(final int local) {
storeInsn(getLocalType(local), local);
}
/**
* Generates the instruction to store the top stack value in the given local
* variable.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
* @param type the type of this local variable.
*/
public void storeLocal(final int local, final Type type) {
setLocalType(local, type);
storeInsn(type, local);
}
/**
* Generates the instruction to load an element from an array.
*
* @param type the type of the array element to be loaded.
*/
public void arrayLoad(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IALOAD));
}
/**
* Generates the instruction to store an element in an array.
*
* @param type the type of the array element to be stored.
*/
public void arrayStore(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IASTORE));
}
// ------------------------------------------------------------------------
// Instructions to manage the stack
// ------------------------------------------------------------------------
/**
* Generates a POP instruction.
*/
public void pop() {
mv.visitInsn(Opcodes.POP);
}
/**
* Generates a POP2 instruction.
*/
public void pop2() {
mv.visitInsn(Opcodes.POP2);
}
/**
* Generates a DUP instruction.
*/
public void dup() {
mv.visitInsn(Opcodes.DUP);
}
/**
* Generates a DUP2 instruction.
*/
public void dup2() {
mv.visitInsn(Opcodes.DUP2);
}
/**
* Generates a DUP_X1 instruction.
*/
public void dupX1() {
mv.visitInsn(Opcodes.DUP_X1);
}
/**
* Generates a DUP_X2 instruction.
*/
public void dupX2() {
mv.visitInsn(Opcodes.DUP_X2);
}
/**
* Generates a DUP2_X1 instruction.
*/
public void dup2X1() {
mv.visitInsn(Opcodes.DUP2_X1);
}
/**
* Generates a DUP2_X2 instruction.
*/
public void dup2X2() {
mv.visitInsn(Opcodes.DUP2_X2);
}
/**
* Generates a SWAP instruction.
*/
public void swap() {
mv.visitInsn(Opcodes.SWAP);
}
/**
* Generates the instructions to swap the top two stack values.
*
* @param prev type of the top - 1 stack value.
* @param type type of the top stack value.
*/
public void swap(final Type prev, final Type type) {
if (type.getSize() == 1) {
if (prev.getSize() == 1) {
swap(); // same as dupX1(), pop();
} else {
dupX2();
pop();
}
} else {
if (prev.getSize() == 1) {
dup2X1();
pop2();
} else {
dup2X2();
pop2();
}
}
}
// ------------------------------------------------------------------------
// Instructions to do mathematical and logical operations
// ------------------------------------------------------------------------
/**
* Generates the instruction to do the specified mathematical or logical
* operation.
*
* @param op a mathematical or logical operation. Must be one of ADD, SUB,
* MUL, DIV, REM, NEG, SHL, SHR, USHR, AND, OR, XOR.
* @param type the type of the operand(s) for this operation.
*/
public void math(final int op, final Type type) {
mv.visitInsn(type.getOpcode(op));
}
/**
* Generates the instructions to compute the bitwise negation of the top
* stack value.
*/
public void not() {
mv.visitInsn(Opcodes.ICONST_1);
mv.visitInsn(Opcodes.IXOR);
}
/**
* Generates the instruction to increment the given local variable.
*
* @param local the local variable to be incremented.
* @param amount the amount by which the local variable must be incremented.
*/
public void iinc(final int local, final int amount) {
mv.visitIincInsn(local, amount);
}
/**
* Generates the instructions to cast a numerical value from one type to
* another.
*
* @param from the type of the top stack value
* @param to the type into which this value must be cast.
*/
public void cast(final Type from, final Type to) {
if (from != to) {
if (from == Type.DOUBLE_TYPE) {
if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.D2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.D2L);
} else {
mv.visitInsn(Opcodes.D2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.FLOAT_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.F2D);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.F2L);
} else {
mv.visitInsn(Opcodes.F2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.LONG_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.L2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.L2F);
} else {
mv.visitInsn(Opcodes.L2I);
cast(Type.INT_TYPE, to);
}
} else {
if (to == Type.BYTE_TYPE) {
mv.visitInsn(Opcodes.I2B);
} else if (to == Type.CHAR_TYPE) {
mv.visitInsn(Opcodes.I2C);
} else if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.I2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.I2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.I2L);
} else if (to == Type.SHORT_TYPE) {
mv.visitInsn(Opcodes.I2S);
}
}
}
}
// ------------------------------------------------------------------------
// Instructions to do boxing and unboxing operations
// ------------------------------------------------------------------------
/**
* Generates the instructions to box the top stack value. This value is
* replaced by its boxed equivalent on top of the stack.
*
* @param type the type of the top stack value.
*/
public void box(final Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return;
}
if (type == Type.VOID_TYPE) {
push((String) null);
} else {
Type boxed = type;
switch (type.getSort()) {
case Type.BYTE:
boxed = BYTE_TYPE;
break;
case Type.BOOLEAN:
boxed = BOOLEAN_TYPE;
break;
case Type.SHORT:
boxed = SHORT_TYPE;
break;
case Type.CHAR:
boxed = CHARACTER_TYPE;
break;
case Type.INT:
boxed = INTEGER_TYPE;
break;
case Type.FLOAT:
boxed = FLOAT_TYPE;
break;
case Type.LONG:
boxed = LONG_TYPE;
break;
case Type.DOUBLE:
boxed = DOUBLE_TYPE;
break;
}
newInstance(boxed);
if (type.getSize() == 2) {
// Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o
dupX2();
dupX2();
pop();
} else {
// p -> po -> opo -> oop -> o
dupX1();
swap();
}
invokeConstructor(boxed, new Method("<init>",
Type.VOID_TYPE,
new Type[] { type }));
}
}
/**
* Generates the instructions to unbox the top stack value. This value is
* replaced by its unboxed equivalent on top of the stack.
*
* @param type the type of the top stack value.
*/
public void unbox(final Type type) {
Type t = NUMBER_TYPE;
Method sig = null;
switch (type.getSort()) {
case Type.VOID:
return;
case Type.CHAR:
t = CHARACTER_TYPE;
sig = CHAR_VALUE;
break;
case Type.BOOLEAN:
t = BOOLEAN_TYPE;
sig = BOOLEAN_VALUE;
break;
case Type.DOUBLE:
sig = DOUBLE_VALUE;
break;
case Type.FLOAT:
sig = FLOAT_VALUE;
break;
case Type.LONG:
sig = LONG_VALUE;
break;
case Type.INT:
case Type.SHORT:
case Type.BYTE:
sig = INT_VALUE;
}
if (sig == null) {
checkCast(type);
} else {
checkCast(t);
invokeVirtual(t, sig);
}
}
// ------------------------------------------------------------------------
// Instructions to jump to other instructions
// ------------------------------------------------------------------------
/**
* Creates a new {@link Label}.
*
* @return a new {@link Label}.
*/
public Label newLabel() {
return new Label();
}
/**
* Marks the current code position with the given label.
*
* @param label a label.
*/
public void mark(final Label label) {
mv.visitLabel(label);
}
/**
* Marks the current code position with a new label.
*
* @return the label that was created to mark the current code position.
*/
public Label mark() {
Label label = new Label();
mv.visitLabel(label);
return label;
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top two stack values.
*
* @param type the type of the top two stack values.
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifCmp(final Type type, final int mode, final Label label) {
int intOp = -1;
switch (type.getSort()) {
case Type.LONG:
mv.visitInsn(Opcodes.LCMP);
break;
case Type.DOUBLE:
mv.visitInsn(Opcodes.DCMPG);
break;
case Type.FLOAT:
mv.visitInsn(Opcodes.FCMPG);
break;
case Type.ARRAY:
case Type.OBJECT:
switch (mode) {
case EQ:
mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label);
return;
case NE:
mv.visitJumpInsn(Opcodes.IF_ACMPNE, label);
return;
}
throw new IllegalArgumentException("Bad comparison for type "
+ type);
default:
switch (mode) {
case EQ:
intOp = Opcodes.IF_ICMPEQ;
break;
case NE:
intOp = Opcodes.IF_ICMPNE;
break;
case GE:
intOp = Opcodes.IF_ICMPGE;
break;
case LT:
intOp = Opcodes.IF_ICMPLT;
break;
case LE:
intOp = Opcodes.IF_ICMPLE;
break;
case GT:
intOp = Opcodes.IF_ICMPGT;
break;
}
mv.visitJumpInsn(intOp, label);
return;
}
int jumpMode = mode;
switch (mode) {
case GE:
jumpMode = LT;
break;
case LE:
jumpMode = GT;
break;
}
mv.visitJumpInsn(jumpMode, label);
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top two integer stack values.
*
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifICmp(final int mode, final Label label) {
ifCmp(Type.INT_TYPE, mode, label);
}
/**
* Generates the instructions to jump to a label based on the comparison of
* the top integer stack value with zero.
*
* @param mode how these values must be compared. One of EQ, NE, LT, GE, GT,
* LE.
* @param label where to jump if the comparison result is <tt>true</tt>.
*/
public void ifZCmp(final int mode, final Label label) {
mv.visitJumpInsn(mode, label);
}
/**
* Generates the instruction to jump to the given label if the top stack
* value is null.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void ifNull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNULL, label);
}
/**
* Generates the instruction to jump to the given label if the top stack
* value is not null.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void ifNonNull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNONNULL, label);
}
/**
* Generates the instruction to jump to the given label.
*
* @param label where to jump if the condition is <tt>true</tt>.
*/
public void goTo(final Label label) {
mv.visitJumpInsn(Opcodes.GOTO, label);
}
/**
* Generates a RET instruction.
*
* @param local a local variable identifier, as returned by
* {@link LocalVariablesSorter#newLocal(Type) newLocal()}.
*/
public void ret(final int local) {
mv.visitVarInsn(Opcodes.RET, local);
}
/**
* Generates the instructions for a switch statement.
*
* @param keys the switch case keys.
* @param generator a generator to generate the code for the switch cases.
*/
public void tableSwitch(
final int[] keys,
final TableSwitchGenerator generator)
{
float density;
if (keys.length == 0) {
density = 0;
} else {
density = (float) keys.length
/ (keys[keys.length - 1] - keys[0] + 1);
}
tableSwitch(keys, generator, density >= 0.5f);
}
/**
* Generates the instructions for a switch statement.
*
* @param keys the switch case keys.
* @param generator a generator to generate the code for the switch cases.
* @param useTable <tt>true</tt> to use a TABLESWITCH instruction, or
* <tt>false</tt> to use a LOOKUPSWITCH instruction.
*/
public void tableSwitch(
final int[] keys,
final TableSwitchGenerator generator,
final boolean useTable)
{
for (int i = 1; i < keys.length; ++i) {
if (keys[i] < keys[i - 1]) {
throw new IllegalArgumentException("keys must be sorted ascending");
}
}
Label def = newLabel();
Label end = newLabel();
if (keys.length > 0) {
int len = keys.length;
int min = keys[0];
int max = keys[len - 1];
int range = max - min + 1;
if (useTable) {
Label[] labels = new Label[range];
Arrays.fill(labels, def);
for (int i = 0; i < len; ++i) {
labels[keys[i] - min] = newLabel();
}
mv.visitTableSwitchInsn(min, max, def, labels);
for (int i = 0; i < range; ++i) {
Label label = labels[i];
if (label != def) {
mark(label);
generator.generateCase(i + min, end);
}
}
} else {
Label[] labels = new Label[len];
for (int i = 0; i < len; ++i) {
labels[i] = newLabel();
}
mv.visitLookupSwitchInsn(def, keys, labels);
for (int i = 0; i < len; ++i) {
mark(labels[i]);
generator.generateCase(keys[i], end);
}
}
}
mark(def);
generator.generateDefault();
mark(end);
}
/**
* Generates the instruction to return the top stack value to the caller.
*/
public void returnValue() {
mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
}
// ------------------------------------------------------------------------
// Instructions to load and store fields
// ------------------------------------------------------------------------
/**
* Generates a get field or set field instruction.
*
* @param opcode the instruction's opcode.
* @param ownerType the class in which the field is defined.
* @param name the name of the field.
* @param fieldType the type of the field.
*/
private void fieldInsn(
final int opcode,
final Type ownerType,
final String name,
final Type fieldType)
{
mv.visitFieldInsn(opcode,
ownerType.getInternalName(),
name,
fieldType.getDescriptor());
}
/**
* Generates the instruction to push the value of a static field on the
* stack.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void getStatic(final Type owner, final String name, final Type type)
{
fieldInsn(Opcodes.GETSTATIC, owner, name, type);
}
/**
* Generates the instruction to store the top stack value in a static field.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void putStatic(final Type owner, final String name, final Type type)
{
fieldInsn(Opcodes.PUTSTATIC, owner, name, type);
}
/**
* Generates the instruction to push the value of a non static field on the
* stack.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void getField(final Type owner, final String name, final Type type) {
fieldInsn(Opcodes.GETFIELD, owner, name, type);
}
/**
* Generates the instruction to store the top stack value in a non static
* field.
*
* @param owner the class in which the field is defined.
* @param name the name of the field.
* @param type the type of the field.
*/
public void putField(final Type owner, final String name, final Type type) {
fieldInsn(Opcodes.PUTFIELD, owner, name, type);
}
// ------------------------------------------------------------------------
// Instructions to invoke methods
// ------------------------------------------------------------------------
/**
* Generates an invoke method instruction.
*
* @param opcode the instruction's opcode.
* @param type the class in which the method is defined.
* @param method the method to be invoked.
*/
private void invokeInsn(
final int opcode,
final Type type,
final Method method)
{
String owner = type.getSort() == Type.ARRAY
? type.getDescriptor()
: type.getInternalName();
mv.visitMethodInsn(opcode,
owner,
method.getName(),
method.getDescriptor());
}
/**
* Generates the instruction to invoke a normal method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeVirtual(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKEVIRTUAL, owner, method);
}
/**
* Generates the instruction to invoke a constructor.
*
* @param type the class in which the constructor is defined.
* @param method the constructor to be invoked.
*/
public void invokeConstructor(final Type type, final Method method) {
invokeInsn(Opcodes.INVOKESPECIAL, type, method);
}
/**
* Generates the instruction to invoke a static method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeStatic(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKESTATIC, owner, method);
}
/**
* Generates the instruction to invoke an interface method.
*
* @param owner the class in which the method is defined.
* @param method the method to be invoked.
*/
public void invokeInterface(final Type owner, final Method method) {
invokeInsn(Opcodes.INVOKEINTERFACE, owner, method);
}
// ------------------------------------------------------------------------
// Instructions to create objects and arrays
// ------------------------------------------------------------------------
/**
* Generates a type dependent instruction.
*
* @param opcode the instruction's opcode.
* @param type the instruction's operand.
*/
private void typeInsn(final int opcode, final Type type) {
mv.visitTypeInsn(opcode, type.getInternalName());
}
/**
* Generates the instruction to create a new object.
*
* @param type the class of the object to be created.
*/
public void newInstance(final Type type) {
typeInsn(Opcodes.NEW, type);
}
/**
* Generates the instruction to create a new array.
*
* @param type the type of the array elements.
*/
public void newArray(final Type type) {
int typ;
switch (type.getSort()) {
case Type.BOOLEAN:
typ = Opcodes.T_BOOLEAN;
break;
case Type.CHAR:
typ = Opcodes.T_CHAR;
break;
case Type.BYTE:
typ = Opcodes.T_BYTE;
break;
case Type.SHORT:
typ = Opcodes.T_SHORT;
break;
case Type.INT:
typ = Opcodes.T_INT;
break;
case Type.FLOAT:
typ = Opcodes.T_FLOAT;
break;
case Type.LONG:
typ = Opcodes.T_LONG;
break;
case Type.DOUBLE:
typ = Opcodes.T_DOUBLE;
break;
default:
typeInsn(Opcodes.ANEWARRAY, type);
return;
}
mv.visitIntInsn(Opcodes.NEWARRAY, typ);
}
// ------------------------------------------------------------------------
// Miscelaneous instructions
// ------------------------------------------------------------------------
/**
* Generates the instruction to compute the length of an array.
*/
public void arrayLength() {
mv.visitInsn(Opcodes.ARRAYLENGTH);
}
/**
* Generates the instruction to throw an exception.
*/
public void throwException() {
mv.visitInsn(Opcodes.ATHROW);
}
/**
* Generates the instructions to create and throw an exception. The
* exception class must have a constructor with a single String argument.
*
* @param type the class of the exception to be thrown.
* @param msg the detailed message of the exception.
*/
public void throwException(final Type type, final String msg) {
newInstance(type);
dup();
push(msg);
invokeConstructor(type, Method.getMethod("void <init> (String)"));
throwException();
}
/**
* Generates the instruction to check that the top stack value is of the
* given type.
*
* @param type a class or interface type.
*/
public void checkCast(final Type type) {
if (!type.equals(OBJECT_TYPE)) {
typeInsn(Opcodes.CHECKCAST, type);
}
}
/**
* Generates the instruction to test if the top stack value is of the given
* type.
*
* @param type a class or interface type.
*/
public void instanceOf(final Type type) {
typeInsn(Opcodes.INSTANCEOF, type);
}
/**
* Generates the instruction to get the monitor of the top stack value.
*/
public void monitorEnter() {
mv.visitInsn(Opcodes.MONITORENTER);
}
/**
* Generates the instruction to release the monitor of the top stack value.
*/
public void monitorExit() {
mv.visitInsn(Opcodes.MONITOREXIT);
}
// ------------------------------------------------------------------------
// Non instructions
// ------------------------------------------------------------------------
/**
* Marks the end of the visited method.
*/
public void endMethod() {
if ((access & Opcodes.ACC_ABSTRACT) == 0) {
mv.visitMaxs(0, 0);
}
mv.visitEnd();
}
/**
* Marks the start of an exception handler.
*
* @param start beginning of the exception handler's scope (inclusive).
* @param end end of the exception handler's scope (exclusive).
* @param exception internal name of the type of exceptions handled by the
* handler.
*/
public void catchException(
final Label start,
final Label end,
final Type exception)
{
mv.visitTryCatchBlock(start, end, mark(), exception.getInternalName());
}
}
| patch of feature request #307378
| src/org/objectweb/asm/commons/GeneratorAdapter.java | patch of feature request #307378 | <ide><path>rc/org/objectweb/asm/commons/GeneratorAdapter.java
<ide> */
<ide> public class GeneratorAdapter extends LocalVariablesSorter {
<ide>
<add> private static final String CLDESC = "Ljava/lang/Class;";
<add>
<ide> private final static Type BYTE_TYPE = Type.getObjectType("java/lang/Byte");
<ide>
<ide> private final static Type BOOLEAN_TYPE = Type.getObjectType("java/lang/Boolean");
<ide> if (value == null) {
<ide> mv.visitInsn(Opcodes.ACONST_NULL);
<ide> } else {
<del> mv.visitLdcInsn(value);
<add> switch (value.getSort()) {
<add> case Type.BOOLEAN:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Boolean",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.CHAR:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Char",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.BYTE:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Byte",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.SHORT:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Short",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.INT:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Integer",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.FLOAT:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Float",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.LONG:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Long",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> case Type.DOUBLE:
<add> mv.visitFieldInsn(Opcodes.GETSTATIC,
<add> "java/lang/Double",
<add> "TYPE",
<add> CLDESC);
<add> break;
<add> default:
<add> mv.visitLdcInsn(value);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | 965697c69ea541bfdab23ac0e80b41cab0ad8e44 | 0 | tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools | package com.azure.tools.apiview.processor;
import com.azure.tools.apiview.processor.analysers.ASTAnalyser;
import com.azure.tools.apiview.processor.analysers.Analyser;
import com.azure.tools.apiview.processor.model.APIListing;
import com.azure.tools.apiview.processor.model.Diagnostic;
import com.azure.tools.apiview.processor.model.DiagnosticKind;
import com.azure.tools.apiview.processor.model.Token;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import static com.azure.tools.apiview.processor.model.TokenKind.LINE_ID_MARKER;
import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_CREATORS;
import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_FIELDS;
import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_GETTERS;
import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_IS_GETTERS;
public class Main {
// expected argument order:
// [inputFiles] <outputDirectory>
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Expected argument order: [comma-separated sources jarFiles] <outputFile>, e.g. /path/to/jarfile.jar ./temp/");
System.exit(-1);
}
final String jarFiles = args[0];
final String[] jarFilesArray = jarFiles.split(",");
final File outputDir = new File(args[1]);
if (!outputDir.exists()) {
if (!outputDir.mkdirs()) {
System.out.printf("Failed to create output directory %s%n", outputDir);
}
}
System.out.println("Running with following configuration:");
System.out.printf(" Output directory: '%s'%n", outputDir);
for (final String jarFile : jarFilesArray) {
System.out.printf(" Processing input .jar file: '%s'%n", jarFile);
final File file = new File(jarFile);
if (!file.exists()) {
System.out.printf("Cannot find file '%s'%n", file);
System.exit(-1);
}
final String jsonFileName = file.getName().substring(0, file.getName().length() - 4) + ".json";
final File outputFile = new File(outputDir, jsonFileName);
processFile(file, outputFile);
}
}
private static ReviewProperties getReviewProperties(File inputFile) {
final ReviewProperties reviewProperties = new ReviewProperties();
// we will firstly try to get the artifact ID from the maven file inside the jar file...if it exists
try (final JarFile jarFile = new JarFile(inputFile)) {
final Enumeration<JarEntry> enumOfJar = jarFile.entries();
while (enumOfJar.hasMoreElements()) {
final JarEntry entry = enumOfJar.nextElement();
final String fullPath = entry.getName();
if (fullPath.startsWith("META-INF/maven") && fullPath.endsWith("pom.xml")) {
final InputStream jarIS = jarFile.getInputStream(entry);
// use xpath to get the artifact ID
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = builderFactory.newDocumentBuilder();
final Document xmlDocument = builder.parse(jarIS);
final XPath xPath = XPathFactory.newInstance().newXPath();
/*
* While it is expected for Azure SDK libraries to contain a groupId in the POM file this is not
* explicitly required by Maven. If the POM has a parent Maven allows the groupId to be omitted as
* it will be inherited from the parent.
*/
final String groupIdExpression = "/project/groupId";
final String parentGroupIdExpression = "/project/parent/groupId";
final Node groupIdNode = Optional
.ofNullable((Node) xPath.evaluate(groupIdExpression, xmlDocument, XPathConstants.NODE))
.orElse((Node) xPath.evaluate(parentGroupIdExpression, xmlDocument, XPathConstants.NODE));
reviewProperties.setMavenGroupId(groupIdNode.getTextContent());
final String artifactIdExpression = "/project/artifactId";
final Node artifactIdNode = (Node) xPath.evaluate(artifactIdExpression, xmlDocument, XPathConstants.NODE);
reviewProperties.setMavenArtifactId(artifactIdNode.getTextContent());
/*
* While it is expected for Azure SDK libraries to contain a version in the POM file this is not
* explicitly required by Maven. If the POM has a parent Maven allows the version to be omitted as
* it will be inherited from the parent.
*/
final String versionExpression = "/project/version";
final String parentVersionExpression = "/project/parent/version";
final Node versionNode = Optional
.ofNullable((Node) xPath.evaluate(versionExpression, xmlDocument, XPathConstants.NODE))
.orElse((Node) xPath.evaluate(parentVersionExpression, xmlDocument, XPathConstants.NODE));
reviewProperties.setPackageVersion(versionNode.getTextContent());
}
}
} catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException e) {
e.printStackTrace();
}
// if we can't get the maven details out of the Jar file, we will just use the filename itself...
if (reviewProperties.getMavenArtifactId() == null || reviewProperties.getMavenArtifactId().isEmpty()) {
// we failed to read it from the maven pom file, we will just take the file name without any extension
final String filename = inputFile.getName();
int i = 0;
while (i < filename.length() && !Character.isDigit(filename.charAt(i))) {
i++;
}
reviewProperties.setMavenArtifactId(filename.substring(0, i - 1));
reviewProperties.setPackageVersion(filename.substring(i, filename.indexOf("-sources.jar")));
}
return reviewProperties;
}
private static void processFile(final File inputFile, final File outputFile) throws IOException {
final ReviewProperties reviewProperties = getReviewProperties(inputFile);
final String reviewName = reviewProperties.getMavenArtifactId() + " (version " + reviewProperties.getPackageVersion() + ")";
System.out.println(" Using '" + reviewName + "' for the review name");
final String packageName = reviewProperties.getMavenGroupId() + ":" + reviewProperties.getMavenArtifactId();
System.out.println(" Using '" + packageName + "' for the package name");
System.out.println(" Using '" + reviewProperties.getPackageVersion() + "' for the package version");
final APIListing apiListing = new APIListing(reviewName);
apiListing.setPackageName(packageName);
apiListing.setPackageVersion(reviewProperties.getPackageVersion());
apiListing.setLanguage("Java");
// empty tokens list that we will fill as we process each class file
final List<Token> tokens = new ArrayList<>();
apiListing.setTokens(tokens);
if (inputFile.getName().endsWith("-sources.jar")) {
final Analyser analyser = new ASTAnalyser(inputFile, apiListing);
// Read all files within the jar file so that we can create a list of files to analyse
final List<Path> allFiles = new ArrayList<>();
try (FileSystem fs = FileSystems.newFileSystem(inputFile.toPath(), Main.class.getClassLoader())) {
fs.getRootDirectories().forEach(root -> {
try (Stream<Path> paths = Files.walk(root)) {
paths.forEach(allFiles::add);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
});
// Do the analysis while the filesystem is still represented in memory
analyser.analyse(allFiles);
}
} else {
apiListing.getTokens().add(new Token(LINE_ID_MARKER, "Error!", "error"));
apiListing.addDiagnostic(new Diagnostic(
DiagnosticKind.ERROR,
"error",
"Uploaded files should end with '-sources.jar', " +
"as the APIView tool only works with source jar files, not compiled jar files. The uploaded file " +
"that was submitted to APIView was named " + inputFile.getName()));
}
// Write out to the filesystem
new ObjectMapper()
.disable(AUTO_DETECT_CREATORS, AUTO_DETECT_FIELDS, AUTO_DETECT_GETTERS, AUTO_DETECT_IS_GETTERS)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.writerWithDefaultPrettyPrinter()
.writeValue(outputFile, apiListing);
}
private static class ReviewProperties {
private String name;
private String mavenGroupId;
private String mavenArtifactId;
private String packageVersion;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getMavenGroupId() {
return mavenGroupId;
}
public void setMavenGroupId(final String mavenGroupId) {
this.mavenGroupId = mavenGroupId;
}
public String getMavenArtifactId() {
return mavenArtifactId;
}
public void setMavenArtifactId(final String mavenArtifactId) {
this.mavenArtifactId = mavenArtifactId;
}
public String getPackageVersion() {
return packageVersion;
}
public void setPackageVersion(final String packageVersion) {
this.packageVersion = packageVersion;
}
}
} | src/java/apiview-java-processor/src/main/java/com/azure/tools/apiview/processor/Main.java | package com.azure.tools.apiview.processor;
import com.azure.tools.apiview.processor.analysers.Analyser;
import com.azure.tools.apiview.processor.model.Diagnostic;
import com.azure.tools.apiview.processor.model.DiagnosticKind;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.azure.tools.apiview.processor.analysers.ASTAnalyser;
import com.azure.tools.apiview.processor.model.APIListing;
import com.azure.tools.apiview.processor.model.Token;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import static com.fasterxml.jackson.databind.MapperFeature.*;
import static com.azure.tools.apiview.processor.model.TokenKind.*;
public class Main {
// expected argument order:
// [inputFiles] <outputDirectory>
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Expected argument order: [comma-separated sources jarFiles] <outputFile>, e.g. /path/to/jarfile.jar ./temp/");
System.exit(-1);
}
final String jarFiles = args[0];
final String[] jarFilesArray = jarFiles.split(",");
final File outputDir = new File(args[1]);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
System.out.println("Running with following configuration:");
System.out.println(" Output directory: '" + outputDir + "'");
for (final String jarFile : jarFilesArray) {
System.out.println(" Processing input .jar file: '" + jarFile + "'");
final File file = new File(jarFile);
if (!file.exists()) {
System.out.println("Cannot find file '" + file + "'");
System.exit(-1);
}
final String jsonFileName = file.getName().substring(0, file.getName().length() - 4) + ".json";
final File outputFile = new File(outputDir, jsonFileName);
processFile(file, outputFile);
}
}
private static ReviewProperties getReviewProperties(File inputFile) {
final ReviewProperties reviewProperties = new ReviewProperties();
// we will firstly try to get the artifact ID from the maven file inside the jar file...if it exists
try (final JarFile jarFile = new JarFile(inputFile)) {
final Enumeration<JarEntry> enumOfJar = jarFile.entries();
while (enumOfJar.hasMoreElements()) {
final JarEntry entry = enumOfJar.nextElement();
final String fullPath = entry.getName();
if (fullPath.startsWith("META-INF/maven") && fullPath.endsWith("pom.xml")) {
final InputStream jarIS = jarFile.getInputStream(entry);
// use xpath to get the artifact ID
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = builderFactory.newDocumentBuilder();
final Document xmlDocument = builder.parse(jarIS);
final XPath xPath = XPathFactory.newInstance().newXPath();
final String groupIdExpression = "/project/groupId";
final Node groupIdNode = (Node) xPath.compile(groupIdExpression).evaluate(xmlDocument, XPathConstants.NODE);
reviewProperties.setMavenGroupId(groupIdNode.getTextContent());
final String artifactIdExpression = "/project/artifactId";
final Node artifactIdNode = (Node) xPath.compile(artifactIdExpression).evaluate(xmlDocument, XPathConstants.NODE);
reviewProperties.setMavenArtifactId(artifactIdNode.getTextContent());
final String versionExpression = "/project/version";
final Node versionNode = (Node) xPath.compile(versionExpression).evaluate(xmlDocument, XPathConstants.NODE);
reviewProperties.setPackageVersion(versionNode.getTextContent());
}
}
} catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException e) {
e.printStackTrace();
}
// if we can't get the maven details out of the Jar file, we will just use the filename itself...
if (reviewProperties.getMavenArtifactId() == null || reviewProperties.getMavenArtifactId().isEmpty()) {
// we failed to read it from the maven pom file, we will just take the file name without any extension
final String filename = inputFile.getName();
int i = 0;
while (i < filename.length() && !Character.isDigit(filename.charAt(i))) {
i++;
}
reviewProperties.setMavenArtifactId(filename.substring(0, i - 1));
reviewProperties.setPackageVersion(filename.substring(i, filename.indexOf("-sources.jar")));
}
return reviewProperties;
}
private static void processFile(final File inputFile, final File outputFile) throws IOException {
final ReviewProperties reviewProperties = getReviewProperties(inputFile);
final String reviewName = reviewProperties.getMavenArtifactId() + " (version " + reviewProperties.getPackageVersion() + ")";
System.out.println(" Using '" + reviewName + "' for the review name");
final String packageName = reviewProperties.getMavenGroupId() + ":" + reviewProperties.getMavenArtifactId();
System.out.println(" Using '" + packageName + "' for the package name");
System.out.println(" Using '" + reviewProperties.getPackageVersion() + "' for the package version");
final APIListing apiListing = new APIListing(reviewName);
apiListing.setPackageName(packageName);
apiListing.setPackageVersion(reviewProperties.getPackageVersion());
apiListing.setLanguage("Java");
// empty tokens list that we will fill as we process each class file
final List<Token> tokens = new ArrayList<>();
apiListing.setTokens(tokens);
if (inputFile.getName().endsWith("-sources.jar")) {
final Analyser analyser = new ASTAnalyser(inputFile, apiListing);
// Read all files within the jar file so that we can create a list of files to analyse
final List<Path> allFiles = new ArrayList<>();
try (FileSystem fs = FileSystems.newFileSystem(inputFile.toPath(), Main.class.getClassLoader())) {
fs.getRootDirectories().forEach(root -> {
try (Stream<Path> paths = Files.walk(root)) {
paths.forEach(allFiles::add);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
});
// Do the analysis while the filesystem is still represented in memory
analyser.analyse(allFiles);
}
} else {
apiListing.getTokens().add(new Token(LINE_ID_MARKER, "Error!", "error"));
apiListing.addDiagnostic(new Diagnostic(
DiagnosticKind.ERROR,
"error",
"Uploaded files should end with '-sources.jar', " +
"as the APIView tool only works with source jar files, not compiled jar files. The uploaded file " +
"that was submitted to APIView was named " + inputFile.getName()));
}
// Write out to the filesystem
new ObjectMapper()
.disable(AUTO_DETECT_CREATORS, AUTO_DETECT_FIELDS, AUTO_DETECT_GETTERS, AUTO_DETECT_IS_GETTERS)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.writerWithDefaultPrettyPrinter()
.writeValue(outputFile, apiListing);
}
private static class ReviewProperties {
private String name;
private String mavenGroupId;
private String mavenArtifactId;
private String packageVersion;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getMavenGroupId() {
return mavenGroupId;
}
public void setMavenGroupId(final String mavenGroupId) {
this.mavenGroupId = mavenGroupId;
}
public String getMavenArtifactId() {
return mavenArtifactId;
}
public void setMavenArtifactId(final String mavenArtifactId) {
this.mavenArtifactId = mavenArtifactId;
}
public String getPackageVersion() {
return packageVersion;
}
public void setPackageVersion(final String packageVersion) {
this.packageVersion = packageVersion;
}
}
} | Handle optional groupId and version when parent exists (#1337)
| src/java/apiview-java-processor/src/main/java/com/azure/tools/apiview/processor/Main.java | Handle optional groupId and version when parent exists (#1337) | <ide><path>rc/java/apiview-java-processor/src/main/java/com/azure/tools/apiview/processor/Main.java
<ide> package com.azure.tools.apiview.processor;
<ide>
<add>import com.azure.tools.apiview.processor.analysers.ASTAnalyser;
<ide> import com.azure.tools.apiview.processor.analysers.Analyser;
<add>import com.azure.tools.apiview.processor.model.APIListing;
<ide> import com.azure.tools.apiview.processor.model.Diagnostic;
<ide> import com.azure.tools.apiview.processor.model.DiagnosticKind;
<add>import com.azure.tools.apiview.processor.model.Token;
<ide> import com.fasterxml.jackson.annotation.JsonInclude;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<del>import com.azure.tools.apiview.processor.analysers.ASTAnalyser;
<del>import com.azure.tools.apiview.processor.model.APIListing;
<del>import com.azure.tools.apiview.processor.model.Token;
<ide> import org.w3c.dom.Document;
<ide> import org.w3c.dom.Node;
<ide> import org.xml.sax.SAXException;
<ide> import java.util.ArrayList;
<ide> import java.util.Enumeration;
<ide> import java.util.List;
<add>import java.util.Optional;
<ide> import java.util.jar.JarEntry;
<ide> import java.util.jar.JarFile;
<ide> import java.util.stream.Stream;
<ide>
<del>import static com.fasterxml.jackson.databind.MapperFeature.*;
<del>import static com.azure.tools.apiview.processor.model.TokenKind.*;
<add>import static com.azure.tools.apiview.processor.model.TokenKind.LINE_ID_MARKER;
<add>import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_CREATORS;
<add>import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_FIELDS;
<add>import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_GETTERS;
<add>import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_IS_GETTERS;
<ide>
<ide> public class Main {
<ide>
<ide>
<ide> final File outputDir = new File(args[1]);
<ide> if (!outputDir.exists()) {
<del> outputDir.mkdirs();
<add> if (!outputDir.mkdirs()) {
<add> System.out.printf("Failed to create output directory %s%n", outputDir);
<add> }
<ide> }
<ide>
<ide> System.out.println("Running with following configuration:");
<del> System.out.println(" Output directory: '" + outputDir + "'");
<add> System.out.printf(" Output directory: '%s'%n", outputDir);
<ide>
<ide> for (final String jarFile : jarFilesArray) {
<del> System.out.println(" Processing input .jar file: '" + jarFile + "'");
<add> System.out.printf(" Processing input .jar file: '%s'%n", jarFile);
<ide>
<ide> final File file = new File(jarFile);
<ide> if (!file.exists()) {
<del> System.out.println("Cannot find file '" + file + "'");
<add> System.out.printf("Cannot find file '%s'%n", file);
<ide> System.exit(-1);
<ide> }
<ide>
<ide> final Document xmlDocument = builder.parse(jarIS);
<ide> final XPath xPath = XPathFactory.newInstance().newXPath();
<ide>
<add> /*
<add> * While it is expected for Azure SDK libraries to contain a groupId in the POM file this is not
<add> * explicitly required by Maven. If the POM has a parent Maven allows the groupId to be omitted as
<add> * it will be inherited from the parent.
<add> */
<ide> final String groupIdExpression = "/project/groupId";
<del> final Node groupIdNode = (Node) xPath.compile(groupIdExpression).evaluate(xmlDocument, XPathConstants.NODE);
<add> final String parentGroupIdExpression = "/project/parent/groupId";
<add> final Node groupIdNode = Optional
<add> .ofNullable((Node) xPath.evaluate(groupIdExpression, xmlDocument, XPathConstants.NODE))
<add> .orElse((Node) xPath.evaluate(parentGroupIdExpression, xmlDocument, XPathConstants.NODE));
<ide> reviewProperties.setMavenGroupId(groupIdNode.getTextContent());
<ide>
<ide> final String artifactIdExpression = "/project/artifactId";
<del> final Node artifactIdNode = (Node) xPath.compile(artifactIdExpression).evaluate(xmlDocument, XPathConstants.NODE);
<add> final Node artifactIdNode = (Node) xPath.evaluate(artifactIdExpression, xmlDocument, XPathConstants.NODE);
<ide> reviewProperties.setMavenArtifactId(artifactIdNode.getTextContent());
<ide>
<add> /*
<add> * While it is expected for Azure SDK libraries to contain a version in the POM file this is not
<add> * explicitly required by Maven. If the POM has a parent Maven allows the version to be omitted as
<add> * it will be inherited from the parent.
<add> */
<ide> final String versionExpression = "/project/version";
<del> final Node versionNode = (Node) xPath.compile(versionExpression).evaluate(xmlDocument, XPathConstants.NODE);
<add> final String parentVersionExpression = "/project/parent/version";
<add> final Node versionNode = Optional
<add> .ofNullable((Node) xPath.evaluate(versionExpression, xmlDocument, XPathConstants.NODE))
<add> .orElse((Node) xPath.evaluate(parentVersionExpression, xmlDocument, XPathConstants.NODE));
<ide> reviewProperties.setPackageVersion(versionNode.getTextContent());
<ide> }
<ide> }
<ide> } else {
<ide> apiListing.getTokens().add(new Token(LINE_ID_MARKER, "Error!", "error"));
<ide> apiListing.addDiagnostic(new Diagnostic(
<del> DiagnosticKind.ERROR,
<del> "error",
<del> "Uploaded files should end with '-sources.jar', " +
<add> DiagnosticKind.ERROR,
<add> "error",
<add> "Uploaded files should end with '-sources.jar', " +
<ide> "as the APIView tool only works with source jar files, not compiled jar files. The uploaded file " +
<ide> "that was submitted to APIView was named " + inputFile.getName()));
<ide> } |
|
JavaScript | mit | b71ffe00ba4c45b7e4f1c2a321bc4a3aab780546 | 0 | Exocen/Website,Exocen/Website,Exocen/Website | customNodeChoice = 1;
customVaccineChoice = 1;
customNeighborChocie = 1;
customOutbreakChoice = 1;
var speed = false;
var toggleDegree = true;
function difficultySelection(clas){
return d3.select(".difficultySelection").append("div")
.attr("class", clas)
}
function difficultySelection2(clas, id, text){
return difficultySelection(clas)
.attr("id", id)
.text(text)
}
function difficultySelectionOver(clas, id, text, ds){
return difficultySelection2(clas, id, text, ds)
.on("mouseover", function() {
d3.select(this).style("color", "#2692F2")
})
.on("mouseout", function() {
d3.select(this).style("color", "#707070")
})
.on("click", function() {
difficultyString = ds;
initBasicGame(ds);
})
}
function initBasicMenu() {
d3.select(".vaxLogoDiv")
.style("visibility", "visible")
d3.select(".vaxLogoDiv")
.style("left", "-12px")
// new game header at top-left
d3.select(".jumbotron").append("div")
.attr("class", "newGameHeader ")
.text("NEW GAME")
d3.select(".jumbotron").append("div")
.attr("class", "row")
// difficulty selection div
d3.select(".row").append("div")
.attr("class", "difficultySelection col-xs-6")
d3.select(".row").append("div")
.attr("class", "gameOptions col-xs-6")
// header for difficulty selection
d3.select(".difficultySelection").append("div")
.attr("class", "difficultyHeader")
.text("DIFFICULTY")
// difficulty menu items
difficultySelectionOver("difficultyItem", "difficultyEasy", "Easy", "easy")
difficultySelection("easyHi")
difficultySelection2("difficultyItemGrey", "difficultyMedium", "Medium")
difficultySelection("mediumHi")
difficultySelection2("difficultyItemGrey", "difficultyHard", "Hard")
difficultySelection("hardHi")
d3.select(".gameOptions").append("div")
.attr("class", "gameOptionsHeader")
.text("GAME OPTIONS")
d3.select(".gameOptions").append("div")
.attr("class", "quarantineModeOptions")
.text("Quarantine Phase")
displayGameOption("turnBasedTrue", "Turn-based", false, ".turnBasedTrue", ".realTimeTrue", vaxEasyHiScore, vaxMediumHiScore, vaxHardHiScore);
displayGameOption("realTimeTrue", "Real-time", true, ".realTimeTrue", ".turnBasedTrue", vaxEasyHiScoreRT, vaxMediumHiScoreRT, vaxHardHiScoreRT);
}
function displayGameOption(clas, txt, speedBool, big, small, easyhiscore, mediumhiscore, hardhiscore){
d3.select(".gameOptions").append("div")
.attr("class", clas)
.text(txt)
.on("click", function() {
d3.select(small).style("color", "#BABABA").style("font-weight", "300")
d3.select(big).style("color", "#2692F2").style("font-weight", "500")
speed = speedBool;
displayScore(easyhiscore.value, ".easyHi");
displayScore(mediumhiscore.value, ".mediumHi");
displayScore(hardhiscore.value, ".hardHi");
})
}
function displayScore(score, clas){
if (score < 0) d3.select(clas).text("")
else d3.select(clas).text("(Best: " + score + "%)")
}
var maxVax = parseInt($.cookie ('customNodes'),10)
| app/assets/javascripts/gameMenu.js | customNodeChoice = 1;
customVaccineChoice = 1;
customNeighborChocie = 1;
customOutbreakChoice = 1;
var speed = false;
var toggleDegree = true;
function difficultySelection(clas){
return d3.select(".difficultySelection").append("div")
.attr("class", clas)
}
function difficultySelection2(clas, id, text){
return difficultySelection(clas)
.attr("id", id)
.text(text)
}
function difficultySelectionOver(clas, id, text, ds){
return difficultySelection2(clas, id, text, ds)
.on("mouseover", function() {
d3.select(this).style("color", "#2692F2")
})
.on("mouseout", function() {
d3.select(this).style("color", "#707070")
})
.on("click", function() {
difficultyString = ds;
initBasicGame(ds);
})
}
function initBasicMenu() {
d3.select(".vaxLogoDiv")
.style("visibility", "visible")
d3.select(".vaxLogoDiv")
.style("left", "-12px")
// new game header at top-left
d3.select(".jumbotron").append("div")
.attr("class", "newGameHeader ")
.text("NEW GAME")
d3.select(".jumbotron").append("div")
.attr("class", "row")
// difficulty selection div
d3.select(".row").append("div")
.attr("class", "difficultySelection col-xs-6")
d3.select(".row").append("div")
.attr("class", "gameOptions col-xs-6")
// header for difficulty selection
d3.select(".difficultySelection").append("div")
.attr("class", "difficultyHeader")
.text("DIFFICULTY")
// difficulty menu items
difficultySelectionOver("difficultyItem", "difficultyEasy", "Easy", "easy")
difficultySelection("easyHi")
difficultySelection2("difficultyItemGrey", "difficultyMedium", "Medium")
difficultySelection("mediumHi")
difficultySelection2("difficultyItemGrey", "difficultyHard", "Hard")
difficultySelection("hardHi")
d3.select(".gameOptions").append("div")
.attr("class", "gameOptionsHeader")
.text("GAME OPTIONS")
d3.select(".gameOptions").append("div")
.attr("class", "quarantineModeOptions")
.text("Quarantine Phase")
d3.select(".gameOptions").append("div")
.attr("class", "turnBasedTrue")
.text("Turn-based")
.on("click", function() {
d3.select(".turnBasedTrue").style("color", "#2692F2").style("font-weight", "500")
d3.select(".realTimeTrue").style("color", "#BABABA").style("font-weight", "300")
speed = false;
displayScore(vaxEasyHiScore.value, ".easyHi");
displayScore(vaxMediumHiScore.value, ".mediumHi");
displayScore(vaxHardHiScore.value, ".hardHi");
})
d3.select(".gameOptions").append("div")
.attr("class", "realTimeTrue")
.text("Real-time")
.on("click", function() {
d3.select(".turnBasedTrue").style("color", "#BABABA").style("font-weight", "300")
d3.select(".realTimeTrue").style("color", "#2692F2").style("font-weight", "500")
speed = true;
displayScore(vaxEasyHiScoreRT.value, ".easyHi");
displayScore(vaxMediumHiScoreRT.value, ".mediumHi");
displayScore(vaxHardHiScoreRT.value, ".hardHi");
})
}
function displayScore(score, clas){
if (score < 0) d3.select(clas).text("")
else d3.select(clas).text("(Best: " + score + "%)")
}
var maxVax = parseInt($.cookie ('customNodes'),10)
| ref gamemenu.js
rem duplicate
| app/assets/javascripts/gameMenu.js | ref gamemenu.js | <ide><path>pp/assets/javascripts/gameMenu.js
<ide> .attr("class", "quarantineModeOptions")
<ide> .text("Quarantine Phase")
<ide>
<add> displayGameOption("turnBasedTrue", "Turn-based", false, ".turnBasedTrue", ".realTimeTrue", vaxEasyHiScore, vaxMediumHiScore, vaxHardHiScore);
<add>
<add> displayGameOption("realTimeTrue", "Real-time", true, ".realTimeTrue", ".turnBasedTrue", vaxEasyHiScoreRT, vaxMediumHiScoreRT, vaxHardHiScoreRT);
<add>}
<add>
<add>function displayGameOption(clas, txt, speedBool, big, small, easyhiscore, mediumhiscore, hardhiscore){
<ide> d3.select(".gameOptions").append("div")
<del> .attr("class", "turnBasedTrue")
<del> .text("Turn-based")
<add> .attr("class", clas)
<add> .text(txt)
<ide> .on("click", function() {
<del> d3.select(".turnBasedTrue").style("color", "#2692F2").style("font-weight", "500")
<del> d3.select(".realTimeTrue").style("color", "#BABABA").style("font-weight", "300")
<add> d3.select(small).style("color", "#BABABA").style("font-weight", "300")
<add> d3.select(big).style("color", "#2692F2").style("font-weight", "500")
<ide>
<del> speed = false;
<add> speed = speedBool;
<add> displayScore(easyhiscore.value, ".easyHi");
<add> displayScore(mediumhiscore.value, ".mediumHi");
<add> displayScore(hardhiscore.value, ".hardHi");
<add> })
<add>}
<ide>
<del> displayScore(vaxEasyHiScore.value, ".easyHi");
<del> displayScore(vaxMediumHiScore.value, ".mediumHi");
<del> displayScore(vaxHardHiScore.value, ".hardHi");
<del>
<del> })
<del>
<del> d3.select(".gameOptions").append("div")
<del> .attr("class", "realTimeTrue")
<del> .text("Real-time")
<del> .on("click", function() {
<del> d3.select(".turnBasedTrue").style("color", "#BABABA").style("font-weight", "300")
<del> d3.select(".realTimeTrue").style("color", "#2692F2").style("font-weight", "500")
<del>
<del> speed = true;
<del> displayScore(vaxEasyHiScoreRT.value, ".easyHi");
<del> displayScore(vaxMediumHiScoreRT.value, ".mediumHi");
<del> displayScore(vaxHardHiScoreRT.value, ".hardHi");
<del> })
<del>
<del>}
<ide> function displayScore(score, clas){
<ide> if (score < 0) d3.select(clas).text("")
<ide> else d3.select(clas).text("(Best: " + score + "%)") |
|
Java | apache-2.0 | d812f545c0ae01fe3f9f5cf1017e294966ee8ea2 | 0 | punkhorn/camel-upstream,nicolaferraro/camel,w4tson/camel,jamesnetherton/camel,jonmcewen/camel,allancth/camel,allancth/camel,DariusX/camel,akhettar/camel,nikhilvibhav/camel,sirlatrom/camel,lburgazzoli/apache-camel,apache/camel,tadayosi/camel,akhettar/camel,jonmcewen/camel,adessaigne/camel,veithen/camel,sverkera/camel,pax95/camel,jkorab/camel,tdiesler/camel,johnpoth/camel,atoulme/camel,salikjan/camel,iweiss/camel,arnaud-deprez/camel,jlpedrosa/camel,DariusX/camel,ssharma/camel,YoshikiHigo/camel,onders86/camel,driseley/camel,gilfernandes/camel,alvinkwekel/camel,sverkera/camel,sverkera/camel,YoshikiHigo/camel,tadayosi/camel,rmarting/camel,CodeSmell/camel,objectiser/camel,nikvaessen/camel,snurmine/camel,anoordover/camel,kevinearls/camel,tdiesler/camel,nboukhed/camel,NickCis/camel,FingolfinTEK/camel,johnpoth/camel,apache/camel,JYBESSON/camel,nikvaessen/camel,RohanHart/camel,pax95/camel,CodeSmell/camel,cunningt/camel,pmoerenhout/camel,nikvaessen/camel,gnodet/camel,davidkarlsen/camel,borcsokj/camel,hqstevenson/camel,jarst/camel,atoulme/camel,w4tson/camel,curso007/camel,scranton/camel,pax95/camel,arnaud-deprez/camel,gautric/camel,brreitme/camel,drsquidop/camel,sverkera/camel,gautric/camel,chirino/camel,atoulme/camel,brreitme/camel,apache/camel,gautric/camel,objectiser/camel,brreitme/camel,nikvaessen/camel,sirlatrom/camel,ssharma/camel,jlpedrosa/camel,anton-k11/camel,trohovsky/camel,curso007/camel,gilfernandes/camel,anton-k11/camel,NickCis/camel,anton-k11/camel,iweiss/camel,RohanHart/camel,bgaudaen/camel,lburgazzoli/apache-camel,jamesnetherton/camel,sebi-hgdata/camel,lburgazzoli/camel,gilfernandes/camel,hqstevenson/camel,nikvaessen/camel,nboukhed/camel,punkhorn/camel-upstream,edigrid/camel,lburgazzoli/apache-camel,jkorab/camel,bgaudaen/camel,tlehoux/camel,curso007/camel,akhettar/camel,atoulme/camel,mcollovati/camel,isavin/camel,brreitme/camel,scranton/camel,allancth/camel,sverkera/camel,dmvolod/camel,Thopap/camel,w4tson/camel,chirino/camel,driseley/camel,jlpedrosa/camel,lburgazzoli/camel,pmoerenhout/camel,NickCis/camel,anton-k11/camel,tdiesler/camel,rmarting/camel,atoulme/camel,onders86/camel,hqstevenson/camel,davidkarlsen/camel,sebi-hgdata/camel,YoshikiHigo/camel,brreitme/camel,apache/camel,gnodet/camel,christophd/camel,adessaigne/camel,yuruki/camel,chirino/camel,jkorab/camel,kevinearls/camel,pmoerenhout/camel,jmandawg/camel,snurmine/camel,pmoerenhout/camel,JYBESSON/camel,tdiesler/camel,erwelch/camel,onders86/camel,YoshikiHigo/camel,borcsokj/camel,pkletsko/camel,snurmine/camel,acartapanis/camel,NickCis/camel,christophd/camel,lburgazzoli/camel,mgyongyosi/camel,sirlatrom/camel,lburgazzoli/apache-camel,gautric/camel,YoshikiHigo/camel,neoramon/camel,driseley/camel,erwelch/camel,jkorab/camel,bgaudaen/camel,tadayosi/camel,pax95/camel,anoordover/camel,gilfernandes/camel,cunningt/camel,edigrid/camel,FingolfinTEK/camel,pmoerenhout/camel,isavin/camel,drsquidop/camel,sabre1041/camel,FingolfinTEK/camel,isavin/camel,rmarting/camel,JYBESSON/camel,curso007/camel,rmarting/camel,sebi-hgdata/camel,jonmcewen/camel,tlehoux/camel,drsquidop/camel,bgaudaen/camel,pkletsko/camel,tadayosi/camel,gautric/camel,tkopczynski/camel,punkhorn/camel-upstream,iweiss/camel,akhettar/camel,edigrid/camel,nboukhed/camel,lburgazzoli/camel,scranton/camel,kevinearls/camel,ullgren/camel,onders86/camel,nikvaessen/camel,veithen/camel,davidkarlsen/camel,pmoerenhout/camel,arnaud-deprez/camel,kevinearls/camel,w4tson/camel,sebi-hgdata/camel,Fabryprog/camel,anoordover/camel,tadayosi/camel,oalles/camel,bhaveshdt/camel,johnpoth/camel,prashant2402/camel,johnpoth/camel,gautric/camel,jkorab/camel,kevinearls/camel,rmarting/camel,davidkarlsen/camel,cunningt/camel,borcsokj/camel,prashant2402/camel,zregvart/camel,objectiser/camel,sabre1041/camel,yuruki/camel,mcollovati/camel,borcsokj/camel,acartapanis/camel,hqstevenson/camel,jonmcewen/camel,Thopap/camel,w4tson/camel,trohovsky/camel,FingolfinTEK/camel,jamesnetherton/camel,lburgazzoli/apache-camel,christophd/camel,RohanHart/camel,arnaud-deprez/camel,RohanHart/camel,atoulme/camel,yuruki/camel,tlehoux/camel,JYBESSON/camel,nikhilvibhav/camel,anoordover/camel,DariusX/camel,tlehoux/camel,bgaudaen/camel,mgyongyosi/camel,prashant2402/camel,nicolaferraro/camel,lburgazzoli/camel,CodeSmell/camel,RohanHart/camel,adessaigne/camel,gilfernandes/camel,CodeSmell/camel,erwelch/camel,cunningt/camel,borcsokj/camel,sabre1041/camel,alvinkwekel/camel,jlpedrosa/camel,dmvolod/camel,scranton/camel,mcollovati/camel,objectiser/camel,veithen/camel,jmandawg/camel,tdiesler/camel,gnodet/camel,cunningt/camel,johnpoth/camel,snurmine/camel,acartapanis/camel,zregvart/camel,tlehoux/camel,yuruki/camel,Thopap/camel,apache/camel,christophd/camel,sebi-hgdata/camel,chirino/camel,driseley/camel,acartapanis/camel,Thopap/camel,iweiss/camel,neoramon/camel,drsquidop/camel,jarst/camel,veithen/camel,onders86/camel,anton-k11/camel,mgyongyosi/camel,ssharma/camel,jarst/camel,pax95/camel,onders86/camel,allancth/camel,FingolfinTEK/camel,jonmcewen/camel,erwelch/camel,anoordover/camel,tdiesler/camel,jarst/camel,anton-k11/camel,nboukhed/camel,kevinearls/camel,sabre1041/camel,bhaveshdt/camel,trohovsky/camel,mgyongyosi/camel,pax95/camel,nikhilvibhav/camel,ullgren/camel,nboukhed/camel,neoramon/camel,sebi-hgdata/camel,jarst/camel,christophd/camel,scranton/camel,YoshikiHigo/camel,prashant2402/camel,chirino/camel,neoramon/camel,driseley/camel,gnodet/camel,erwelch/camel,NickCis/camel,jmandawg/camel,jamesnetherton/camel,ssharma/camel,oalles/camel,brreitme/camel,edigrid/camel,pkletsko/camel,allancth/camel,jamesnetherton/camel,sirlatrom/camel,JYBESSON/camel,trohovsky/camel,lburgazzoli/camel,adessaigne/camel,mcollovati/camel,w4tson/camel,yuruki/camel,trohovsky/camel,arnaud-deprez/camel,akhettar/camel,christophd/camel,jmandawg/camel,adessaigne/camel,pkletsko/camel,acartapanis/camel,curso007/camel,gnodet/camel,veithen/camel,gilfernandes/camel,FingolfinTEK/camel,oalles/camel,DariusX/camel,isavin/camel,zregvart/camel,prashant2402/camel,sirlatrom/camel,jlpedrosa/camel,jamesnetherton/camel,tlehoux/camel,driseley/camel,hqstevenson/camel,Fabryprog/camel,oalles/camel,johnpoth/camel,sirlatrom/camel,bhaveshdt/camel,cunningt/camel,scranton/camel,alvinkwekel/camel,nboukhed/camel,nicolaferraro/camel,punkhorn/camel-upstream,ullgren/camel,jarst/camel,bgaudaen/camel,rmarting/camel,neoramon/camel,jkorab/camel,trohovsky/camel,pkletsko/camel,snurmine/camel,alvinkwekel/camel,prashant2402/camel,allancth/camel,Fabryprog/camel,jmandawg/camel,hqstevenson/camel,tkopczynski/camel,mgyongyosi/camel,RohanHart/camel,mgyongyosi/camel,isavin/camel,edigrid/camel,veithen/camel,snurmine/camel,dmvolod/camel,dmvolod/camel,tkopczynski/camel,anoordover/camel,edigrid/camel,ssharma/camel,drsquidop/camel,iweiss/camel,adessaigne/camel,iweiss/camel,ullgren/camel,arnaud-deprez/camel,nicolaferraro/camel,jonmcewen/camel,jmandawg/camel,ssharma/camel,tadayosi/camel,neoramon/camel,bhaveshdt/camel,isavin/camel,JYBESSON/camel,lburgazzoli/apache-camel,yuruki/camel,Thopap/camel,akhettar/camel,pkletsko/camel,acartapanis/camel,bhaveshdt/camel,tkopczynski/camel,chirino/camel,oalles/camel,nikhilvibhav/camel,salikjan/camel,borcsokj/camel,sabre1041/camel,bhaveshdt/camel,curso007/camel,dmvolod/camel,sabre1041/camel,oalles/camel,sverkera/camel,tkopczynski/camel,apache/camel,drsquidop/camel,Thopap/camel,NickCis/camel,dmvolod/camel,Fabryprog/camel,tkopczynski/camel,erwelch/camel,zregvart/camel,jlpedrosa/camel | /**
* 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.camel.component.facebook;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
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 java.util.concurrent.TimeUnit;
import facebook4j.Facebook;
import facebook4j.Reading;
import facebook4j.json.DataObjectFactory;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.facebook.data.FacebookMethodsType;
import org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.MatchType;
import org.apache.camel.component.facebook.data.FacebookPropertiesHelper;
import org.apache.camel.component.facebook.data.ReadingBuilder;
import org.apache.camel.impl.ScheduledPollConsumer;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.component.facebook.FacebookConstants.FACEBOOK_DATE_FORMAT;
import static org.apache.camel.component.facebook.FacebookConstants.READING_PREFIX;
import static org.apache.camel.component.facebook.FacebookConstants.READING_PROPERTY;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.filterMethods;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getHighestPriorityMethod;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getMissingProperties;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.invokeMethod;
/**
* The Facebook consumer.
*/
public class FacebookConsumer extends ScheduledPollConsumer {
private static final Logger LOG = LoggerFactory.getLogger(FacebookConsumer.class);
private static final String SINCE_PREFIX = "since=";
private final FacebookEndpoint endpoint;
private final FacebookMethodsType method;
private final Map<String, Object> endpointProperties;
private String sinceTime;
private String untilTime;
public FacebookConsumer(FacebookEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
// determine the consumer method to invoke
this.method = findMethod();
// get endpoint properties in a map
final HashMap<String, Object> properties = new HashMap<String, Object>();
FacebookPropertiesHelper.getEndpointProperties(endpoint.getConfiguration(), properties);
// skip since and until fields?
final Reading reading = (Reading) properties.get(READING_PROPERTY);
if (reading != null) {
final String queryString = reading.toString();
if (queryString.contains(SINCE_PREFIX)) {
// use the user supplied value to start with
final int startIndex = queryString.indexOf(SINCE_PREFIX) + SINCE_PREFIX.length();
int endIndex = queryString.indexOf('&', startIndex);
if (endIndex == -1) {
// ignore the closing square bracket
endIndex = queryString.length() - 1;
}
final String strSince = queryString.substring(startIndex, endIndex);
try {
this.sinceTime = URLDecoder.decode(strSince, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeCamelException(String.format("Error decoding %s.since with value %s due to: %s"
, READING_PREFIX, strSince, e.getMessage()), e);
}
LOG.debug("Using supplied property {}since value {}", READING_PREFIX, this.sinceTime);
}
if (queryString.contains("until=")) {
LOG.debug("Overriding configured property {}until", READING_PREFIX);
}
}
this.endpointProperties = Collections.unmodifiableMap(properties);
}
@Override
public boolean isGreedy() {
// make this consumer not greedy to avoid making too many Facebook calls
return false;
}
private FacebookMethodsType findMethod() {
FacebookMethodsType result;
// find one that takes the largest subset of endpoint parameters
final Set<String> argNames = new HashSet<String>();
argNames.addAll(FacebookPropertiesHelper.getEndpointPropertyNames(endpoint.getConfiguration()));
// add reading property for polling, if it doesn't already exist!
argNames.add(READING_PROPERTY);
final String[] argNamesArray = argNames.toArray(new String[argNames.size()]);
List<FacebookMethodsType> filteredMethods = filterMethods(
endpoint.getCandidates(), MatchType.SUPER_SET, argNamesArray);
if (filteredMethods.isEmpty()) {
throw new IllegalArgumentException(
String.format("Missing properties for %s, need one or more from %s",
endpoint.getMethod(),
getMissingProperties(endpoint.getMethod(), endpoint.getNameStyle(), argNames)));
} else if (filteredMethods.size() == 1) {
// single match
result = filteredMethods.get(0);
} else {
result = getHighestPriorityMethod(filteredMethods);
LOG.warn("Using highest priority method {} from methods {}", method, filteredMethods);
}
return result;
}
@Override
protected int poll() throws Exception {
// invoke the consumer method
final Map<String, Object> args = getMethodArguments();
try {
// also check whether we need to get raw JSON
String rawJSON = null;
Object result;
if (endpoint.getConfiguration().getJsonStoreEnabled() == null
|| !endpoint.getConfiguration().getJsonStoreEnabled()) {
result = invokeMethod(endpoint.getConfiguration().getFacebook(),
method, args);
} else {
final Facebook facebook = endpoint.getConfiguration().getFacebook();
synchronized (facebook) {
result = invokeMethod(facebook, method, args);
rawJSON = DataObjectFactory.getRawJSON(result);
}
}
// process result according to type
if (result != null && (result instanceof Collection || result.getClass().isArray())) {
// create an exchange for every element
final Object array = getResultAsArray(result);
final int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
processResult(Array.get(array, i), rawJSON);
}
return length;
} else {
processResult(result, rawJSON);
return 1; // number of messages polled
}
} catch (Throwable t) {
throw ObjectHelper.wrapRuntimeCamelException(t);
}
}
private void processResult(Object result, String rawJSON) throws Exception {
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody(result);
if (rawJSON != null) {
exchange.getIn().setHeader(FacebookConstants.RAW_JSON_HEADER, rawJSON);
}
try {
// send message to next processor in the route
getProcessor().process(exchange);
} finally {
// log exception if an exception occurred and was not handled
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
}
}
}
private Object getResultAsArray(Object result) {
if (result.getClass().isArray()) {
// no conversion needed
return result;
}
// must be a Collection
// TODO add support for Paging using ResponseList
Collection<?> collection = (Collection<?>) result;
return collection.toArray(new Object[collection.size()]);
}
private Map<String, Object> getMethodArguments() {
// start by setting the Reading since and until fields,
// these are used to avoid reading duplicate results across polls
Map<String, Object> arguments = new HashMap<String, Object>();
arguments.putAll(endpointProperties);
Reading reading = (Reading) arguments.remove(READING_PROPERTY);
if (reading == null) {
reading = new Reading();
} else {
try {
reading = ReadingBuilder.copy(reading, true);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(String.format("Error creating property [%s]: %s",
READING_PROPERTY, e.getMessage()), e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Error creating property [%s]: %s",
READING_PROPERTY, e.getMessage()), e);
}
}
// now set since and until for this poll
final SimpleDateFormat dateFormat = new SimpleDateFormat(FACEBOOK_DATE_FORMAT);
final long currentMillis = System.currentTimeMillis();
if (this.sinceTime == null) {
// first poll, set this to (current time - initial poll delay)
final Date startTime = new Date(currentMillis
- TimeUnit.MILLISECONDS.convert(getInitialDelay(), getTimeUnit()));
this.sinceTime = dateFormat.format(startTime);
} else if (this.untilTime != null) {
// use the last 'until' time
this.sinceTime = this.untilTime;
}
this.untilTime = dateFormat.format(new Date(currentMillis));
reading.since(this.sinceTime);
reading.until(this.untilTime);
arguments.put(READING_PROPERTY, reading);
return arguments;
}
}
| components/camel-facebook/src/main/java/org/apache/camel/component/facebook/FacebookConsumer.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.camel.component.facebook;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
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 java.util.concurrent.TimeUnit;
import facebook4j.Facebook;
import facebook4j.Reading;
import facebook4j.json.DataObjectFactory;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.facebook.data.FacebookMethodsType;
import org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.MatchType;
import org.apache.camel.component.facebook.data.FacebookPropertiesHelper;
import org.apache.camel.component.facebook.data.ReadingBuilder;
import org.apache.camel.impl.ScheduledPollConsumer;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.component.facebook.FacebookConstants.FACEBOOK_DATE_FORMAT;
import static org.apache.camel.component.facebook.FacebookConstants.READING_PROPERTY;
import static org.apache.camel.component.facebook.FacebookConstants.READING_PREFIX;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.filterMethods;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getHighestPriorityMethod;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getMissingProperties;
import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.invokeMethod;
/**
* The Facebook consumer.
*/
public class FacebookConsumer extends ScheduledPollConsumer {
private static final Logger LOG = LoggerFactory.getLogger(FacebookConsumer.class);
private static final String SINCE_PREFIX = "since=";
private final FacebookEndpoint endpoint;
private final FacebookMethodsType method;
private final Map<String, Object> endpointProperties;
private String sinceTime;
private String untilTime;
public FacebookConsumer(FacebookEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
// determine the consumer method to invoke
this.method = findMethod();
// get endpoint properties in a map
final HashMap<String, Object> properties = new HashMap<String, Object>();
FacebookPropertiesHelper.getEndpointProperties(endpoint.getConfiguration(), properties);
// skip since and until fields?
final Reading reading = (Reading) properties.get(READING_PROPERTY);
if (reading != null) {
final String queryString = reading.toString();
if (queryString.contains(SINCE_PREFIX)) {
// use the user supplied value to start with
final int startIndex = queryString.indexOf(SINCE_PREFIX) + SINCE_PREFIX.length();
int endIndex = queryString.indexOf('&', startIndex);
if (endIndex == -1) {
// ignore the closing square bracket
endIndex = queryString.length() - 1;
}
final String strSince = queryString.substring(startIndex, endIndex);
try {
this.sinceTime = URLDecoder.decode(strSince, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeCamelException(String.format("Error decoding %s.since with value %s due to: %s"
, READING_PREFIX, strSince, e.getMessage()), e);
}
LOG.debug("Using supplied property {}since value {}", READING_PREFIX, this.sinceTime);
}
if (queryString.contains("until=")) {
LOG.debug("Overriding configured property {}until", READING_PREFIX);
}
}
this.endpointProperties = Collections.unmodifiableMap(properties);
}
@Override
public boolean isGreedy() {
// make this consumer not greedy to avoid making too many Facebook calls
return false;
}
private FacebookMethodsType findMethod() {
FacebookMethodsType result;
// find one that takes the largest subset of endpoint parameters
final Set<String> argNames = new HashSet<String>();
argNames.addAll(FacebookPropertiesHelper.getEndpointPropertyNames(endpoint.getConfiguration()));
// add reading property for polling, if it doesn't already exist!
argNames.add(READING_PROPERTY);
final String[] argNamesArray = argNames.toArray(new String[argNames.size()]);
List<FacebookMethodsType> filteredMethods = filterMethods(
endpoint.getCandidates(), MatchType.SUPER_SET, argNamesArray);
if (filteredMethods.isEmpty()) {
throw new IllegalArgumentException(
String.format("Missing properties for %s, need one or more from %s",
endpoint.getMethod(),
getMissingProperties(endpoint.getMethod(), endpoint.getNameStyle(), argNames)));
} else if (filteredMethods.size() == 1) {
// single match
result = filteredMethods.get(0);
} else {
result = getHighestPriorityMethod(filteredMethods);
LOG.warn("Using highest priority method {} from methods {}", method, filteredMethods);
}
return result;
}
@Override
protected int poll() throws Exception {
// invoke the consumer method
final Map<String, Object> args = getMethodArguments();
try {
// also check whether we need to get raw JSON
String rawJSON = null;
Object result;
if (endpoint.getConfiguration().getJsonStoreEnabled() == null
|| !endpoint.getConfiguration().getJsonStoreEnabled()) {
result = invokeMethod(endpoint.getConfiguration().getFacebook(),
method, args);
} else {
final Facebook facebook = endpoint.getConfiguration().getFacebook();
synchronized (facebook) {
result = invokeMethod(facebook, method, args);
rawJSON = DataObjectFactory.getRawJSON(result);
}
}
// process result according to type
if (result != null && (result instanceof Collection || result.getClass().isArray())) {
// create an exchange for every element
final Object array = getResultAsArray(result);
final int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
processResult(Array.get(array, i), rawJSON);
}
return length;
} else {
processResult(result, rawJSON);
return 1; // number of messages polled
}
} catch (Throwable t) {
throw ObjectHelper.wrapRuntimeCamelException(t);
}
}
private void processResult(Object result, String rawJSON) throws Exception {
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody(result);
if (rawJSON != null) {
exchange.getIn().setHeader(FacebookConstants.RAW_JSON_HEADER, rawJSON);
}
try {
// send message to next processor in the route
getProcessor().process(exchange);
} finally {
// log exception if an exception occurred and was not handled
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
}
}
}
private Object getResultAsArray(Object result) {
if (result.getClass().isArray()) {
// no conversion needed
return result;
}
// must be a Collection
// TODO add support for Paging using ResponseList
Collection<?> collection = (Collection<?>) result;
return collection.toArray(new Object[collection.size()]);
}
private Map<String, Object> getMethodArguments() {
// start by setting the Reading since and until fields,
// these are used to avoid reading duplicate results across polls
Map<String, Object> arguments = new HashMap<String, Object>();
arguments.putAll(endpointProperties);
Reading reading = (Reading) arguments.remove(READING_PROPERTY);
if (reading == null) {
reading = new Reading();
} else {
try {
reading = ReadingBuilder.copy(reading, true);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(String.format("Error creating property [%s]: %s",
READING_PROPERTY, e.getMessage()), e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Error creating property [%s]: %s",
READING_PROPERTY, e.getMessage()), e);
}
}
// now set since and until for this poll
final SimpleDateFormat dateFormat = new SimpleDateFormat(FACEBOOK_DATE_FORMAT);
final long currentMillis = System.currentTimeMillis();
if (this.sinceTime == null) {
// first poll, set this to (current time - initial poll delay)
final Date startTime = new Date(currentMillis
- TimeUnit.MILLISECONDS.convert(getInitialDelay(), getTimeUnit()));
this.sinceTime = dateFormat.format(startTime);
} else if (this.untilTime != null) {
// use the last 'until' time
this.sinceTime = this.untilTime;
}
this.untilTime = dateFormat.format(new Date(currentMillis));
reading.since(this.sinceTime);
reading.until(this.untilTime);
arguments.put(READING_PROPERTY, reading);
return arguments;
}
}
| Fix Checkstyle issues
Signed-off-by: Gregor Zurowski <[email protected]> | components/camel-facebook/src/main/java/org/apache/camel/component/facebook/FacebookConsumer.java | Fix Checkstyle issues | <ide><path>omponents/camel-facebook/src/main/java/org/apache/camel/component/facebook/FacebookConsumer.java
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide> import static org.apache.camel.component.facebook.FacebookConstants.FACEBOOK_DATE_FORMAT;
<add>import static org.apache.camel.component.facebook.FacebookConstants.READING_PREFIX;
<ide> import static org.apache.camel.component.facebook.FacebookConstants.READING_PROPERTY;
<del>import static org.apache.camel.component.facebook.FacebookConstants.READING_PREFIX;
<ide> import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.filterMethods;
<ide> import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getHighestPriorityMethod;
<ide> import static org.apache.camel.component.facebook.data.FacebookMethodsTypeHelper.getMissingProperties; |
|
Java | apache-2.0 | 6d5f2972726865fdb51ae2096ed91b041ee3cc1b | 0 | utcompling/textgrounder,utcompling/textgrounder,utcompling/textgrounder | ///////////////////////////////////////////////////////////////////////////////
// Copyright 2010 Taesun Moon <[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.
// under the License.
///////////////////////////////////////////////////////////////////////////////
package opennlp.textgrounder.bayesian.converters;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import opennlp.textgrounder.bayesian.apps.*;
import opennlp.textgrounder.bayesian.structs.IntDoublePair;
import opennlp.textgrounder.bayesian.structs.NormalizedProbabilityWrapper;
import opennlp.textgrounder.bayesian.textstructs.Lexicon;
import opennlp.textgrounder.bayesian.topostructs.Region;
import opennlp.textgrounder.bayesian.wrapper.io.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
*
* @author Taesun Moon <[email protected]>
*/
public class ProbabilityPrettyPrinter {
/**
* Hyperparameter for region*doc priors
*/
protected double alpha;
/**
* Hyperparameter for word*region priors
*/
protected double beta;
/**
* Normalization term for word*region gibbs sampler
*/
protected double betaW;
/**
* Number of documents
*/
protected int D;
/**
* Number of tokens
*/
protected int N;
/**
* Number of regions
*/
protected int R;
/**
* Number of non-stopword word types. Equivalent to <p>fW-sW</p>.
*/
protected int W;
/**
*
*/
protected double[] normalizedRegionCounts;
/**
*
*/
protected double[] normalizedWordByRegionCounts;
/**
*
*/
protected double[] normalizedRegionByDocumentCounts;
/**
*
*/
protected Lexicon lexicon = null;
/**
*
*/
protected Region[][] regionMatrix = null;
/**
*
*/
protected HashMap<Integer, Region> regionIdToRegionMap;
/**
*
*/
protected ConverterExperimentParameters experimentParameters = null;
/**
*
*/
protected InputReader inputReader = null;
public ProbabilityPrettyPrinter(ConverterExperimentParameters _parameters) {
experimentParameters = _parameters;
inputReader = new BinaryInputReader(experimentParameters);
}
public void readFiles() {
NormalizedProbabilityWrapper normalizedProbabilityWrapper = inputReader.readProbabilities();
alpha = normalizedProbabilityWrapper.alpha;
beta = normalizedProbabilityWrapper.beta;
betaW = normalizedProbabilityWrapper.betaW;
D = normalizedProbabilityWrapper.D;
N = normalizedProbabilityWrapper.N;
R = normalizedProbabilityWrapper.R;
W = normalizedProbabilityWrapper.W;
normalizedRegionByDocumentCounts = normalizedProbabilityWrapper.normalizedRegionByDocumentCounts;
normalizedRegionCounts = normalizedProbabilityWrapper.normalizedRegionCounts;
normalizedWordByRegionCounts = normalizedProbabilityWrapper.normalizedWordByRegionCounts;
lexicon = inputReader.readLexicon();
regionMatrix = inputReader.readRegions();
regionIdToRegionMap = new HashMap<Integer, Region>();
for (Region[] regions : regionMatrix) {
for (Region region : regions) {
if (region != null) {
regionIdToRegionMap.put(region.id, region);
}
}
}
}
public void writeTfIdfWords(XMLStreamWriter w) throws XMLStreamException {
int outputPerClass = experimentParameters.getOutputPerClass();
String outputPath = experimentParameters.getXmlConditionalProbabilitiesFilename();
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("probabilities");
w.writeStartElement("word-by-region");
double sum = 0.0;
double[] wordFreqTotals = new double[W];
Arrays.fill(wordFreqTotals, 0.0);
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
for (int j = 0; j < W; ++j) {
wordFreqTotals[j] += normalizedWordByRegionCounts[j * R + i];
}
}
double[] idfs = new double[W];
for (int i = 0; i < W; ++i) {
idfs[i] = Math.log(R / wordFreqTotals[i]);
}
double[] normalizedTfIdfs = new double[R * W];
for (int i = 0; i < R; ++i) {
double total = 0.0;
for (int j = 0; j < W; ++j) {
total += normalizedWordByRegionCounts[j * R + i] * idfs[j];
}
for (int j = 0; j < W; ++j) {
normalizedTfIdfs[j * R + i] = normalizedWordByRegionCounts[j * R + i] * idfs[j] / total;
}
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedTfIdfs[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
w.writeStartElement("region");
w.writeAttribute("id", String.format("%04d", i));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", normalizedRegionCounts[i] / sum));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("word");
IntDoublePair pair = topWords.get(j);
w.writeAttribute("term", lexicon.getWordForInt(pair.index));
w.writeAttribute("prob", String.format("%.8e", pair.count / normalizedRegionCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
w.writeEndElement();
w.close();
}
public void normalizeAndPrintXMLProbabilities() {
int outputPerClass = experimentParameters.getOutputPerClass();
String outputPath = experimentParameters.getXmlConditionalProbabilitiesFilename();
try {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter w = factory.createXMLStreamWriter(new BufferedWriter(new FileWriter(outputPath)));
String rootName = "probabilities";
String wordByRegionName = "word-by-region";
String regionByWordName = "region-by-word";
String regionByDocumentName = "region-by-document";
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement(rootName);
{
w.writeStartElement(wordByRegionName);
double sum = 0.;
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedWordByRegionCounts[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
w.writeStartElement("region");
w.writeAttribute("id", String.format("%04d", i));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", normalizedRegionCounts[i] / sum));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("word");
IntDoublePair pair = topWords.get(j);
w.writeAttribute("term", lexicon.getWordForInt(pair.index));
w.writeAttribute("prob", String.format("%.8e", pair.count / normalizedRegionCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
{
w.writeStartElement(regionByWordName);
double[] wordCounts = new double[W];
for (int i = 0; i < W; ++i) {
wordCounts[i] = 0;
int wordoff = i * R;
for (int j = 0; j < R; ++j) {
wordCounts[i] += normalizedWordByRegionCounts[wordoff + j];
}
}
for (int i = 0; i < W; ++i) {
int wordoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedWordByRegionCounts[wordoff + j]));
}
Collections.sort(topRegions);
w.writeStartElement("word");
w.writeAttribute("term", lexicon.getWordForInt(i));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("region");
IntDoublePair pair = topRegions.get(j);
Region region = regionIdToRegionMap.get(pair.index);
w.writeAttribute("id", String.format("%04d", pair.index));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", pair.count / wordCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
{
Document trdoc = null;
try {
trdoc = (new SAXBuilder()).build(experimentParameters.getInputPath());
} catch (JDOMException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
HashMap<Integer, String> docidToName = new HashMap<Integer, String>();
int docid = 0;
Element trroot = trdoc.getRootElement();
ArrayList<Element> documents = new ArrayList<Element>(trroot.getChildren());
for (Element document : documents) {
String docidName = document.getAttributeValue("id");
if (docidName == null) {
docidName = String.format("doc%06d", docid);
}
docidToName.put(docid, docidName);
docid += 1;
}
w.writeStartElement(regionByDocumentName);
double[] docWordCounts = new double[D];
for (int i = 0; i < D; ++i) {
docWordCounts[i] = 0;
int docoff = i * R;
for (int j = 0; j < R; ++j) {
docWordCounts[i] += normalizedRegionByDocumentCounts[docoff + j];
}
}
for (int i = 0; i < D; ++i) {
int docoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedRegionByDocumentCounts[docoff + j]));
}
Collections.sort(topRegions);
w.writeStartElement("document");
w.writeAttribute("id", docidToName.get(i));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("region");
IntDoublePair pair = topRegions.get(j);
Region region = regionIdToRegionMap.get(pair.index);
w.writeAttribute("id", String.format("%04d", pair.index));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", pair.count / docWordCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
w.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
} catch (XMLStreamException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
*/
public void normalizeAndPrintWordByRegion() {
try {
String wordByRegionFilename = experimentParameters.getWordByRegionProbabilitiesPath();
BufferedWriter wordByRegionWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(wordByRegionFilename))));
double sum = 0.;
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedWordByRegionCounts[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
wordByRegionWriter.write(String.format("Region%04d\t%.2f\t%.2f\t%.8e", i, region.centLon, region.centLat, normalizedRegionCounts[i] / sum));
wordByRegionWriter.newLine();
for (IntDoublePair pair : topWords) {
wordByRegionWriter.write(String.format("%s\t%.8e", lexicon.getWordForInt(pair.index), pair.count / normalizedRegionCounts[i]));
wordByRegionWriter.newLine();
}
wordByRegionWriter.newLine();
}
wordByRegionWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
/**
*
*/
public void normalizeAndPrintRegionByWord() {
try {
String regionByWordFilename = experimentParameters.getRegionByWordProbabilitiesPath();
BufferedWriter regionByWordWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(regionByWordFilename))));
double[] wordCounts = new double[W];
for (int i = 0; i < W; ++i) {
wordCounts[i] = 0;
int wordoff = i * R;
for (int j = 0; j < R; ++j) {
wordCounts[i] += normalizedWordByRegionCounts[wordoff + j];
}
}
for (int i = 0; i < W; ++i) {
int wordoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedWordByRegionCounts[wordoff + j]));
}
Collections.sort(topRegions);
regionByWordWriter.write(String.format("%s", lexicon.getWordForInt(i)));
regionByWordWriter.newLine();
for (IntDoublePair pair : topRegions) {
Region region = regionIdToRegionMap.get(pair.index);
regionByWordWriter.write(String.format("%.2f\t%.2f\t%.8e", region.centLon, region.centLat, pair.count / wordCounts[i]));
regionByWordWriter.newLine();
}
regionByWordWriter.newLine();
}
regionByWordWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
/**
*
*/
public void normalizeAndPrintRegionByDocument() {
try {
String regionByDocumentFilename = experimentParameters.getRegionByDocumentProbabilitiesPath();
BufferedWriter regionByDocumentWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(regionByDocumentFilename))));
SAXBuilder builder = new SAXBuilder();
Document trdoc = null;
try {
trdoc = builder.build(experimentParameters.getInputPath());
} catch (JDOMException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
HashMap<Integer, String> docidToName = new HashMap<Integer, String>();
int docid = 0;
Element root = trdoc.getRootElement();
ArrayList<Element> documents = new ArrayList<Element>(root.getChildren());
for (Element document : documents) {
docidToName.put(docid, document.getAttributeValue("id"));
docid += 1;
}
double[] docWordCounts = new double[D];
for (int i = 0; i < D; ++i) {
docWordCounts[i] = 0;
int docoff = i * R;
for (int j = 0; j < R; ++j) {
docWordCounts[i] += normalizedRegionByDocumentCounts[docoff + j];
}
}
for (int i = 0; i < D; ++i) {
int docoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedRegionByDocumentCounts[docoff + j]));
}
Collections.sort(topRegions);
regionByDocumentWriter.write(String.format("%s", docidToName.get(i)));
regionByDocumentWriter.newLine();
for (IntDoublePair pair : topRegions) {
Region region = regionIdToRegionMap.get(pair.index);
regionByDocumentWriter.write(String.format("%.2f\t%.2f\t%.8e", region.centLon, region.centLat, pair.count / docWordCounts[i]));
regionByDocumentWriter.newLine();
}
regionByDocumentWriter.newLine();
}
regionByDocumentWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
| java/opennlp/textgrounder/bayesian/converters/ProbabilityPrettyPrinter.java | ///////////////////////////////////////////////////////////////////////////////
// Copyright 2010 Taesun Moon <[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.
// under the License.
///////////////////////////////////////////////////////////////////////////////
package opennlp.textgrounder.bayesian.converters;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import opennlp.textgrounder.bayesian.apps.*;
import opennlp.textgrounder.bayesian.structs.IntDoublePair;
import opennlp.textgrounder.bayesian.structs.NormalizedProbabilityWrapper;
import opennlp.textgrounder.bayesian.textstructs.Lexicon;
import opennlp.textgrounder.bayesian.topostructs.Region;
import opennlp.textgrounder.bayesian.wrapper.io.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
*
* @author Taesun Moon <[email protected]>
*/
public class ProbabilityPrettyPrinter {
/**
* Hyperparameter for region*doc priors
*/
protected double alpha;
/**
* Hyperparameter for word*region priors
*/
protected double beta;
/**
* Normalization term for word*region gibbs sampler
*/
protected double betaW;
/**
* Number of documents
*/
protected int D;
/**
* Number of tokens
*/
protected int N;
/**
* Number of regions
*/
protected int R;
/**
* Number of non-stopword word types. Equivalent to <p>fW-sW</p>.
*/
protected int W;
/**
*
*/
protected double[] normalizedRegionCounts;
/**
*
*/
protected double[] normalizedWordByRegionCounts;
/**
*
*/
protected double[] normalizedRegionByDocumentCounts;
/**
*
*/
protected Lexicon lexicon = null;
/**
*
*/
protected Region[][] regionMatrix = null;
/**
*
*/
protected HashMap<Integer, Region> regionIdToRegionMap;
/**
*
*/
protected ConverterExperimentParameters experimentParameters = null;
/**
*
*/
protected InputReader inputReader = null;
public ProbabilityPrettyPrinter(ConverterExperimentParameters _parameters) {
experimentParameters = _parameters;
inputReader = new BinaryInputReader(experimentParameters);
}
public void readFiles() {
NormalizedProbabilityWrapper normalizedProbabilityWrapper = inputReader.readProbabilities();
alpha = normalizedProbabilityWrapper.alpha;
beta = normalizedProbabilityWrapper.beta;
betaW = normalizedProbabilityWrapper.betaW;
D = normalizedProbabilityWrapper.D;
N = normalizedProbabilityWrapper.N;
R = normalizedProbabilityWrapper.R;
W = normalizedProbabilityWrapper.W;
normalizedRegionByDocumentCounts = normalizedProbabilityWrapper.normalizedRegionByDocumentCounts;
normalizedRegionCounts = normalizedProbabilityWrapper.normalizedRegionCounts;
normalizedWordByRegionCounts = normalizedProbabilityWrapper.normalizedWordByRegionCounts;
lexicon = inputReader.readLexicon();
regionMatrix = inputReader.readRegions();
regionIdToRegionMap = new HashMap<Integer, Region>();
for (Region[] regions : regionMatrix) {
for (Region region : regions) {
if (region != null) {
regionIdToRegionMap.put(region.id, region);
}
}
}
}
public void writeTfIdfWords(XMLStreamWriter w) throws XMLStreamException {
int outputPerClass = experimentParameters.getOutputPerClass();
String outputPath = experimentParameters.getXmlConditionalProbabilitiesFilename();
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("probabilities");
w.writeStartElement("word-by-region");
double sum = 0.0;
double[] idfs = new double[W];
Arrays.fill(idfs, 0.0);
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
for (int j = 0; j < W; ++j) {
idfs[j] += Math.log(R / normalizedWordByRegionCounts[j * R + i]);
}
}
double[] normalizedTfIdfs = new double[R * W];
for (int i = 0; i < R; ++i) {
double total = 0.0;
for (int j = 0; j < W; ++j) {
total += normalizedWordByRegionCounts[j * R + i] * idfs[j];
}
for (int j = 0; j < W; ++j) {
normalizedTfIdfs[j * R + i] = normalizedWordByRegionCounts[j * R + i] * idfs[j] / total;
}
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedTfIdfs[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
w.writeStartElement("region");
w.writeAttribute("id", String.format("%04d", i));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", normalizedRegionCounts[i] / sum));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("word");
IntDoublePair pair = topWords.get(j);
w.writeAttribute("term", lexicon.getWordForInt(pair.index));
w.writeAttribute("prob", String.format("%.8e", pair.count / normalizedRegionCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
w.writeEndElement();
w.close();
}
public void normalizeAndPrintXMLProbabilities() {
int outputPerClass = experimentParameters.getOutputPerClass();
String outputPath = experimentParameters.getXmlConditionalProbabilitiesFilename();
try {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter w = factory.createXMLStreamWriter(new BufferedWriter(new FileWriter(outputPath)));
String rootName = "probabilities";
String wordByRegionName = "word-by-region";
String regionByWordName = "region-by-word";
String regionByDocumentName = "region-by-document";
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement(rootName);
{
w.writeStartElement(wordByRegionName);
double sum = 0.;
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedWordByRegionCounts[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
w.writeStartElement("region");
w.writeAttribute("id", String.format("%04d", i));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", normalizedRegionCounts[i] / sum));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("word");
IntDoublePair pair = topWords.get(j);
w.writeAttribute("term", lexicon.getWordForInt(pair.index));
w.writeAttribute("prob", String.format("%.8e", pair.count / normalizedRegionCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
{
w.writeStartElement(regionByWordName);
double[] wordCounts = new double[W];
for (int i = 0; i < W; ++i) {
wordCounts[i] = 0;
int wordoff = i * R;
for (int j = 0; j < R; ++j) {
wordCounts[i] += normalizedWordByRegionCounts[wordoff + j];
}
}
for (int i = 0; i < W; ++i) {
int wordoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedWordByRegionCounts[wordoff + j]));
}
Collections.sort(topRegions);
w.writeStartElement("word");
w.writeAttribute("term", lexicon.getWordForInt(i));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("region");
IntDoublePair pair = topRegions.get(j);
Region region = regionIdToRegionMap.get(pair.index);
w.writeAttribute("id", String.format("%04d", pair.index));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", pair.count / wordCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
{
Document trdoc = null;
try {
trdoc = (new SAXBuilder()).build(experimentParameters.getInputPath());
} catch (JDOMException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
HashMap<Integer, String> docidToName = new HashMap<Integer, String>();
int docid = 0;
Element trroot = trdoc.getRootElement();
ArrayList<Element> documents = new ArrayList<Element>(trroot.getChildren());
for (Element document : documents) {
String docidName = document.getAttributeValue("id");
if (docidName == null) {
docidName = String.format("doc%06d", docid);
}
docidToName.put(docid, docidName);
docid += 1;
}
w.writeStartElement(regionByDocumentName);
double[] docWordCounts = new double[D];
for (int i = 0; i < D; ++i) {
docWordCounts[i] = 0;
int docoff = i * R;
for (int j = 0; j < R; ++j) {
docWordCounts[i] += normalizedRegionByDocumentCounts[docoff + j];
}
}
for (int i = 0; i < D; ++i) {
int docoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedRegionByDocumentCounts[docoff + j]));
}
Collections.sort(topRegions);
w.writeStartElement("document");
w.writeAttribute("id", docidToName.get(i));
for (int j = 0; j < outputPerClass; ++j) {
w.writeStartElement("region");
IntDoublePair pair = topRegions.get(j);
Region region = regionIdToRegionMap.get(pair.index);
w.writeAttribute("id", String.format("%04d", pair.index));
w.writeAttribute("lat", String.format("%.2f", region.centLat));
w.writeAttribute("lon", String.format("%.2f", region.centLon));
w.writeAttribute("prob", String.format("%.8e", pair.count / docWordCounts[i]));
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
}
w.writeEndElement();
w.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
} catch (XMLStreamException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
*/
public void normalizeAndPrintWordByRegion() {
try {
String wordByRegionFilename = experimentParameters.getWordByRegionProbabilitiesPath();
BufferedWriter wordByRegionWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(wordByRegionFilename))));
double sum = 0.;
for (int i = 0; i < R; ++i) {
sum += normalizedRegionCounts[i];
}
for (int i = 0; i < R; ++i) {
ArrayList<IntDoublePair> topWords = new ArrayList<IntDoublePair>();
for (int j = 0; j < W; ++j) {
topWords.add(new IntDoublePair(j, normalizedWordByRegionCounts[j * R + i]));
}
Collections.sort(topWords);
Region region = regionIdToRegionMap.get(i);
wordByRegionWriter.write(String.format("Region%04d\t%.2f\t%.2f\t%.8e", i, region.centLon, region.centLat, normalizedRegionCounts[i] / sum));
wordByRegionWriter.newLine();
for (IntDoublePair pair : topWords) {
wordByRegionWriter.write(String.format("%s\t%.8e", lexicon.getWordForInt(pair.index), pair.count / normalizedRegionCounts[i]));
wordByRegionWriter.newLine();
}
wordByRegionWriter.newLine();
}
wordByRegionWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
/**
*
*/
public void normalizeAndPrintRegionByWord() {
try {
String regionByWordFilename = experimentParameters.getRegionByWordProbabilitiesPath();
BufferedWriter regionByWordWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(regionByWordFilename))));
double[] wordCounts = new double[W];
for (int i = 0; i < W; ++i) {
wordCounts[i] = 0;
int wordoff = i * R;
for (int j = 0; j < R; ++j) {
wordCounts[i] += normalizedWordByRegionCounts[wordoff + j];
}
}
for (int i = 0; i < W; ++i) {
int wordoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedWordByRegionCounts[wordoff + j]));
}
Collections.sort(topRegions);
regionByWordWriter.write(String.format("%s", lexicon.getWordForInt(i)));
regionByWordWriter.newLine();
for (IntDoublePair pair : topRegions) {
Region region = regionIdToRegionMap.get(pair.index);
regionByWordWriter.write(String.format("%.2f\t%.2f\t%.8e", region.centLon, region.centLat, pair.count / wordCounts[i]));
regionByWordWriter.newLine();
}
regionByWordWriter.newLine();
}
regionByWordWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
/**
*
*/
public void normalizeAndPrintRegionByDocument() {
try {
String regionByDocumentFilename = experimentParameters.getRegionByDocumentProbabilitiesPath();
BufferedWriter regionByDocumentWriter = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(regionByDocumentFilename))));
SAXBuilder builder = new SAXBuilder();
Document trdoc = null;
try {
trdoc = builder.build(experimentParameters.getInputPath());
} catch (JDOMException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(XMLToInternalConverter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
HashMap<Integer, String> docidToName = new HashMap<Integer, String>();
int docid = 0;
Element root = trdoc.getRootElement();
ArrayList<Element> documents = new ArrayList<Element>(root.getChildren());
for (Element document : documents) {
docidToName.put(docid, document.getAttributeValue("id"));
docid += 1;
}
double[] docWordCounts = new double[D];
for (int i = 0; i < D; ++i) {
docWordCounts[i] = 0;
int docoff = i * R;
for (int j = 0; j < R; ++j) {
docWordCounts[i] += normalizedRegionByDocumentCounts[docoff + j];
}
}
for (int i = 0; i < D; ++i) {
int docoff = i * R;
ArrayList<IntDoublePair> topRegions = new ArrayList<IntDoublePair>();
for (int j = 0; j < R; ++j) {
topRegions.add(new IntDoublePair(j, normalizedRegionByDocumentCounts[docoff + j]));
}
Collections.sort(topRegions);
regionByDocumentWriter.write(String.format("%s", docidToName.get(i)));
regionByDocumentWriter.newLine();
for (IntDoublePair pair : topRegions) {
Region region = regionIdToRegionMap.get(pair.index);
regionByDocumentWriter.write(String.format("%.2f\t%.2f\t%.8e", region.centLon, region.centLat, pair.count / docWordCounts[i]));
regionByDocumentWriter.newLine();
}
regionByDocumentWriter.newLine();
}
regionByDocumentWriter.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(ProbabilityPrettyPrinter.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
| Fixed stupid mistake in IDF logic.
| java/opennlp/textgrounder/bayesian/converters/ProbabilityPrettyPrinter.java | Fixed stupid mistake in IDF logic. | <ide><path>ava/opennlp/textgrounder/bayesian/converters/ProbabilityPrettyPrinter.java
<ide>
<ide> double sum = 0.0;
<ide>
<del> double[] idfs = new double[W];
<del> Arrays.fill(idfs, 0.0);
<add> double[] wordFreqTotals = new double[W];
<add> Arrays.fill(wordFreqTotals, 0.0);
<ide>
<ide> for (int i = 0; i < R; ++i) {
<ide> sum += normalizedRegionCounts[i];
<ide>
<ide> for (int j = 0; j < W; ++j) {
<del> idfs[j] += Math.log(R / normalizedWordByRegionCounts[j * R + i]);
<del> }
<add> wordFreqTotals[j] += normalizedWordByRegionCounts[j * R + i];
<add> }
<add> }
<add>
<add> double[] idfs = new double[W];
<add> for (int i = 0; i < W; ++i) {
<add> idfs[i] = Math.log(R / wordFreqTotals[i]);
<ide> }
<ide>
<ide> double[] normalizedTfIdfs = new double[R * W]; |
|
Java | apache-2.0 | 930a26ac9b09900d87b79a297b7d272a2fa151e1 | 0 | jomof/cmakeify,jomof/cmakeify,jomof/cmakeify | package com.jomofisher.cmakeify;
import com.jomofisher.cmakeify.CMakeify.OSType;
import com.jomofisher.cmakeify.model.*;
import java.io.*;
import java.util.*;
public class BashScriptBuilder extends ScriptBuilder {
final private static String ABORT_LAST_FAILED = "rc=$?; if [[ $rc != 0 ]]; then exit -$rc; fi";
final private static String TOOLS_FOLDER = ".cmakeify/tools";
final private static String DOWNLOADS_FOLDER = ".cmakeify/downloads";
final private StringBuilder body = new StringBuilder();
final private Map<String, String> zips = new HashMap<>();
final private OSType hostOS;
final private File workingFolder;
final private File rootBuildFolder;
final private File zipsFolder;
final private File cdepFile;
final private File androidFolder;
final private String targetGroupId;
final private String targetArtifactId;
final private String targetVersion;
final private Set<File> outputLocations = new HashSet<>();
final private PrintStream out;
final private OS specificTargetOS;
BashScriptBuilder(PrintStream out,
OSType hostOS,
File workingFolder,
String targetGroupId,
String targetArtifactId,
String targetVersion,
OS specificTargetOS) {
this.out = out;
this.hostOS = hostOS;
this.workingFolder = workingFolder.getAbsoluteFile();
this.rootBuildFolder = new File(workingFolder, "build");
this.zipsFolder = new File(rootBuildFolder, "zips");
if (specificTargetOS == null) {
this.cdepFile = new File(zipsFolder, "cdep-manifest.yml");
} else {
this.cdepFile = new File(zipsFolder, String.format("cdep-manifest-%s.yml", specificTargetOS));
}
this.androidFolder = new File(rootBuildFolder, "Android");
this.targetGroupId = targetGroupId;
this.targetArtifactId = targetArtifactId;
this.targetVersion = targetVersion;
this.specificTargetOS = specificTargetOS;
}
private BashScriptBuilder body(String format, Object... args) {
String write = String.format(format + "\n", args);
if (write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
if (write.contains("&")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder bodyWithRedirect(String format, Object... args) {
String write = String.format(format + "\n", args);
if (!write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder cdep(String format, Object... args) {
String embed = String.format(format, args);
body.append(String.format("printf \"%%s\\r\\n\" \"%s\" >> %s \n", embed, cdepFile));
return this;
}
private void recordOutputLocation(File folder) {
out.printf("Writing to %s\n", folder);
if (this.outputLocations.contains(folder)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
try {
File canonical = folder.getCanonicalFile();
if (this.outputLocations.contains(canonical)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
this.outputLocations.add(folder);
this.outputLocations.add(canonical);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
ScriptBuilder createEmptyBuildFolder(HardNameDependency dependencies[]) {
body("rm -rf %s", rootBuildFolder);
body("mkdir -p %s", zipsFolder);
body("mkdir -p %s/", TOOLS_FOLDER);
body("mkdir -p %s/", DOWNLOADS_FOLDER);
cdep("# Generated by CMakeify");
cdep("coordinate:");
cdep(" groupId: %s", targetGroupId);
cdep(" artifactId: %s", targetArtifactId);
cdep(" version: %s", targetVersion);
if (dependencies != null && dependencies.length > 0) {
cdep("dependencies:");
for (HardNameDependency dependency : dependencies) {
cdep(" - compile: %s", dependency.compile);
cdep(" sha256: %s", dependency.sha256);
}
}
return this;
}
private ArchiveUrl getHostArchive(RemoteArchive remote) {
switch (hostOS) {
case Linux:
return remote.linux;
case MacOS:
return remote.darwin;
}
throw new RuntimeException(hostOS.toString());
}
@Override
ScriptBuilder download(RemoteArchive remote) {
ArchiveInfo archive = new ArchiveInfo(getHostArchive(remote));
return bodyWithRedirect(archive.downloadToFolder(DOWNLOADS_FOLDER)).bodyWithRedirect(archive.uncompressToFolder(
DOWNLOADS_FOLDER,
TOOLS_FOLDER));
}
@Override
File writeToShellScript() {
BufferedWriter writer = null;
File file = new File(".cmakeify/build.sh");
file.getAbsoluteFile().mkdirs();
file.delete();
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(body.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
return file;
}
@Override
ScriptBuilder checkForCompilers(Collection<String> compilers) {
for (String compiler : compilers) {
body("if [[ -z \"$(which %s)\" ]]; then", compiler);
body(" echo CMAKEIFY ERROR: Missing %s. Please install.", compiler);
body(" exit -110");
body("fi");
}
return this;
}
@Override
ScriptBuilder cmakeAndroid(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String ndkVersion,
RemoteArchive ndkRemote,
String includes[],
String lib,
String compiler,
String runtime,
String platform,
String abi,
boolean multipleFlavors,
boolean multipleCMake,
boolean multipleNDK,
boolean multipleCompiler,
boolean multipleRuntime,
boolean multiplePlatforms,
boolean multipleAbi) {
body("echo Executing script for %s %s %s %s %s %s %s", flavor, ndkVersion, platform, compiler, runtime, target, abi);
if (lib != null && lib.length() > 0) {
throw new RuntimeException("lib is no longer supported, use buildTarget");
}
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = androidFolder;
String zipName = targetArtifactId + "-android";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleNDK) {
outputFolder = new File(outputFolder, ndkVersion);
zipName += "-" + ndkVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, compiler);
zipName += "-" + compiler;
}
if (multipleRuntime) {
String fixedRuntime = runtime.replace('+', 'x');
outputFolder = new File(outputFolder, fixedRuntime);
zipName += "-" + fixedRuntime;
}
if (multiplePlatforms) {
outputFolder = new File(outputFolder, "android-" + platform);
zipName += "-platform-" + platform;
}
if (multipleFlavors) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multipleAbi) {
outputFolder = new File(outputFolder, "abi-" + abi);
zipName += "-" + abi;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
recordOutputLocation(zip);
File buildFolder = new File(outputFolder, "cmake-generated-files");
String ndkFolder = String.format("%s/%s", TOOLS_FOLDER, getHostArchive(ndkRemote).unpackroot);
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
File abiBuildFolder = new File(buildFolder, abi);
File archFolder = new File(String.format("%s/platforms/android-%s/arch-%s",
new File(ndkFolder).getAbsolutePath(),
platform,
Abi.getByName(abi).getArchitecture()));
body("if [ -d '%s' ]; then", archFolder);
body(" echo Creating make project in %s", abiBuildFolder);
File stagingAbiFolder = new File(String.format("%s/lib/%s", stagingFolder, abi));
recordOutputLocation(stagingAbiFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG=1 \\\n" +
" -DCMAKE_SYSTEM_NAME=Android \\\n" +
" -DCMAKE_SYSTEM_VERSION=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ANDROID_STL_TYPE=%s_static \\\n" +
" -DCMAKE_ANDROID_NDK=%s \\\n" +
" -DCMAKE_ANDROID_ARCH_ABI=%s %s %s\n",
cmakeExe,
workingFolder,
abiBuildFolder,
compiler,
platform,
headerFolder,
stagingAbiFolder,
stagingAbiFolder,
runtime,
new File(ndkFolder).getAbsolutePath(),
abi,
flavorFlags,
cmakeFlags);
body(" echo Executing %s", command);
body(" " + command);
body(" " + ABORT_LAST_FAILED);
if (target != null && target.length() > 0) {
body(String.format(" %s --build %s --target %s -- -j8", cmakeExe, abiBuildFolder, target));
} else {
body(String.format(" %s --build %s -- -j8", cmakeExe, abiBuildFolder));
}
body(" " + ABORT_LAST_FAILED);
String stagingLib = String.format("%s/%s", stagingAbiFolder, lib);
File redistAbiFolder = new File(String.format("%s/lib/%s", redistFolder, abi));
recordOutputLocation(redistAbiFolder);
if (lib != null && lib.length() > 0) {
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s", redistAbiFolder);
body(" cp %s %s/%s", stagingLib, redistAbiFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit -100");
body(" fi");
} else {
body(" echo cmakeify.yml did not specify lib or target. No output library expected.");
}
body("else");
body(" echo Build skipped ABI %s because arch folder didnt exist: %s", abi, archFolder);
body("fi");
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo Android %s %s %s %s %s %s > %s/cmakeify.txt",
cmakeVersion,
flavor,
ndkVersion,
platform,
compiler,
runtime,
redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavors) {
cdep(" flavor: %s", flavor);
}
cdep(" runtime: %s", runtime);
cdep(" platform: %s", platform);
cdep(" ndk: %s", ndkVersion);
cdep(" abi: %s", abi);
if (multipleCompiler) {
cdep(" compiler: %s", compiler);
}
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
return this;
}
private void writeCreateHeaderZip(File headers, File headerFolder) {
body(" if [ -d '%s' ]; then", headerFolder);
writeCreateZipFromRedistFolderToBody(headers, headerFolder);
body(" else");
body(" echo CMAKEIFY ERROR: Header folder %s was not found", headerFolder);
body(" exit -699");
body(" fi");
}
private void writeZipFileStatisticsToBody(File zip) {
body(" SHASUM256=$(shasum -a 256 %s | awk '{print $1}')", zip);
body(" " + ABORT_LAST_FAILED);
body(" ARCHIVESIZE=$(ls -l %s | awk '{print $5}')", zip);
body(" " + ABORT_LAST_FAILED);
}
@Override
ScriptBuilder cmakeLinux(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
Toolset toolset,
String lib,
boolean multipleCMake,
boolean multipleCompiler) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "Linux");
String zipName = targetArtifactId + "-linux";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, toolset.c);
zipName += "-" + toolset.c;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
body("echo Building to %s", outputFolder);
body("mkdir -p %s/include", redistFolder);
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
body(String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_SYSTEM_NAME=Linux \\\n" +
" -DCMAKE_C_COMPILER=%s \\\n" +
" -DCMAKE_CXX_COMPILER=%s %s",
cmakeExe,
workingFolder,
buildFolder,
headerFolder,
redistFolder,
redistFolder,
toolset.c,
toolset.cxx,
cmakeFlags));
if (target != null && target.length() > 0) {
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(ABORT_LAST_FAILED);
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("# Zip Linux redist if folder was created in %s", redistFolder);
body("if [ -d '%s' ]; then", redistFolder);
body(" if [ -f '%s' ]; then", zip);
body(" echo CMAKEIFY ERROR: Linux zip %s would be overwritten", zip);
body(" exit -500");
body(" fi");
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
body(" " + ABORT_LAST_FAILED);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
body("else");
body(" echo CMAKEIFY ERROR: Did not create %s", redistFolder);
body(" exit -520");
body("fi");
return this;
}
@Override
ScriptBuilder cmakeiOS(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String includes[],
String lib,
iOSPlatform platform,
iOSArchitecture architecture,
String sdk,
boolean multipleFlavor,
boolean multipleCMake,
boolean multiplePlatform,
boolean multipleArchitecture,
boolean multipleSdk) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
if (!isSupportediOSPlatformArchitecture(platform, architecture)) {
out.printf("Skipping iOS %s %s because it isn't supported by XCode\n", platform, architecture);
return this;
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "iOS");
String zipName = targetArtifactId + "-ios";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleFlavor) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multiplePlatform) {
outputFolder = new File(outputFolder, "platform-" + platform.toString());
zipName += "-platform-" + platform.toString();
}
if (multipleArchitecture) {
outputFolder = new File(outputFolder, "architecture-" + architecture.toString());
zipName += "-architecture-" + architecture.toString();
}
if (multipleSdk) {
outputFolder = new File(outputFolder, "sdk-" + sdk);
zipName += "-sdk-" + sdk;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
if (hostOS != OSType.MacOS) {
body("echo No XCode available. NOT building to %s", outputFolder);
} else {
body("CDEP_IOS_CLANG=$(xcrun -sdk iphoneos -find clang)");
body("CDEP_IOS_AR=$(xcrun -sdk iphoneos -find ar)");
body("CDEP_XCODE_DEVELOPER_DIR=$(xcode-select -print-path)");
body("CDEP_IOS_DEVELOPER_ROOT=${CDEP_XCODE_DEVELOPER_DIR}/Platforms/%s.platform/Developer", platform);
body("CDEP_IOS_SDK_ROOT=${CDEP_IOS_DEVELOPER_ROOT}/SDKs/%s%s.sdk", platform, sdk);
body("if [ ! -d \"${CDEP_IOS_SDK_ROOT}\" ]; then");
body(" echo Not building for non-existent SDK root ${CDEP_IOS_SDK_ROOT}. Listing available:");
body(" ls ${CDEP_IOS_DEVELOPER_ROOT}/SDKs");
body("else");
body(" echo Building to %s", outputFolder);
body(" mkdir -p %s/include", redistFolder);
}
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
recordOutputLocation(stagingFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_C_COMPILER=${CDEP_IOS_CLANG}\\\n" +
" -DCMAKE_CXX_COMPILER=${CDEP_IOS_CLANG} \\\n" +
" -DCMAKE_C_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_CXX_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_AR=${CDEP_IOS_AR}\\\n" +
" -DCMAKE_OSX_SYSROOT=${CDEP_IOS_SDK_ROOT} \\\n" +
" -DCMAKE_OSX_ARCHITECTURES=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib %s %s \\\n",
cmakeExe,
workingFolder,
buildFolder,
architecture,
headerFolder,
stagingFolder,
stagingFolder,
cmakeFlags,
flavorFlags);
if (hostOS == OSType.MacOS) {
body(" echo Executing %s", command);
body(" " + command);
if (target != null && target.length() > 0) {
body(String.format("echo %s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("echo %s --build %s -- -j8", cmakeExe, buildFolder));
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(" " + ABORT_LAST_FAILED);
if (lib != null && lib.length() > 0) {
String stagingLib = String.format("%s/lib/%s", stagingFolder, lib);
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s/lib", redistFolder);
body(" cp %s %s/lib/%s", stagingLib, redistFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit -100");
body(" fi");
}
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body(" if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo iOS %s %s > %s/cmakeify.txt", cmakeVersion, platform, redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
if (lib == null || lib.length() > 0) {
body(" else");
body(" echo CMAKEIFY ERROR: Build did not produce an output in %s", stagingFolder);
body(" exit -200");
}
body(" fi");
// Still create the manifest for what would have been built.
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavor) {
cdep(" flavor: %s", flavor);
}
cdep(" platform: %s", platform);
cdep(" architecture: %s", architecture);
cdep(" sdk: %s", sdk);
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
}
return this;
}
private boolean isSupportediOSPlatformArchitecture(iOSPlatform platform, iOSArchitecture architecture) {
if (platform.equals(iOSPlatform.iPhoneOS)) {
if (architecture.equals(iOSArchitecture.arm64)) {
return true;
}
if (architecture.equals(iOSArchitecture.armv7)) {
return true;
}
return architecture.equals(iOSArchitecture.armv7s);
}
if (platform.equals(iOSPlatform.iPhoneSimulator)) {
if (architecture.equals(iOSArchitecture.i386)) {
return true;
}
return architecture.equals(iOSArchitecture.x86_64);
}
throw new RuntimeException(platform.toString());
}
private void writeCreateZipFromRedistFolderToBody(File zip, File folder) {
body(" pushd %s", folder);
body(" " + ABORT_LAST_FAILED);
body(" zip %s . -r", zip);
body(" " + ABORT_LAST_FAILED);
body(" if [ -f '%s' ]; then", zip);
body(" echo Zip %s was created", zip);
body(" else");
body(" echo CMAKEIFY ERROR: Zip %s was not created", zip);
body(" exit -402");
body(" fi");
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
private void writeExtraIncludesToBody(String[] includes, File includesRedistFolder) {
if (includes != null) {
for (String include : includes) {
body(" if [ ! -d '%s/%s' ]; then", workingFolder, include);
body(" echo CMAKEIFY ERROR: Extra include folder '%s/%s' does not exist", workingFolder, include);
body(" exit -600");
body(" fi");
body(" pushd %s", workingFolder);
if (include.startsWith("include")) {
body(" echo find %s -name '*.h' {pipe} cpio -pdm %s", include, includesRedistFolder);
body(" find %s -name '*.h' | cpio -pdm %s", include, includesRedistFolder);
body(" echo find %s -name '*.hpp' {pipe} cpio -pdm %s", include, includesRedistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s", include, includesRedistFolder);
} else {
body(" find %s -name '*.h' | cpio -pdm %s/include", include, includesRedistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s/include", include, includesRedistFolder);
}
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
}
}
@Override
ScriptBuilder startBuilding(OS target) {
switch (target) {
case android:
cdep("android:");
cdep(" archives:");
return this;
case linux:
cdep("linux:");
cdep(" archives:");
return this;
case windows:
cdep("windows:");
cdep(" archives:");
return this;
case iOS:
cdep("iOS:");
cdep(" archives:");
return this;
}
throw new RuntimeException(target.toString());
}
@Override
ScriptBuilder buildRedistFiles(File workingFolder, String[] includes, String example) {
if (example != null && example.length() > 0) {
cdep("example: |");
String lines[] = example.split("\\r?\\n");
for (String line : lines) {
cdep(" %s", line);
}
}
body("cat %s", cdepFile);
body("echo - %s", new File(cdepFile.getParentFile(), "cdep-manifest.yml"));
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo - %s", relativeZip);
body("fi");
}
return this;
}
@Override
ScriptBuilder deployRedistFiles(
RemoteArchive githubRelease,
OS[] allTargets,
boolean uploadBadges) {
File combinedManifest = new File(cdepFile.getParentFile(), "cdep-manifest.yml");
File headers = new File(cdepFile.getParentFile(), "headers.zip");
body("echo %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, cdepFile);
body("%s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, cdepFile);
body(ABORT_LAST_FAILED);
if (targetVersion == null || targetVersion.length() == 0 || targetVersion.equals("0.0.0")) {
body("echo Skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
if (!combinedManifest.equals(cdepFile)) {
body("# cdep-manifest.yml tracking: %s to %s", cdepFile, combinedManifest);
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
} else {
body("# cdep-manifest.yml tracking: not copying because it has the same name as combined");
body("echo not copying %s to %s because it was already there. Still merge head", combinedManifest, cdepFile);
body("ls %s", combinedManifest.getParent());
body(ABORT_LAST_FAILED);
}
return this;
}
body("echo Not skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
// Merging manifests from multiple travis runs is a PITA.
// All runs need to upload cdep-manifest-[targetOS].yml.
// The final run needs to figure out that it is the final run and also upload a merged
// cdep-manifest.yml.
// None of this needs to happen if specificTargetOS is null because that means there aren't
// multiple travis runs.
if (specificTargetOS != null) {
assert !cdepFile.toString().endsWith("cdep-manifest.yml");
if (allTargets.length == 1) {
// There is a specificTargetOS specified but it is the only one.
// We can combine the file locally.
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
} else {
// Accumulate a list of all targets to merge except for this one
String otherCoordinates = "";
for (OS os : allTargets) {
if (os != specificTargetOS) {
otherCoordinates += String.format("%s:%s/%s:%s ", targetGroupId, targetArtifactId, os, targetVersion);
}
}
// Now add this file
String coordinates = otherCoordinates + cdepFile.toString();
// Merge any existing manifest with the currently generated one.
body("echo %s/cdep merge %s %s", workingFolder, coordinates, combinedManifest);
body("%s/cdep merge %s %s", workingFolder, coordinates, combinedManifest);
body(ABORT_LAST_FAILED);
// If the merge succeeded, that means we got all of the coordinates.
// We can upload. Also need to fetch any partial dependencies so that
// downstream calls to ./cdep for tests will have assets all ready.
body("if [ -f '%s' ]; then", combinedManifest);
body(" echo Fetching partial dependencies");
body(" echo %s/cdep fetch %s", workingFolder, coordinates);
body(" %s/cdep fetch %s", workingFolder, coordinates);
body(" " + ABORT_LAST_FAILED);
body(" echo Uploading %s", combinedManifest);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
body("else");
// If the merged failed then we still have to create a combined manifest for test
// purposes but it won't be uploaded. Do the header merge at the same time as the
// copy.
body(" echo %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, combinedManifest);
body(" %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, combinedManifest);
body(" " + ABORT_LAST_FAILED);
body("fi");
// Upload the uncombined manifest
upload(cdepFile, githubRelease);
}
} else {
// There is not a specificTargetOS so there aren't multiple travis runs.
// Just upload cdep-manifest.yml.
assert cdepFile.toString().endsWith("cdep-manifest.yml");
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(cdepFile, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
}
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo Uploading %s", relativeZip);
upload(new File(relativeZip), githubRelease);
body("fi");
}
return this;
}
private void upload(File file, RemoteArchive githubRelease) {
String user = targetGroupId.substring(targetGroupId.lastIndexOf(".") + 1);
body(" echo %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(" %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(ABORT_LAST_FAILED);
}
private ScriptBuilder uploadBadges() {
// Record build information
String badgeUrl = String.format("%s:%s:%s", targetGroupId, targetArtifactId, targetVersion);
badgeUrl = badgeUrl.replace(":", "%3A");
badgeUrl = badgeUrl.replace("-", "--");
badgeUrl = String.format("https://img.shields.io/badge/cdep-%s-brightgreen.svg", badgeUrl);
String badgeFolder = String.format("%s/%s", targetGroupId, targetArtifactId);
body("if [ -n \"$TRAVIS_TAG\" ]; then");
body(" if [ -n \"$CDEP_BADGES_API_KEY\" ]; then");
body(" echo git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" " + ABORT_LAST_FAILED);
body(" pushd cdep-io.github.io");
body(" mkdir -p %s/latest", badgeFolder);
bodyWithRedirect(" echo curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
bodyWithRedirect(" curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git add %s/latest/latest.svg", badgeFolder);
body(" git add %s/latest/latest.svg", badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" " + ABORT_LAST_FAILED);
body(" echo git push -f -q https://cdep-io:[email protected]/cdep-io/cdep-io.github.io");
body(" git push -f -q https://cdep-io:[email protected]/cdep-io/cdep-io.github.io");
body(" " + ABORT_LAST_FAILED);
body(" popd");
body(" else");
body(" echo Add CDEP_BADGES_API_KEY to Travis settings to get badges!");
body(" fi");
body("fi");
return this;
}
@Override
public String toString() {
return body.toString();
}
}
| src/main/java/com/jomofisher/cmakeify/BashScriptBuilder.java | package com.jomofisher.cmakeify;
import com.jomofisher.cmakeify.CMakeify.OSType;
import com.jomofisher.cmakeify.model.*;
import java.io.*;
import java.util.*;
public class BashScriptBuilder extends ScriptBuilder {
final private static String ABORT_LAST_FAILED = "rc=$?; if [[ $rc != 0 ]]; then exit -$rc; fi";
final private static String TOOLS_FOLDER = ".cmakeify/tools";
final private static String DOWNLOADS_FOLDER = ".cmakeify/downloads";
final private StringBuilder body = new StringBuilder();
final private Map<String, String> zips = new HashMap<>();
final private OSType hostOS;
final private File workingFolder;
final private File rootBuildFolder;
final private File zipsFolder;
final private File cdepFile;
final private File androidFolder;
final private String targetGroupId;
final private String targetArtifactId;
final private String targetVersion;
final private Set<File> outputLocations = new HashSet<>();
final private PrintStream out;
final private OS specificTargetOS;
BashScriptBuilder(PrintStream out,
OSType hostOS,
File workingFolder,
String targetGroupId,
String targetArtifactId,
String targetVersion,
OS specificTargetOS) {
this.out = out;
this.hostOS = hostOS;
this.workingFolder = workingFolder;
this.rootBuildFolder = new File(workingFolder, "build");
this.zipsFolder = new File(rootBuildFolder, "zips");
if (specificTargetOS == null) {
this.cdepFile = new File(zipsFolder, "cdep-manifest.yml");
} else {
this.cdepFile = new File(zipsFolder, String.format("cdep-manifest-%s.yml", specificTargetOS));
}
this.androidFolder = new File(rootBuildFolder, "Android");
this.targetGroupId = targetGroupId;
this.targetArtifactId = targetArtifactId;
this.targetVersion = targetVersion;
this.specificTargetOS = specificTargetOS;
}
private BashScriptBuilder body(String format, Object... args) {
String write = String.format(format + "\n", args);
if (write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
if (write.contains("&")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder bodyWithRedirect(String format, Object... args) {
String write = String.format(format + "\n", args);
if (!write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder cdep(String format, Object... args) {
String embed = String.format(format, args);
body.append(String.format("printf \"%%s\\r\\n\" \"%s\" >> %s \n", embed, cdepFile));
return this;
}
private void recordOutputLocation(File folder) {
out.printf("Writing to %s\n", folder);
if (this.outputLocations.contains(folder)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
try {
File canonical = folder.getCanonicalFile();
if (this.outputLocations.contains(canonical)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
this.outputLocations.add(folder);
this.outputLocations.add(canonical);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
ScriptBuilder createEmptyBuildFolder(HardNameDependency dependencies[]) {
body("rm -rf %s", rootBuildFolder);
body("mkdir -p %s", zipsFolder);
body("mkdir -p %s/", TOOLS_FOLDER);
body("mkdir -p %s/", DOWNLOADS_FOLDER);
cdep("# Generated by CMakeify");
cdep("coordinate:");
cdep(" groupId: %s", targetGroupId);
cdep(" artifactId: %s", targetArtifactId);
cdep(" version: %s", targetVersion);
if (dependencies != null && dependencies.length > 0) {
cdep("dependencies:");
for (HardNameDependency dependency : dependencies) {
cdep(" - compile: %s", dependency.compile);
cdep(" sha256: %s", dependency.sha256);
}
}
return this;
}
private ArchiveUrl getHostArchive(RemoteArchive remote) {
switch (hostOS) {
case Linux:
return remote.linux;
case MacOS:
return remote.darwin;
}
throw new RuntimeException(hostOS.toString());
}
@Override
ScriptBuilder download(RemoteArchive remote) {
ArchiveInfo archive = new ArchiveInfo(getHostArchive(remote));
return bodyWithRedirect(archive.downloadToFolder(DOWNLOADS_FOLDER)).bodyWithRedirect(archive.uncompressToFolder(
DOWNLOADS_FOLDER,
TOOLS_FOLDER));
}
@Override
File writeToShellScript() {
BufferedWriter writer = null;
File file = new File(".cmakeify/build.sh");
file.getAbsoluteFile().mkdirs();
file.delete();
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(body.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
return file;
}
@Override
ScriptBuilder checkForCompilers(Collection<String> compilers) {
for (String compiler : compilers) {
body("if [[ -z \"$(which %s)\" ]]; then", compiler);
body(" echo CMAKEIFY ERROR: Missing %s. Please install.", compiler);
body(" exit -110");
body("fi");
}
return this;
}
@Override
ScriptBuilder cmakeAndroid(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String ndkVersion,
RemoteArchive ndkRemote,
String includes[],
String lib,
String compiler,
String runtime,
String platform,
String abi,
boolean multipleFlavors,
boolean multipleCMake,
boolean multipleNDK,
boolean multipleCompiler,
boolean multipleRuntime,
boolean multiplePlatforms,
boolean multipleAbi) {
body("echo Executing script for %s %s %s %s %s %s %s", flavor, ndkVersion, platform, compiler, runtime, target, abi);
if (lib != null && lib.length() > 0) {
throw new RuntimeException("lib is no longer supported, use buildTarget");
}
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = androidFolder;
String zipName = targetArtifactId + "-android";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleNDK) {
outputFolder = new File(outputFolder, ndkVersion);
zipName += "-" + ndkVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, compiler);
zipName += "-" + compiler;
}
if (multipleRuntime) {
String fixedRuntime = runtime.replace('+', 'x');
outputFolder = new File(outputFolder, fixedRuntime);
zipName += "-" + fixedRuntime;
}
if (multiplePlatforms) {
outputFolder = new File(outputFolder, "android-" + platform);
zipName += "-platform-" + platform;
}
if (multipleFlavors) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multipleAbi) {
outputFolder = new File(outputFolder, "abi-" + abi);
zipName += "-" + abi;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
recordOutputLocation(zip);
File buildFolder = new File(outputFolder, "cmake-generated-files");
String ndkFolder = String.format("%s/%s", TOOLS_FOLDER, getHostArchive(ndkRemote).unpackroot);
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
File abiBuildFolder = new File(buildFolder, abi);
File archFolder = new File(String.format("%s/platforms/android-%s/arch-%s",
new File(ndkFolder).getAbsolutePath(),
platform,
Abi.getByName(abi).getArchitecture()));
body("if [ -d '%s' ]; then", archFolder);
body(" echo Creating make project in %s", abiBuildFolder);
File stagingAbiFolder = new File(String.format("%s/lib/%s", stagingFolder, abi));
recordOutputLocation(stagingAbiFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG=1 \\\n" +
" -DCMAKE_SYSTEM_NAME=Android \\\n" +
" -DCMAKE_SYSTEM_VERSION=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ANDROID_STL_TYPE=%s_static \\\n" +
" -DCMAKE_ANDROID_NDK=%s \\\n" +
" -DCMAKE_ANDROID_ARCH_ABI=%s %s %s\n",
cmakeExe,
workingFolder,
abiBuildFolder,
compiler,
platform,
headerFolder,
stagingAbiFolder,
stagingAbiFolder,
runtime,
new File(ndkFolder).getAbsolutePath(),
abi,
flavorFlags,
cmakeFlags);
body(" echo Executing %s", command);
body(" " + command);
body(" " + ABORT_LAST_FAILED);
if (target != null && target.length() > 0) {
body(String.format(" %s --build %s --target %s -- -j8", cmakeExe, abiBuildFolder, target));
} else {
body(String.format(" %s --build %s -- -j8", cmakeExe, abiBuildFolder));
}
body(" " + ABORT_LAST_FAILED);
String stagingLib = String.format("%s/%s", stagingAbiFolder, lib);
File redistAbiFolder = new File(String.format("%s/lib/%s", redistFolder, abi));
recordOutputLocation(redistAbiFolder);
if (lib != null && lib.length() > 0) {
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s", redistAbiFolder);
body(" cp %s %s/%s", stagingLib, redistAbiFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit -100");
body(" fi");
} else {
body(" echo cmakeify.yml did not specify lib or target. No output library expected.");
}
body("else");
body(" echo Build skipped ABI %s because arch folder didnt exist: %s", abi, archFolder);
body("fi");
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo Android %s %s %s %s %s %s > %s/cmakeify.txt",
cmakeVersion,
flavor,
ndkVersion,
platform,
compiler,
runtime,
redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavors) {
cdep(" flavor: %s", flavor);
}
cdep(" runtime: %s", runtime);
cdep(" platform: %s", platform);
cdep(" ndk: %s", ndkVersion);
cdep(" abi: %s", abi);
if (multipleCompiler) {
cdep(" compiler: %s", compiler);
}
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
return this;
}
private void writeCreateHeaderZip(File headers, File headerFolder) {
body(" if [ -d '%s' ]; then", headerFolder);
writeCreateZipFromRedistFolderToBody(headers, headerFolder);
body(" else");
body(" echo CMAKEIFY ERROR: Header folder %s was not found", headerFolder);
body(" exit -699");
body(" fi");
}
private void writeZipFileStatisticsToBody(File zip) {
body(" SHASUM256=$(shasum -a 256 %s | awk '{print $1}')", zip);
body(" " + ABORT_LAST_FAILED);
body(" ARCHIVESIZE=$(ls -l %s | awk '{print $5}')", zip);
body(" " + ABORT_LAST_FAILED);
}
@Override
ScriptBuilder cmakeLinux(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
Toolset toolset,
String lib,
boolean multipleCMake,
boolean multipleCompiler) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "Linux");
String zipName = targetArtifactId + "-linux";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, toolset.c);
zipName += "-" + toolset.c;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
body("echo Building to %s", outputFolder);
body("mkdir -p %s/include", redistFolder);
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
body(String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_SYSTEM_NAME=Linux \\\n" +
" -DCMAKE_C_COMPILER=%s \\\n" +
" -DCMAKE_CXX_COMPILER=%s %s",
cmakeExe,
workingFolder,
buildFolder,
headerFolder,
redistFolder,
redistFolder,
toolset.c,
toolset.cxx,
cmakeFlags));
if (target != null && target.length() > 0) {
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(ABORT_LAST_FAILED);
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("# Zip Linux redist if folder was created in %s", redistFolder);
body("if [ -d '%s' ]; then", redistFolder);
body(" if [ -f '%s' ]; then", zip);
body(" echo CMAKEIFY ERROR: Linux zip %s would be overwritten", zip);
body(" exit -500");
body(" fi");
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
body(" " + ABORT_LAST_FAILED);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
body("else");
body(" echo CMAKEIFY ERROR: Did not create %s", redistFolder);
body(" exit -520");
body("fi");
return this;
}
@Override
ScriptBuilder cmakeiOS(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String includes[],
String lib,
iOSPlatform platform,
iOSArchitecture architecture,
String sdk,
boolean multipleFlavor,
boolean multipleCMake,
boolean multiplePlatform,
boolean multipleArchitecture,
boolean multipleSdk) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
if (!isSupportediOSPlatformArchitecture(platform, architecture)) {
out.printf("Skipping iOS %s %s because it isn't supported by XCode\n", platform, architecture);
return this;
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "iOS");
String zipName = targetArtifactId + "-ios";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleFlavor) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multiplePlatform) {
outputFolder = new File(outputFolder, "platform-" + platform.toString());
zipName += "-platform-" + platform.toString();
}
if (multipleArchitecture) {
outputFolder = new File(outputFolder, "architecture-" + architecture.toString());
zipName += "-architecture-" + architecture.toString();
}
if (multipleSdk) {
outputFolder = new File(outputFolder, "sdk-" + sdk);
zipName += "-sdk-" + sdk;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
if (hostOS != OSType.MacOS) {
body("echo No XCode available. NOT building to %s", outputFolder);
} else {
body("CDEP_IOS_CLANG=$(xcrun -sdk iphoneos -find clang)");
body("CDEP_IOS_AR=$(xcrun -sdk iphoneos -find ar)");
body("CDEP_XCODE_DEVELOPER_DIR=$(xcode-select -print-path)");
body("CDEP_IOS_DEVELOPER_ROOT=${CDEP_XCODE_DEVELOPER_DIR}/Platforms/%s.platform/Developer", platform);
body("CDEP_IOS_SDK_ROOT=${CDEP_IOS_DEVELOPER_ROOT}/SDKs/%s%s.sdk", platform, sdk);
body("if [ ! -d \"${CDEP_IOS_SDK_ROOT}\" ]; then");
body(" echo Not building for non-existent SDK root ${CDEP_IOS_SDK_ROOT}. Listing available:");
body(" ls ${CDEP_IOS_DEVELOPER_ROOT}/SDKs");
body("else");
body(" echo Building to %s", outputFolder);
body(" mkdir -p %s/include", redistFolder);
}
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
recordOutputLocation(stagingFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_C_COMPILER=${CDEP_IOS_CLANG}\\\n" +
" -DCMAKE_CXX_COMPILER=${CDEP_IOS_CLANG} \\\n" +
" -DCMAKE_C_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_CXX_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_AR=${CDEP_IOS_AR}\\\n" +
" -DCMAKE_OSX_SYSROOT=${CDEP_IOS_SDK_ROOT} \\\n" +
" -DCMAKE_OSX_ARCHITECTURES=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib %s %s \\\n",
cmakeExe,
workingFolder,
buildFolder,
architecture,
headerFolder,
stagingFolder,
stagingFolder,
cmakeFlags,
flavorFlags);
if (hostOS == OSType.MacOS) {
body(" echo Executing %s", command);
body(" " + command);
if (target != null && target.length() > 0) {
body(String.format("echo %s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("echo %s --build %s -- -j8", cmakeExe, buildFolder));
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(" " + ABORT_LAST_FAILED);
if (lib != null && lib.length() > 0) {
String stagingLib = String.format("%s/lib/%s", stagingFolder, lib);
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s/lib", redistFolder);
body(" cp %s %s/lib/%s", stagingLib, redistFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit -100");
body(" fi");
}
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body(" if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo iOS %s %s > %s/cmakeify.txt", cmakeVersion, platform, redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
writeCreateHeaderZip(headers, headerFolder);
writeZipFileStatisticsToBody(zip);
if (lib == null || lib.length() > 0) {
body(" else");
body(" echo CMAKEIFY ERROR: Build did not produce an output in %s", stagingFolder);
body(" exit -200");
}
body(" fi");
// Still create the manifest for what would have been built.
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavor) {
cdep(" flavor: %s", flavor);
}
cdep(" platform: %s", platform);
cdep(" architecture: %s", architecture);
cdep(" sdk: %s", sdk);
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
}
return this;
}
private boolean isSupportediOSPlatformArchitecture(iOSPlatform platform, iOSArchitecture architecture) {
if (platform.equals(iOSPlatform.iPhoneOS)) {
if (architecture.equals(iOSArchitecture.arm64)) {
return true;
}
if (architecture.equals(iOSArchitecture.armv7)) {
return true;
}
return architecture.equals(iOSArchitecture.armv7s);
}
if (platform.equals(iOSPlatform.iPhoneSimulator)) {
if (architecture.equals(iOSArchitecture.i386)) {
return true;
}
return architecture.equals(iOSArchitecture.x86_64);
}
throw new RuntimeException(platform.toString());
}
private void writeCreateZipFromRedistFolderToBody(File zip, File folder) {
body(" pushd %s", folder);
body(" " + ABORT_LAST_FAILED);
body(" zip %s . -r", zip);
body(" " + ABORT_LAST_FAILED);
body(" if [ -f '%s' ]; then", zip);
body(" echo Zip %s was created", zip);
body(" else");
body(" echo CMAKEIFY ERROR: Zip %s was not created", zip);
body(" exit -402");
body(" fi");
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
private void writeExtraIncludesToBody(String[] includes, File includesRedistFolder) {
if (includes != null) {
for (String include : includes) {
body(" if [ ! -d '%s/%s' ]; then", workingFolder, include);
body(" echo CMAKEIFY ERROR: Extra include folder '%s/%s' does not exist", workingFolder, include);
body(" exit -600");
body(" fi");
body(" pushd %s", workingFolder);
if (include.startsWith("include")) {
body(" echo find %s -name '*.h' {pipe} cpio -pdm %s", include, includesRedistFolder);
body(" find %s -name '*.h' | cpio -pdm %s", include, includesRedistFolder);
body(" echo find %s -name '*.hpp' {pipe} cpio -pdm %s", include, includesRedistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s", include, includesRedistFolder);
} else {
body(" find %s -name '*.h' | cpio -pdm %s/include", include, includesRedistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s/include", include, includesRedistFolder);
}
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
}
}
@Override
ScriptBuilder startBuilding(OS target) {
switch (target) {
case android:
cdep("android:");
cdep(" archives:");
return this;
case linux:
cdep("linux:");
cdep(" archives:");
return this;
case windows:
cdep("windows:");
cdep(" archives:");
return this;
case iOS:
cdep("iOS:");
cdep(" archives:");
return this;
}
throw new RuntimeException(target.toString());
}
@Override
ScriptBuilder buildRedistFiles(File workingFolder, String[] includes, String example) {
if (example != null && example.length() > 0) {
cdep("example: |");
String lines[] = example.split("\\r?\\n");
for (String line : lines) {
cdep(" %s", line);
}
}
body("cat %s", cdepFile);
body("echo - %s", new File(cdepFile.getParentFile(), "cdep-manifest.yml"));
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo - %s", relativeZip);
body("fi");
}
return this;
}
@Override
ScriptBuilder deployRedistFiles(
RemoteArchive githubRelease,
OS[] allTargets,
boolean uploadBadges) {
File combinedManifest = new File(cdepFile.getParentFile(), "cdep-manifest.yml");
File headers = new File(cdepFile.getParentFile(), "headers.zip");
body("echo %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, cdepFile);
body("%s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, cdepFile);
body(ABORT_LAST_FAILED);
if (targetVersion == null || targetVersion.length() == 0 || targetVersion.equals("0.0.0")) {
body("echo Skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
if (!combinedManifest.equals(cdepFile)) {
body("# cdep-manifest.yml tracking: %s to %s", cdepFile, combinedManifest);
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
} else {
body("# cdep-manifest.yml tracking: not copying because it has the same name as combined");
body("echo not copying %s to %s because it was already there. Still merge head", combinedManifest, cdepFile);
body("ls %s", combinedManifest.getParent());
body(ABORT_LAST_FAILED);
}
return this;
}
body("echo Not skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
// Merging manifests from multiple travis runs is a PITA.
// All runs need to upload cdep-manifest-[targetOS].yml.
// The final run needs to figure out that it is the final run and also upload a merged
// cdep-manifest.yml.
// None of this needs to happen if specificTargetOS is null because that means there aren't
// multiple travis runs.
if (specificTargetOS != null) {
assert !cdepFile.toString().endsWith("cdep-manifest.yml");
if (allTargets.length == 1) {
// There is a specificTargetOS specified but it is the only one.
// We can combine the file locally.
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
} else {
// Accumulate a list of all targets to merge except for this one
String otherCoordinates = "";
for (OS os : allTargets) {
if (os != specificTargetOS) {
otherCoordinates += String.format("%s:%s/%s:%s ", targetGroupId, targetArtifactId, os, targetVersion);
}
}
// Now add this file
String coordinates = otherCoordinates + cdepFile.toString();
// Merge any existing manifest with the currently generated one.
body("echo %s/cdep merge %s %s", workingFolder, coordinates, combinedManifest);
body("%s/cdep merge %s %s", workingFolder, coordinates, combinedManifest);
body(ABORT_LAST_FAILED);
// If the merge succeeded, that means we got all of the coordinates.
// We can upload. Also need to fetch any partial dependencies so that
// downstream calls to ./cdep for tests will have assets all ready.
body("if [ -f '%s' ]; then", combinedManifest);
body(" echo Fetching partial dependencies");
body(" echo %s/cdep fetch %s", workingFolder, coordinates);
body(" %s/cdep fetch %s", workingFolder, coordinates);
body(" " + ABORT_LAST_FAILED);
body(" echo Uploading %s", combinedManifest);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
body("else");
// If the merged failed then we still have to create a combined manifest for test
// purposes but it won't be uploaded. Do the header merge at the same time as the
// copy.
body(" echo %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, combinedManifest);
body(" %s/cdep merge headers %s %s include %s", workingFolder, cdepFile, headers, combinedManifest);
body(" " + ABORT_LAST_FAILED);
body("fi");
// Upload the uncombined manifest
upload(cdepFile, githubRelease);
}
} else {
// There is not a specificTargetOS so there aren't multiple travis runs.
// Just upload cdep-manifest.yml.
assert cdepFile.toString().endsWith("cdep-manifest.yml");
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
upload(cdepFile, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
}
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo Uploading %s", relativeZip);
upload(new File(relativeZip), githubRelease);
body("fi");
}
return this;
}
private void upload(File file, RemoteArchive githubRelease) {
String user = targetGroupId.substring(targetGroupId.lastIndexOf(".") + 1);
body(" echo %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(" %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(ABORT_LAST_FAILED);
}
private ScriptBuilder uploadBadges() {
// Record build information
String badgeUrl = String.format("%s:%s:%s", targetGroupId, targetArtifactId, targetVersion);
badgeUrl = badgeUrl.replace(":", "%3A");
badgeUrl = badgeUrl.replace("-", "--");
badgeUrl = String.format("https://img.shields.io/badge/cdep-%s-brightgreen.svg", badgeUrl);
String badgeFolder = String.format("%s/%s", targetGroupId, targetArtifactId);
body("if [ -n \"$TRAVIS_TAG\" ]; then");
body(" if [ -n \"$CDEP_BADGES_API_KEY\" ]; then");
body(" echo git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" " + ABORT_LAST_FAILED);
body(" pushd cdep-io.github.io");
body(" mkdir -p %s/latest", badgeFolder);
bodyWithRedirect(" echo curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
bodyWithRedirect(" curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git add %s/latest/latest.svg", badgeFolder);
body(" git add %s/latest/latest.svg", badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" " + ABORT_LAST_FAILED);
body(" echo git push -f -q https://cdep-io:[email protected]/cdep-io/cdep-io.github.io");
body(" git push -f -q https://cdep-io:[email protected]/cdep-io/cdep-io.github.io");
body(" " + ABORT_LAST_FAILED);
body(" popd");
body(" else");
body(" echo Add CDEP_BADGES_API_KEY to Travis settings to get badges!");
body(" fi");
body("fi");
return this;
}
@Override
public String toString() {
return body.toString();
}
}
| Single ABI
| src/main/java/com/jomofisher/cmakeify/BashScriptBuilder.java | Single ABI | <ide><path>rc/main/java/com/jomofisher/cmakeify/BashScriptBuilder.java
<ide> OS specificTargetOS) {
<ide> this.out = out;
<ide> this.hostOS = hostOS;
<del> this.workingFolder = workingFolder;
<add> this.workingFolder = workingFolder.getAbsoluteFile();
<ide> this.rootBuildFolder = new File(workingFolder, "build");
<ide> this.zipsFolder = new File(rootBuildFolder, "zips");
<ide> if (specificTargetOS == null) { |
|
Java | apache-2.0 | 086f3241bf6ec11e1dc1707ba1625c9d69b53b3f | 0 | martin-g/wicket-osgi,topicusonderwijs/wicket,AlienQueen/wicket,freiheit-com/wicket,freiheit-com/wicket,zwsong/wicket,freiheit-com/wicket,apache/wicket,aldaris/wicket,astrapi69/wicket,AlienQueen/wicket,martin-g/wicket-osgi,klopfdreh/wicket,bitstorm/wicket,freiheit-com/wicket,Servoy/wicket,astrapi69/wicket,zwsong/wicket,apache/wicket,mosoft521/wicket,mosoft521/wicket,bitstorm/wicket,mafulafunk/wicket,bitstorm/wicket,klopfdreh/wicket,astrapi69/wicket,zwsong/wicket,topicusonderwijs/wicket,klopfdreh/wicket,bitstorm/wicket,apache/wicket,dashorst/wicket,aldaris/wicket,AlienQueen/wicket,aldaris/wicket,topicusonderwijs/wicket,klopfdreh/wicket,Servoy/wicket,mafulafunk/wicket,dashorst/wicket,klopfdreh/wicket,mafulafunk/wicket,mosoft521/wicket,aldaris/wicket,selckin/wicket,martin-g/wicket-osgi,AlienQueen/wicket,selckin/wicket,mosoft521/wicket,aldaris/wicket,Servoy/wicket,topicusonderwijs/wicket,Servoy/wicket,AlienQueen/wicket,Servoy/wicket,dashorst/wicket,selckin/wicket,apache/wicket,freiheit-com/wicket,selckin/wicket,mosoft521/wicket,selckin/wicket,dashorst/wicket,astrapi69/wicket,bitstorm/wicket,topicusonderwijs/wicket,zwsong/wicket,apache/wicket,dashorst/wicket | ///////////////////////////////////////////////////////////////////////////////////
//
// Created May 21, 2004
//
// Copyright 2004, Jonathan W. Locke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package signin;
import com.voicetribe.util.value.ValueMap;
import com.voicetribe.wicket.PageParameters;
import com.voicetribe.wicket.PropertyModel;
import com.voicetribe.wicket.RequestCycle;
import com.voicetribe.wicket.markup.html.HtmlPage;
import com.voicetribe.wicket.markup.html.form.Form;
import com.voicetribe.wicket.markup.html.form.PasswordTextField;
import com.voicetribe.wicket.markup.html.form.TextField;
import com.voicetribe.wicket.markup.html.panel.FeedbackPanel;
/**
* Simple example of a sign in page.
* @author Jonathan Locke
*/
public final class SignIn extends HtmlPage
{
/**
* Constructor
* @param parameters The page parameters
*/
public SignIn(final PageParameters parameters)
{
// Create feedback panel and add to page
final FeedbackPanel feedback = new FeedbackPanel("feedback");
add(feedback);
// Add sign-in form to page, passing feedback panel as validation error handler
add(new SignInForm("signInForm", feedback));
}
/**
* Sign in form
* @author Jonathan Locke
*/
public final class SignInForm extends Form
{
/**
* Constructor
* @param componentName Name of the form component
* @param feedback The feedback panel to update
*/
public SignInForm(final String componentName, final FeedbackPanel feedback)
{
super(componentName, feedback);
// Attach textfield components that edit properties map model
add(new TextField("username", new PropertyModel(properties, "username")));
add(new PasswordTextField("password", new PropertyModel(properties, "password")));
}
/**
* @see com.voicetribe.wicket.markup.html.form.Form#handleSubmit(com.voicetribe.wicket.RequestCycle)
*/
public final void handleSubmit(final RequestCycle cycle)
{
// Sign the user in
if (properties.getString("username").equals("jonathan") &&
properties.getString("password").equals("password"))
{
cycle.getSession().setProperty("user", "jonathan");
if (!cycle.continueToOriginalDestination())
{
cycle.setPage(new Home(PageParameters.NULL));
}
}
else
{
// Form method that will notify feedback panel
errorMessage("Couldn't sign you in");
}
}
// El-cheapo model for form
private final ValueMap properties = new ValueMap();
}
}
///////////////////////////////// End of File /////////////////////////////////
| wicket-examples/src/java/signin/SignIn.java | ///////////////////////////////////////////////////////////////////////////////////
//
// Created May 21, 2004
//
// Copyright 2004, Jonathan W. Locke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package signin;
import com.voicetribe.util.value.ValueMap;
import com.voicetribe.wicket.PageParameters;
import com.voicetribe.wicket.RequestCycle;
import com.voicetribe.wicket.markup.html.HtmlPage;
import com.voicetribe.wicket.markup.html.form.Form;
import com.voicetribe.wicket.markup.html.form.PasswordTextField;
import com.voicetribe.wicket.markup.html.form.TextField;
import com.voicetribe.wicket.markup.html.panel.FeedbackPanel;
/**
* Simple example of a sign in page.
* @author Jonathan Locke
*/
public final class SignIn extends HtmlPage
{
/**
* Constructor
* @param parameters The page parameters
*/
public SignIn(final PageParameters parameters)
{
// Create feedback panel and add to page
final FeedbackPanel feedback = new FeedbackPanel("feedback");
add(feedback);
// Add sign-in form to page, passing feedback panel as validation error handler
add(new SignInForm("signInForm", feedback));
}
/**
* Sign in form
* @author Jonathan Locke
*/
public final class SignInForm extends Form
{
/**
* Constructor
* @param componentName Name of the form component
* @param feedback The feedback panel to update
*/
public SignInForm(final String componentName, final FeedbackPanel feedback)
{
super(componentName, feedback);
// Attach textfield components that edit properties map model
add(new TextField("username", properties));
add(new PasswordTextField("password", properties));
}
/**
* @see com.voicetribe.wicket.markup.html.form.Form#handleSubmit(com.voicetribe.wicket.RequestCycle)
*/
public final void handleSubmit(final RequestCycle cycle)
{
// Sign the user in
if (properties.getString("username").equals("jonathan") &&
properties.getString("password").equals("password"))
{
cycle.getSession().setProperty("user", "jonathan");
if (!cycle.continueToOriginalDestination())
{
cycle.setPage(new Home(PageParameters.NULL));
}
}
else
{
// Form method that will notify feedback panel
errorMessage("Couldn't sign you in");
}
}
// El-cheapo model for form
private final ValueMap properties = new ValueMap();
}
}
///////////////////////////////// End of File /////////////////////////////////
| new Model setup
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@454898 13f79535-47bb-0310-9956-ffa450edef68
| wicket-examples/src/java/signin/SignIn.java | new Model setup | <ide><path>icket-examples/src/java/signin/SignIn.java
<ide>
<ide> import com.voicetribe.util.value.ValueMap;
<ide> import com.voicetribe.wicket.PageParameters;
<add>import com.voicetribe.wicket.PropertyModel;
<ide> import com.voicetribe.wicket.RequestCycle;
<ide> import com.voicetribe.wicket.markup.html.HtmlPage;
<ide> import com.voicetribe.wicket.markup.html.form.Form;
<ide> super(componentName, feedback);
<ide>
<ide> // Attach textfield components that edit properties map model
<del> add(new TextField("username", properties));
<del> add(new PasswordTextField("password", properties));
<add> add(new TextField("username", new PropertyModel(properties, "username")));
<add> add(new PasswordTextField("password", new PropertyModel(properties, "password")));
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | bf29d771365383c31fda47f2b28d56d097e35511 | 0 | ccvcd/Mycat-Server,ccvcd/Mycat-Server,ccvcd/Mycat-Server,ccvcd/Mycat-Server,magicdoom/Mycat-Server,magicdoom/Mycat-Server,magicdoom/Mycat-Server,magicdoom/Mycat-Server | package demo.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author mycat
*
*/
public class TestClass1 {
public static void main( String args[] ) throws SQLException , ClassNotFoundException {
String jdbcdriver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://127.0.0.1:8066/TESTDB?useUnicode=true&characterEncoding=utf-8";
String username="test";
String password="test";
System.out.println("开始连接mysql:"+jdbcurl);
Class.forName(jdbcdriver);
Connection c = DriverManager.getConnection(jdbcurl,username,password);
Statement st = c.createStatement();
print( "test jdbc " , st.executeQuery("select count(*) from travelrecord "));
System.out.println("OK......");
}
static void print( String name , ResultSet res )
throws SQLException {
System.out.println( name);
ResultSetMetaData meta=res.getMetaData();
//System.out.println( "\t"+res.getRow()+"条记录");
String str="";
for(int i=1;i<=meta.getColumnCount();i++){
str+=meta.getColumnName(i)+" ";
//System.out.println( meta.getColumnName(i)+" ");
}
System.out.println("\t"+str);
str="";
while ( res.next() ){
for(int i=1;i<=meta.getColumnCount();i++){
str+= res.getString(i)+" ";
}
System.out.println("\t"+str);
str="";
}
}
}
| src/test/java/demo/test/TestClass1.java | package demo.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author mycat
*
*/
public class TestClass1 {
public static void main( String args[] ) throws SQLException , ClassNotFoundException {
String jdbcdriver="com.mysql.jdbc.Driver";
String jdbcurl="jdbc:mysql://127.0.0.1:8066/TESTDB?useUnicode=true&characterEncoding=utf-8";
String username="test";
String password="test";
System.out.println("开始连接mysql:"+jdbcurl);
Class.forName(jdbcdriver);
Connection c = DriverManager.getConnection(jdbcurl,username,password);
Statement st = c.createStatement();
print( "test jdbc " , st.executeQuery("select count(*) from t_sys_log "));
System.out.println("OK......");
}
static void print( String name , ResultSet res )
throws SQLException {
System.out.println( name);
ResultSetMetaData meta=res.getMetaData();
//System.out.println( "\t"+res.getRow()+"条记录");
String str="";
for(int i=1;i<=meta.getColumnCount();i++){
str+=meta.getColumnName(i)+" ";
//System.out.println( meta.getColumnName(i)+" ");
}
System.out.println("\t"+str);
str="";
while ( res.next() ){
for(int i=1;i<=meta.getColumnCount();i++){
str+= res.getString(i)+" ";
}
System.out.println("\t"+str);
str="";
}
}
}
| test jdbc | src/test/java/demo/test/TestClass1.java | test jdbc | <ide><path>rc/test/java/demo/test/TestClass1.java
<ide> Class.forName(jdbcdriver);
<ide> Connection c = DriverManager.getConnection(jdbcurl,username,password);
<ide> Statement st = c.createStatement();
<del> print( "test jdbc " , st.executeQuery("select count(*) from t_sys_log "));
<add> print( "test jdbc " , st.executeQuery("select count(*) from travelrecord "));
<ide> System.out.println("OK......");
<ide> }
<ide> |
|
JavaScript | mit | 6aff481e9bacf2702785a7f9b212c03a6622cf37 | 0 | BionicClick/mermaid,mehulsbhatt/mermaid,pnkfelix/mermaid,dbrans/mermaid,gillesdemey/mermaid,mehulsbhatt/mermaid,9n/mermaid,mcanthony/mermaid,wcy123/mermaid,dbrans/mermaid,mcanthony/mermaid,pnkfelix/mermaid,wuguanghai45/mermaid,knsv/mermaid,BionicClick/mermaid,wcy123/mermaid,DataMcFly/mermaid,codeaudit/mermaid,guiquanz/mermaid,DataMcFly/mermaid,tylingsoft/mermaid,ollie314/mermaid,mehulsbhatt/mermaid,mcanthony/mermaid,wewelove/mermaid,9n/mermaid,9n/mermaid,tylingsoft/mermaid,dbrans/mermaid,ollie314/mermaid,BionicClick/mermaid,tylingsoft/mermaid,gillesdemey/mermaid,wewelove/mermaid,wewelove/mermaid,Muoversi/mermaid,wuguanghai45/mermaid,codeaudit/mermaid,DataMcFly/mermaid,Muoversi/mermaid,Muoversi/mermaid,knsv/mermaid,codeaudit/mermaid,wuguanghai45/mermaid,guiquanz/mermaid,ollie314/mermaid,gillesdemey/mermaid,wcy123/mermaid,pnkfelix/mermaid,guiquanz/mermaid | var graph = require('./diagrams/flowchart/graphDb');
var flow = require('./diagrams/flowchart/parser/flow');
var utils = require('./utils');
var flowRenderer = require('./diagrams/flowchart/flowRenderer');
var seq = require('./diagrams/sequenceDiagram/sequenceRenderer');
var info = require('./diagrams/example/exampleRenderer');
var he = require('he');
var infoParser = require('./diagrams/example/parser/example');
var flowParser = require('./diagrams/flowchart/parser/flow');
var dotParser = require('./diagrams/flowchart/parser/dot');
var sequenceParser = require('./diagrams/sequenceDiagram/parser/sequenceDiagram');
var sequenceDb = require('./diagrams/sequenceDiagram/sequenceDb');
var infoDb = require('./diagrams/example/exampleDb');
var gantt = require('./diagrams/gantt/ganttRenderer');
var ganttParser = require('./diagrams/gantt/parser/gantt');
var ganttDb = require('./diagrams/gantt/ganttDb');
var nextId = 0;
/**
* Function that parses a mermaid diagram defintion. If parsing fails the parseError callback is called and an error is
* thrown and
* @param text
*/
var parse = function(text){
var graphType = utils.detectType(text);
var parser;
switch(graphType){
case 'graph':
parser = flowParser;
parser.parser.yy = graph;
break;
case 'dotGraph':
parser = dotParser;
parser.parser.yy = graph;
break;
case 'sequenceDiagram':
parser = sequenceParser;
parser.parser.yy = sequenceDb;
break;
case 'info':
parser = infoParser;
parser.parser.yy = infoDb;
break;
case 'gantt':
parser = ganttParser;
parser.parser.yy = ganttDb;
break;
}
try{
parser.parse(text);
return true;
}
catch(err){
return false;
}
};
/**
* Function that goes through the document to find the chart definitions in there and render them.
*
* The function tags the processed attributes with the attribute data-processed and ignores found elements with the
* attribute already set. This way the init function can be triggered several times.
*
* ```
* graph LR;
* a(Find elements)-->b{Processed};
* b-->|Yes|c(Leave element);
* c-->|No |d(Transform);
* ```
*/
var init = function (sequenceConfig) {
var arr = document.querySelectorAll('.mermaid');
var i;
if (sequenceConfig !== 'undefined' && (typeof sequenceConfig !== 'undefined')) {
if(typeof sequenceConfig === 'object'){
seq.setConf(sequenceConfig);
} else{
seq.setConf(JSON.parse(sequenceConfig));
}
}
for (i = 0; i < arr.length; i++) {
var element = arr[i];
// Check if previously processed
if(!element.getAttribute("data-processed")) {
element.setAttribute("data-processed", true);
} else {
continue;
}
id = 'mermaidChart' + nextId++;
var txt = element.innerHTML;
txt = txt.replace(/>/g,'>');
txt = txt.replace(/</g,'<');
txt = he.decode(txt).trim();
element.innerHTML = '<svg id="' + id + '" width="100%" xmlns="http://www.w3.org/2000/svg">' +
'<g />' +
'</svg>';
var graphType = utils.detectType(txt);
var classes = {};
switch(graphType){
case 'graph':
classes = flowRenderer.getClasses(txt, false);
if(typeof mermaid.flowchartConfig === 'object'){
flowRenderer.setConf(mermaid.flowchartConfig);
}
flowRenderer.draw(txt, id, false);
utils.cloneCssStyles(element.firstChild, classes);
graph.bindFunctions();
break;
case 'dotGraph':
classes = flowRenderer.getClasses(txt, true);
flowRenderer.draw(txt, id, true);
utils.cloneCssStyles(element.firstChild, classes);
break;
case 'sequenceDiagram':
seq.draw(txt,id);
utils.cloneCssStyles(element.firstChild, []);
break;
case 'gantt':
if(typeof mermaid.ganttConfig === 'object'){
gantt.setConf(mermaid.ganttConfig);
}
gantt.draw(txt,id);
utils.cloneCssStyles(element.firstChild, []);
break;
case 'info':
info.draw(txt,id,exports.version());
utils.cloneCssStyles(element.firstChild, []);
break;
}
}
};
exports.tester = function(){};
/**
* Function returning version information
* @returns {string} A string containing the version info
*/
exports.version = function(){
return require('../package.json').version;
};
var equals = function (val, variable){
if(typeof variable === 'undefined'){
return false;
}
else{
return (val === variable);
}
};
global.mermaid = {
startOnLoad:true,
htmlLabels:true,
init:function(sequenceConfig){
init(sequenceConfig);
},
version:function(){
return exports.version();
},
getParser:function(){
return flow.parser;
},
parse:function(text){
return parse(text);
},
parseError:function(err,hash){
console.log('Mermaid Syntax error:');
console.log(err);
}
};
exports.contentLoaded = function(){
// Check state of start config mermaid namespece
//console.log('global.mermaid.startOnLoad',global.mermaid.startOnLoad);
//console.log('mermaid_config',mermaid_config);
if (typeof mermaid_config !== 'undefined') {
if (equals(false, mermaid_config.htmlLabels)) {
global.mermaid.htmlLabels = false;
}
}
if(global.mermaid.startOnLoad) {
// For backwards compatability reasons also check mermaid_config variable
if (typeof mermaid_config !== 'undefined') {
// Check if property startOnLoad is set
if (equals(true, mermaid_config.startOnLoad)) {
global.mermaid.init(mermaid.sequenceConfig);
}
}
else {
// No config found, do autostart in this simple case
global.mermaid.init(mermaid.sequenceConfig);
}
}
};
if(typeof document !== 'undefined'){
/**
* Wait for document loaded before starting the execution
*/
document.addEventListener('DOMContentLoaded', function(){
exports.contentLoaded();
}, false);
}
| src/main.js | var graph = require('./diagrams/flowchart/graphDb');
var flow = require('./diagrams/flowchart/parser/flow');
var utils = require('./utils');
var flowRenderer = require('./diagrams/flowchart/flowRenderer');
var seq = require('./diagrams/sequenceDiagram/sequenceRenderer');
var info = require('./diagrams/example/exampleRenderer');
var he = require('he');
var infoParser = require('./diagrams/example/parser/example');
var flowParser = require('./diagrams/flowchart/parser/flow');
var dotParser = require('./diagrams/flowchart/parser/dot');
var sequenceParser = require('./diagrams/sequenceDiagram/parser/sequenceDiagram');
var sequenceDb = require('./diagrams/sequenceDiagram/sequenceDb');
var infoDb = require('./diagrams/example/exampleDb');
var gantt = require('./diagrams/gantt/ganttRenderer');
var ganttParser = require('./diagrams/gantt/parser/gantt');
var ganttDb = require('./diagrams/gantt/ganttDb');
/**
* Function that parses a mermaid diagram defintion. If parsing fails the parseError callback is called and an error is
* thrown and
* @param text
*/
var parse = function(text){
var graphType = utils.detectType(text);
var parser;
switch(graphType){
case 'graph':
parser = flowParser;
parser.parser.yy = graph;
break;
case 'dotGraph':
parser = dotParser;
parser.parser.yy = graph;
break;
case 'sequenceDiagram':
parser = sequenceParser;
parser.parser.yy = sequenceDb;
break;
case 'info':
parser = infoParser;
parser.parser.yy = infoDb;
break;
case 'gantt':
parser = ganttParser;
parser.parser.yy = ganttDb;
break;
}
try{
parser.parse(text);
return true;
}
catch(err){
return false;
}
};
/**
* Function that goes through the document to find the chart definitions in there and render them.
*
* The function tags the processed attributes with the attribute data-processed and ignores found elements with the
* attribute already set. This way the init function can be triggered several times.
*
* ```
* graph LR;
* a(Find elements)-->b{Processed};
* b-->|Yes|c(Leave element);
* c-->|No |d(Transform);
* ```
*/
var init = function (sequenceConfig) {
var arr = document.querySelectorAll('.mermaid');
var i;
if (sequenceConfig !== 'undefined' && (typeof sequenceConfig !== 'undefined')) {
if(typeof sequenceConfig === 'object'){
seq.setConf(sequenceConfig);
} else{
seq.setConf(JSON.parse(sequenceConfig));
}
}
var cnt = 0;
for (i = 0; i < arr.length; i++) {
var element = arr[i];
// Check if previously processed
if(!element.getAttribute("data-processed")) {
element.setAttribute("data-processed", true);
} else {
continue;
}
var id;
id = 'mermaidChart' + cnt;
cnt++;
var txt = element.innerHTML;
txt = txt.replace(/>/g,'>');
txt = txt.replace(/</g,'<');
txt = he.decode(txt).trim();
element.innerHTML = '<svg id="' + id + '" width="100%" xmlns="http://www.w3.org/2000/svg">' +
'<g />' +
'</svg>';
var graphType = utils.detectType(txt);
var classes = {};
switch(graphType){
case 'graph':
classes = flowRenderer.getClasses(txt, false);
if(typeof mermaid.flowchartConfig === 'object'){
flowRenderer.setConf(mermaid.flowchartConfig);
}
flowRenderer.draw(txt, id, false);
utils.cloneCssStyles(element.firstChild, classes);
graph.bindFunctions();
break;
case 'dotGraph':
classes = flowRenderer.getClasses(txt, true);
flowRenderer.draw(txt, id, true);
utils.cloneCssStyles(element.firstChild, classes);
break;
case 'sequenceDiagram':
seq.draw(txt,id);
utils.cloneCssStyles(element.firstChild, []);
break;
case 'gantt':
if(typeof mermaid.ganttConfig === 'object'){
gantt.setConf(mermaid.ganttConfig);
}
gantt.draw(txt,id);
utils.cloneCssStyles(element.firstChild, []);
break;
case 'info':
info.draw(txt,id,exports.version());
utils.cloneCssStyles(element.firstChild, []);
break;
}
}
};
exports.tester = function(){};
/**
* Function returning version information
* @returns {string} A string containing the version info
*/
exports.version = function(){
return require('../package.json').version;
};
var equals = function (val, variable){
if(typeof variable === 'undefined'){
return false;
}
else{
return (val === variable);
}
};
global.mermaid = {
startOnLoad:true,
htmlLabels:true,
init:function(sequenceConfig){
init(sequenceConfig);
},
version:function(){
return exports.version();
},
getParser:function(){
return flow.parser;
},
parse:function(text){
return parse(text);
},
parseError:function(err,hash){
console.log('Mermaid Syntax error:');
console.log(err);
}
};
exports.contentLoaded = function(){
// Check state of start config mermaid namespece
//console.log('global.mermaid.startOnLoad',global.mermaid.startOnLoad);
//console.log('mermaid_config',mermaid_config);
if (typeof mermaid_config !== 'undefined') {
if (equals(false, mermaid_config.htmlLabels)) {
global.mermaid.htmlLabels = false;
}
}
if(global.mermaid.startOnLoad) {
// For backwards compatability reasons also check mermaid_config variable
if (typeof mermaid_config !== 'undefined') {
// Check if property startOnLoad is set
if (equals(true, mermaid_config.startOnLoad)) {
global.mermaid.init(mermaid.sequenceConfig);
}
}
else {
// No config found, do autostart in this simple case
global.mermaid.init(mermaid.sequenceConfig);
}
}
};
if(typeof document !== 'undefined'){
/**
* Wait for document loaded before starting the execution
*/
document.addEventListener('DOMContentLoaded', function(){
exports.contentLoaded();
}, false);
}
| Use a library-level variable for assigning ids
The current behavior is unexpected when re-running `init()`, as every run through will start with the first `.mermaid` it finds, and start re-indexing at 0, irrespective if the original `id=mermaidChart0` is still around.
This change ensures that successive runs will not clobber old ones. | src/main.js | Use a library-level variable for assigning ids | <ide><path>rc/main.js
<ide> var gantt = require('./diagrams/gantt/ganttRenderer');
<ide> var ganttParser = require('./diagrams/gantt/parser/gantt');
<ide> var ganttDb = require('./diagrams/gantt/ganttDb');
<add>
<add>var nextId = 0;
<ide>
<ide> /**
<ide> * Function that parses a mermaid diagram defintion. If parsing fails the parseError callback is called and an error is
<ide> }
<ide> }
<ide>
<del> var cnt = 0;
<ide> for (i = 0; i < arr.length; i++) {
<ide> var element = arr[i];
<ide>
<ide> continue;
<ide> }
<ide>
<del> var id;
<del>
<del> id = 'mermaidChart' + cnt;
<del> cnt++;
<add> id = 'mermaidChart' + nextId++;
<ide>
<ide> var txt = element.innerHTML;
<ide> txt = txt.replace(/>/g,'>'); |
|
Java | mit | 63df10126f7bde92f8a52666b05ce7ab0d3e66dd | 0 | ivoryworks/PGMA | package com.ivoryworks.pgma;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TakePhotoFragment extends Fragment implements View.OnClickListener {
private final int REQ_CODE_ACTION_IMAGE_CAPTURE = 1;
private Uri mPhotoUri;
private ImageView mPreviewPhoto;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment TakePhotoFragment.
*/
// TODO: Rename and change types and number of parameters
public static TakePhotoFragment newInstance() {
TakePhotoFragment fragment = new TakePhotoFragment();
return fragment;
}
public TakePhotoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layoutView = inflater.inflate(R.layout.fragment_take_photo, container, false);
layoutView.findViewById(R.id.btnCamera).setOnClickListener(this);
mPreviewPhoto = (ImageView) layoutView.findViewById(R.id.previewPhoto);
return layoutView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCamera:
mPhotoUri = createPhotoUri();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent, REQ_CODE_ACTION_IMAGE_CAPTURE);
break;
default:
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CODE_ACTION_IMAGE_CAPTURE:
if (resultCode == Activity.RESULT_OK) {
int orientation = getOrientationType(mPhotoUri);
// mPreviewPhoto.setImageURI(mPhotoUri);
setMatrix(mPreviewPhoto, mPhotoUri, orientation);
}
break;
}
}
private Uri createPhotoUri() {
// DCIM directory
File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String timeStamp = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss").format(new Date());
File mediaFile = new File(dcim.getPath() + File.separator + timeStamp + ".jpg");
return Uri.fromFile(mediaFile);
}
private int getOrientationType(Uri uri) {
ExifInterface exifIf = null;
try {
exifIf = new ExifInterface(uri.getPath());
} catch (IOException e) {
e.printStackTrace();
}
return exifIf.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
}
private void setMatrix(ImageView imageView, Uri photoUri, int orientationType) {
Context context = getActivity().getBaseContext();
try {
Bitmap photoBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), photoUri);
int width = photoBitmap.getWidth();
int height = photoBitmap.getHeight();
Bitmap rotateBitmap;
Matrix mat = new Matrix();
switch(orientationType) {
case ExifInterface.ORIENTATION_NORMAL:
rotateBitmap = photoBitmap;
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
rotateBitmap = photoBitmap;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
mat.postRotate(180);
rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
rotateBitmap = photoBitmap;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
mat.postRotate(270);
rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
mat.postRotate(90);
rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
rotateBitmap = photoBitmap;
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
rotateBitmap = photoBitmap;
break;
case ExifInterface.ORIENTATION_UNDEFINED:
default:
rotateBitmap = photoBitmap;
break;
}
imageView.setImageBitmap(rotateBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| com.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/TakePhotoFragment.java | package com.ivoryworks.pgma;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TakePhotoFragment extends Fragment implements View.OnClickListener {
private final int REQ_CODE_ACTION_IMAGE_CAPTURE = 1;
private File mDCIM;
private Uri mPhotoUri;
private ImageView mPreviewPhoto;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment TakePhotoFragment.
*/
// TODO: Rename and change types and number of parameters
public static TakePhotoFragment newInstance() {
TakePhotoFragment fragment = new TakePhotoFragment();
return fragment;
}
public TakePhotoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// DCIM directory
mDCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String timeStamp = new SimpleDateFormat(
"yyyy_MM_dd__HH_mm_ss").format(new Date());
File mediaFile = new File(mDCIM.getPath() + File.separator + timeStamp + ".jpg");
mPhotoUri = Uri.fromFile(mediaFile);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layoutView = inflater.inflate(R.layout.fragment_take_photo, container, false);
layoutView.findViewById(R.id.btnCamera).setOnClickListener(this);
mPreviewPhoto = (ImageView) layoutView.findViewById(R.id.previewPhoto);
return layoutView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCamera:
//mPhotoUri = Uri.parse(mDCIM.getPath() + "/test.jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent, REQ_CODE_ACTION_IMAGE_CAPTURE);
break;
default:
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CODE_ACTION_IMAGE_CAPTURE:
if (resultCode == Activity.RESULT_OK) {
mPreviewPhoto.setImageURI(mPhotoUri);
}
break;
}
}
}
| [fix]#5 カメラから読み込んだ画像をImageViewに表示すると向きが不正である問題
Exif情報から画像向きを取得判定し、Bitmapを回転してからImageViewへ
セットするよう修正
* 反転、および反転+回転の特性をもつ写真について未対応
| com.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/TakePhotoFragment.java | [fix]#5 カメラから読み込んだ画像をImageViewに表示すると向きが不正である問題 | <ide><path>om.ivoryworks.pgma/app/src/main/java/com/ivoryworks/pgma/TakePhotoFragment.java
<ide> package com.ivoryworks.pgma;
<ide>
<ide> import android.app.Activity;
<add>import android.content.Context;
<ide> import android.content.Intent;
<add>import android.graphics.Bitmap;
<add>import android.graphics.Matrix;
<add>import android.media.ExifInterface;
<ide> import android.net.Uri;
<ide> import android.os.Bundle;
<ide> import android.os.Environment;
<ide> import android.provider.MediaStore;
<add>import android.support.v4.app.Fragment;
<ide> import android.view.LayoutInflater;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<del>import android.support.v4.app.Fragment;
<ide> import android.widget.ImageView;
<ide>
<ide> import java.io.File;
<add>import java.io.IOException;
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.Date;
<ide>
<ide> public class TakePhotoFragment extends Fragment implements View.OnClickListener {
<ide>
<ide> private final int REQ_CODE_ACTION_IMAGE_CAPTURE = 1;
<del> private File mDCIM;
<ide> private Uri mPhotoUri;
<ide> private ImageView mPreviewPhoto;
<ide>
<ide> @Override
<ide> public void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<del> // DCIM directory
<del> mDCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
<del> String timeStamp = new SimpleDateFormat(
<del> "yyyy_MM_dd__HH_mm_ss").format(new Date());
<del> File mediaFile = new File(mDCIM.getPath() + File.separator + timeStamp + ".jpg");
<del> mPhotoUri = Uri.fromFile(mediaFile);
<ide> }
<ide>
<ide> @Override
<ide> public void onClick(View v) {
<ide> switch (v.getId()) {
<ide> case R.id.btnCamera:
<del> //mPhotoUri = Uri.parse(mDCIM.getPath() + "/test.jpg");
<add> mPhotoUri = createPhotoUri();
<ide> Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
<ide> intent.addCategory(Intent.CATEGORY_DEFAULT);
<ide> intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
<ide> switch (requestCode) {
<ide> case REQ_CODE_ACTION_IMAGE_CAPTURE:
<ide> if (resultCode == Activity.RESULT_OK) {
<del> mPreviewPhoto.setImageURI(mPhotoUri);
<add> int orientation = getOrientationType(mPhotoUri);
<add>// mPreviewPhoto.setImageURI(mPhotoUri);
<add> setMatrix(mPreviewPhoto, mPhotoUri, orientation);
<ide> }
<ide> break;
<ide> }
<ide> }
<add>
<add> private Uri createPhotoUri() {
<add> // DCIM directory
<add> File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
<add>
<add> String timeStamp = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss").format(new Date());
<add> File mediaFile = new File(dcim.getPath() + File.separator + timeStamp + ".jpg");
<add> return Uri.fromFile(mediaFile);
<add> }
<add>
<add> private int getOrientationType(Uri uri) {
<add> ExifInterface exifIf = null;
<add> try {
<add> exifIf = new ExifInterface(uri.getPath());
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<add> return exifIf.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
<add> }
<add>
<add> private void setMatrix(ImageView imageView, Uri photoUri, int orientationType) {
<add> Context context = getActivity().getBaseContext();
<add> try {
<add> Bitmap photoBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), photoUri);
<add> int width = photoBitmap.getWidth();
<add> int height = photoBitmap.getHeight();
<add> Bitmap rotateBitmap;
<add> Matrix mat = new Matrix();
<add> switch(orientationType) {
<add> case ExifInterface.ORIENTATION_NORMAL:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> case ExifInterface.ORIENTATION_FLIP_VERTICAL:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> case ExifInterface.ORIENTATION_ROTATE_180:
<add> mat.postRotate(180);
<add> rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
<add> break;
<add> case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> case ExifInterface.ORIENTATION_ROTATE_270:
<add> mat.postRotate(270);
<add> rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
<add> break;
<add> case ExifInterface.ORIENTATION_ROTATE_90:
<add> mat.postRotate(90);
<add> rotateBitmap = Bitmap.createBitmap(photoBitmap, 0, 0, width, height, mat, true);
<add> break;
<add> case ExifInterface.ORIENTATION_TRANSPOSE:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> case ExifInterface.ORIENTATION_TRANSVERSE:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> case ExifInterface.ORIENTATION_UNDEFINED:
<add> default:
<add> rotateBitmap = photoBitmap;
<add> break;
<add> }
<add> imageView.setImageBitmap(rotateBitmap);
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<add> }
<ide> } |
|
Java | lgpl-2.1 | 0b6cd78a032ab873e063bef3a89126a62827b3a1 | 0 | gallardo/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,victos/opencms-core,serrapos/opencms-core,victos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,victos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,alkacon/opencms-core,gallardo/opencms-core,serrapos/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,it-tavis/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/monitor/CmsMemoryMonitor.java,v $
* Date : $Date: 2003/11/12 14:42:45 $
* Version: $Revision: 1.13 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2003 Alkacon Software (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, 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.monitor;
import org.opencms.cache.CmsLruCache;
import org.opencms.cache.I_CmsLruCacheObject;
import org.opencms.cron.I_CmsCronJob;
import org.opencms.flex.CmsFlexCache.CmsFlexCacheVariation;
import org.opencms.main.CmsEvent;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsEventListener;
import org.opencms.main.OpenCms;
import org.opencms.main.OpenCmsCore;
import org.opencms.main.OpenCmsSessionManager;
import org.opencms.security.CmsAccessControlList;
import org.opencms.security.CmsPermissionSet;
import org.opencms.util.PrintfFormat;
import com.opencms.core.CmsCoreSession;
import com.opencms.core.CmsException;
import com.opencms.defaults.CmsMail;
import com.opencms.file.CmsFile;
import com.opencms.file.CmsGroup;
import com.opencms.file.CmsObject;
import com.opencms.file.CmsProject;
import com.opencms.file.CmsResource;
import com.opencms.file.CmsUser;
import com.opencms.util.Utils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.collections.LRUMap;
/**
* Monitors OpenCms memory consumtion.<p>
*
* @version $Revision: 1.13 $ $Date: 2003/11/12 14:42:45 $
*
* @author Carsten Weinholz ([email protected])
* @author Michael Emmerich ([email protected])
* @author Alexander Kandzior ([email protected])
*/
public class CmsMemoryMonitor implements I_CmsCronJob {
/** set interval for clearing the caches to 15 minutes */
private static final int C_INTERVAL_CLEAR = 1000 * 60 * 15;
/** max depth for object size recursion */
private static final int C_MAX_DEPTH = 5;
private static boolean m_currentlyRunning = false;
/** receivers fro status emails */
private String[] m_emailReceiver;
/** sender for status emails */
private String m_emailSender;
/** the interval to use for sending emails */
private int m_intervalEmail;
/** the interval to use for the logging */
private int m_intervalLog;
/** the interval to use for warnings if status is disabled */
private int m_intervalWarning;
/** the time the caches where last cleared */
private long m_lastClearCache;
/** the time the last status email was send */
private long m_lastEmailStatus;
/** the time the last warning email was send */
private long m_lastEmailWarning;
/** the time the last status log was written */
private long m_lastLogStatus;
/** the time the last warning log was written */
private long m_lastLogWarning;
/** memory limit that triggers a warning */
private int m_maxUsagePercent;
/** contains the object to be monitored */
private Map m_monitoredObjects;
/** flag for memory warning mail send */
private boolean m_warningSendSinceLastStatus;
/** flag for memory warning mail send */
private boolean m_warningLoggedSinceLastStatus;
/**
* Empty constructor, required by OpenCms scheduler.<p>
*/
public CmsMemoryMonitor() {
// empty
}
/**
* Creates a new monitor with the provided configuration.<p>
*
* @param configuration the configuration to use
*/
public CmsMemoryMonitor(ExtendedProperties configuration) {
m_warningSendSinceLastStatus = false;
m_warningLoggedSinceLastStatus = false;
m_lastEmailWarning = 0;
m_lastEmailStatus = 0;
m_lastLogStatus = 0;
m_lastLogWarning = 0;
m_lastClearCache = 0;
m_monitoredObjects = new HashMap();
m_emailSender = configuration.getString("memorymonitor.email.sender", null);
m_emailReceiver = configuration.getStringArray("memorymonitor.email.receiver");
m_intervalEmail = configuration.getInteger("memorymonitor.email.interval", 0) * 60000;
m_intervalLog = configuration.getInteger("memorymonitor.log.interval", 0) * 60000;
m_intervalWarning = configuration.getInteger("memorymonitor.warning.interval", 360) * 60000;
m_maxUsagePercent = configuration.getInteger("memorymonitor.maxUsagePercent", 90);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval log : " + (m_intervalLog / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval email : " + (m_intervalEmail / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval warning : " + (m_intervalWarning / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM max usage : " + m_maxUsagePercent + "%");
if ((m_emailReceiver == null) || (m_emailSender == null)) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email : disabled");
} else {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email sender : " + m_emailSender);
for (int i=0, s=m_emailReceiver.length; i < s; i++) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email receiver : " + (i+1) + " - " + m_emailReceiver[i]);
}
}
}
if (OpenCms.getLog(this).isDebugEnabled()) {
// this will happen only once during system startup
OpenCms.getLog(this).debug(", New instance of CmsMemoryMonitor created at " + (new Date(System.currentTimeMillis())));
}
}
/**
* Initalizes the Memory Monitor.<p>
*
* @param configuration the OpenCms configurations
* @return the initialized CmsMemoryMonitor
*/
public static CmsMemoryMonitor initialize(ExtendedProperties configuration) {
return new CmsMemoryMonitor(configuration);
}
/**
* Clears the OpenCms caches.<p>
*/
private void clearCaches() {
if ((m_lastClearCache + C_INTERVAL_CLEAR) > System.currentTimeMillis()) {
// if the cache has already been cleared less then 15 minutes ago we skip this because
// clearing the caches to often will hurt system performance and the
// setup seems to be in trouble anyway
return;
}
m_lastClearCache = System.currentTimeMillis();
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn(", Clearing caches because memory consumption has reached a critical level");
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false));
System.gc();
}
/**
* Returns if monitoring is enabled.<p>
*
* @return true if monitoring is enabled
*/
public boolean enabled() {
return true;
}
/**
* Returns the cache costs of a monitored object.<p>
* obj must be of type CmsLruCache
*
* @param obj the object
* @return the cache costs or "-"
*/
private long getCosts(Object obj) {
long costs = 0;
if (obj instanceof CmsLruCache) {
costs = ((CmsLruCache)obj).getObjectCosts();
if (costs < 0) {
costs = 0;
}
}
return costs;
}
/**
* Returns the number of items within a monitored object.<p>
* obj must be of type CmsLruCache, CmsLruHashMap or Map
*
* @param obj the object
* @return the number of items or "-"
*/
private String getItems(Object obj) {
if (obj instanceof CmsLruCache) {
return Integer.toString(((CmsLruCache)obj).size());
}
if (obj instanceof Map) {
return Integer.toString(((Map)obj).size());
}
return "-";
}
/**
* Returns the total size of key strings within a monitored object.<p>
* obj must be of type map, the keys must be of type String.
*
* @param obj the object
* @return the total size of key strings
*/
private long getKeySize(Object obj) {
if (obj instanceof Map) {
return getKeySize ((Map)obj, 1);
}
return 0;
}
/**
* Returns the total size of key strings within a monitored map.<p>
* the keys must be of type String.
*
* @param map the map
* @param depth the max recursion depth for calculation the size
* @return total size of key strings
*/
private long getKeySize(Map map, int depth) {
long keySize = 0;
Object[] values = map.values().toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof Map && depth < C_MAX_DEPTH) {
keySize += getKeySize((Map)obj, depth+1);
continue;
}
}
values = null;
Object[] keys = map.keySet().toArray();
for (int i=0, s=keys.length; i<s; i++) {
Object obj = keys[i];
if (obj instanceof String) {
String st = (String)obj;
keySize += (st.length() * 2);
}
}
return keySize;
}
/**
* Returns the max costs for all items within a monitored object.<p>
* obj must be of type CmsLruCache, CmsLruHashMap
*
* @param obj the object
* @return max cost limit or "-"
*/
private String getLimit(Object obj) {
if (obj instanceof CmsLruCache) {
return Integer.toString(((CmsLruCache)obj).getMaxCacheCosts());
}
if (obj instanceof LRUMap) {
return Integer.toString(((LRUMap)obj).getMaximumSize());
}
return "-";
}
/**
* Returns the value sizes of value objects within the monitored object.<p>
* obj must be of type map
*
* @param obj the object
* @return the value sizes of value objects or "-"-fields
*/
private long getValueSize(Object obj) {
if (obj instanceof CmsLruCache) {
return ((CmsLruCache)obj).size();
}
if (obj instanceof Map) {
return getValueSize((Map)obj, 1);
}
if (obj instanceof List) {
return getValueSize((List)obj, 1);
}
try {
return getMemorySize(obj);
} catch (Exception exc) {
return 0;
}
}
/**
* Returns the total value size of a map object.<p>
*
* @param mapValue the map object
* @param depth the max recursion depth for calculation the size
* @return the size of the map object
*/
private long getValueSize(Map mapValue, int depth) {
long totalSize = 0;
Object[] values = mapValue.values().toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof CmsAccessControlList) {
obj = ((CmsAccessControlList)obj).getPermissionMap();
}
if (obj instanceof CmsFlexCacheVariation) {
obj = ((CmsFlexCacheVariation)obj).m_map;
}
if (obj instanceof Map && depth < C_MAX_DEPTH) {
totalSize += getValueSize((Map)obj, depth+1);
continue;
}
if (obj instanceof List && depth < C_MAX_DEPTH) {
totalSize += getValueSize((List)obj, depth+1);
continue;
}
totalSize += getMemorySize(obj);
}
return totalSize;
}
/**
* Returns the total value size of a list object.<p>
*
* @param listValue the list object
* @param depth the max recursion depth for calculation the size
* @return the size of the list object
*/
private long getValueSize(List listValue, int depth) {
long totalSize = 0;
Object[] values = listValue.toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof CmsAccessControlList) {
obj = ((CmsAccessControlList)obj).getPermissionMap();
}
if (obj instanceof CmsFlexCacheVariation) {
obj = ((CmsFlexCacheVariation)obj).m_map;
}
if (obj instanceof Map && depth < C_MAX_DEPTH) {
totalSize += getValueSize((Map)obj, depth+1);
continue;
}
if (obj instanceof List && depth < C_MAX_DEPTH) {
totalSize += getValueSize((List)obj, depth+1);
continue;
}
totalSize += getMemorySize(obj);
}
return totalSize;
}
/**
* Returns the size of objects that are instances of
* <code>byte[]</code>, <code>String</code>, <code>CmsFile</code>,<code>I_CmsLruCacheObject</code>.<p>
* For other objects, a size of 0 is returned.
*
* @param obj the object
* @return the size of the object
*/
private long getMemorySize(Object obj) {
if (obj instanceof I_CmsLruCacheObject) {
return ((I_CmsLruCacheObject)obj).getLruCacheCosts();
}
if (obj instanceof byte[]) {
return ((byte[])obj).length;
}
if (obj instanceof String) {
return ((String)obj).length() * 2;
}
if (obj instanceof CmsFile) {
CmsFile f = (CmsFile)obj;
if (f.getContents() != null) {
return f.getContents().length;
}
}
if (obj instanceof CmsPermissionSet) {
return 8; // two ints
}
if (obj instanceof CmsResource) {
return 512; // estimated size
}
if (obj instanceof CmsUser) {
return 1024; // estimated size
}
if (obj instanceof CmsGroup) {
return 260; // estimated size
}
if (obj instanceof CmsProject) {
return 344;
}
if (obj instanceof Boolean) {
return 1; // one boolean
}
// System.err.println("Unresolved: " + obj.getClass().getName());
return 0;
}
/**a
* @see org.opencms.cron.I_CmsCronJob#launch(com.opencms.file.CmsObject, java.lang.String)
*/
public String launch(CmsObject cms, String params) throws Exception {
CmsMemoryMonitor monitor = OpenCms.getMemoryMonitor();
if (m_currentlyRunning) {
return "";
} else {
m_currentlyRunning = true;
}
// check if the system is in a low memory condition
if (monitor.lowMemory()) {
// log warning
monitor.monitorWriteLog(true);
// send warning email
monitor.monitorSendEmail(true);
// clean up caches
monitor.clearCaches();
}
// check if regular a log entry must be written
if ((System.currentTimeMillis() - monitor.m_lastLogStatus) > monitor.m_intervalLog) {
monitor.monitorWriteLog(false);
}
// check if the memory status email must be send
if ((System.currentTimeMillis() - monitor.m_lastEmailStatus) > monitor.m_intervalEmail) {
monitor.monitorSendEmail(false);
}
m_currentlyRunning = false;
return "";
}
/**
* Returns true if the system runs low on memory.<p>
*
* @return true if the system runs low on memory
*/
public boolean lowMemory() {
long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long usage = usedMemory * 100 / Runtime.getRuntime().maxMemory();
return ((m_maxUsagePercent > 0) && (usage > m_maxUsagePercent));
}
/**
* Sends a warning or status email with OpenCms Memory information.<p>
*
* @param warning if true, send a memory warning email
*/
private void monitorSendEmail(boolean warning) {
if ((m_emailSender == null) || (m_emailReceiver == null)) {
// send no mails if not fully configured
return;
} else if (warning && (m_warningSendSinceLastStatus && !((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning))))) {
// send no warning email if no status email has been send since the last warning
// if status is disabled, send no warn email if warn interval has not passed
return;
} else if ((! warning) && (m_intervalEmail <= 0)) {
// if email iterval is <= 0 status email is disabled
return;
}
String date = Utils.getNiceDate(System.currentTimeMillis());
String subject;
String content = "";
if (warning) {
m_warningSendSinceLastStatus = true;
m_lastEmailWarning = System.currentTimeMillis();
subject = "OpenCms Memory W A R N I N G [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
content += "W A R N I N G !\nOpenCms memory consumption on server " + OpenCms.getServerName().toUpperCase() + " has reached a critical level !\n\n"
+ "The configured limit is " + m_maxUsagePercent + "%\n\n";
} else {
m_warningSendSinceLastStatus = false;
m_lastEmailStatus = System.currentTimeMillis();
subject = "OpenCms Memory Status [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
}
long maxMemory = Runtime.getRuntime().maxMemory() / 1048576;
long totalMemory = Runtime.getRuntime().totalMemory() / 1048576;
long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
long freeMemory = maxMemory - usedMemory;
long usage = usedMemory * 100 / maxMemory;
content += "Memory usage report of OpenCms server " + OpenCms.getServerName().toUpperCase() + " at " + date + "\n\n"
+ "Memory maximum heap size: " + maxMemory + " mb\n"
+ "Memory current heap size: " + totalMemory + " mb\n\n"
+ "Memory currently used : " + usedMemory + " mb (" + usage + "%)\n"
+ "Memory currently unused : " + freeMemory + " mb\n\n\n";
if (warning) {
content += "*** Please take action NOW to ensure that no OutOfMemoryException occurs.\n\n\n";
}
OpenCmsSessionManager sm = OpenCmsCore.getInstance().getSessionManager();
CmsCoreSession cs = OpenCmsCore.getInstance().getSessionStorage();
if ((sm != null) && (cs != null)) {
content += "Current status of the sessions:\n\n";
content += "Logged in users : " + cs.getLoggedInUsers().size() + "\n";
content += "Currently active sessions: " + sm.getCurrentSessions() + "\n";
content += "Total created sessions : " + sm.getTotalSessions() + "\n\n\n";
}
sm = null;
cs = null;
content += "Current status of the caches:\n\n";
List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
Collections.sort(keyList);
long totalSize = 0;
for (Iterator keys = keyList.iterator(); keys.hasNext();) {
String key = (String)keys.next();
String shortKeys[] = key.split("\\.");
String shortKey = shortKeys[shortKeys.length - 2] + "." + shortKeys[shortKeys.length - 1];
PrintfFormat form = new PrintfFormat("%9s");
Object obj = m_monitoredObjects.get(key);
long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
totalSize += size;
content += new PrintfFormat("%-42.42s").sprintf(shortKey) + " "
+ "Entries: " + form.sprintf(getItems(obj)) + " "
+ "Limit: " + form.sprintf(getLimit(obj)) + " "
+ "Size: " + form.sprintf(Long.toString(size)) + "\n";
}
content += "\nTotal size of cache memory monitored: " + totalSize + " (" + totalSize / 1048576 + ")\n\n";
String from = m_emailSender;
String[] to = m_emailReceiver;
try {
if (from != null && to != null) {
CmsMail email = new CmsMail(from, to, subject, content, "text/plain");
email.start();
}
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info(", Memory Monitor " + (warning?"warning":"status") + " email send");
}
} catch (CmsException e) {
e.printStackTrace();
}
}
/**
* Write a warning or status log entry with OpenCms Memory information.<p>
*
* @param warning if true, write a memory warning log entry
*/
private void monitorWriteLog(boolean warning) {
if (! OpenCms.getLog(this).isWarnEnabled()) {
// we need at last warn level for this output
return;
} else if ((! warning) && (! OpenCms.getLog(this).isDebugEnabled())) {
// if not warning we need debug level
return;
} else if (warning && (m_warningLoggedSinceLastStatus && !(((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))))) {
// write no warning log if no status log has been written since the last warning
// if status is disabled, log no warn entry if warn interval has not passed
return;
} else if ((! warning) && (m_intervalLog <= 0)) {
// if log iterval is <= 0 status log is disabled
return;
}
long maxMemory = Runtime.getRuntime().maxMemory() / 1048576;
long totalMemory = Runtime.getRuntime().totalMemory() / 1048576;
long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
long freeMemory = maxMemory - usedMemory;
long usage = usedMemory * 100 / maxMemory;
if (warning) {
m_lastLogWarning = System.currentTimeMillis();
m_warningLoggedSinceLastStatus = true;
OpenCms.getLog(this).warn(", W A R N I N G Memory consumption of " + usage
+ "% has reached a critical level"
+ " (" + m_maxUsagePercent + "% configured)");
} else {
m_warningLoggedSinceLastStatus = false;
m_lastLogStatus = System.currentTimeMillis();
}
String memStatus = ", Memory max: " + maxMemory + " mb "
+ "total: " + totalMemory + " mb "
+ "free: " + freeMemory + " mb "
+ "used: " + usedMemory + " mb";
if (warning) {
OpenCms.getLog(this).warn(memStatus);
} else {
OpenCms.getLog(this).debug(", Memory monitor log for server " + OpenCms.getServerName().toUpperCase());
List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
Collections.sort(keyList);
long totalSize = 0;
for (Iterator keys = keyList.iterator(); keys.hasNext();) {
String key = (String)keys.next();
Object obj = m_monitoredObjects.get(key);
long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
totalSize += size;
PrintfFormat name1 = new PrintfFormat("%-80s");
PrintfFormat name2 = new PrintfFormat("%-50s");
PrintfFormat form = new PrintfFormat("%9s");
OpenCms.getLog(this).debug(",, "
+ "Monitored:, " + name1.sprintf(key) + ", "
+ "Type:, " + name2.sprintf(obj.getClass().getName()) + ", "
+ "Entries:, " + form.sprintf(getItems(obj)) + ", "
+ "Limit:, " + form.sprintf(getLimit(obj)) + ", "
+ "Size:, " + form.sprintf(Long.toString(size)));
}
memStatus += " " + "size monitored: " + totalSize + " (" + totalSize / 1048576 + ")";
OpenCms.getLog(this).debug(memStatus);
OpenCmsSessionManager sm = OpenCmsCore.getInstance().getSessionManager();
CmsCoreSession cs = OpenCmsCore.getInstance().getSessionStorage();
if ((sm != null) && (cs != null)) {
OpenCms.getLog(this).debug(", Sessions users: " + cs.getLoggedInUsers().size() + " current: " + sm.getCurrentSessions() + " total: " + sm.getTotalSessions());
}
sm = null;
cs = null;
}
}
/**
* Adds a new object to the monitor.<p>
*
* @param objectName name of the object
* @param object the object for monitoring
*/
public void register(String objectName, Object object) {
m_monitoredObjects.put(objectName, object);
}
}
| src/org/opencms/monitor/CmsMemoryMonitor.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/monitor/CmsMemoryMonitor.java,v $
* Date : $Date: 2003/11/12 11:33:54 $
* Version: $Revision: 1.12 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2003 Alkacon Software (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, 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.monitor;
import org.opencms.cache.CmsLruCache;
import org.opencms.cache.I_CmsLruCacheObject;
import org.opencms.cron.I_CmsCronJob;
import org.opencms.flex.CmsFlexCache.CmsFlexCacheVariation;
import org.opencms.main.CmsEvent;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsEventListener;
import org.opencms.main.OpenCms;
import org.opencms.main.OpenCmsCore;
import org.opencms.main.OpenCmsSessionManager;
import org.opencms.security.CmsAccessControlList;
import org.opencms.security.CmsPermissionSet;
import org.opencms.util.PrintfFormat;
import com.opencms.core.CmsCoreSession;
import com.opencms.core.CmsException;
import com.opencms.defaults.CmsMail;
import com.opencms.file.CmsFile;
import com.opencms.file.CmsGroup;
import com.opencms.file.CmsObject;
import com.opencms.file.CmsProject;
import com.opencms.file.CmsResource;
import com.opencms.file.CmsUser;
import com.opencms.util.Utils;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.collections.LRUMap;
/**
* Monitors OpenCms memory consumtion.<p>
*
* @version $Revision: 1.12 $ $Date: 2003/11/12 11:33:54 $
*
* @author Carsten Weinholz ([email protected])
* @author Michael Emmerich ([email protected])
* @author Alexander Kandzior ([email protected])
*/
public class CmsMemoryMonitor implements I_CmsCronJob {
/** set interval for clearing the caches to 15 minutes */
private static final int C_INTERVAL_CLEAR = 1000 * 60 * 15;
/** max depth for object size recursion */
private static final int C_MAX_DEPTH = 5;
private static boolean m_currentlyRunning = false;
/** receivers fro status emails */
private String[] m_emailReceiver;
/** sender for status emails */
private String m_emailSender;
/** the interval to use for sending emails */
private int m_intervalEmail;
/** the interval to use for the logging */
private int m_intervalLog;
/** the interval to use for warnings if status is disabled */
private int m_intervalWarning;
/** the time the caches where last cleared */
private long m_lastClearCache;
/** the time the last status email was send */
private long m_lastEmailStatus;
/** the time the last warning email was send */
private long m_lastEmailWarning;
/** the time the last status log was written */
private long m_lastLogStatus;
/** the time the last warning log was written */
private long m_lastLogWarning;
/** memory limit that triggers a warning */
private int m_maxUsagePercent;
/** contains the object to be monitored */
private Map m_monitoredObjects;
/** flag for memory warning mail send */
private boolean m_warningSendSinceLastEmail;
/** flag for memory warning mail send */
private boolean m_warningLoggedSinceLastLog;
/**
* Empty constructor, required by OpenCms scheduler.<p>
*/
public CmsMemoryMonitor() {
// empty
}
/**
* Creates a new monitor with the provided configuration.<p>
*
* @param configuration the configuration to use
*/
public CmsMemoryMonitor(ExtendedProperties configuration) {
m_warningSendSinceLastEmail = false;
m_warningLoggedSinceLastLog = false;
m_lastEmailWarning = 0;
m_lastEmailStatus = 0;
m_lastLogStatus = 0;
m_lastLogWarning = 0;
m_lastClearCache = 0;
m_monitoredObjects = new HashMap();
m_emailSender = configuration.getString("memorymonitor.email.sender");
m_emailReceiver = configuration.getStringArray("memorymonitor.email.receiver");
m_intervalEmail = configuration.getInteger("memorymonitor.email.interval", 0) * 60000;
m_intervalLog = configuration.getInteger("memorymonitor.log.interval", 0) * 60000;
m_intervalWarning = configuration.getInteger("memorymonitor.warning.interval", 360) * 60000;
m_maxUsagePercent = configuration.getInteger("memorymonitor.maxUsagePercent", 90);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval log : " + (m_intervalLog / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval email : " + (m_intervalEmail / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval warning : " + (m_intervalWarning / 60000) + " min");
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM max usage : " + m_maxUsagePercent + "%");
if ((m_emailReceiver == null) || (m_emailSender == null)) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email : disabled");
} else {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email sender : " + m_emailSender);
for (int i=0, s=m_emailReceiver.length; i < s; i++) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email receiver : " + (i+1) + " - " + m_emailReceiver[i]);
}
}
}
}
/**
* Initalizes the Memory Monitor.<p>
*
* @param configuration the OpenCms configurations
* @return the initialized CmsMemoryMonitor
*/
public static CmsMemoryMonitor initialize(ExtendedProperties configuration) {
return new CmsMemoryMonitor(configuration);
}
/**
* Clears the OpenCms caches.<p>
*/
private void clearCaches() {
if ((m_lastClearCache + C_INTERVAL_CLEAR) > System.currentTimeMillis()) {
// if the cache has already been cleared less then 15 minutes ago we skip this because
// clearing the caches to often will hurt system performance and the
// setup seems to be in trouble anyway
return;
}
m_lastClearCache = System.currentTimeMillis();
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn(", Clearing caches because memory consumption has reached a critical level");
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false));
System.gc();
}
/**
* Returns if monitoring is enabled.<p>
*
* @return true if monitoring is enabled
*/
public boolean enabled() {
return true;
}
/**
* Returns the cache costs of a monitored object.<p>
* obj must be of type CmsLruCache
*
* @param obj the object
* @return the cache costs or "-"
*/
private long getCosts(Object obj) {
long costs = 0;
if (obj instanceof CmsLruCache) {
costs = ((CmsLruCache)obj).getObjectCosts();
if (costs < 0) {
costs = 0;
}
}
return costs;
}
/**
* Returns the number of items within a monitored object.<p>
* obj must be of type CmsLruCache, CmsLruHashMap or Map
*
* @param obj the object
* @return the number of items or "-"
*/
private String getItems(Object obj) {
if (obj instanceof CmsLruCache) {
return Integer.toString(((CmsLruCache)obj).size());
}
if (obj instanceof Map) {
return Integer.toString(((Map)obj).size());
}
return "-";
}
/**
* Returns the total size of key strings within a monitored object.<p>
* obj must be of type map, the keys must be of type String.
*
* @param obj the object
* @return the total size of key strings
*/
private long getKeySize(Object obj) {
if (obj instanceof Map) {
return getKeySize ((Map)obj, 1);
}
return 0;
}
/**
* Returns the total size of key strings within a monitored map.<p>
* the keys must be of type String.
*
* @param map the map
* @param depth the max recursion depth for calculation the size
* @return total size of key strings
*/
private long getKeySize(Map map, int depth) {
long keySize = 0;
Object[] values = map.values().toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof Map && depth < C_MAX_DEPTH) {
keySize += getKeySize((Map)obj, depth+1);
continue;
}
}
values = null;
Object[] keys = map.keySet().toArray();
for (int i=0, s=keys.length; i<s; i++) {
Object obj = keys[i];
if (obj instanceof String) {
String st = (String)obj;
keySize += (st.length() * 2);
}
}
return keySize;
}
/**
* Returns the max costs for all items within a monitored object.<p>
* obj must be of type CmsLruCache, CmsLruHashMap
*
* @param obj the object
* @return max cost limit or "-"
*/
private String getLimit(Object obj) {
if (obj instanceof CmsLruCache) {
return Integer.toString(((CmsLruCache)obj).getMaxCacheCosts());
}
if (obj instanceof LRUMap) {
return Integer.toString(((LRUMap)obj).getMaximumSize());
}
return "-";
}
/**
* Returns the value sizes of value objects within the monitored object.<p>
* obj must be of type map
*
* @param obj the object
* @return the value sizes of value objects or "-"-fields
*/
private long getValueSize(Object obj) {
if (obj instanceof CmsLruCache) {
return ((CmsLruCache)obj).size();
}
if (obj instanceof Map) {
return getValueSize((Map)obj, 1);
}
if (obj instanceof List) {
return getValueSize((List)obj, 1);
}
try {
return getMemorySize(obj);
} catch (Exception exc) {
return 0;
}
}
/**
* Returns the total value size of a map object.<p>
*
* @param mapValue the map object
* @param depth the max recursion depth for calculation the size
* @return the size of the map object
*/
private long getValueSize(Map mapValue, int depth) {
long totalSize = 0;
Object[] values = mapValue.values().toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof CmsAccessControlList) {
obj = ((CmsAccessControlList)obj).getPermissionMap();
}
if (obj instanceof CmsFlexCacheVariation) {
obj = ((CmsFlexCacheVariation)obj).m_map;
}
if (obj instanceof Map && depth < C_MAX_DEPTH) {
totalSize += getValueSize((Map)obj, depth+1);
continue;
}
if (obj instanceof List && depth < C_MAX_DEPTH) {
totalSize += getValueSize((List)obj, depth+1);
continue;
}
totalSize += getMemorySize(obj);
}
return totalSize;
}
/**
* Returns the total value size of a list object.<p>
*
* @param listValue the list object
* @param depth the max recursion depth for calculation the size
* @return the size of the list object
*/
private long getValueSize(List listValue, int depth) {
long totalSize = 0;
Object[] values = listValue.toArray();
for (int i=0, s=values.length; i<s; i++) {
Object obj = values[i];
if (obj instanceof CmsAccessControlList) {
obj = ((CmsAccessControlList)obj).getPermissionMap();
}
if (obj instanceof CmsFlexCacheVariation) {
obj = ((CmsFlexCacheVariation)obj).m_map;
}
if (obj instanceof Map && depth < C_MAX_DEPTH) {
totalSize += getValueSize((Map)obj, depth+1);
continue;
}
if (obj instanceof List && depth < C_MAX_DEPTH) {
totalSize += getValueSize((List)obj, depth+1);
continue;
}
totalSize += getMemorySize(obj);
}
return totalSize;
}
/**
* Returns the size of objects that are instances of
* <code>byte[]</code>, <code>String</code>, <code>CmsFile</code>,<code>I_CmsLruCacheObject</code>.<p>
* For other objects, a size of 0 is returned.
*
* @param obj the object
* @return the size of the object
*/
private long getMemorySize(Object obj) {
if (obj instanceof I_CmsLruCacheObject) {
return ((I_CmsLruCacheObject)obj).getLruCacheCosts();
}
if (obj instanceof byte[]) {
return ((byte[])obj).length;
}
if (obj instanceof String) {
return ((String)obj).length() * 2;
}
if (obj instanceof CmsFile) {
CmsFile f = (CmsFile)obj;
if (f.getContents() != null) {
return f.getContents().length;
}
}
if (obj instanceof CmsPermissionSet) {
return 8; // two ints
}
if (obj instanceof CmsResource) {
return 512; // estimated size
}
if (obj instanceof CmsUser) {
return 1024; // estimated size
}
if (obj instanceof CmsGroup) {
return 260; // estimated size
}
if (obj instanceof CmsProject) {
return 344;
}
if (obj instanceof Boolean) {
return 1; // one boolean
}
// System.err.println("Unresolved: " + obj.getClass().getName());
return 0;
}
/**a
* @see org.opencms.cron.I_CmsCronJob#launch(com.opencms.file.CmsObject, java.lang.String)
*/
public String launch(CmsObject cms, String params) throws Exception {
CmsMemoryMonitor monitor = OpenCms.getMemoryMonitor();
if (m_currentlyRunning) {
return "";
} else {
m_currentlyRunning = true;
}
// check if the system is in a low memory condition
if (monitor.lowMemory()) {
// log warning
monitor.monitorWriteLog(true);
// send warning email
monitor.monitorSendEmail(true);
// clean up caches
monitor.clearCaches();
}
// check if regular a log entry must be written
if ((System.currentTimeMillis() - monitor.m_lastLogStatus) > monitor.m_intervalLog) {
monitor.monitorWriteLog(false);
}
// check if the memory status email must be send
if ((System.currentTimeMillis() - monitor.m_lastEmailStatus) > monitor.m_intervalEmail) {
monitor.monitorSendEmail(false);
}
m_currentlyRunning = false;
return "";
}
/**
* Returns true if the system runs low on memory.<p>
*
* @return true if the system runs low on memory
*/
public boolean lowMemory() {
long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long usage = usedMemory * 100 / Runtime.getRuntime().maxMemory();
return ((m_maxUsagePercent > 0) && (usage > m_maxUsagePercent));
}
/**
* Sends a warning or status email with OpenCms Memory information.<p>
*
* @param warning if true, send a memory warning email
*/
private void monitorSendEmail(boolean warning) {
if ((warning && m_warningSendSinceLastEmail)
|| ((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning)))) {
// send only one warning email between regular status emails OR if status is disabled and warn interval has passed
return;
} else if ((! warning) && (m_intervalEmail <= 0)) {
// if email iterval is <= 0 status email is disabled
return;
}
String date = Utils.getNiceDate(System.currentTimeMillis());
String subject;
String content = "";
if (warning) {
m_warningSendSinceLastEmail = true;
m_lastEmailWarning = System.currentTimeMillis();
subject = "OpenCms Memory W A R N I N G [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
content += "W A R N I N G !\nOpenCms memory consumption on server " + OpenCms.getServerName().toUpperCase() + " has reached a critical level !\n\n"
+ "The configured limit is " + m_maxUsagePercent + "%\n\n";
} else {
m_warningSendSinceLastEmail = false;
m_lastEmailStatus = System.currentTimeMillis();
subject = "OpenCms Memory Status [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
}
long maxMemory = Runtime.getRuntime().maxMemory() / 1048576;
long totalMemory = Runtime.getRuntime().totalMemory() / 1048576;
long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
long freeMemory = maxMemory - usedMemory;
long usage = usedMemory * 100 / maxMemory;
content += "Memory usage report of OpenCms server " + OpenCms.getServerName().toUpperCase() + " at " + date + "\n\n"
+ "Memory maximum heap size: " + maxMemory + " mb\n"
+ "Memory current heap size: " + totalMemory + " mb\n\n"
+ "Memory currently used : " + usedMemory + " mb (" + usage + "%)\n"
+ "Memory currently unused : " + freeMemory + " mb\n\n\n";
if (warning) {
content += "*** Please take action NOW to ensure that no OutOfMemoryException occurs.\n\n\n";
}
OpenCmsSessionManager sm = OpenCmsCore.getInstance().getSessionManager();
CmsCoreSession cs = OpenCmsCore.getInstance().getSessionStorage();
if ((sm != null) && (cs != null)) {
content += "Current status of the sessions:\n\n";
content += "Logged in users : " + cs.getLoggedInUsers().size() + "\n";
content += "Currently active sessions: " + sm.getCurrentSessions() + "\n";
content += "Total created sessions : " + sm.getTotalSessions() + "\n\n\n";
}
sm = null;
cs = null;
content += "Current status of the caches:\n\n";
List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
Collections.sort(keyList);
long totalSize = 0;
for (Iterator keys = keyList.iterator(); keys.hasNext();) {
String key = (String)keys.next();
String shortKeys[] = key.split("\\.");
String shortKey = shortKeys[shortKeys.length - 2] + "." + shortKeys[shortKeys.length - 1];
PrintfFormat form = new PrintfFormat("%9s");
Object obj = m_monitoredObjects.get(key);
long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
totalSize += size;
content += new PrintfFormat("%-42.42s").sprintf(shortKey) + " "
+ "Entries: " + form.sprintf(getItems(obj)) + " "
+ "Limit: " + form.sprintf(getLimit(obj)) + " "
+ "Size: " + form.sprintf(Long.toString(size)) + "\n";
}
content += "\nTotal size of cache memory monitored: " + totalSize + " (" + totalSize / 1048576 + ")\n\n";
String from = m_emailSender;
String[] to = m_emailReceiver;
try {
if (from != null && to != null) {
CmsMail email = new CmsMail(from, to, subject, content, "text/plain");
email.start();
}
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info(", Memory Monitor " + (warning?"warning":"status") + " email send");
}
} catch (CmsException e) {
e.printStackTrace();
}
}
/**
* Write a warning or status log entry with OpenCms Memory information.<p>
*
* @param warning if true, write a memory warning log entry
*/
private void monitorWriteLog(boolean warning) {
if ((warning && m_warningLoggedSinceLastLog)
|| ((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))) {
// send only one warning email between regular status emails OR if status is disabled and warn interval has passed
return;
} else if ((! OpenCms.getLog(this).isDebugEnabled()) || ((! warning) && (m_intervalLog <= 0))) {
// if email iterval is <= 0 status email is disabled
return;
}
long maxMemory = Runtime.getRuntime().maxMemory() / 1048576;
long totalMemory = Runtime.getRuntime().totalMemory() / 1048576;
long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
long freeMemory = maxMemory - usedMemory;
long usage = usedMemory * 100 / maxMemory;
if (warning) {
m_lastLogWarning = System.currentTimeMillis();
m_warningLoggedSinceLastLog = true;
OpenCms.getLog(this).warn(", W A R N I N G Memory consumption of " + usage
+ "% has reached a critical level"
+ " (" + m_maxUsagePercent + "% configured)");
} else {
m_warningLoggedSinceLastLog = false;
m_lastLogStatus = System.currentTimeMillis();
}
String memStatus = ", Memory max: " + maxMemory + " mb "
+ "total: " + totalMemory + " mb "
+ "free: " + freeMemory + " mb "
+ "used: " + usedMemory + " mb";
if (warning) {
OpenCms.getLog(this).warn(memStatus);
} else {
OpenCms.getLog(this).debug(", Memory monitor log for server " + OpenCms.getServerName().toUpperCase());
List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
Collections.sort(keyList);
long totalSize = 0;
for (Iterator keys = keyList.iterator(); keys.hasNext();) {
String key = (String)keys.next();
Object obj = m_monitoredObjects.get(key);
long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
totalSize += size;
PrintfFormat name1 = new PrintfFormat("%-100s");
PrintfFormat name2 = new PrintfFormat("%-50s");
PrintfFormat form = new PrintfFormat("%9s");
OpenCms.getLog(this).debug(",, "
+ "Monitored:, " + name1.sprintf(key) + ", "
+ "Type:, " + name2.sprintf(obj.getClass().getName()) + ", "
+ "Entries:, " + form.sprintf(getItems(obj)) + ", "
+ "Limit:, " + form.sprintf(getLimit(obj)) + ", "
+ "Size:, " + form.sprintf(Long.toString(size)));
}
memStatus += " " + "size monitored: " + totalSize + " (" + totalSize / 1048576 + ")";
OpenCms.getLog(this).debug(memStatus);
OpenCmsSessionManager sm = OpenCmsCore.getInstance().getSessionManager();
CmsCoreSession cs = OpenCmsCore.getInstance().getSessionStorage();
if ((sm != null) && (cs != null)) {
OpenCms.getLog(this).debug(", Sessions users: " + cs.getLoggedInUsers().size() + " current: " + sm.getCurrentSessions() + " total: " + sm.getTotalSessions());
}
sm = null;
cs = null;
}
}
/**
* Adds a new object to the monitor.<p>
*
* @param objectName name of the object
* @param object the object for monitoring
*/
public void register(String objectName, Object object) {
m_monitoredObjects.put(objectName, object);
}
}
| Further improvements to memory monitor
| src/org/opencms/monitor/CmsMemoryMonitor.java | Further improvements to memory monitor | <ide><path>rc/org/opencms/monitor/CmsMemoryMonitor.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/monitor/CmsMemoryMonitor.java,v $
<del> * Date : $Date: 2003/11/12 11:33:54 $
<del> * Version: $Revision: 1.12 $
<add> * Date : $Date: 2003/11/12 14:42:45 $
<add> * Version: $Revision: 1.13 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Mananagement System
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<add>import java.util.Date;
<ide> import java.util.HashMap;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<ide> /**
<ide> * Monitors OpenCms memory consumtion.<p>
<ide> *
<del> * @version $Revision: 1.12 $ $Date: 2003/11/12 11:33:54 $
<add> * @version $Revision: 1.13 $ $Date: 2003/11/12 14:42:45 $
<ide> *
<ide> * @author Carsten Weinholz ([email protected])
<ide> * @author Michael Emmerich ([email protected])
<ide> private Map m_monitoredObjects;
<ide>
<ide> /** flag for memory warning mail send */
<del> private boolean m_warningSendSinceLastEmail;
<add> private boolean m_warningSendSinceLastStatus;
<ide>
<ide> /** flag for memory warning mail send */
<del> private boolean m_warningLoggedSinceLastLog;
<add> private boolean m_warningLoggedSinceLastStatus;
<ide>
<ide> /**
<ide> * Empty constructor, required by OpenCms scheduler.<p>
<ide> * @param configuration the configuration to use
<ide> */
<ide> public CmsMemoryMonitor(ExtendedProperties configuration) {
<del> m_warningSendSinceLastEmail = false;
<del> m_warningLoggedSinceLastLog = false;
<add> m_warningSendSinceLastStatus = false;
<add> m_warningLoggedSinceLastStatus = false;
<ide> m_lastEmailWarning = 0;
<ide> m_lastEmailStatus = 0;
<ide> m_lastLogStatus = 0;
<ide> m_lastClearCache = 0;
<ide> m_monitoredObjects = new HashMap();
<ide>
<del> m_emailSender = configuration.getString("memorymonitor.email.sender");
<add> m_emailSender = configuration.getString("memorymonitor.email.sender", null);
<ide> m_emailReceiver = configuration.getStringArray("memorymonitor.email.receiver");
<ide> m_intervalEmail = configuration.getInteger("memorymonitor.email.interval", 0) * 60000;
<ide> m_intervalLog = configuration.getInteger("memorymonitor.log.interval", 0) * 60000;
<ide> OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email receiver : " + (i+1) + " - " + m_emailReceiver[i]);
<ide> }
<ide> }
<del> }
<add> }
<add>
<add> if (OpenCms.getLog(this).isDebugEnabled()) {
<add> // this will happen only once during system startup
<add> OpenCms.getLog(this).debug(", New instance of CmsMemoryMonitor created at " + (new Date(System.currentTimeMillis())));
<add> }
<add>
<ide> }
<ide>
<ide> /**
<ide> * @param warning if true, send a memory warning email
<ide> */
<ide> private void monitorSendEmail(boolean warning) {
<del> if ((warning && m_warningSendSinceLastEmail)
<del> || ((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning)))) {
<del> // send only one warning email between regular status emails OR if status is disabled and warn interval has passed
<add> if ((m_emailSender == null) || (m_emailReceiver == null)) {
<add> // send no mails if not fully configured
<add> return;
<add> } else if (warning && (m_warningSendSinceLastStatus && !((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning))))) {
<add> // send no warning email if no status email has been send since the last warning
<add> // if status is disabled, send no warn email if warn interval has not passed
<ide> return;
<ide> } else if ((! warning) && (m_intervalEmail <= 0)) {
<ide> // if email iterval is <= 0 status email is disabled
<ide> String subject;
<ide> String content = "";
<ide> if (warning) {
<del> m_warningSendSinceLastEmail = true;
<add> m_warningSendSinceLastStatus = true;
<ide> m_lastEmailWarning = System.currentTimeMillis();
<ide> subject = "OpenCms Memory W A R N I N G [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
<ide> content += "W A R N I N G !\nOpenCms memory consumption on server " + OpenCms.getServerName().toUpperCase() + " has reached a critical level !\n\n"
<ide> + "The configured limit is " + m_maxUsagePercent + "%\n\n";
<ide> } else {
<del> m_warningSendSinceLastEmail = false;
<add> m_warningSendSinceLastStatus = false;
<ide> m_lastEmailStatus = System.currentTimeMillis();
<ide> subject = "OpenCms Memory Status [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]";
<ide> }
<ide> * @param warning if true, write a memory warning log entry
<ide> */
<ide> private void monitorWriteLog(boolean warning) {
<del> if ((warning && m_warningLoggedSinceLastLog)
<del> || ((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))) {
<del> // send only one warning email between regular status emails OR if status is disabled and warn interval has passed
<add> if (! OpenCms.getLog(this).isWarnEnabled()) {
<add> // we need at last warn level for this output
<ide> return;
<del> } else if ((! OpenCms.getLog(this).isDebugEnabled()) || ((! warning) && (m_intervalLog <= 0))) {
<del> // if email iterval is <= 0 status email is disabled
<add> } else if ((! warning) && (! OpenCms.getLog(this).isDebugEnabled())) {
<add> // if not warning we need debug level
<add> return;
<add> } else if (warning && (m_warningLoggedSinceLastStatus && !(((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))))) {
<add> // write no warning log if no status log has been written since the last warning
<add> // if status is disabled, log no warn entry if warn interval has not passed
<add> return;
<add> } else if ((! warning) && (m_intervalLog <= 0)) {
<add> // if log iterval is <= 0 status log is disabled
<ide> return;
<ide> }
<ide>
<ide>
<ide> if (warning) {
<ide> m_lastLogWarning = System.currentTimeMillis();
<del> m_warningLoggedSinceLastLog = true;
<add> m_warningLoggedSinceLastStatus = true;
<ide> OpenCms.getLog(this).warn(", W A R N I N G Memory consumption of " + usage
<ide> + "% has reached a critical level"
<ide> + " (" + m_maxUsagePercent + "% configured)");
<ide> } else {
<del> m_warningLoggedSinceLastLog = false;
<add> m_warningLoggedSinceLastStatus = false;
<ide> m_lastLogStatus = System.currentTimeMillis();
<ide> }
<ide>
<ide> long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
<ide> totalSize += size;
<ide>
<del> PrintfFormat name1 = new PrintfFormat("%-100s");
<add> PrintfFormat name1 = new PrintfFormat("%-80s");
<ide> PrintfFormat name2 = new PrintfFormat("%-50s");
<ide> PrintfFormat form = new PrintfFormat("%9s");
<ide> OpenCms.getLog(this).debug(",, " |
|
JavaScript | mit | 05b64095ac6d24f7ffd82eb834aca68fd3af5a29 | 0 | mercmobily/hotplate,shelsonjava/hotplate,mercmobily/hotplate,shelsonjava/hotplate | define([
"dojo/_base/declare"
, "dojo/on"
, "dojo/when"
, "dojo/dom-class"
, "dojo/topic"
, "dijit/_WidgetBase"
, "dijit/_CssStateMixin"
, "dijit/_TemplatedMixin"
, "dijit/Destroyable"
, "hotplate/hotDojoStores/stores"
, "hotplate/hotDojoWidgets/_OverlayMixin"
, "hotplate/hotDojoSubmit/defaultSubmit"
], function(
declare
, on
, when
, domClass
, topic
, _WidgetBase
, _CssStateMixin
, _TemplatedMixin
, Destroyable
, stores
, _OverlayMixin
, ds
){
var templateString = '' +
'<span>\n' +
' <span class="toggle"><span class="unticked" data-dojo-attach-point="toggleNode" data-dojo-attach-event="ondijitclick: click"></span></span>\n' +
'</span>\n'+
'';
return declare( [ _WidgetBase, _TemplatedMixin, _CssStateMixin, _OverlayMixin ], {
baseClass: 'toggle-widget',
store: null,
storeName: '',
storeParameters: {},
recordId: null,
toggleField: '',
templateString: templateString,
ticked: false,
postCreate: function(){
this.inherited( arguments );
var self = this;
self.own(
self.store.on( 'add,update,remove', function( event ){
if( event.target[ self.store.idProperty ] == self.recordId ){
self.set( 'ticked', event.target[ self.toggleField ] );
}
})
);
},
postMixInProperties: function(){
this.inherited(arguments);
this.store = stores( this.storeName, this.storeParameters );
},
_setTickedAttr: function( value ){
this._set( 'ticked', value );
// Remove all previous classes
domClass.remove( this.toggleNode, 'ticked' );
domClass.remove( this.toggleNode, 'unticked' );
// Add the appropriate one
if( value ){
domClass.add( this.toggleNode, 'ticked' );
} else {
domClass.add( this.toggleNode, 'unticked' );
}
},
// Toggle the 'ticked' attribute
click: function( e ){
var self = this;
self.emit( 'toggle-click' );
// Set futureValue to what the star will need
// to be, and `o` accordingly
var futureValue, o = {};
if( self.ticked ){
futureValue = false;
} else {
futureValue = true;
}
o[ self.toggleField ] = futureValue;
o[ self.store.idProperty ] = self.recordId;
// Try to save the values
self.set('overlayStatus', { overlayed: true, clickable: false } ); // LOADING ON
when( self.store.put( o )) .then(
function( res ){
self.set('overlayStatus', { overlayed: false, clickable: false } ); // LOADING OFF
self.set( 'ticked', futureValue );
},
function( err ){
self.set('overlayStatus', { overlayed: false, clickable: false } ); // LOADING OFF
(ds.UIErrorMsg( null, null, null ))(err); // Mainly for the global alert bar
}
);
}
});
});
| node_modules/hotDojoWidgets/client/StoreToggle.js | define([
"dojo/_base/declare"
, "dojo/on"
, "dojo/when"
, "dojo/dom-class"
, "dojo/topic"
, "dijit/_WidgetBase"
, "dijit/_CssStateMixin"
, "dijit/_TemplatedMixin"
, "dijit/Destroyable"
, "hotplate/hotDojoStores/stores"
, "hotplate/hotDojoWidgets/_OverlayMixin"
, "hotplate/hotDojoSubmit/defaultSubmit"
], function(
declare
, on
, when
, domClass
, topic
, _WidgetBase
, _CssStateMixin
, _TemplatedMixin
, Destroyable
, stores
, _OverlayMixin
, ds
){
var templateString = '' +
'<span>\n' +
' <span class="toggle"><span class="unticked" data-dojo-attach-point="toggleNode" data-dojo-attach-event="ondijitclick: click"></span></span>\n' +
'</span>\n'+
'';
return declare( [ _WidgetBase, _TemplatedMixin, _CssStateMixin, _OverlayMixin ], {
baseClass: 'toggle-widget',
store: null,
storeName: '',
storeParameters: {},
recordId: null,
toggleField: '',
templateString: templateString,
ticked: false,
postCreate: function(){
this.inherited( arguments );
var self = this;
self.store.on( 'add,update,remove', function( event ){
if( event.target[ self.store.idProperty ] == self.recordId ){
self.set( 'ticked', event.target[ self.toggleField ] );
}
});
},
postMixInProperties: function(){
this.inherited(arguments);
this.store = stores( this.storeName, this.storeParameters );
},
_setTickedAttr: function( value ){
this._set( 'ticked', value );
// Remove all previous classes
domClass.remove( this.toggleNode, 'ticked' );
domClass.remove( this.toggleNode, 'unticked' );
// Add the appropriate one
if( value ){
domClass.add( this.toggleNode, 'ticked' );
} else {
domClass.add( this.toggleNode, 'unticked' );
}
},
// Toggle the 'ticked' attribute
click: function( e ){
var self = this;
self.emit( 'toggle-click' );
// Set futureValue to what the star will need
// to be, and `o` accordingly
var futureValue, o = {};
if( self.ticked ){
futureValue = false;
} else {
futureValue = true;
}
o[ self.toggleField ] = futureValue;
o[ self.store.idProperty ] = self.recordId;
// Try to save the values
self.set('overlayStatus', { overlayed: true, clickable: false } ); // LOADING ON
when( self.store.put( o )) .then(
function( res ){
self.set('overlayStatus', { overlayed: false, clickable: false } ); // LOADING OFF
self.set( 'ticked', futureValue );
},
function( err ){
self.set('overlayStatus', { overlayed: false, clickable: false } ); // LOADING OFF
(ds.UIErrorMsg( null, null, null ))(err); // Mainly for the global alert bar
}
);
}
});
});
| Added self.own to make sure widget is destroyed (or it will hang around)
| node_modules/hotDojoWidgets/client/StoreToggle.js | Added self.own to make sure widget is destroyed (or it will hang around) | <ide><path>ode_modules/hotDojoWidgets/client/StoreToggle.js
<ide> this.inherited( arguments );
<ide> var self = this;
<ide>
<del> self.store.on( 'add,update,remove', function( event ){
<del> if( event.target[ self.store.idProperty ] == self.recordId ){
<del> self.set( 'ticked', event.target[ self.toggleField ] );
<del> }
<del> });
<add> self.own(
<add> self.store.on( 'add,update,remove', function( event ){
<add> if( event.target[ self.store.idProperty ] == self.recordId ){
<add> self.set( 'ticked', event.target[ self.toggleField ] );
<add> }
<add> })
<add> );
<ide>
<ide> },
<ide> |
|
Java | apache-2.0 | e1c5b2554cb9c463a5cc7ca1f51c9f0f419536a3 | 0 | project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform | package com.cloudera.kitten.appmaster.service;
import gr.ntua.cslab.asap.client.RestClient;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.client.api.AMRMClient;
import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
import org.apache.hadoop.yarn.client.api.async.NMClientAsync;
import com.cloudera.kitten.ContainerLaunchContextFactory;
import com.cloudera.kitten.ContainerLaunchParameters;
import com.google.common.collect.Maps;
public class ContainerTracker implements NMClientAsync.CallbackHandler {
private static final Log LOG = LogFactory.getLog(ContainerTracker.class);
public final ContainerLaunchParameters params;
private final ConcurrentMap<ContainerId, Container> containers = Maps.newConcurrentMap();
private AtomicInteger needed = new AtomicInteger();
private AtomicInteger started = new AtomicInteger();
public AtomicInteger completed = new AtomicInteger();
private AtomicInteger failed = new AtomicInteger();
private NMClientAsync nodeManager;
private Resource resource;
private Priority priority;
private ContainerLaunchContext ctxt;
private List<ContainerTracker> nextTrackers;
private List<ContainerTracker> previousTrackers;
public boolean isInitilized;
private List<AMRMClient.ContainerRequest> containerRequests;
private WorkflowService service;
private long startTime;
public ContainerTracker(WorkflowService service, ContainerLaunchParameters parameters) {
this.service = service;
this.params = parameters;
this.nextTrackers = new ArrayList<ContainerTracker>();
this.previousTrackers = new ArrayList<ContainerTracker>();
needed.set(1);
isInitilized=false;
}
public void addNextTracker(ContainerTracker tracker){
this.nextTrackers.add(tracker);
// LOG.info("NextTrackers for: " +params.getName());
// for(ContainerTracker t:nextTrackers){
// LOG.info("Tracker: " +t.params.getName());
// }
}
public void addPreviousTracker(ContainerTracker tracker){
this.previousTrackers.add(tracker);
}
private boolean allPreviousFinished(){
boolean ret = true;
for(ContainerTracker tracker : previousTrackers){
if(tracker.needsContainers()){
ret=false;
break;
}
}
return ret;
}
public void init(ContainerLaunchContextFactory factory) throws IOException {
if(!allPreviousFinished())
return;
service.parameters.workflow.getOperator(params.getName()).setStatus("running");
startTime = System.currentTimeMillis();
this.nodeManager = NMClientAsync.createNMClientAsync(this);
nodeManager.init(service.conf);
nodeManager.start();
isInitilized=true;
this.resource = factory.createResource(params);
//this.priority = factory.createPriority(params.getPriority());
//hack for https://issues.apache.org/jira/browse/YARN-314
this.priority = factory.createPriority(service.prior);
service.prior++;
//hack for https://issues.apache.org/jira/browse/YARN-314
int numInstances = params.getNumInstances();
LOG.info("Operator: "+params.getName()+" requesting " + numInstances+" containers");
LOG.info("Resource cores: "+ resource.getVirtualCores());
LOG.info("Resource memory: "+ resource.getMemory());
LOG.info("Has nodes: "+ params.getNodes());
String[] nodes = params.getNodes();//= {"slave1"};
String labels = params.getLabels();
AMRMClient.ContainerRequest containerRequest=null;
if(labels==null){
LOG.info("Resource nodes: all");
containerRequest = new AMRMClient.ContainerRequest(
resource,
nodes, // nodes
null, // racks
priority,
true, //true for relaxed locality
"");
}
else{
LOG.info("Resource labels: "+ labels);
for (int i = 0; i < nodes.length; i++) {
LOG.info("Resource nodes: "+ nodes[i]);
}
containerRequest = new AMRMClient.ContainerRequest(
resource,
nodes, // nodes
null, // racks
priority,
false, //true for relaxed locality
"");
}
this.containerRequests = new ArrayList<AMRMClient.ContainerRequest>();
//restartResourceManager();
for (int j = 0; j < numInstances; j++) {
service.resourceManager.addContainerRequest(containerRequest);
containerRequests.add(containerRequest);
}
needed.set(numInstances);
}
@Override
public void onContainerStarted(ContainerId containerId, Map<String, ByteBuffer> allServiceResponse) {
Container container = containers.get(containerId);
if (container != null) {
LOG.info("Starting container id = " + containerId);
started.incrementAndGet();
nodeManager.getContainerStatusAsync(containerId, container.getNodeId());
}
}
@Override
public void onContainerStatusReceived(ContainerId containerId, ContainerStatus containerStatus) {
if (LOG.isDebugEnabled()) {
LOG.debug("Received status for container: " + containerId + " = " + containerStatus);
}
}
@Override
public void onContainerStopped(ContainerId containerId) {
LOG.info("Stopping container id = " + containerId);
Container v = containers.remove(containerId);
if(v==null)
return;
completed.incrementAndGet();
/*if(!hasMoreContainers()){
LOG.info("Starting next trackers" );
for(ContainerTracker t : nextTrackers){
try {
t.init(factory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
}
public void removeContainerRequests(){
LOG.info("Removing container requests");
for(ContainerRequest c : containerRequests){
LOG.info("Removing cores: "+c.getCapability().getVirtualCores()+" mem: "+c.getCapability().getMemory());
service.resourceManager.removeContainerRequest(c);
}
LOG.info("Blockers: "+service.resourceManager.getBlockers());
}
public void containerCompleted(ContainerId containerId) {
isInitilized=false;
LOG.info("Completed container id = " + containerId+" operator: "+params.getName());
long stop = System.currentTimeMillis();
double time = (stop-startTime)/1000.0-5;//5sec init container
service.parameters.workflow.getOperator(params.getName()).setCost(time+"");
containers.remove(containerId);
completed.incrementAndGet();
service.parameters.workflow.setOutputsRunning(params.getName());
if(!hasMoreContainers()){
removeContainerRequests();
LOG.info("Starting next trackers" );
for(ContainerTracker t : nextTrackers){
try {
t.init(service.factory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void onStartContainerError(ContainerId containerId, Throwable throwable) {
LOG.warn("Start container error for container id = " + containerId, throwable);
containers.remove(containerId);
completed.incrementAndGet();
failed.incrementAndGet();
}
@Override
public void onGetContainerStatusError(ContainerId containerId, Throwable throwable) {
LOG.error("Could not get status for container: " + containerId, throwable);
}
@Override
public void onStopContainerError(ContainerId containerId, Throwable throwable) {
LOG.error("Failed to stop container: " + containerId, throwable);
completed.incrementAndGet();
}
public boolean needsContainers() {
//LOG.info("operator: "+params.getName()+" needed: "+needed);
return needed.get() > 0;
}
public boolean matches(Container c) {
return containerRequests.get(0).getCapability().getVirtualCores()==c.getResource().getVirtualCores() && containerRequests.get(0).getCapability().getMemory()==c.getResource().getMemory();
}
public void launchContainer(Container c) {
RestClient rc = new RestClient();
String restclient = null;
try{
//restclient = rc.issueRequest( "GET", "clusterStatus", null);
}
catch( Exception e){
}
//LOG.info("RestClient response: "+ restclient);
LOG.info("Launching container id = " + c.getId() + " on node = " + c.getNodeId()+" operator: "+params.getName());
containers.put(c.getId(), c);
needed.decrementAndGet();
try {
this.ctxt = service.factory.create(params);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nodeManager.startContainerAsync(c, ctxt);
}
public boolean hasRunningContainers() {
return !containers.isEmpty();
}
public void kill() {
for (Container c : containers.values()) {
nodeManager.stopContainerAsync(c.getId(), c.getNodeId());
}
}
public boolean hasMoreContainers() {
return needsContainers() || hasRunningContainers();
}
}
| cloudera-kitten/java/master/src/main/java/com/cloudera/kitten/appmaster/service/ContainerTracker.java | package com.cloudera.kitten.appmaster.service;
import gr.ntua.cslab.asap.client.RestClient;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.client.api.AMRMClient;
import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
import org.apache.hadoop.yarn.client.api.async.NMClientAsync;
import com.cloudera.kitten.ContainerLaunchContextFactory;
import com.cloudera.kitten.ContainerLaunchParameters;
import com.google.common.collect.Maps;
public class ContainerTracker implements NMClientAsync.CallbackHandler {
private static final Log LOG = LogFactory.getLog(ContainerTracker.class);
public final ContainerLaunchParameters params;
private final ConcurrentMap<ContainerId, Container> containers = Maps.newConcurrentMap();
private AtomicInteger needed = new AtomicInteger();
private AtomicInteger started = new AtomicInteger();
public AtomicInteger completed = new AtomicInteger();
private AtomicInteger failed = new AtomicInteger();
private NMClientAsync nodeManager;
private Resource resource;
private Priority priority;
private ContainerLaunchContext ctxt;
private List<ContainerTracker> nextTrackers;
private List<ContainerTracker> previousTrackers;
public boolean isInitilized;
private List<AMRMClient.ContainerRequest> containerRequests;
private WorkflowService service;
private long startTime;
public ContainerTracker(WorkflowService service, ContainerLaunchParameters parameters) {
this.service = service;
this.params = parameters;
this.nextTrackers = new ArrayList<ContainerTracker>();
this.previousTrackers = new ArrayList<ContainerTracker>();
needed.set(1);
isInitilized=false;
}
public void addNextTracker(ContainerTracker tracker){
this.nextTrackers.add(tracker);
// LOG.info("NextTrackers for: " +params.getName());
// for(ContainerTracker t:nextTrackers){
// LOG.info("Tracker: " +t.params.getName());
// }
}
public void addPreviousTracker(ContainerTracker tracker){
this.previousTrackers.add(tracker);
}
private boolean allPreviousFinished(){
boolean ret = true;
for(ContainerTracker tracker : previousTrackers){
if(tracker.needsContainers()){
ret=false;
break;
}
}
return ret;
}
public void init(ContainerLaunchContextFactory factory) throws IOException {
if(!allPreviousFinished())
return;
service.parameters.workflow.getOperator(params.getName()).setStatus("running");
startTime = System.currentTimeMillis();
this.nodeManager = NMClientAsync.createNMClientAsync(this);
nodeManager.init(service.conf);
nodeManager.start();
isInitilized=true;
this.resource = factory.createResource(params);
//this.priority = factory.createPriority(params.getPriority());
//hack for https://issues.apache.org/jira/browse/YARN-314
this.priority = factory.createPriority(service.prior);
service.prior++;
//hack for https://issues.apache.org/jira/browse/YARN-314
int numInstances = params.getNumInstances();
LOG.info("Operator: "+params.getName()+" requesting " + numInstances+" containers");
LOG.info("Resource cores: "+ resource.getVirtualCores());
LOG.info("Resource memory: "+ resource.getMemory());
LOG.info("Has nodes: "+ params.getNodes());
String[] nodes = params.getNodes();//= {"slave1"};
String labels = params.getLabels();
AMRMClient.ContainerRequest containerRequest=null;
if(labels==null){
LOG.info("Resource nodes: all");
containerRequest = new AMRMClient.ContainerRequest(
resource,
nodes, // nodes
null, // racks
priority,
true, //true for relaxed locality
"");
}
else{
LOG.info("Resource labels: "+ labels);
for (int i = 0; i < nodes.length; i++) {
LOG.info("Resource nodes: "+ nodes[i]);
}
containerRequest = new AMRMClient.ContainerRequest(
resource,
nodes, // nodes
null, // racks
priority,
false, //true for relaxed locality
"");
}
this.containerRequests = new ArrayList<AMRMClient.ContainerRequest>();
//restartResourceManager();
for (int j = 0; j < numInstances; j++) {
service.resourceManager.addContainerRequest(containerRequest);
containerRequests.add(containerRequest);
}
needed.set(numInstances);
}
@Override
public void onContainerStarted(ContainerId containerId, Map<String, ByteBuffer> allServiceResponse) {
Container container = containers.get(containerId);
if (container != null) {
LOG.info("Starting container id = " + containerId);
started.incrementAndGet();
nodeManager.getContainerStatusAsync(containerId, container.getNodeId());
}
}
@Override
public void onContainerStatusReceived(ContainerId containerId, ContainerStatus containerStatus) {
if (LOG.isDebugEnabled()) {
LOG.debug("Received status for container: " + containerId + " = " + containerStatus);
}
}
@Override
public void onContainerStopped(ContainerId containerId) {
LOG.info("Stopping container id = " + containerId);
Container v = containers.remove(containerId);
if(v==null)
return;
completed.incrementAndGet();
/*if(!hasMoreContainers()){
LOG.info("Starting next trackers" );
for(ContainerTracker t : nextTrackers){
try {
t.init(factory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
}
public void removeContainerRequests(){
LOG.info("Removing container requests");
for(ContainerRequest c : containerRequests){
LOG.info("Removing cores: "+c.getCapability().getVirtualCores()+" mem: "+c.getCapability().getMemory());
service.resourceManager.removeContainerRequest(c);
}
LOG.info("Blockers: "+service.resourceManager.getBlockers());
}
public void containerCompleted(ContainerId containerId) {
isInitilized=false;
LOG.info("Completed container id = " + containerId+" operator: "+params.getName());
long stop = System.currentTimeMillis();
double time = (stop-startTime)/1000.0-5;//5sec init container
service.parameters.workflow.getOperator(params.getName()).setCost(time+"");
containers.remove(containerId);
completed.incrementAndGet();
service.parameters.workflow.setOutputsRunning(params.getName());
if(!hasMoreContainers()){
removeContainerRequests();
LOG.info("Starting next trackers" );
for(ContainerTracker t : nextTrackers){
try {
t.init(service.factory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void onStartContainerError(ContainerId containerId, Throwable throwable) {
LOG.warn("Start container error for container id = " + containerId, throwable);
containers.remove(containerId);
completed.incrementAndGet();
failed.incrementAndGet();
}
@Override
public void onGetContainerStatusError(ContainerId containerId, Throwable throwable) {
LOG.error("Could not get status for container: " + containerId, throwable);
}
@Override
public void onStopContainerError(ContainerId containerId, Throwable throwable) {
LOG.error("Failed to stop container: " + containerId, throwable);
completed.incrementAndGet();
}
public boolean needsContainers() {
//LOG.info("operator: "+params.getName()+" needed: "+needed);
return needed.get() > 0;
}
public boolean matches(Container c) {
return containerRequests.get(0).getCapability().getVirtualCores()==c.getResource().getVirtualCores() && containerRequests.get(0).getCapability().getMemory()==c.getResource().getMemory();
}
public void launchContainer(Container c) {
RestClient rc = new RestClient();
String restclient = null;
try{
restclient = rc.issueRequest( "GET", "clusterStatus", null);
}
catch( Exception e){
}
LOG.info("RestClient response: "+ restclient);
LOG.info("Launching container id = " + c.getId() + " on node = " + c.getNodeId()+" operator: "+params.getName());
containers.put(c.getId(), c);
needed.decrementAndGet();
try {
this.ctxt = service.factory.create(params);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nodeManager.startContainerAsync(c, ctxt);
}
public boolean hasRunningContainers() {
return !containers.isEmpty();
}
public void kill() {
for (Container c : containers.values()) {
nodeManager.stopContainerAsync(c.getId(), c.getNodeId());
}
}
public boolean hasMoreContainers() {
return needsContainers() || hasRunningContainers();
}
}
| Replanning on execution
| cloudera-kitten/java/master/src/main/java/com/cloudera/kitten/appmaster/service/ContainerTracker.java | Replanning on execution | <ide><path>loudera-kitten/java/master/src/main/java/com/cloudera/kitten/appmaster/service/ContainerTracker.java
<ide> RestClient rc = new RestClient();
<ide> String restclient = null;
<ide> try{
<del> restclient = rc.issueRequest( "GET", "clusterStatus", null);
<add> //restclient = rc.issueRequest( "GET", "clusterStatus", null);
<ide> }
<ide> catch( Exception e){
<ide>
<ide> }
<del> LOG.info("RestClient response: "+ restclient);
<add> //LOG.info("RestClient response: "+ restclient);
<ide> LOG.info("Launching container id = " + c.getId() + " on node = " + c.getNodeId()+" operator: "+params.getName());
<ide> containers.put(c.getId(), c);
<ide> needed.decrementAndGet(); |
|
Java | apache-2.0 | 8c639261b577095d4e97260b88b6d08fe95fc4aa | 0 | JetBrains/ttorrent-lib,mpetazzoni/ttorrent,JetBrains/ttorrent-lib,mpetazzoni/ttorrent | package com.turn.ttorrent.client;
import com.turn.ttorrent.common.AnnounceableInformation;
import com.turn.ttorrent.common.Pair;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TorrentsStorage {
private final ReadWriteLock myReadWriteLock;
private final Map<String, SharedTorrent> myActiveTorrents;
private final Map<String, LoadedTorrent> myAnnounceableTorrents;
public TorrentsStorage() {
myReadWriteLock = new ReentrantReadWriteLock();
myActiveTorrents = new HashMap<String, SharedTorrent>();
myAnnounceableTorrents = new HashMap<String, LoadedTorrent>();
}
public boolean hasTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myAnnounceableTorrents.containsKey(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public LoadedTorrent getAnnounceableTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myAnnounceableTorrents.get(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void peerDisconnected(String torrentHash) {
final SharedTorrent torrent;
try {
myReadWriteLock.writeLock().lock();
torrent = myActiveTorrents.get(torrentHash);
if (torrent == null) return;
boolean isTorrentFinished = torrent.isFinished();
if (torrent.getDownloadersCount() == 0 && isTorrentFinished) {
myActiveTorrents.remove(torrentHash);
} else {
return;
}
} finally {
myReadWriteLock.writeLock().unlock();
}
torrent.close();
}
public SharedTorrent getTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myActiveTorrents.get(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void addAnnounceableTorrent(String hash, LoadedTorrent torrent) {
try {
myReadWriteLock.writeLock().lock();
myAnnounceableTorrents.put(hash, torrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
}
public SharedTorrent putIfAbsentActiveTorrent(String hash, SharedTorrent torrent) {
try {
myReadWriteLock.writeLock().lock();
final SharedTorrent old = myActiveTorrents.get(hash);
if (old != null) return old;
return myActiveTorrents.put(hash, torrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
}
public Pair<SharedTorrent, LoadedTorrent> remove(String hash) {
final Pair<SharedTorrent, LoadedTorrent> result;
try {
myReadWriteLock.writeLock().lock();
final SharedTorrent sharedTorrent = myActiveTorrents.remove(hash);
final LoadedTorrent loadedTorrent = myAnnounceableTorrents.remove(hash);
result = new Pair<SharedTorrent, LoadedTorrent>(sharedTorrent, loadedTorrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
if (result.first() != null) {
result.first().close();
}
return result;
}
public List<SharedTorrent> activeTorrents() {
try {
myReadWriteLock.readLock().lock();
return new ArrayList<SharedTorrent>(myActiveTorrents.values());
} finally {
myReadWriteLock.readLock().unlock();
}
}
public List<AnnounceableInformation> announceableTorrents() {
List<AnnounceableInformation> result = new ArrayList<AnnounceableInformation>();
try {
myReadWriteLock.readLock().lock();
for (LoadedTorrent loadedTorrent : myAnnounceableTorrents.values()) {
result.add(loadedTorrent.createAnnounceableInformation());
}
return result;
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void clear() {
final Collection<SharedTorrent> sharedTorrents;
try {
myReadWriteLock.writeLock().lock();
sharedTorrents = new ArrayList<SharedTorrent>(myActiveTorrents.values());
myAnnounceableTorrents.clear();
myActiveTorrents.clear();
} finally {
myReadWriteLock.writeLock().unlock();
}
for (SharedTorrent sharedTorrent : sharedTorrents) {
sharedTorrent.close();
}
}
}
| ttorrent-client/src/main/java/com/turn/ttorrent/client/TorrentsStorage.java | package com.turn.ttorrent.client;
import com.turn.ttorrent.common.AnnounceableInformation;
import com.turn.ttorrent.common.Pair;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TorrentsStorage {
private final ReadWriteLock myReadWriteLock;
private final Map<String, SharedTorrent> myActiveTorrents;
private final Map<String, LoadedTorrent> myAnnounceableTorrents;
public TorrentsStorage() {
myReadWriteLock = new ReentrantReadWriteLock();
myActiveTorrents = new HashMap<String, SharedTorrent>();
myAnnounceableTorrents = new HashMap<String, LoadedTorrent>();
}
public boolean hasTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myAnnounceableTorrents.containsKey(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public LoadedTorrent getAnnounceableTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myAnnounceableTorrents.get(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void peerDisconnected(String torrentHash) {
final SharedTorrent torrent;
try {
myReadWriteLock.writeLock().lock();
torrent = myActiveTorrents.get(torrentHash);
if (torrent == null) return;
final ClientState clientState = torrent.getClientState();
boolean isTorrentFinished = torrent.isFinished();
if (torrent.getDownloadersCount() == 0 && isTorrentFinished) {
myActiveTorrents.remove(torrentHash);
} else {
return;
}
} finally {
myReadWriteLock.writeLock().unlock();
}
torrent.close();
}
public SharedTorrent getTorrent(String hash) {
try {
myReadWriteLock.readLock().lock();
return myActiveTorrents.get(hash);
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void addAnnounceableTorrent(String hash, LoadedTorrent torrent) {
try {
myReadWriteLock.writeLock().lock();
myAnnounceableTorrents.put(hash, torrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
}
public SharedTorrent putIfAbsentActiveTorrent(String hash, SharedTorrent torrent) {
try {
myReadWriteLock.writeLock().lock();
final SharedTorrent old = myActiveTorrents.get(hash);
if (old != null) return old;
return myActiveTorrents.put(hash, torrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
}
public Pair<SharedTorrent, LoadedTorrent> remove(String hash) {
final Pair<SharedTorrent, LoadedTorrent> result;
try {
myReadWriteLock.writeLock().lock();
final SharedTorrent sharedTorrent = myActiveTorrents.remove(hash);
final LoadedTorrent loadedTorrent = myAnnounceableTorrents.remove(hash);
result = new Pair<SharedTorrent, LoadedTorrent>(sharedTorrent, loadedTorrent);
} finally {
myReadWriteLock.writeLock().unlock();
}
if (result.first() != null) {
result.first().close();
}
return result;
}
public List<SharedTorrent> activeTorrents() {
try {
myReadWriteLock.readLock().lock();
return new ArrayList<SharedTorrent>(myActiveTorrents.values());
} finally {
myReadWriteLock.readLock().unlock();
}
}
public List<AnnounceableInformation> announceableTorrents() {
List<AnnounceableInformation> result = new ArrayList<AnnounceableInformation>();
try {
myReadWriteLock.readLock().lock();
for (LoadedTorrent loadedTorrent : myAnnounceableTorrents.values()) {
result.add(loadedTorrent.createAnnounceableInformation());
}
return result;
} finally {
myReadWriteLock.readLock().unlock();
}
}
public void clear() {
final Collection<SharedTorrent> sharedTorrents;
try {
myReadWriteLock.writeLock().lock();
sharedTorrents = new ArrayList<SharedTorrent>(myActiveTorrents.values());
myAnnounceableTorrents.clear();
myActiveTorrents.clear();
} finally {
myReadWriteLock.writeLock().unlock();
}
for (SharedTorrent sharedTorrent : sharedTorrents) {
sharedTorrent.close();
}
}
}
| remove unused statement
| ttorrent-client/src/main/java/com/turn/ttorrent/client/TorrentsStorage.java | remove unused statement | <ide><path>torrent-client/src/main/java/com/turn/ttorrent/client/TorrentsStorage.java
<ide> torrent = myActiveTorrents.get(torrentHash);
<ide> if (torrent == null) return;
<ide>
<del> final ClientState clientState = torrent.getClientState();
<ide> boolean isTorrentFinished = torrent.isFinished();
<ide> if (torrent.getDownloadersCount() == 0 && isTorrentFinished) {
<ide> myActiveTorrents.remove(torrentHash); |
|
Java | epl-1.0 | fe6fefe151ab739a2790bb4a68a271131038c934 | 0 | collaborative-modeling/egit,paulvi/egit,wdliu/egit,SmithAndr/egit,collaborative-modeling/egit,blizzy78/egit,paulvi/egit,SmithAndr/egit,wdliu/egit | /*******************************************************************************
* Copyright (c) 2010, 2013 SAP AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mathias Kinzler (SAP AG) - initial implementation
* Dariusz Luksza ([email protected]) - disable command when HEAD cannot be
* resolved
*******************************************************************************/
package org.eclipse.egit.ui.internal.commands.shared;
import static org.eclipse.ui.handlers.HandlerUtil.getCurrentSelectionChecked;
import java.io.IOException;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.egit.core.op.RebaseOperation;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.dialogs.BasicConfigurationDialog;
import org.eclipse.egit.ui.internal.dialogs.RebaseTargetSelectionDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.osgi.util.NLS;
/**
* Implements "Rebase" to the currently checked out {@link Ref}
*/
public class RebaseCurrentRefCommand extends AbstractRebaseCommandHandler {
private Ref ref;
/** */
public RebaseCurrentRefCommand() {
super(UIText.RebaseCurrentRefCommand_RebasingCurrentJobName,
UIText.RebaseCurrentRefCommand_RebaseCanceledMessage);
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// we need the ref from the event in createRebaseOperation
setRef(event);
if (ref == null)
return null;
return super.execute(event);
}
private void setRef(ExecutionEvent event) throws ExecutionException {
ISelection currentSelection = getCurrentSelectionChecked(event);
if (currentSelection instanceof IStructuredSelection) {
IStructuredSelection selection = (IStructuredSelection) currentSelection;
Object selected = selection.getFirstElement();
ref = getRef(selected);
} else
ref = null;
final Repository repository = getRepository(event);
if (repository == null)
return;
BasicConfigurationDialog.show(repository);
String currentFullBranch = getFullBranch(repository);
if (ref != null && ref.getName().equals(currentFullBranch))
ref = null;
if (ref == null) {
RebaseTargetSelectionDialog rebaseTargetSelectionDialog = new RebaseTargetSelectionDialog(
getShell(event), repository);
if (rebaseTargetSelectionDialog.open() == IDialogConstants.OK_ID) {
String refName = rebaseTargetSelectionDialog.getRefName();
try {
ref = repository.getRef(refName);
} catch (IOException e) {
throw new ExecutionException(e.getMessage(), e);
}
} else
return;
}
jobname = NLS.bind(
UIText.RebaseCurrentRefCommand_RebasingCurrentJobName,
Repository.shortenRefName(currentFullBranch), ref.getName());
}
@Override
public void setEnabled(Object evaluationContext) {
if (evaluationContext instanceof IEvaluationContext) {
IEvaluationContext ctx = (IEvaluationContext) evaluationContext;
Object selection = getSelection(ctx);
if (selection instanceof ISelection) {
Repository repo = getRepository((ISelection) selection, getActiveEditorInput(ctx));
if (repo != null) {
boolean enabled = isEnabledForState(repo,
repo.getRepositoryState());
setBaseEnabled(enabled);
} else
setBaseEnabled(false);
return;
}
}
setBaseEnabled(true);
}
/**
* @param repo
* @param state
* @return whether this command is enabled for the repository state
*/
public static boolean isEnabledForState(Repository repo,
RepositoryState state) {
return state == RepositoryState.SAFE && hasHead(repo);
}
private static boolean hasHead(Repository repo) {
try {
Ref headRef = repo.getRef(Constants.HEAD);
return headRef != null && headRef.getObjectId() != null;
} catch (IOException e) {
return false;
}
}
private String getFullBranch(Repository repository)
throws ExecutionException {
try {
return repository.getFullBranch();
} catch (IOException e) {
throw new ExecutionException(
UIText.RebaseCurrentRefCommand_ErrorGettingCurrentBranchMessage,
e);
}
}
@Override
protected RebaseOperation createRebaseOperation(Repository repository)
throws ExecutionException {
return new RebaseOperation(repository, ref);
}
}
| org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/RebaseCurrentRefCommand.java | /*******************************************************************************
* Copyright (c) 2010, 2013 SAP AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mathias Kinzler (SAP AG) - initial implementation
* Dariusz Luksza ([email protected]) - disable command when HEAD cannot be
* resolved
*******************************************************************************/
package org.eclipse.egit.ui.internal.commands.shared;
import static org.eclipse.ui.handlers.HandlerUtil.getCurrentSelectionChecked;
import java.io.IOException;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.egit.core.op.RebaseOperation;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.dialogs.BasicConfigurationDialog;
import org.eclipse.egit.ui.internal.dialogs.RebaseTargetSelectionDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.osgi.util.NLS;
/**
* Implements "Rebase" to the currently checked out {@link Ref}
*/
public class RebaseCurrentRefCommand extends AbstractRebaseCommandHandler {
private Ref ref;
/** */
public RebaseCurrentRefCommand() {
super(UIText.RebaseCurrentRefCommand_RebasingCurrentJobName,
UIText.RebaseCurrentRefCommand_RebaseCanceledMessage);
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// we need the ref from the event in createRebaseOperation
ref = setRef(event);
if (ref == null)
return null;
return super.execute(event);
}
private Ref setRef(ExecutionEvent event) throws ExecutionException {
ISelection currentSelection = getCurrentSelectionChecked(event);
if (currentSelection instanceof IStructuredSelection) {
IStructuredSelection selection = (IStructuredSelection) currentSelection;
Object selected = selection.getFirstElement();
ref = getRef(selected);
} else
ref = null;
final Repository repository = getRepository(event);
if (repository == null)
return null;
BasicConfigurationDialog.show(repository);
String currentFullBranch = getFullBranch(repository);
if (ref != null && ref.getName().equals(currentFullBranch))
ref = null;
if (ref == null) {
RebaseTargetSelectionDialog rebaseTargetSelectionDialog = new RebaseTargetSelectionDialog(
getShell(event), repository);
if (rebaseTargetSelectionDialog.open() == IDialogConstants.OK_ID) {
String refName = rebaseTargetSelectionDialog.getRefName();
try {
ref = repository.getRef(refName);
} catch (IOException e) {
throw new ExecutionException(e.getMessage(), e);
}
} else
return null;
}
jobname = NLS.bind(
UIText.RebaseCurrentRefCommand_RebasingCurrentJobName,
Repository.shortenRefName(currentFullBranch), ref.getName());
return null;
}
@Override
public void setEnabled(Object evaluationContext) {
if (evaluationContext instanceof IEvaluationContext) {
IEvaluationContext ctx = (IEvaluationContext) evaluationContext;
Object selection = getSelection(ctx);
if (selection instanceof ISelection) {
Repository repo = getRepository((ISelection) selection, getActiveEditorInput(ctx));
if (repo != null) {
boolean enabled = isEnabledForState(repo,
repo.getRepositoryState());
setBaseEnabled(enabled);
} else
setBaseEnabled(false);
return;
}
}
setBaseEnabled(true);
}
/**
* @param repo
* @param state
* @return whether this command is enabled for the repository state
*/
public static boolean isEnabledForState(Repository repo,
RepositoryState state) {
return state == RepositoryState.SAFE && hasHead(repo);
}
private static boolean hasHead(Repository repo) {
try {
Ref headRef = repo.getRef(Constants.HEAD);
return headRef != null && headRef.getObjectId() != null;
} catch (IOException e) {
return false;
}
}
private String getFullBranch(Repository repository)
throws ExecutionException {
try {
return repository.getFullBranch();
} catch (IOException e) {
throw new ExecutionException(
UIText.RebaseCurrentRefCommand_ErrorGettingCurrentBranchMessage,
e);
}
}
@Override
protected RebaseOperation createRebaseOperation(Repository repository)
throws ExecutionException {
return new RebaseOperation(repository, ref);
}
}
| Fix rebase triggered from Git Repositories View
Commit c498ed5baf44cee961385448b39b4ed750bfdae9 introduced a bug.
Rebase... triggered from Git Repositories View did not work anymore.
Bug: 422138
Change-Id: I555d9e87c72bfcdc6e9315191bbe79a08836db8a
Signed-off-by: Stefan Lay <[email protected]> | org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/RebaseCurrentRefCommand.java | Fix rebase triggered from Git Repositories View | <ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/RebaseCurrentRefCommand.java
<ide> @Override
<ide> public Object execute(ExecutionEvent event) throws ExecutionException {
<ide> // we need the ref from the event in createRebaseOperation
<del> ref = setRef(event);
<add> setRef(event);
<ide> if (ref == null)
<ide> return null;
<ide> return super.execute(event);
<ide> }
<ide>
<del> private Ref setRef(ExecutionEvent event) throws ExecutionException {
<add> private void setRef(ExecutionEvent event) throws ExecutionException {
<ide> ISelection currentSelection = getCurrentSelectionChecked(event);
<ide> if (currentSelection instanceof IStructuredSelection) {
<ide> IStructuredSelection selection = (IStructuredSelection) currentSelection;
<ide>
<ide> final Repository repository = getRepository(event);
<ide> if (repository == null)
<del> return null;
<add> return;
<ide>
<ide> BasicConfigurationDialog.show(repository);
<ide>
<ide> throw new ExecutionException(e.getMessage(), e);
<ide> }
<ide> } else
<del> return null;
<add> return;
<ide> }
<ide>
<ide> jobname = NLS.bind(
<ide> UIText.RebaseCurrentRefCommand_RebasingCurrentJobName,
<ide> Repository.shortenRefName(currentFullBranch), ref.getName());
<del> return null;
<ide> }
<ide>
<ide> @Override |
|
Java | epl-1.0 | 230a172c65fec3112c4ce739f2736f5e60b21626 | 0 | johannrichard/openhab2-addons,jarlebh/openhab2-addons,gerrieg/openhab2,jarlebh/openhab2-addons,Mr-Eskildsen/openhab2-addons,trokohl/openhab2-addons,pgfeller/openhab2-addons,lewie/openhab2,aogorek/openhab2-addons,johannrichard/openhab2-addons,afuechsel/openhab2,pgfeller/openhab2-addons,dimalo/openhab2-addons,tavalin/openhab2-addons,Snickermicker/openhab2,aogorek/openhab2-addons,tavalin/openhab2-addons,jarlebh/openhab2-addons,trokohl/openhab2-addons,pail23/openhab2-addons,dimalo/openhab2-addons,aogorek/openhab2-addons,gerrieg/openhab2,clinique/openhab2,Snickermicker/openhab2,clinique/openhab2,tavalin/openhab2-addons,lewie/openhab2,theoweiss/openhab2,tavalin/openhab2-addons,digitaldan/openhab2,trokohl/openhab2-addons,digitaldan/openhab2,theoweiss/openhab2,trokohl/openhab2-addons,pail23/openhab2-addons,afuechsel/openhab2,Mr-Eskildsen/openhab2-addons,trokohl/openhab2-addons,aogorek/openhab2-addons,clinique/openhab2,pgfeller/openhab2-addons,tavalin/openhab2-addons,theoweiss/openhab2,theoweiss/openhab2,dimalo/openhab2-addons,afuechsel/openhab2,Snickermicker/openhab2,jarlebh/openhab2-addons,johannrichard/openhab2-addons,Snickermicker/openhab2,gerrieg/openhab2,jarlebh/openhab2-addons,jarlebh/openhab2-addons,Mr-Eskildsen/openhab2-addons,aogorek/openhab2-addons,pail23/openhab2-addons,aogorek/openhab2-addons,johannrichard/openhab2-addons,trokohl/openhab2-addons,Mr-Eskildsen/openhab2-addons,pgfeller/openhab2-addons,digitaldan/openhab2,pail23/openhab2-addons,tavalin/openhab2-addons,johannrichard/openhab2-addons,Mr-Eskildsen/openhab2-addons,lewie/openhab2,dimalo/openhab2-addons,clinique/openhab2,pgfeller/openhab2-addons,pail23/openhab2-addons,dimalo/openhab2-addons,digitaldan/openhab2,gerrieg/openhab2 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.knx.internal.dpt;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.smarthome.core.library.types.DateTimeType;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.HSBType;
import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.OpenClosedType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.StopMoveType;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.library.types.UpDownType;
import org.eclipse.smarthome.core.types.Type;
import org.eclipse.smarthome.core.types.UnDefType;
import org.openhab.binding.knx.KNXTypeMapper;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tuwien.auto.calimero.KNXException;
import tuwien.auto.calimero.KNXFormatException;
import tuwien.auto.calimero.KNXIllegalArgumentException;
import tuwien.auto.calimero.datapoint.Datapoint;
import tuwien.auto.calimero.dptxlator.DPT;
import tuwien.auto.calimero.dptxlator.DPTXlator;
import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;
import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat;
import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlator64BitSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator8BitSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;
import tuwien.auto.calimero.dptxlator.DPTXlatorDate;
import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;
import tuwien.auto.calimero.dptxlator.DPTXlatorRGB;
import tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl;
import tuwien.auto.calimero.dptxlator.DPTXlatorSceneNumber;
import tuwien.auto.calimero.dptxlator.DPTXlatorString;
import tuwien.auto.calimero.dptxlator.DPTXlatorTime;
import tuwien.auto.calimero.dptxlator.DPTXlatorUtf8;
import tuwien.auto.calimero.dptxlator.TranslatorTypes;
/**
* This class provides type mapping between all openHAB core types and KNX data point types.
*
* Each 'MainType' delivered from calimero, has a default mapping
* for all it's children to a openHAB Typeclass.
* All these 'MainType' mapping's are put into 'dptMainTypeMap'.
*
* Default 'MainType' mapping's we can override by a specific mapping.
* All specific mapping's are put into 'dptTypeMap'.
*
* If for a 'MainType' there is currently no specific mapping registered,
* you can find a commented example line, with it's correct 'DPTXlator' class.
*
* @author Kai Kreuzer
* @author Volker Daube
* @author Jan N. Klug
* @author Helmut Lehmeyer - Java8, generic DPT Mapper
*/
@Component
public class KNXCoreTypeMapper implements KNXTypeMapper {
private final Logger logger = LoggerFactory.getLogger(KNXCoreTypeMapper.class);
private static final String TIME_DAY_FORMAT = new String("EEE, HH:mm:ss");
private static final String DATE_FORMAT = new String("yyyy-MM-dd");
/**
* stores the openHAB type class for (supported) KNX datapoint types in a generic way.
* dptTypeMap stores more specific type class and exceptions.
*/
private final Map<Integer, Class<? extends Type>> dptMainTypeMap;
/** stores the openHAB type class for all (supported) KNX datapoint types */
private final Map<String, Class<? extends Type>> dptTypeMap;
/** stores the default KNX DPT to use for each openHAB type */
private final Map<Class<? extends Type>, String> defaultDptMap;
public KNXCoreTypeMapper() {
@SuppressWarnings("unused")
final List<Class<?>> xlators = Arrays.<Class<?>> asList(DPTXlator1BitControlled.class,
DPTXlator2ByteFloat.class, DPTXlator2ByteUnsigned.class, DPTXlator3BitControlled.class,
DPTXlator4ByteFloat.class, DPTXlator4ByteSigned.class, DPTXlator4ByteUnsigned.class,
DPTXlator64BitSigned.class, DPTXlator8BitSigned.class, DPTXlator8BitUnsigned.class,
DPTXlatorBoolean.class, DPTXlatorDate.class, DPTXlatorDateTime.class, DPTXlatorRGB.class,
DPTXlatorSceneControl.class, DPTXlatorSceneNumber.class, DPTXlatorString.class, DPTXlatorTime.class,
DPTXlatorUtf8.class);
dptTypeMap = new HashMap<String, Class<? extends Type>>();
dptMainTypeMap = new HashMap<Integer, Class<? extends Type>>();
/**
* MainType: 1
* 1.005: Alarm, values: 0 = no alarm, 1 = alarm
* 1.016: Acknowledge, values: 0 = no action, 1 = acknowledge
* 1.006: Binary value, values: 0 = low, 1 = high
* 1.017: Trigger, values: 0 = trigger, 1 = trigger
* 1.007: Step, values: 0 = decrease, 1 = increase
* 1.018: Occupancy, values: 0 = not occupied, 1 = occupied
* 1.008: Up/Down, values: 0 = up, 1 = down
* 1.019: Window/Door, values: 0 = closed, 1 = open
* 1.009: Open/Close, values: 0 = open, 1 = close
* 1.010: Start, values: 0 = stop, 1 = start
* 1.021: Logical function, values: 0 = OR, 1 = AND
* 1.011: State, values: 0 = inactive, 1 = active
* 1.022: Scene A/B, values: 0 = scene A, 1 = scene B
* 1.001: Switch, values: 0 = off, 1 = on
* 1.012: Invert, values: 0 = not inverted, 1 = inverted
* 1.023: Shutter/Blinds mode, values: 0 = only move up/down, 1 = move up/down + step-stop
* 1.100: Heat/Cool, values: 0 = cooling, 1 = heating
* 1.002: Boolean, values: 0 = false, 1 = true
* 1.013: Dim send-style, values: 0 = start/stop, 1 = cyclic
* 1.003: Enable, values: 0 = disable, 1 = enable
* 1.014: Input source, values: 0 = fixed, 1 = calculated
* 1.004: Ramp, values: 0 = no ramp, 1 = ramp
* 1.015: Reset, values: 0 = no action, 1 = reset
*/
dptMainTypeMap.put(1, OnOffType.class);
/** Exceptions Datapoint Types "B1", Main number 1 */
dptTypeMap.put(DPTXlatorBoolean.DPT_UPDOWN.getID(), UpDownType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_OPENCLOSE.getID(), OpenClosedType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_START.getID(), StopMoveType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_WINDOW_DOOR.getID(), OpenClosedType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_SCENE_AB.getID(), DecimalType.class);
/**
* MainType: 2
* 2.002: Boolean Controlled, values: 0 = false, 1 = true
* 2.003: Enable Controlled, values: 0 = disable, 1 = enable
* 2.011: State Controlled, values: 0 = inactive, 1 = active
* 2.001: Switch Controlled, values: 0 = off, 1 = on
* 2.012: Invert Controlled, values: 0 = not inverted, 1 = inverted
* 2.010: Start Controlled, values: 0 = stop, 1 = start
* 2.008: Up/Down Controlled, values: 0 = up, 1 = down
* 2.009: Open/Close Controlled, values: 0 = open, 1 = close
* 2.006: Binary Controlled, values: 0 = low, 1 = high
* 2.007: Step Controlled, values: 0 = decrease, 1 = increase
* 2.004: Ramp Controlled, values: 0 = no ramp, 1 = ramp
* 2.005: Alarm Controlled, values: 0 = no alarm, 1 = alarm
*/
dptMainTypeMap.put(2, DecimalType.class);
/** Exceptions Datapoint Types "B2", Main number 2 */
// Example: dptTypeMap.put(DPTXlator1BitControlled.DPT_SWITCH_CONTROL.getID(), DecimalType.class);
/**
* MainType: 3
* 3.007: Dimming, values: 0 = decrease, 1 = increase
* 3.008: Blinds, values: 0 = up, 1 = down
*/
dptMainTypeMap.put(3, IncreaseDecreaseType.class);
/** Exceptions Datapoint Types "B1U3", Main number 3 */
dptTypeMap.put(DPTXlator3BitControlled.DPT_CONTROL_BLINDS.getID(), UpDownType.class);
/**
* MainType: 5
* 5.010: Unsigned count, values: 0...255 counter pulses
* 5.001: Scaling, values: 0...100 %
* 5.003: Angle, values: 0...360 °
* 5.004: Percent (8 Bit), values: 0...255 %
* 5.005: Decimal factor, values: 0...255 ratio
* 5.006: Tariff information, values: 0...254
*/
dptMainTypeMap.put(5, DecimalType.class);
/** Exceptions Types "8-Bit Unsigned Value", Main number 5 */
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_SCALING.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID(), PercentType.class);
/**
* MainType: 6
* 6.001: Percent (8 Bit), values: -128...127 %
* 6.020: status with mode, values: 0/0/0/0/0 0...1/1/1/1/1 2
* 6.010: signed count, values: -128...127 counter pulses
*/
dptMainTypeMap.put(6, DecimalType.class);
/** Exceptions Datapoint Types "8-Bit Signed Value", Main number 6 */
dptTypeMap.put(DPTXlator8BitSigned.DPT_PERCENT_V8.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitSigned.DPT_STATUS_MODE3.getID(), StringType.class);
/**
* MainType: 7
* 7.003: Time period (resolution 10 ms), values: 0...655350 ms
* 7.004: Time period (resolution 100 ms), values: 0...6553500 ms
* 7.005: Time period in seconds, values: 0...65535 s
* 7.006: Time period in minutes, values: 0...65535 min
* 7.010: Interface object property ID, values: 0...65535
* 7.011: Length in mm, values: 0...65535 mm
* 7.001: Unsigned count, values: 0...65535 pulses
* 7.012: Electrical current, values: 0...65535 mA
* 7.002: Time period in ms, values: 0...65535 ms
* 7.013: Brightness, values: 0...65535 lx
* 7.007: Time period in hours, values: 0...65535 h
*/
dptMainTypeMap.put(7, DecimalType.class);
/** Exceptions Datapoint Types "2-Octet Unsigned Value", Main number 7 */
dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
/**
* MainType: 9
* 9.020: Voltage, values: -670760...+670760 mV
* 9.010: Time difference 1, values: -670760...+670760 s
* 9.021: Electrical current, values: -670760...+670760 mA
* 9.011: Time difference 2, values: -670760...+670760 ms
* 9.022: Power density, values: -670760...+670760 W/m²
* 9.001: Temperature, values: -273...+670760 °C
* 9.023: Kelvin/percent, values: -670760...+670760 K/%
* 9.002: Temperature difference, values: -670760...+670760 K
* 9.024: Power, values: -670760...+670760 kW
* 9.003: Temperature gradient, values: -670760...+670760 K/h
* 9.025: Volume flow, values: -670760...+670760 l/h
* 9.004: Light intensity, values: 0...+670760 lx
* 9.026: Rain amount, values: -671088.64...670760.96 l/m²
* 9.005: Wind speed, values: 0...+670760 m/s
* 9.027: Temperature, values: -459.6...670760.96 °F
* 9.006: Air pressure, values: 0...+670760 Pa
* 9.028: Wind speed, values: 0...670760.96 km/h
* 9.007: Humidity, values: 0...+670760 %
* 9.008: Air quality, values: 0...+670760 ppm
*/
dptMainTypeMap.put(9, DecimalType.class);
/** Exceptions Datapoint Types "2-Octet Float Value", Main number 9 */
dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
/**
* MainType: 10
* 10.001: Time of day, values: 1 = Monday...7 = Sunday, 0 = no-day, 00:00:00 Sun, 23:59:59 dow, hh:mm:ss
*/
dptMainTypeMap.put(10, DateTimeType.class);
/** Exceptions Datapoint Types "Time", Main number 10 */
// Example: dptTypeMap.put(DPTXlatorTime.DPT_TIMEOFDAY.getID(), DateTimeType.class);
/**
* MainType: 11
* 11.001: Date, values: 1990-01-01...2089-12-31, yyyy-mm-dd
*/
dptMainTypeMap.put(11, DateTimeType.class);
/** Exceptions Datapoint Types “Date”", Main number 11 */
// Example: dptTypeMap.put(DPTXlatorDate.DPT_DATE.getID(), DateTimeType.class);
/**
* MainType: 12
* 12.001: Unsigned count, values: 0...4294967295 counter pulses
*/
dptMainTypeMap.put(12, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Unsigned Value", Main number 12 */
// Example: dptTypeMap.put(DPTXlator4ByteUnsigned.DPT_VALUE_4_UCOUNT.getID(), DecimalType.class);
/**
* MainType: 13
* 13.010: Active Energy, values: -2147483648...2147483647 Wh
* 13.001: Counter pulses, values: -2147483648...2147483647 counter pulses
* 13.012: Reactive energy, values: -2147483648...2147483647 VARh
* 13.100: Delta time in seconds, values: -2147483648...2147483647 s
* 13.011: Apparent energy, values: -2147483648...2147483647 VAh
* 13.014: Apparent energy in kVAh, values: -2147483648...2147483647 kVAh
* 13.002: Flow rate, values: -2147483648...2147483647 m3/h
* 13.013: Active energy in kWh, values: -2147483648...2147483647 kWh
* 13.015: Reactive energy in kVARh, values: -2147483648...2147483647 kVARh
*/
dptMainTypeMap.put(13, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Signed Value", Main number 13 */
// Example: dptTypeMap.put(DPTXlator4ByteSigned.DPT_COUNT.getID(), DecimalType.class);
/**
* MainType: 14, Range: [-3.40282347e+38f...3.40282347e+38f]
* 14.019: Electric current, values: A
* 14.018: Electric charge, values: C
* 14.017: Density, values: kg m⁻³
* 14.016: Conductivity, electrical, values: Ω⁻¹m⁻¹
* 14.015: Conductance, values: Ω⁻¹
* 14.059: Reactance, values: Ω
* 14.014: Compressibility, values: m²/N
* 14.058: Pressure, values: Pa
* 14.013: Charge density (volume), values: C m⁻³
* 14.057: Power factor, values:
* 14.012: Charge density (surface), values: C m⁻²
* 14.056: Power, values: W
* 14.011: Capacitance, values: F
* 14.055: Phase angle, degree, values: °
* 14.010: Area, values: m²
* 14.054: Phase angle, radiant, values: rad
* 14.053: Momentum, values: N/s
* 14.052: Mass flux, values: kg/s
* 14.051: Mass, values: kg
* 14.050: Magneto motive force, values: A
* 14.060: Resistance, values: Ω
* 14.029: Electromagnetic moment, values: A m²
* 14.028: Electric potential difference, values: V
* 14.027: Electric potential, values: V
* 14.026: Electric polarization, values: C m⁻²
* 14.025: Electric flux density, values: C m⁻²
* 14.069: Temperature, absolute, values: K
* 14.024: Electric flux, values: Vm
* 14.068: Temperature in Celsius Degree, values: °C
* 14.023: Electric field strength, values: V/m
* 14.067: Surface tension, values: N/m
* 14.022: Electric displacement, values: C m⁻²
* 14.066: Stress, values: Pa
* 14.021: Electric dipole moment, values: Cm
* 14.065: Speed, values: m/s
* 14.020: Electric current density, values: A m⁻²
* 14.064: Sound intensity, values: W m⁻²
* 14.063: Solid angle, values: sr
* 14.062: Self inductance, values: H
* 14.061: Resistivity, values: Ωm
* 14.071: Thermal capacity, values: J/K
* 14.070: Temperature difference, values: K
* 14.039: Length, values: m
* 14.038: Impedance, values: Ω
* 14.037: Heat quantity, values: J
* 14.036: Heat flow rate, values: W
* 14.035: Heat capacity, values: J/K
* 14.079: Work, values: J
* 14.034: Frequency, angular, values: rad/s
* 14.078: Weight, values: N
* 14.033: Frequency, values: Hz
* 14.077: Volume flux, values: m³/s
* 14.032: Force, values: N
* 14.076: Volume, values: m³
* 14.031: Energy, values: J
* 14.075: Torque, values: Nm
* 14.030: Electromotive force, values: V
* 14.074: Time, values: s
* 14.073: Thermoelectric power, values: V/K
* 14.072: Thermal conductivity, values: W/m K⁻¹
* 14.009: Angular velocity, values: rad/s
* 14.008: Momentum, values: Js
* 14.007: Angle, values: °
* 14.006: Angle, values: rad
* 14.005: Amplitude, values:
* 14.049: Magnetization, values: A/m
* 14.004: Mol, values: mol
* 14.048: Magnetic polarization, values: T
* 14.003: Activity, values: s⁻¹
* 14.047: Magnetic moment, values: A m²
* 14.002: Activation energy, values: J/mol
* 14.046: Magnetic flux density, values: T
* 14.001: Acceleration, angular, values: rad s⁻²
* 14.045: Magnetic flux, values: Wb
* 14.000: Acceleration, values: ms⁻²
* 14.044: Magnetic field strength, values: A/m
* 14.043: Luminous intensity, values: cd
* 14.042: Luminous flux, values: lm
* 14.041: Luminance, values: cd m⁻²
* 14.040: Quantity of Light, values: J
*/
dptMainTypeMap.put(14, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Float Value", Main number 14 */
// Example: dptTypeMap.put(DPTXlator4ByteFloat.DPT_ACCELERATION_ANGULAR.getID(), DecimalType.class);
/**
* MainType: 16
* 16.000: ASCII string
* 16.001: ISO-8859-1 string (Latin 1)
*/
dptMainTypeMap.put(16, StringType.class);
/** Exceptions Datapoint Types "String", Main number 16 */
dptTypeMap.put(DPTXlatorString.DPT_STRING_8859_1.getID(), StringType.class);
dptTypeMap.put(DPTXlatorString.DPT_STRING_ASCII.getID(), StringType.class);
/**
* MainType: 17
* 17.001: Scene Number, values: 0...63
*/
dptMainTypeMap.put(17, DecimalType.class);
/** Exceptions Datapoint Types "Scene Number", Main number 17 */
// Example: dptTypeMap.put(DPTXlatorSceneNumber.DPT_SCENE_NUMBER.getID(), DecimalType.class);
/**
* MainType: 18
* 18.001: Scene Control, values: 0...63, 0 = activate, 1 = learn
*/
dptMainTypeMap.put(18, DecimalType.class);
/** Exceptions Datapoint Types "Scene Control", Main number 18 */
// Example: dptTypeMap.put(DPTXlatorSceneControl.DPT_SCENE_CONTROL.getID(), DecimalType.class);
/**
* MainType: 19
* 19.001: Date with time, values: 0 = 1900, 255 = 2155, 01/01 00:00:00, 12/31 24:00:00 yr/mth/day hr:min:sec
*/
dptMainTypeMap.put(19, DateTimeType.class);
/** Exceptions Datapoint Types "DateTime", Main number 19 */
// Example: dptTypeMap.put(DPTXlatorDateTime.DPT_DATE_TIME.getID(), DateTimeType.class);
/**
* MainType: 20
* 20.606: PB Action, enumeration [0..3]
* 20.804: Blinds Control Mode, enumeration [0..1]
* 20.607: Dimm PB Model, enumeration [1..4]
* 20.608: Switch On Mode, enumeration [0..2]
* 20.609: Load Type Set, enumeration [0..2]
* 20.008: PSU Mode, enumeration [0..2]
* 20.602: DALI Fade Time, enumeration [0..15]
* 20.603: Blinking Mode, enumeration [0..2]
* 20.801: SAB Except Behavior, enumeration [0..4]
* 20.604: Light Control Mode, enumeration [0..1]
* 20.802: SAB Behavior Lock/Unlock, enumeration [0..6]
* 20.605: Switch PB Model, enumeration [1..2]
* 20.803: SSSB Mode, enumeration [1..4]
* 20.004: Priority, enumeration [0..3]
* 20.005: Light Application Mode, enumeration [0..2]
* 20.006: Application Area, enumeration [0..14]
* 20.600: Behavior Lock/Unlock, enumeration [0..6]
* 20.007: Alarm Class Type, enumeration [0..3]
* 20.601: Behavior Bus Power Up/Down, enumeration [0..4]
* 20.121: Backup Mode, enumeration [0..1]
* 20.001: System Clock Mode, enumeration [0..2]
* 20.122: Start Synchronization, enumeration [0..2]
* 20.002: Building Mode, enumeration [0..2]
* 20.003: Occupancy Mode, enumeration [0..2]
* 20.610: Load Type Detected, enumeration [0..3]
* 20.017: Sensor Select, enumeration [0..4]
* 20.011: Error Class System, enumeration [0..18]
* 20.012: Error Class HVAC, enumeration [0..4]
* 20.013: Time Delay, enumeration [0..25]
* 20.014: Beaufort Wind Force Scale, enumeration [0..12]
* 20.020: Actuator Connect Type, enumeration [1..2]
* 20.107: Changeover Mode, enumeration [0..2]
* 20.108: Valve Mode, enumeration [1..5]
* 20.109: Damper Mode, enumeration [1..4]
* 20.103: DHW Mode, enumeration [0..4]
* 20.104: Load Priority, enumeration [0..2]
* 20.105: HVAC Control Mode, enumeration [0..20]
* 20.106: HVAC Emergency Mode, enumeration [0..5]
* 20.100: Fuel Type, enumeration [0..3]
* 20.101: Burner Type, enumeration [0..3]
* 20.102: HVAC Mode, enumeration [0..4]
* 20.114: Metering Device Type, enumeration [0..41/255]
* 20.110: Heater Mode, enumeration [1..3]
* 20.1202: Gas Measurement Condition, enumeration [0..3]
* 20.111: Fan Mode, enumeration [0..2]
* 20.1003: RF Filter Select, enumeration [0..3]
* 20.112: Master/Slave Mode, enumeration [0..2]
* 20.1002: RF Mode Select, enumeration [0..2]
* 20.1200: M-Bus Breaker/Valve State, enumeration [0..255]
* 20.113: Status Room Setpoint, enumeration [0..2]
* 20.1001: Additional Info Type, enumeration [0..7]
* 20.1000: Comm Mode, enumeration [0..255]
* 20.120: Air Damper Actuator Type, enumeration [1..2]
*/
dptMainTypeMap.put(20, StringType.class);
/** Exceptions Datapoint Types, Main number 20 */
// Example since calimero 2.4: dptTypeMap.put(DPTXlator8BitEnum.DptSystemClockMode.getID(), StringType.class);
/**
* MainType: 21
* 21.106: Ventilation Controller Status, values: 0...15
* 21.601: Light Actuator Error Info, values: 0...127
* 21.001: General Status, values: 0...31
* 21.100: Forcing Signal, values: 0...255
* 21.002: Device Control, values: 0...7
* 21.101: Forcing Signal Cool, values: 0...1
* 21.1010: Channel Activation State, values: 0...255
* 21.1000: R F Comm Mode Info, values: 0...7
* 21.1001: R F Filter Modes, values: 0...7
* 21.104: Fuel Type Set, values: 0...7
* 21.105: Room Cooling Controller Status, values: 0...1
* 21.102: Room Heating Controller Status, values: 0...255
* 21.103: Solar Dhw Controller Status, values: 0...7
*/
dptMainTypeMap.put(21, StringType.class);
/** Exceptions Datapoint Types, Main number 21 */
// Example since calimero 2.4: dptTypeMap.put(DptXlator8BitSet.DptGeneralStatus.getID(), StringType.class);
/**
* MainType: 28
* 28.001: UTF-8
*/
dptMainTypeMap.put(28, StringType.class);
/** Exceptions Datapoint Types "String" UTF-8, Main number 28 */
// Example: dptTypeMap.put(DPTXlatorUtf8.DPT_UTF8.getID(), StringType.class);
/**
* MainType: 29
* 29.012: Reactive energy, values: -9223372036854775808...9223372036854775807 VARh
* 29.011: Apparent energy, values: -9223372036854775808...9223372036854775807 VAh
* 29.010: Active Energy, values: -9223372036854775808...9223372036854775807 Wh
*/
dptMainTypeMap.put(29, DecimalType.class);
/** Exceptions Datapoint Types "64-Bit Signed Value", Main number 29 */
// Example: dptTypeMap.put(DPTXlator64BitSigned.DPT_ACTIVE_ENERGY.getID(), DecimalType.class);
/**
* MainType: 229
* 229.001: Metering Value, values: -2147483648...2147483647
*/
dptMainTypeMap.put(229, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Signed Value", Main number 229 */
// Example: dptTypeMap.put(DptXlatorMeteringValue.DptMeteringValue.getID(), DecimalType.class);
/**
* MainType: 232
* 232.600: RGB, values: 0 0 0...255 255 255, r g b
*/
dptMainTypeMap.put(232, HSBType.class);
/** Exceptions Datapoint Types "RGB Color", Main number 232 */
// Example: dptTypeMap.put(DPTXlatorRGB.DPT_RGB.getID(), HSBType.class);
defaultDptMap = new HashMap<Class<? extends Type>, String>();
defaultDptMap.put(OnOffType.class, DPTXlatorBoolean.DPT_SWITCH.getID());
defaultDptMap.put(UpDownType.class, DPTXlatorBoolean.DPT_UPDOWN.getID());
defaultDptMap.put(StopMoveType.class, DPTXlatorBoolean.DPT_START.getID());
defaultDptMap.put(OpenClosedType.class, DPTXlatorBoolean.DPT_WINDOW_DOOR.getID());
defaultDptMap.put(IncreaseDecreaseType.class, DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID());
defaultDptMap.put(PercentType.class, DPTXlator8BitUnsigned.DPT_SCALING.getID());
defaultDptMap.put(DecimalType.class, DPTXlator2ByteFloat.DPT_TEMPERATURE.getID());
defaultDptMap.put(DateTimeType.class, DPTXlatorTime.DPT_TIMEOFDAY.getID());
defaultDptMap.put(StringType.class, DPTXlatorString.DPT_STRING_8859_1.getID());
defaultDptMap.put(HSBType.class, DPTXlatorRGB.DPT_RGB.getID());
}
@Override
public String toDPTValue(Type type, String dptID) {
DPT dpt;
int mainNumber = getMainNumber(dptID);
if (mainNumber == -1) {
logger.error("toDPTValue couldn't identify mainnumber in dptID: {}", dptID);
return null;
}
try {
DPTXlator translator = TranslatorTypes.createTranslator(mainNumber, dptID);
dpt = translator.getType();
} catch (KNXException e) {
return null;
}
try {
// check for HSBType first, because it extends PercentType as well
if (type instanceof HSBType) {
HSBType hc = ((HSBType) type);
return "r:" + hc.getRed().intValue() + " g:" + hc.getGreen().intValue() + " b:"
+ hc.getBlue().intValue();
} else if (type instanceof OnOffType) {
return type.equals(OnOffType.OFF) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof UpDownType) {
return type.equals(UpDownType.UP) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof IncreaseDecreaseType) {
DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();
return type.equals(IncreaseDecreaseType.DECREASE) ? valueDPT.getLowerValue() + " 5"
: valueDPT.getUpperValue() + " 5";
} else if (type instanceof OpenClosedType) {
return type.equals(OpenClosedType.CLOSED) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof StopMoveType) {
return type.equals(StopMoveType.STOP) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof PercentType) {
return String.valueOf(((DecimalType) type).intValue());
} else if (type instanceof DecimalType) {
switch (mainNumber) {
case 2:
DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();
switch (((DecimalType) type).intValue()) {
case 0:
return "0 " + valueDPT.getLowerValue();
case 1:
return "0 " + valueDPT.getUpperValue();
case 2:
return "1 " + valueDPT.getLowerValue();
default:
return "1 " + valueDPT.getUpperValue();
}
case 18:
int intVal = ((DecimalType) type).intValue();
if (intVal > 63) {
return "learn " + (intVal - 0x80);
} else {
return "activate " + intVal;
}
default:
return type.toString();
}
} else if (type instanceof StringType) {
return type.toString();
} else if (type instanceof DateTimeType) {
return formatDateTime((DateTimeType) type, dptID);
}
} catch (Exception e) {
logger.warn("An exception occurred converting type {} to dpt id {}: error message={}", type, dptID,
e.getMessage());
return null;
}
logger.debug("toDPTValue: Couldn't convert type {} to dpt id {} (no mapping).", type, dptID);
return null;
}
@Override
public Type toType(Datapoint datapoint, byte[] data) {
try {
DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
translator.setData(data);
String value = translator.getValue();
String id = translator.getType().getID();
logger.trace("toType datapoint DPT = {}", datapoint.getDPT());
int mainNumber = getMainNumber(id);
if (mainNumber == -1) {
logger.debug("toType: couldn't identify mainnumber in dptID: {}.", id);
return null;
}
int subNumber = getSubNumber(id);
if (subNumber == -1) {
logger.debug("toType: couldn't identify sub number in dptID: {}.", id);
return null;
}
/*
* Following code section deals with specific mapping of values from KNX to openHAB types were the String
* received from the DPTXlator is not sufficient to set the openHAB type or has bugs
*/
switch (mainNumber) {
case 1:
DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
switch (subNumber) {
case 8:
return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
case 9:
return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
case 10:
return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
case 19:
return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
case 22:
return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
default:
return translatorBoolean.getValueBoolean() ? OnOffType.ON : OnOffType.OFF;
}
case 2:
DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
+ (translator1BitControlled.getValueBit() ? 1 : 0);
return new DecimalType(decValue);
case 3:
DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
if (translator3BitControlled.getStepCode() == 0) {
logger.debug("toType: KNX DPT_Control_Dimming: break received.");
return UnDefType.UNDEF;
}
switch (subNumber) {
case 7:
return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
: IncreaseDecreaseType.DECREASE;
case 8:
return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
}
case 14:
/*
* FIXME: Workaround for a bug in Calimero / Openhab DPTXlator4ByteFloat.makeString(): is using a
* locale when
* translating a Float to String. It could happen the a ',' is used as separator, such as
* 3,14159E20.
* Openhab's DecimalType expects this to be in US format and expects '.': 3.14159E20.
* There is no issue with DPTXlator2ByteFloat since calimero is using a non-localized translation
* there.
*/
DPTXlator4ByteFloat translator4ByteFloat = (DPTXlator4ByteFloat) translator;
Float f = translator4ByteFloat.getValueFloat();
if (Math.abs(f) < 100000) {
value = String.valueOf(f);
} else {
NumberFormat dcf = NumberFormat.getInstance(Locale.US);
if (dcf instanceof DecimalFormat) {
((DecimalFormat) dcf).applyPattern("0.#####E0");
}
value = dcf.format(f);
}
break;
case 18:
DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
int decimalValue = translatorSceneControl.getSceneNumber();
if (value.startsWith("learn")) {
decimalValue += 0x80;
}
value = String.valueOf(decimalValue);
break;
case 19:
DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
if (translatorDateTime.isFaultyClock()) {
// Not supported: faulty clock
logger.debug("toType: KNX clock msg ignored: clock faulty bit set, which is not supported");
return null;
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
// Not supported: "/1/1" (month and day without year)
logger.debug(
"toType: KNX clock msg ignored: no year, but day and month, which is not supported");
return null;
} else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
// Not supported: "1900" (year without month and day)
logger.debug(
"toType: KNX clock msg ignored: no day and month, but year, which is not supported");
return null;
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Not supported: No year, no date and no time
logger.debug("toType: KNX clock msg ignored: no day and month or year, which is not supported");
return null;
}
Calendar cal = Calendar.getInstance();
if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Pure date format, no time information
cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Pure time format, no date information
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
cal.set(Calendar.SECOND, translatorDateTime.getSecond());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
} else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Date format and time information
cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
}
break;
}
Class<? extends Type> typeClass = toTypeClass(id);
if (typeClass == null) {
return null;
}
if (typeClass.equals(PercentType.class)) {
return new PercentType(BigDecimal.valueOf(Math.round(translator.getNumericValue())));
}
if (typeClass.equals(DecimalType.class)) {
return new DecimalType(translator.getNumericValue());
}
if (typeClass.equals(StringType.class)) {
return StringType.valueOf(value);
}
if (typeClass.equals(DateTimeType.class)) {
String date = formatDateTime(value, datapoint.getDPT());
if ((date == null) || (date.isEmpty())) {
logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);
return null;
} else {
return DateTimeType.valueOf(date);
}
}
if (typeClass.equals(HSBType.class)) {
// value has format of "r:<red value> g:<green value> b:<blue value>"
int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);
int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);
int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);
return HSBType.fromRGB(r, g, b);
}
} catch (KNXFormatException kfe) {
logger.info("Translator couldn't parse data for datapoint type '{}' (KNXFormatException).",
datapoint.getDPT());
} catch (KNXIllegalArgumentException kiae) {
logger.info("Translator couldn't parse data for datapoint type '{}' (KNXIllegalArgumentException).",
datapoint.getDPT());
} catch (KNXException e) {
logger.warn("Failed creating a translator for datapoint type '{}'.", datapoint.getDPT(), e);
}
return null;
}
/**
* Converts a datapoint type id into an openHAB type class
*
* @param dptId the datapoint type id
* @return the openHAB type (command or state) class or {@code null} if the datapoint type id is not supported.
*/
@Override
public Class<? extends Type> toTypeClass(String dptId) {
Class<? extends Type> ohClass = dptTypeMap.get(dptId);
if (ohClass == null) {
int mainNumber = getMainNumber(dptId);
if (mainNumber == -1) {
logger.debug("Couldn't convert KNX datapoint type id into openHAB type class for dptId: {}.", dptId);
return null;
}
ohClass = dptMainTypeMap.get(mainNumber);
}
return ohClass;
}
/**
* Converts an openHAB type class into a datapoint type id.
*
* @param typeClass the openHAB type class
* @return the datapoint type id
*/
public String toDPTid(Class<? extends Type> typeClass) {
return defaultDptMap.get(typeClass);
}
/**
* Formats the given <code>value</code> according to the datapoint type
* <code>dpt</code> to a String which can be processed by {@link DateTimeType}.
*
* @param value
* @param dpt
*
* @return a formatted String like </code>yyyy-MM-dd'T'HH:mm:ss</code> which
* is target format of the {@link DateTimeType}
*/
private String formatDateTime(String value, String dpt) {
Date date = null;
try {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
date = new SimpleDateFormat(DATE_FORMAT).parse(value);
} else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
if (value.contains("no-day")) {
/*
* KNX "no-day" needs special treatment since openHAB's DateTimeType doesn't support "no-day".
* Workaround: remove the "no-day" String, parse the remaining time string, which will result in a
* date of "1970-01-01".
* Replace "no-day" with the current day name
*/
StringBuffer stb = new StringBuffer(value);
int start = stb.indexOf("no-day");
int end = start + "no-day".length();
stb.replace(start, end, String.format(Locale.US, "%1$ta", Calendar.getInstance()));
value = stb.toString();
}
date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
}
} catch (ParseException pe) {
// do nothing but logging
logger.warn("Could not parse '{}' to a valid date", value);
}
return date != null ? new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date) : "";
}
/**
* Formats the given internal <code>dateType</code> to a knx readable String
* according to the target datapoint type <code>dpt</code>.
*
* @param dateType
* @param dpt the target datapoint type
*
* @return a String which contains either an ISO8601 formatted date (yyyy-mm-dd),
* a formatted 24-hour clock with the day of week prepended (Mon, 12:00:00) or
* a formatted 24-hour clock (12:00:00)
*
* @throws IllegalArgumentException if none of the datapoint types DPT_DATE or
* DPT_TIMEOFDAY has been used.
*/
static private String formatDateTime(DateTimeType dateType, String dpt) {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
return dateType.format("%tF");
} else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
return dateType.format(Locale.US, "%1$ta, %1$tT");
} else if (DPTXlatorDateTime.DPT_DATE_TIME.getID().equals(dpt)) {
return dateType.format(Locale.US, "%tF %1$tT");
} else {
throw new IllegalArgumentException("Could not format date to datapoint type '" + dpt + "'");
}
}
/**
* Retrieves sub number from a DTP ID such as "14.001"
*
* @param dptID String with DPT ID
* @return sub number or -1
*/
private int getSubNumber(String dptID) {
int result = -1;
if (dptID == null) {
throw new IllegalArgumentException("Parameter dptID cannot be null");
}
int dptSepratorPosition = dptID.indexOf('.');
if (dptSepratorPosition > 0) {
try {
result = Integer.parseInt(dptID.substring(dptSepratorPosition + 1, dptID.length()));
} catch (NumberFormatException nfe) {
logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
dptID);
} catch (IndexOutOfBoundsException ioobe) {
logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
dptID);
}
}
return result;
}
/**
* Retrieves main number from a DTP ID such as "14.001"
*
* @param dptID String with DPT ID
* @return main number or -1
*/
private int getMainNumber(String dptID) {
int result = -1;
if (dptID == null) {
throw new IllegalArgumentException("Parameter dptID cannot be null");
}
int dptSepratorPosition = dptID.indexOf('.');
if (dptSepratorPosition > 0) {
try {
result = Integer.parseInt(dptID.substring(0, dptSepratorPosition));
} catch (NumberFormatException nfe) {
logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
dptID);
} catch (IndexOutOfBoundsException ioobe) {
logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
dptID);
}
}
return result;
}
}
| addons/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.knx.internal.dpt;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.smarthome.core.library.types.DateTimeType;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.HSBType;
import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.OpenClosedType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.StopMoveType;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.library.types.UpDownType;
import org.eclipse.smarthome.core.types.Type;
import org.eclipse.smarthome.core.types.UnDefType;
import org.openhab.binding.knx.KNXTypeMapper;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tuwien.auto.calimero.KNXException;
import tuwien.auto.calimero.KNXFormatException;
import tuwien.auto.calimero.KNXIllegalArgumentException;
import tuwien.auto.calimero.datapoint.Datapoint;
import tuwien.auto.calimero.dptxlator.DPT;
import tuwien.auto.calimero.dptxlator.DPTXlator;
import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;
import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat;
import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator4ByteUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlator64BitSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator8BitSigned;
import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;
import tuwien.auto.calimero.dptxlator.DPTXlatorDate;
import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;
import tuwien.auto.calimero.dptxlator.DPTXlatorRGB;
import tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl;
import tuwien.auto.calimero.dptxlator.DPTXlatorSceneNumber;
import tuwien.auto.calimero.dptxlator.DPTXlatorString;
import tuwien.auto.calimero.dptxlator.DPTXlatorTime;
import tuwien.auto.calimero.dptxlator.DPTXlatorUtf8;
import tuwien.auto.calimero.dptxlator.TranslatorTypes;
/**
* This class provides type mapping between all openHAB core types and KNX data point types.
*
* Each 'MainType' delivered from calimero, has a default mapping
* for all it's children to a openHAB Typeclass.
* All these 'MainType' mapping's are put into 'dptMainTypeMap'.
*
* Default 'MainType' mapping's we can override by a specific mapping.
* All specific mapping's are put into 'dptTypeMap'.
*
* If for a 'MainType' there is currently no specific mapping registered,
* you can find a commented example line, with it's correct 'DPTXlator' class.
*
* @author Kai Kreuzer
* @author Volker Daube
* @author Jan N. Klug
* @author Helmut Lehmeyer - Java8, generic DPT Mapper
*/
@Component
public class KNXCoreTypeMapper implements KNXTypeMapper {
private final Logger logger = LoggerFactory.getLogger(KNXCoreTypeMapper.class);
private static final String TIME_DAY_FORMAT = new String("EEE, HH:mm:ss");
private static final String DATE_FORMAT = new String("yyyy-MM-dd");
/**
* stores the openHAB type class for (supported) KNX datapoint types in a generic way.
* dptTypeMap stores more specific type class and exceptions.
*/
private final Map<Integer, Class<? extends Type>> dptMainTypeMap;
/** stores the openHAB type class for all (supported) KNX datapoint types */
private final Map<String, Class<? extends Type>> dptTypeMap;
/** stores the default KNX DPT to use for each openHAB type */
private final Map<Class<? extends Type>, String> defaultDptMap;
public KNXCoreTypeMapper() {
@SuppressWarnings("unused")
final List<Class<?>> xlators = Arrays.<Class<?>> asList(DPTXlator1BitControlled.class,
DPTXlator2ByteFloat.class, DPTXlator2ByteUnsigned.class, DPTXlator3BitControlled.class,
DPTXlator4ByteFloat.class, DPTXlator4ByteSigned.class, DPTXlator4ByteUnsigned.class,
DPTXlator64BitSigned.class, DPTXlator8BitSigned.class, DPTXlator8BitUnsigned.class,
DPTXlatorBoolean.class, DPTXlatorDate.class, DPTXlatorDateTime.class, DPTXlatorRGB.class,
DPTXlatorSceneControl.class, DPTXlatorSceneNumber.class, DPTXlatorString.class, DPTXlatorTime.class,
DPTXlatorUtf8.class);
dptTypeMap = new HashMap<String, Class<? extends Type>>();
dptMainTypeMap = new HashMap<Integer, Class<? extends Type>>();
/**
* MainType: 1
* 1.005: Alarm, values: 0 = no alarm, 1 = alarm
* 1.016: Acknowledge, values: 0 = no action, 1 = acknowledge
* 1.006: Binary value, values: 0 = low, 1 = high
* 1.017: Trigger, values: 0 = trigger, 1 = trigger
* 1.007: Step, values: 0 = decrease, 1 = increase
* 1.018: Occupancy, values: 0 = not occupied, 1 = occupied
* 1.008: Up/Down, values: 0 = up, 1 = down
* 1.019: Window/Door, values: 0 = closed, 1 = open
* 1.009: Open/Close, values: 0 = open, 1 = close
* 1.010: Start, values: 0 = stop, 1 = start
* 1.021: Logical function, values: 0 = OR, 1 = AND
* 1.011: State, values: 0 = inactive, 1 = active
* 1.022: Scene A/B, values: 0 = scene A, 1 = scene B
* 1.001: Switch, values: 0 = off, 1 = on
* 1.012: Invert, values: 0 = not inverted, 1 = inverted
* 1.023: Shutter/Blinds mode, values: 0 = only move up/down, 1 = move up/down + step-stop
* 1.100: Heat/Cool, values: 0 = cooling, 1 = heating
* 1.002: Boolean, values: 0 = false, 1 = true
* 1.013: Dim send-style, values: 0 = start/stop, 1 = cyclic
* 1.003: Enable, values: 0 = disable, 1 = enable
* 1.014: Input source, values: 0 = fixed, 1 = calculated
* 1.004: Ramp, values: 0 = no ramp, 1 = ramp
* 1.015: Reset, values: 0 = no action, 1 = reset
*/
dptMainTypeMap.put(1, OnOffType.class);
/** Exceptions Datapoint Types "B1", Main number 1 */
dptTypeMap.put(DPTXlatorBoolean.DPT_UPDOWN.getID(), UpDownType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_OPENCLOSE.getID(), OpenClosedType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_START.getID(), StopMoveType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_WINDOW_DOOR.getID(), OpenClosedType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_SCENE_AB.getID(), DecimalType.class);
/**
* MainType: 2
* 2.002: Boolean Controlled, values: 0 = false, 1 = true
* 2.003: Enable Controlled, values: 0 = disable, 1 = enable
* 2.011: State Controlled, values: 0 = inactive, 1 = active
* 2.001: Switch Controlled, values: 0 = off, 1 = on
* 2.012: Invert Controlled, values: 0 = not inverted, 1 = inverted
* 2.010: Start Controlled, values: 0 = stop, 1 = start
* 2.008: Up/Down Controlled, values: 0 = up, 1 = down
* 2.009: Open/Close Controlled, values: 0 = open, 1 = close
* 2.006: Binary Controlled, values: 0 = low, 1 = high
* 2.007: Step Controlled, values: 0 = decrease, 1 = increase
* 2.004: Ramp Controlled, values: 0 = no ramp, 1 = ramp
* 2.005: Alarm Controlled, values: 0 = no alarm, 1 = alarm
*/
dptMainTypeMap.put(2, DecimalType.class);
/** Exceptions Datapoint Types "B2", Main number 2 */
// Example: dptTypeMap.put(DPTXlator1BitControlled.DPT_SWITCH_CONTROL.getID(), DecimalType.class);
/**
* MainType: 3
* 3.007: Dimming, values: 0 = decrease, 1 = increase
* 3.008: Blinds, values: 0 = up, 1 = down
*/
dptMainTypeMap.put(3, IncreaseDecreaseType.class);
/** Exceptions Datapoint Types "B1U3", Main number 3 */
dptTypeMap.put(DPTXlator3BitControlled.DPT_CONTROL_BLINDS.getID(), UpDownType.class);
/**
* MainType: 5
* 5.010: Unsigned count, values: 0...255 counter pulses
* 5.001: Scaling, values: 0...100 %
* 5.003: Angle, values: 0...360 °
* 5.004: Percent (8 Bit), values: 0...255 %
* 5.005: Decimal factor, values: 0...255 ratio
* 5.006: Tariff information, values: 0...254
*/
dptMainTypeMap.put(5, DecimalType.class);
/** Exceptions Types "8-Bit Unsigned Value", Main number 5 */
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_SCALING.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID(), PercentType.class);
/**
* MainType: 6
* 6.001: Percent (8 Bit), values: -128...127 %
* 6.020: status with mode, values: 0/0/0/0/0 0...1/1/1/1/1 2
* 6.010: signed count, values: -128...127 counter pulses
*/
dptMainTypeMap.put(6, DecimalType.class);
/** Exceptions Datapoint Types "8-Bit Signed Value", Main number 6 */
dptTypeMap.put(DPTXlator8BitSigned.DPT_PERCENT_V8.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitSigned.DPT_STATUS_MODE3.getID(), StringType.class);
/**
* MainType: 7
* 7.003: Time period (resolution 10 ms), values: 0...655350 ms
* 7.004: Time period (resolution 100 ms), values: 0...6553500 ms
* 7.005: Time period in seconds, values: 0...65535 s
* 7.006: Time period in minutes, values: 0...65535 min
* 7.010: Interface object property ID, values: 0...65535
* 7.011: Length in mm, values: 0...65535 mm
* 7.001: Unsigned count, values: 0...65535 pulses
* 7.012: Electrical current, values: 0...65535 mA
* 7.002: Time period in ms, values: 0...65535 ms
* 7.013: Brightness, values: 0...65535 lx
* 7.007: Time period in hours, values: 0...65535 h
*/
dptMainTypeMap.put(7, DecimalType.class);
/** Exceptions Datapoint Types "2-Octet Unsigned Value", Main number 7 */
dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
/**
* MainType: 9
* 9.020: Voltage, values: -670760...+670760 mV
* 9.010: Time difference 1, values: -670760...+670760 s
* 9.021: Electrical current, values: -670760...+670760 mA
* 9.011: Time difference 2, values: -670760...+670760 ms
* 9.022: Power density, values: -670760...+670760 W/m²
* 9.001: Temperature, values: -273...+670760 °C
* 9.023: Kelvin/percent, values: -670760...+670760 K/%
* 9.002: Temperature difference, values: -670760...+670760 K
* 9.024: Power, values: -670760...+670760 kW
* 9.003: Temperature gradient, values: -670760...+670760 K/h
* 9.025: Volume flow, values: -670760...+670760 l/h
* 9.004: Light intensity, values: 0...+670760 lx
* 9.026: Rain amount, values: -671088.64...670760.96 l/m²
* 9.005: Wind speed, values: 0...+670760 m/s
* 9.027: Temperature, values: -459.6...670760.96 °F
* 9.006: Air pressure, values: 0...+670760 Pa
* 9.028: Wind speed, values: 0...670760.96 km/h
* 9.007: Humidity, values: 0...+670760 %
* 9.008: Air quality, values: 0...+670760 ppm
*/
dptMainTypeMap.put(9, DecimalType.class);
/** Exceptions Datapoint Types "2-Octet Float Value", Main number 9 */
// Example: dptTypeMap.put(DPTXlator2ByteFloat.DPT_TEMPERATURE.getID(), DecimalType.class);
/**
* MainType: 10
* 10.001: Time of day, values: 1 = Monday...7 = Sunday, 0 = no-day, 00:00:00 Sun, 23:59:59 dow, hh:mm:ss
*/
dptMainTypeMap.put(10, DateTimeType.class);
/** Exceptions Datapoint Types "Time", Main number 10 */
// Example: dptTypeMap.put(DPTXlatorTime.DPT_TIMEOFDAY.getID(), DateTimeType.class);
/**
* MainType: 11
* 11.001: Date, values: 1990-01-01...2089-12-31, yyyy-mm-dd
*/
dptMainTypeMap.put(11, DateTimeType.class);
/** Exceptions Datapoint Types “Date”", Main number 11 */
// Example: dptTypeMap.put(DPTXlatorDate.DPT_DATE.getID(), DateTimeType.class);
/**
* MainType: 12
* 12.001: Unsigned count, values: 0...4294967295 counter pulses
*/
dptMainTypeMap.put(12, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Unsigned Value", Main number 12 */
// Example: dptTypeMap.put(DPTXlator4ByteUnsigned.DPT_VALUE_4_UCOUNT.getID(), DecimalType.class);
/**
* MainType: 13
* 13.010: Active Energy, values: -2147483648...2147483647 Wh
* 13.001: Counter pulses, values: -2147483648...2147483647 counter pulses
* 13.012: Reactive energy, values: -2147483648...2147483647 VARh
* 13.100: Delta time in seconds, values: -2147483648...2147483647 s
* 13.011: Apparent energy, values: -2147483648...2147483647 VAh
* 13.014: Apparent energy in kVAh, values: -2147483648...2147483647 kVAh
* 13.002: Flow rate, values: -2147483648...2147483647 m3/h
* 13.013: Active energy in kWh, values: -2147483648...2147483647 kWh
* 13.015: Reactive energy in kVARh, values: -2147483648...2147483647 kVARh
*/
dptMainTypeMap.put(13, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Signed Value", Main number 13 */
// Example: dptTypeMap.put(DPTXlator4ByteSigned.DPT_COUNT.getID(), DecimalType.class);
/**
* MainType: 14, Range: [-3.40282347e+38f...3.40282347e+38f]
* 14.019: Electric current, values: A
* 14.018: Electric charge, values: C
* 14.017: Density, values: kg m⁻³
* 14.016: Conductivity, electrical, values: Ω⁻¹m⁻¹
* 14.015: Conductance, values: Ω⁻¹
* 14.059: Reactance, values: Ω
* 14.014: Compressibility, values: m²/N
* 14.058: Pressure, values: Pa
* 14.013: Charge density (volume), values: C m⁻³
* 14.057: Power factor, values:
* 14.012: Charge density (surface), values: C m⁻²
* 14.056: Power, values: W
* 14.011: Capacitance, values: F
* 14.055: Phase angle, degree, values: °
* 14.010: Area, values: m²
* 14.054: Phase angle, radiant, values: rad
* 14.053: Momentum, values: N/s
* 14.052: Mass flux, values: kg/s
* 14.051: Mass, values: kg
* 14.050: Magneto motive force, values: A
* 14.060: Resistance, values: Ω
* 14.029: Electromagnetic moment, values: A m²
* 14.028: Electric potential difference, values: V
* 14.027: Electric potential, values: V
* 14.026: Electric polarization, values: C m⁻²
* 14.025: Electric flux density, values: C m⁻²
* 14.069: Temperature, absolute, values: K
* 14.024: Electric flux, values: Vm
* 14.068: Temperature in Celsius Degree, values: °C
* 14.023: Electric field strength, values: V/m
* 14.067: Surface tension, values: N/m
* 14.022: Electric displacement, values: C m⁻²
* 14.066: Stress, values: Pa
* 14.021: Electric dipole moment, values: Cm
* 14.065: Speed, values: m/s
* 14.020: Electric current density, values: A m⁻²
* 14.064: Sound intensity, values: W m⁻²
* 14.063: Solid angle, values: sr
* 14.062: Self inductance, values: H
* 14.061: Resistivity, values: Ωm
* 14.071: Thermal capacity, values: J/K
* 14.070: Temperature difference, values: K
* 14.039: Length, values: m
* 14.038: Impedance, values: Ω
* 14.037: Heat quantity, values: J
* 14.036: Heat flow rate, values: W
* 14.035: Heat capacity, values: J/K
* 14.079: Work, values: J
* 14.034: Frequency, angular, values: rad/s
* 14.078: Weight, values: N
* 14.033: Frequency, values: Hz
* 14.077: Volume flux, values: m³/s
* 14.032: Force, values: N
* 14.076: Volume, values: m³
* 14.031: Energy, values: J
* 14.075: Torque, values: Nm
* 14.030: Electromotive force, values: V
* 14.074: Time, values: s
* 14.073: Thermoelectric power, values: V/K
* 14.072: Thermal conductivity, values: W/m K⁻¹
* 14.009: Angular velocity, values: rad/s
* 14.008: Momentum, values: Js
* 14.007: Angle, values: °
* 14.006: Angle, values: rad
* 14.005: Amplitude, values:
* 14.049: Magnetization, values: A/m
* 14.004: Mol, values: mol
* 14.048: Magnetic polarization, values: T
* 14.003: Activity, values: s⁻¹
* 14.047: Magnetic moment, values: A m²
* 14.002: Activation energy, values: J/mol
* 14.046: Magnetic flux density, values: T
* 14.001: Acceleration, angular, values: rad s⁻²
* 14.045: Magnetic flux, values: Wb
* 14.000: Acceleration, values: ms⁻²
* 14.044: Magnetic field strength, values: A/m
* 14.043: Luminous intensity, values: cd
* 14.042: Luminous flux, values: lm
* 14.041: Luminance, values: cd m⁻²
* 14.040: Quantity of Light, values: J
*/
dptMainTypeMap.put(14, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Float Value", Main number 14 */
// Example: dptTypeMap.put(DPTXlator4ByteFloat.DPT_ACCELERATION_ANGULAR.getID(), DecimalType.class);
/**
* MainType: 16
* 16.000: ASCII string
* 16.001: ISO-8859-1 string (Latin 1)
*/
dptMainTypeMap.put(16, StringType.class);
/** Exceptions Datapoint Types "String", Main number 16 */
dptTypeMap.put(DPTXlatorString.DPT_STRING_8859_1.getID(), StringType.class);
dptTypeMap.put(DPTXlatorString.DPT_STRING_ASCII.getID(), StringType.class);
/**
* MainType: 17
* 17.001: Scene Number, values: 0...63
*/
dptMainTypeMap.put(17, DecimalType.class);
/** Exceptions Datapoint Types "Scene Number", Main number 17 */
// Example: dptTypeMap.put(DPTXlatorSceneNumber.DPT_SCENE_NUMBER.getID(), DecimalType.class);
/**
* MainType: 18
* 18.001: Scene Control, values: 0...63, 0 = activate, 1 = learn
*/
dptMainTypeMap.put(18, DecimalType.class);
/** Exceptions Datapoint Types "Scene Control", Main number 18 */
// Example: dptTypeMap.put(DPTXlatorSceneControl.DPT_SCENE_CONTROL.getID(), DecimalType.class);
/**
* MainType: 19
* 19.001: Date with time, values: 0 = 1900, 255 = 2155, 01/01 00:00:00, 12/31 24:00:00 yr/mth/day hr:min:sec
*/
dptMainTypeMap.put(19, DateTimeType.class);
/** Exceptions Datapoint Types "DateTime", Main number 19 */
// Example: dptTypeMap.put(DPTXlatorDateTime.DPT_DATE_TIME.getID(), DateTimeType.class);
/**
* MainType: 20
* 20.606: PB Action, enumeration [0..3]
* 20.804: Blinds Control Mode, enumeration [0..1]
* 20.607: Dimm PB Model, enumeration [1..4]
* 20.608: Switch On Mode, enumeration [0..2]
* 20.609: Load Type Set, enumeration [0..2]
* 20.008: PSU Mode, enumeration [0..2]
* 20.602: DALI Fade Time, enumeration [0..15]
* 20.603: Blinking Mode, enumeration [0..2]
* 20.801: SAB Except Behavior, enumeration [0..4]
* 20.604: Light Control Mode, enumeration [0..1]
* 20.802: SAB Behavior Lock/Unlock, enumeration [0..6]
* 20.605: Switch PB Model, enumeration [1..2]
* 20.803: SSSB Mode, enumeration [1..4]
* 20.004: Priority, enumeration [0..3]
* 20.005: Light Application Mode, enumeration [0..2]
* 20.006: Application Area, enumeration [0..14]
* 20.600: Behavior Lock/Unlock, enumeration [0..6]
* 20.007: Alarm Class Type, enumeration [0..3]
* 20.601: Behavior Bus Power Up/Down, enumeration [0..4]
* 20.121: Backup Mode, enumeration [0..1]
* 20.001: System Clock Mode, enumeration [0..2]
* 20.122: Start Synchronization, enumeration [0..2]
* 20.002: Building Mode, enumeration [0..2]
* 20.003: Occupancy Mode, enumeration [0..2]
* 20.610: Load Type Detected, enumeration [0..3]
* 20.017: Sensor Select, enumeration [0..4]
* 20.011: Error Class System, enumeration [0..18]
* 20.012: Error Class HVAC, enumeration [0..4]
* 20.013: Time Delay, enumeration [0..25]
* 20.014: Beaufort Wind Force Scale, enumeration [0..12]
* 20.020: Actuator Connect Type, enumeration [1..2]
* 20.107: Changeover Mode, enumeration [0..2]
* 20.108: Valve Mode, enumeration [1..5]
* 20.109: Damper Mode, enumeration [1..4]
* 20.103: DHW Mode, enumeration [0..4]
* 20.104: Load Priority, enumeration [0..2]
* 20.105: HVAC Control Mode, enumeration [0..20]
* 20.106: HVAC Emergency Mode, enumeration [0..5]
* 20.100: Fuel Type, enumeration [0..3]
* 20.101: Burner Type, enumeration [0..3]
* 20.102: HVAC Mode, enumeration [0..4]
* 20.114: Metering Device Type, enumeration [0..41/255]
* 20.110: Heater Mode, enumeration [1..3]
* 20.1202: Gas Measurement Condition, enumeration [0..3]
* 20.111: Fan Mode, enumeration [0..2]
* 20.1003: RF Filter Select, enumeration [0..3]
* 20.112: Master/Slave Mode, enumeration [0..2]
* 20.1002: RF Mode Select, enumeration [0..2]
* 20.1200: M-Bus Breaker/Valve State, enumeration [0..255]
* 20.113: Status Room Setpoint, enumeration [0..2]
* 20.1001: Additional Info Type, enumeration [0..7]
* 20.1000: Comm Mode, enumeration [0..255]
* 20.120: Air Damper Actuator Type, enumeration [1..2]
*/
dptMainTypeMap.put(20, StringType.class);
/** Exceptions Datapoint Types, Main number 20 */
// Example since calimero 2.4: dptTypeMap.put(DPTXlator8BitEnum.DptSystemClockMode.getID(), StringType.class);
/**
* MainType: 21
* 21.106: Ventilation Controller Status, values: 0...15
* 21.601: Light Actuator Error Info, values: 0...127
* 21.001: General Status, values: 0...31
* 21.100: Forcing Signal, values: 0...255
* 21.002: Device Control, values: 0...7
* 21.101: Forcing Signal Cool, values: 0...1
* 21.1010: Channel Activation State, values: 0...255
* 21.1000: R F Comm Mode Info, values: 0...7
* 21.1001: R F Filter Modes, values: 0...7
* 21.104: Fuel Type Set, values: 0...7
* 21.105: Room Cooling Controller Status, values: 0...1
* 21.102: Room Heating Controller Status, values: 0...255
* 21.103: Solar Dhw Controller Status, values: 0...7
*/
dptMainTypeMap.put(21, StringType.class);
/** Exceptions Datapoint Types, Main number 21 */
// Example since calimero 2.4: dptTypeMap.put(DptXlator8BitSet.DptGeneralStatus.getID(), StringType.class);
/**
* MainType: 28
* 28.001: UTF-8
*/
dptMainTypeMap.put(28, StringType.class);
/** Exceptions Datapoint Types "String" UTF-8, Main number 28 */
// Example: dptTypeMap.put(DPTXlatorUtf8.DPT_UTF8.getID(), StringType.class);
/**
* MainType: 29
* 29.012: Reactive energy, values: -9223372036854775808...9223372036854775807 VARh
* 29.011: Apparent energy, values: -9223372036854775808...9223372036854775807 VAh
* 29.010: Active Energy, values: -9223372036854775808...9223372036854775807 Wh
*/
dptMainTypeMap.put(29, DecimalType.class);
/** Exceptions Datapoint Types "64-Bit Signed Value", Main number 29 */
// Example: dptTypeMap.put(DPTXlator64BitSigned.DPT_ACTIVE_ENERGY.getID(), DecimalType.class);
/**
* MainType: 229
* 229.001: Metering Value, values: -2147483648...2147483647
*/
dptMainTypeMap.put(229, DecimalType.class);
/** Exceptions Datapoint Types "4-Octet Signed Value", Main number 229 */
// Example: dptTypeMap.put(DptXlatorMeteringValue.DptMeteringValue.getID(), DecimalType.class);
/**
* MainType: 232
* 232.600: RGB, values: 0 0 0...255 255 255, r g b
*/
dptMainTypeMap.put(232, HSBType.class);
/** Exceptions Datapoint Types "RGB Color", Main number 232 */
// Example: dptTypeMap.put(DPTXlatorRGB.DPT_RGB.getID(), HSBType.class);
defaultDptMap = new HashMap<Class<? extends Type>, String>();
defaultDptMap.put(OnOffType.class, DPTXlatorBoolean.DPT_SWITCH.getID());
defaultDptMap.put(UpDownType.class, DPTXlatorBoolean.DPT_UPDOWN.getID());
defaultDptMap.put(StopMoveType.class, DPTXlatorBoolean.DPT_START.getID());
defaultDptMap.put(OpenClosedType.class, DPTXlatorBoolean.DPT_WINDOW_DOOR.getID());
defaultDptMap.put(IncreaseDecreaseType.class, DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID());
defaultDptMap.put(PercentType.class, DPTXlator8BitUnsigned.DPT_SCALING.getID());
defaultDptMap.put(DecimalType.class, DPTXlator2ByteFloat.DPT_TEMPERATURE.getID());
defaultDptMap.put(DateTimeType.class, DPTXlatorTime.DPT_TIMEOFDAY.getID());
defaultDptMap.put(StringType.class, DPTXlatorString.DPT_STRING_8859_1.getID());
defaultDptMap.put(HSBType.class, DPTXlatorRGB.DPT_RGB.getID());
}
@Override
public String toDPTValue(Type type, String dptID) {
DPT dpt;
int mainNumber = getMainNumber(dptID);
if (mainNumber == -1) {
logger.error("toDPTValue couldn't identify mainnumber in dptID: {}", dptID);
return null;
}
try {
DPTXlator translator = TranslatorTypes.createTranslator(mainNumber, dptID);
dpt = translator.getType();
} catch (KNXException e) {
return null;
}
try {
// check for HSBType first, because it extends PercentType as well
if (type instanceof HSBType) {
HSBType hc = ((HSBType) type);
return "r:" + hc.getRed().intValue() + " g:" + hc.getGreen().intValue() + " b:"
+ hc.getBlue().intValue();
} else if (type instanceof OnOffType) {
return type.equals(OnOffType.OFF) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof UpDownType) {
return type.equals(UpDownType.UP) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof IncreaseDecreaseType) {
DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();
return type.equals(IncreaseDecreaseType.DECREASE) ? valueDPT.getLowerValue() + " 5"
: valueDPT.getUpperValue() + " 5";
} else if (type instanceof OpenClosedType) {
return type.equals(OpenClosedType.CLOSED) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof StopMoveType) {
return type.equals(StopMoveType.STOP) ? dpt.getLowerValue() : dpt.getUpperValue();
} else if (type instanceof PercentType) {
return String.valueOf(((DecimalType) type).intValue());
} else if (type instanceof DecimalType) {
switch (mainNumber) {
case 2:
DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();
switch (((DecimalType) type).intValue()) {
case 0:
return "0 " + valueDPT.getLowerValue();
case 1:
return "0 " + valueDPT.getUpperValue();
case 2:
return "1 " + valueDPT.getLowerValue();
default:
return "1 " + valueDPT.getUpperValue();
}
case 18:
int intVal = ((DecimalType) type).intValue();
if (intVal > 63) {
return "learn " + (intVal - 0x80);
} else {
return "activate " + intVal;
}
default:
return type.toString();
}
} else if (type instanceof StringType) {
return type.toString();
} else if (type instanceof DateTimeType) {
return formatDateTime((DateTimeType) type, dptID);
}
} catch (Exception e) {
logger.warn("An exception occurred converting type {} to dpt id {}: error message={}", type, dptID,
e.getMessage());
return null;
}
logger.debug("toDPTValue: Couldn't convert type {} to dpt id {} (no mapping).", type, dptID);
return null;
}
@Override
public Type toType(Datapoint datapoint, byte[] data) {
try {
DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
translator.setData(data);
String value = translator.getValue();
String id = translator.getType().getID();
logger.trace("toType datapoint DPT = {}", datapoint.getDPT());
int mainNumber = getMainNumber(id);
if (mainNumber == -1) {
logger.debug("toType: couldn't identify mainnumber in dptID: {}.", id);
return null;
}
int subNumber = getSubNumber(id);
if (subNumber == -1) {
logger.debug("toType: couldn't identify sub number in dptID: {}.", id);
return null;
}
/*
* Following code section deals with specific mapping of values from KNX to openHAB types were the String
* received from the DPTXlator is not sufficient to set the openHAB type or has bugs
*/
switch (mainNumber) {
case 1:
DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
switch (subNumber) {
case 8:
return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
case 9:
return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
case 10:
return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
case 19:
return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
case 22:
return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
default:
return translatorBoolean.getValueBoolean() ? OnOffType.ON : OnOffType.OFF;
}
case 2:
DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
+ (translator1BitControlled.getValueBit() ? 1 : 0);
return new DecimalType(decValue);
case 3:
DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
if (translator3BitControlled.getStepCode() == 0) {
logger.debug("toType: KNX DPT_Control_Dimming: break received.");
return UnDefType.UNDEF;
}
switch (subNumber) {
case 7:
return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
: IncreaseDecreaseType.DECREASE;
case 8:
return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
}
case 14:
/*
* FIXME: Workaround for a bug in Calimero / Openhab DPTXlator4ByteFloat.makeString(): is using a
* locale when
* translating a Float to String. It could happen the a ',' is used as separator, such as
* 3,14159E20.
* Openhab's DecimalType expects this to be in US format and expects '.': 3.14159E20.
* There is no issue with DPTXlator2ByteFloat since calimero is using a non-localized translation
* there.
*/
DPTXlator4ByteFloat translator4ByteFloat = (DPTXlator4ByteFloat) translator;
Float f = translator4ByteFloat.getValueFloat();
if (Math.abs(f) < 100000) {
value = String.valueOf(f);
} else {
NumberFormat dcf = NumberFormat.getInstance(Locale.US);
if (dcf instanceof DecimalFormat) {
((DecimalFormat) dcf).applyPattern("0.#####E0");
}
value = dcf.format(f);
}
break;
case 18:
DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
int decimalValue = translatorSceneControl.getSceneNumber();
if (value.startsWith("learn")) {
decimalValue += 0x80;
}
value = String.valueOf(decimalValue);
break;
case 19:
DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
if (translatorDateTime.isFaultyClock()) {
// Not supported: faulty clock
logger.debug("toType: KNX clock msg ignored: clock faulty bit set, which is not supported");
return null;
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
// Not supported: "/1/1" (month and day without year)
logger.debug(
"toType: KNX clock msg ignored: no year, but day and month, which is not supported");
return null;
} else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
// Not supported: "1900" (year without month and day)
logger.debug(
"toType: KNX clock msg ignored: no day and month, but year, which is not supported");
return null;
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Not supported: No year, no date and no time
logger.debug("toType: KNX clock msg ignored: no day and month or year, which is not supported");
return null;
}
Calendar cal = Calendar.getInstance();
if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Pure date format, no time information
cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
} else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Pure time format, no date information
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
cal.set(Calendar.SECOND, translatorDateTime.getSecond());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
} else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
&& translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
// Date format and time information
cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
return DateTimeType.valueOf(value);
}
break;
}
Class<? extends Type> typeClass = toTypeClass(id);
if (typeClass == null) {
return null;
}
if (typeClass.equals(PercentType.class)) {
return new PercentType(BigDecimal.valueOf(Math.round(translator.getNumericValue())));
}
if (typeClass.equals(DecimalType.class)) {
return new DecimalType(translator.getNumericValue());
}
if (typeClass.equals(StringType.class)) {
return StringType.valueOf(value);
}
if (typeClass.equals(DateTimeType.class)) {
String date = formatDateTime(value, datapoint.getDPT());
if ((date == null) || (date.isEmpty())) {
logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);
return null;
} else {
return DateTimeType.valueOf(date);
}
}
if (typeClass.equals(HSBType.class)) {
// value has format of "r:<red value> g:<green value> b:<blue value>"
int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);
int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);
int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);
return HSBType.fromRGB(r, g, b);
}
} catch (KNXFormatException kfe) {
logger.info("Translator couldn't parse data for datapoint type '{}' (KNXFormatException).",
datapoint.getDPT());
} catch (KNXIllegalArgumentException kiae) {
logger.info("Translator couldn't parse data for datapoint type '{}' (KNXIllegalArgumentException).",
datapoint.getDPT());
} catch (KNXException e) {
logger.warn("Failed creating a translator for datapoint type '{}'.", datapoint.getDPT(), e);
}
return null;
}
/**
* Converts a datapoint type id into an openHAB type class
*
* @param dptId the datapoint type id
* @return the openHAB type (command or state) class or {@code null} if the datapoint type id is not supported.
*/
@Override
public Class<? extends Type> toTypeClass(String dptId) {
Class<? extends Type> ohClass = dptTypeMap.get(dptId);
if (ohClass == null) {
int mainNumber = getMainNumber(dptId);
if (mainNumber == -1) {
logger.debug("Couldn't convert KNX datapoint type id into openHAB type class for dptId: {}.", dptId);
return null;
}
ohClass = dptMainTypeMap.get(mainNumber);
}
return ohClass;
}
/**
* Converts an openHAB type class into a datapoint type id.
*
* @param typeClass the openHAB type class
* @return the datapoint type id
*/
public String toDPTid(Class<? extends Type> typeClass) {
return defaultDptMap.get(typeClass);
}
/**
* Formats the given <code>value</code> according to the datapoint type
* <code>dpt</code> to a String which can be processed by {@link DateTimeType}.
*
* @param value
* @param dpt
*
* @return a formatted String like </code>yyyy-MM-dd'T'HH:mm:ss</code> which
* is target format of the {@link DateTimeType}
*/
private String formatDateTime(String value, String dpt) {
Date date = null;
try {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
date = new SimpleDateFormat(DATE_FORMAT).parse(value);
} else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
if (value.contains("no-day")) {
/*
* KNX "no-day" needs special treatment since openHAB's DateTimeType doesn't support "no-day".
* Workaround: remove the "no-day" String, parse the remaining time string, which will result in a
* date of "1970-01-01".
* Replace "no-day" with the current day name
*/
StringBuffer stb = new StringBuffer(value);
int start = stb.indexOf("no-day");
int end = start + "no-day".length();
stb.replace(start, end, String.format(Locale.US, "%1$ta", Calendar.getInstance()));
value = stb.toString();
}
date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
}
} catch (ParseException pe) {
// do nothing but logging
logger.warn("Could not parse '{}' to a valid date", value);
}
return date != null ? new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date) : "";
}
/**
* Formats the given internal <code>dateType</code> to a knx readable String
* according to the target datapoint type <code>dpt</code>.
*
* @param dateType
* @param dpt the target datapoint type
*
* @return a String which contains either an ISO8601 formatted date (yyyy-mm-dd),
* a formatted 24-hour clock with the day of week prepended (Mon, 12:00:00) or
* a formatted 24-hour clock (12:00:00)
*
* @throws IllegalArgumentException if none of the datapoint types DPT_DATE or
* DPT_TIMEOFDAY has been used.
*/
static private String formatDateTime(DateTimeType dateType, String dpt) {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
return dateType.format("%tF");
} else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
return dateType.format(Locale.US, "%1$ta, %1$tT");
} else if (DPTXlatorDateTime.DPT_DATE_TIME.getID().equals(dpt)) {
return dateType.format(Locale.US, "%tF %1$tT");
} else {
throw new IllegalArgumentException("Could not format date to datapoint type '" + dpt + "'");
}
}
/**
* Retrieves sub number from a DTP ID such as "14.001"
*
* @param dptID String with DPT ID
* @return sub number or -1
*/
private int getSubNumber(String dptID) {
int result = -1;
if (dptID == null) {
throw new IllegalArgumentException("Parameter dptID cannot be null");
}
int dptSepratorPosition = dptID.indexOf('.');
if (dptSepratorPosition > 0) {
try {
result = Integer.parseInt(dptID.substring(dptSepratorPosition + 1, dptID.length()));
} catch (NumberFormatException nfe) {
logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
dptID);
} catch (IndexOutOfBoundsException ioobe) {
logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
dptID);
}
}
return result;
}
/**
* Retrieves main number from a DTP ID such as "14.001"
*
* @param dptID String with DPT ID
* @return main number or -1
*/
private int getMainNumber(String dptID) {
int result = -1;
if (dptID == null) {
throw new IllegalArgumentException("Parameter dptID cannot be null");
}
int dptSepratorPosition = dptID.indexOf('.');
if (dptSepratorPosition > 0) {
try {
result = Integer.parseInt(dptID.substring(0, dptSepratorPosition));
} catch (NumberFormatException nfe) {
logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
dptID);
} catch (IndexOutOfBoundsException ioobe) {
logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
dptID);
}
}
return result;
}
}
| update mapping 9.007 to PercentType (#3410)
Signed-off-by: lewie <[email protected]> | addons/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java | update mapping 9.007 to PercentType (#3410) | <ide><path>ddons/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java
<ide> */
<ide> dptMainTypeMap.put(9, DecimalType.class);
<ide> /** Exceptions Datapoint Types "2-Octet Float Value", Main number 9 */
<del> // Example: dptTypeMap.put(DPTXlator2ByteFloat.DPT_TEMPERATURE.getID(), DecimalType.class);
<add> dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
<ide>
<ide> /**
<ide> * MainType: 10 |
|
Java | epl-1.0 | 57a93194fede8ce91ce3179fd8e752149b8e8b10 | 0 | rbevers/fitnesse,hansjoachim/fitnesse,amolenaar/fitnesse,amolenaar/fitnesse,rbevers/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,hansjoachim/fitnesse,jdufner/fitnesse,jdufner/fitnesse | package fitnesse.wikitext.parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import util.Maybe;
public class Symbol {
public static final Maybe<Symbol> nothing = new Maybe<Symbol>();
public static final Symbol emptySymbol = new Symbol(SymbolType.Empty);
private static final List<Symbol> NO_CHILDREN = Collections.emptyList();
private SymbolType type;
private String content;
private List<Symbol> children;
private Properties variables;
private Properties properties;
public Symbol(SymbolType type) { this(type, ""); }
public Symbol(SymbolType type, String content) {
this.content = content;
this.type = type;
this.children = type.matchesFor(SymbolType.SymbolList)
? new ArrayList<Symbol>(2)
: NO_CHILDREN;
}
public SymbolType getType() { return type; }
public boolean isType(SymbolType type) { return this.type.matchesFor(type); }
public boolean isStartCell() { return isType(Table.symbolType) || isType(SymbolType.EndCell); }
public boolean isStartLine() { return isType(HorizontalRule.symbolType) || isType(Nesting.symbolType); }
public boolean isLineType() {
return isType(HeaderLine.symbolType) || isType(SymbolType.CenterLine) || isType(SymbolType.Meta) ||
isType(SymbolType.NoteLine);
}
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public Symbol childAt(int index) { return getChildren().get(index); }
public Symbol lastChild() { return childAt(getChildren().size() - 1); }
public List<Symbol> getChildren() { return children; }
private List<Symbol> children() {
if (children == NO_CHILDREN) {
children = new ArrayList<Symbol>(1);
}
return children;
}
public Symbol addToFront(Symbol child) {
children().add(0, child);
return this;
}
public Symbol add(Symbol child) {
children().add(child);
return this;
}
public Symbol add(String text) {
children().add(new Symbol(SymbolType.Text, text));
return this;
}
public Symbol childrenAfter(int after) {
Symbol result = new Symbol(SymbolType.SymbolList);
for (int i = after + 1; i < children.size(); i++) result.add(children.get(i));
return result;
}
public boolean walkPostOrder(SymbolTreeWalker walker) {
if (walker.visitChildren(this)) {
for (Symbol child: children) {
if (!child.walkPostOrder(walker)) return false;
}
}
return walker.visit(this);
}
public boolean walkPreOrder(SymbolTreeWalker walker) {
if (!walker.visit(this)) return false;
if (walker.visitChildren(this)) {
for (Symbol child: children) {
if (!child.walkPreOrder(walker)) return false;
}
}
return true;
}
public void evaluateVariables(String[] names, VariableSource source) {
if (variables == null) variables = new Properties();
for (String name: names) {
Maybe<String> value = source.findVariable(name);
if (!value.isNothing()) variables.put(name, value.getValue());
}
}
public String getVariable(String name, String defaultValue) {
return variables != null && variables.containsKey(name) ? variables.getProperty(name) : defaultValue;
}
public Symbol putProperty(String key, String value) {
if (properties == null) properties = new Properties();
properties.put(key, value);
return this;
}
public boolean hasProperty(String key) {
return properties != null && properties.containsKey(key);
}
public String getProperty(String key, String defaultValue) {
return properties != null && properties.containsKey(key) ? properties.getProperty(key) : defaultValue;
}
public String getProperty(String key) {
return getProperty(key, "");
}
public SymbolType closeType() {
return type == SymbolType.OpenBrace ? SymbolType.CloseBrace
: type == SymbolType.OpenBracket ? SymbolType.CloseBracket
: type == SymbolType.OpenParenthesis ? SymbolType.CloseParenthesis
: type == Literal.symbolType ? SymbolType.CloseLiteral
: type == Comment.symbolType ? SymbolType.Newline
: SymbolType.Empty;
}
}
| src/fitnesse/wikitext/parser/Symbol.java | package fitnesse.wikitext.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import util.Maybe;
public class Symbol {
public static final Maybe<Symbol> nothing = new Maybe<Symbol>();
public static final Symbol emptySymbol = new Symbol(SymbolType.Empty);
private SymbolType type;
private String content = "";
private List<Symbol> children = new ArrayList<Symbol>();
private Properties variables;
private Properties properties;
public Symbol(SymbolType type) { this.type = type; }
public Symbol(SymbolType type, String content) {
this.content = content;
this.type = type;
}
public SymbolType getType() { return type; }
public boolean isType(SymbolType type) { return this.type.matchesFor(type); }
public boolean isStartCell() { return isType(Table.symbolType) || isType(SymbolType.EndCell); }
public boolean isStartLine() { return isType(HorizontalRule.symbolType) || isType(Nesting.symbolType); }
public boolean isLineType() {
return isType(HeaderLine.symbolType) || isType(SymbolType.CenterLine) || isType(SymbolType.Meta) ||
isType(SymbolType.NoteLine);
}
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public Symbol childAt(int index) { return getChildren().get(index); }
public Symbol lastChild() { return childAt(getChildren().size() - 1); }
public List<Symbol> getChildren() { return children; }
public Symbol addToFront(Symbol child) {
ArrayList<Symbol> newChildren = new ArrayList<Symbol>();
newChildren.add(child);
newChildren.addAll(children);
children = newChildren;
return this;
}
public Symbol add(Symbol child) {
children.add(child);
return this;
}
public Symbol add(String text) {
children.add(new Symbol(SymbolType.Text, text));
return this;
}
public Symbol childrenAfter(int after) {
Symbol result = new Symbol(SymbolType.SymbolList);
for (int i = after + 1; i < children.size(); i++) result.add(children.get(i));
return result;
}
public boolean walkPostOrder(SymbolTreeWalker walker) {
if (walker.visitChildren(this)) {
for (Symbol child: children) {
if (!child.walkPostOrder(walker)) return false;
}
}
return walker.visit(this);
}
public boolean walkPreOrder(SymbolTreeWalker walker) {
if (!walker.visit(this)) return false;
if (walker.visitChildren(this)) {
for (Symbol child: children) {
if (!child.walkPreOrder(walker)) return false;
}
}
return true;
}
public void evaluateVariables(String[] names, VariableSource source) {
if (variables == null) variables = new Properties();
for (String name: names) {
Maybe<String> value = source.findVariable(name);
if (!value.isNothing()) variables.put(name, value.getValue());
}
}
public String getVariable(String name, String defaultValue) {
return variables != null && variables.containsKey(name) ? variables.getProperty(name) : defaultValue;
}
public Symbol putProperty(String key, String value) {
if (properties == null) properties = new Properties();
properties.put(key, value);
return this;
}
public boolean hasProperty(String key) {
return properties != null && properties.containsKey(key);
}
public String getProperty(String key, String defaultValue) {
return properties != null && properties.containsKey(key) ? properties.getProperty(key) : defaultValue;
}
public String getProperty(String key) {
return getProperty(key, "");
}
public SymbolType closeType() {
return type == SymbolType.OpenBrace ? SymbolType.CloseBrace
: type == SymbolType.OpenBracket ? SymbolType.CloseBracket
: type == SymbolType.OpenParenthesis ? SymbolType.CloseParenthesis
: type == Literal.symbolType ? SymbolType.CloseLiteral
: type == Comment.symbolType ? SymbolType.Newline
: SymbolType.Empty;
}
}
| Don't allocate a new 'children' list by default (use singleton empty list)
* Upon add() allocate minimal capacity list;
* For "SymbolList"s allocate new 'children' with capacity of 2, by default.
| src/fitnesse/wikitext/parser/Symbol.java | Don't allocate a new 'children' list by default (use singleton empty list) | <ide><path>rc/fitnesse/wikitext/parser/Symbol.java
<ide> package fitnesse.wikitext.parser;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Properties;
<ide>
<ide> public static final Maybe<Symbol> nothing = new Maybe<Symbol>();
<ide> public static final Symbol emptySymbol = new Symbol(SymbolType.Empty);
<ide>
<add> private static final List<Symbol> NO_CHILDREN = Collections.emptyList();
<add>
<ide> private SymbolType type;
<del> private String content = "";
<del> private List<Symbol> children = new ArrayList<Symbol>();
<add> private String content;
<add> private List<Symbol> children;
<ide> private Properties variables;
<ide> private Properties properties;
<ide>
<del> public Symbol(SymbolType type) { this.type = type; }
<add> public Symbol(SymbolType type) { this(type, ""); }
<ide>
<ide> public Symbol(SymbolType type, String content) {
<ide> this.content = content;
<ide> this.type = type;
<add> this.children = type.matchesFor(SymbolType.SymbolList)
<add> ? new ArrayList<Symbol>(2)
<add> : NO_CHILDREN;
<ide> }
<ide>
<ide> public SymbolType getType() { return type; }
<ide> public Symbol lastChild() { return childAt(getChildren().size() - 1); }
<ide> public List<Symbol> getChildren() { return children; }
<ide>
<add> private List<Symbol> children() {
<add> if (children == NO_CHILDREN) {
<add> children = new ArrayList<Symbol>(1);
<add> }
<add> return children;
<add> }
<add>
<ide> public Symbol addToFront(Symbol child) {
<del> ArrayList<Symbol> newChildren = new ArrayList<Symbol>();
<del> newChildren.add(child);
<del> newChildren.addAll(children);
<del> children = newChildren;
<add> children().add(0, child);
<ide> return this;
<ide> }
<ide>
<ide> public Symbol add(Symbol child) {
<del> children.add(child);
<add> children().add(child);
<ide> return this;
<ide> }
<ide>
<ide> public Symbol add(String text) {
<del> children.add(new Symbol(SymbolType.Text, text));
<add> children().add(new Symbol(SymbolType.Text, text));
<ide> return this;
<ide> }
<ide> |
|
JavaScript | mit | 8451702488f1b73e233cd9e8579afa362ef4216d | 0 | openT2T/translators,ChuckFerring/translators | // This code uses ES2015 syntax that requires at least Node.js v4.
// For Node.js ES2015 support details, reference http://node.green/
"use strict";
var OpenT2T = require('opent2t').OpenT2T;
var Firebase = require("firebase");
/**
* This translator class implements the "Hub" interface.
*/
class Translator {
constructor(accessToken) {
this._accessToken = accessToken;
this._baseUrl = "https://developer-api.nest.com";
this._devicesPath = 'devices/';
this._structPath = 'structures/';
this._name = "Nest Hub";
this._firebaseRef = new Firebase(this._baseUrl);
this._firebaseRef.authWithCustomToken(this._accessToken.accessToken);
}
/**
* Get the hub definition and devices
*/
get(expand, payload) {
return this.getPlatforms(expand, payload);
}
/**
* Get the list of devices discovered through the hub.
*/
getPlatforms(expand, payload) {
if(payload !== undefined){
return this._providerSchemaToPlatformSchema( payload, expand );
} else {
return this._firebaseRef.child(this._devicesPath).once('value').then((snapshot) => {
return this._providerSchemaToPlatformSchema(snapshot.val(), expand);
});
}
}
/* eslint no-unused-vars: "off" */
/**
* Subscribe to notifications for a platform.
* This function is intended to be called by the platform translator for initial subscription,
* and on the hub translator (this) for verification.
*/
_subscribe(subscriptionInfo) {
// Error case: waiting for design decision
throw new Error("Not implemented");
}
/**
* Unsubscribe from a platform subscription.
* This function is intended to be called by a platform translator
*/
_unsubscribe(subscriptionInfo) {
// Error case: waiting for design decision
throw new Error("Not implemented");
}
/* eslint no-unused-vars: "warn" */
/**
* Translates an array of provider schemas into an opent2t/OCF representations
*/
_providerSchemaToPlatformSchema(providerSchemas, expand) {
var platformPromises = [];
if(providerSchemas.thermostats !== undefined){
// get the opent2t schema and translator for Nest thermostat
var opent2tInfo = {
"schema": 'org.opent2t.sample.thermostat.superpopular',
"translator": "opent2t-translator-com-nest-thermostat"
};
var nestThermostatIds = Object.keys(providerSchemas.thermostats);
nestThermostatIds.forEach((nestThermostatId) => {
// set the opent2t info for the Nest Device
var deviceInfo = {};
deviceInfo.opent2t = {};
deviceInfo.opent2t.controlId = nestThermostatId;
// Create a translator for this device and get the platform information, possibly expanded
platformPromises.push(OpenT2T.createTranslatorAsync(opent2tInfo.translator, { 'deviceInfo': deviceInfo, 'hub': this })
.then((translator) => {
// Use get to translate the Nest formatted device that we already got in the previous request.
// We already have this data, so no need to make an unnecesary request over the wire.
var deviceSchema = providerSchemas.thermostats[nestThermostatId];
return this._getAwayStatus(deviceSchema['structure_id']).then((result) => {
deviceSchema.away = result;
return OpenT2T.invokeMethodAsync(translator, opent2tInfo.schema, 'get', [expand, deviceSchema ])
.then((platformResponse) => {
return platformResponse;
});
});
}));
});
}
return Promise.all(platformPromises)
.then((platforms) => {
var toReturn = {};
toReturn.schema = "opent2t.p.hub";
toReturn.platforms = platforms;
return toReturn;
});
}
/**
* Get the name of the hub. Ties to the n property from oic.core
*/
getN() {
return this._name;
}
/**
* Gets device details (all fields), response formatted per nest api
*/
getDeviceDetailsAsync(deviceType, deviceId) {
return this._firebaseRef.child(this._devicesPath + deviceType + '/' +deviceId).once('value').then((snapshot) => {
var deviceSchema = snapshot.val();
return this._getAwayStatus(deviceSchema['structure_id']).then((result) => {
deviceSchema.away = result;
return deviceSchema;
});
});
}
/**
* Puts device details (all fields) payload formatted per nest api
*/
putDeviceDetailsAsync(deviceType, deviceId, putPayload) {
var propertyName = Object.keys(putPayload);
var path = this._devicesPath + deviceType + '/' + deviceId + '/' + propertyName[0];
return this._firebaseRef.child(path).set(putPayload[propertyName[0]]).then((response) => {
if (response === undefined) { //success
var result = {
device_id:deviceId
};
result[propertyName] = putPayload[propertyName[0]];
//get temperature scale
if (propertyName[0].includes('_temperature_')) {
result['temperature_scale'] = propertyName[0].charAt(propertyName[0].length -1);
}
return result;
}
}).catch(function (err) {
var str = err.toString();
var startInd = str.indexOf('{');
var endInd = str.lastIndexOf('}');
var errorMsg = JSON.parse(str.substring(startInd, endInd + 1));
throw new Error(errorMsg.error);
});
}
/**
* Internal Helper function to get the away status for structure with structureId
*/
_getAwayStatus(structureId) {
return this._firebaseRef.child(this._structPath + structureId + '/away').once('value').then((snapshot) => {
return snapshot.val();
});
}
}
module.exports = Translator; | org.opent2t.sample.hub.superpopular/com.nest.hub/js/thingTranslator.js | // This code uses ES2015 syntax that requires at least Node.js v4.
// For Node.js ES2015 support details, reference http://node.green/
"use strict";
var OpenT2T = require('opent2t').OpenT2T;
var Firebase = require("firebase");
/**
* This translator class implements the "Hub" interface.
*/
class Translator {
constructor(accessToken) {
this._accessToken = accessToken;
this._baseUrl = "https://developer-api.nest.com";
this._devicesPath = 'devices/';
this._structPath = 'structures/';
this._name = "Nest Hub";
this._firebaseRef = new Firebase(this._baseUrl);
this._firebaseRef.authWithCustomToken(this._accessToken.accessToken);
}
/**
* Get the hub definition and devices
*/
get(expand, payload) {
return this.getPlatforms(expand, payload);
}
/**
* Get the list of devices discovered through the hub.
*/
getPlatforms(expand, payload) {
if(payload !== undefined){
return this._providerSchemaToPlatformSchema( payload, expand );
} else {
return this._firebaseRef.child(this._devicesPath).once('value').then((snapshot) => {
return this._providerSchemaToPlatformSchema(snapshot.val(), expand);
});
}
}
/* eslint no-unused-vars: "off" */
/**
* Subscribe to notifications for a platform.
* This function is intended to be called by the platform translator for initial subscription,
* and on the hub translator (this) for verification.
*/
_subscribe(subscriptionInfo) {
// Error case: waiting for design decision
throw new Error("Not implemented");
}
/**
* Unsubscribe from a platform subscription.
* This function is intended to be called by a platform translator
*/
_unsubscribe(subscriptionInfo) {
// Error case: waiting for design decision
throw new Error("Not implemented");
}
/* eslint no-unused-vars: "warn" */
/**
* Translates an array of provider schemas into an opent2t/OCF representations
*/
_providerSchemaToPlatformSchema(providerSchemas, expand) {
var platformPromises = [];
if(providerSchemas.thermostats !== undefined){
// get the opent2t schema and translator for Nest thermostat
var opent2tInfo = {
"schema": 'org.opent2t.sample.thermostat.superpopular',
"translator": "opent2t-translator-com-nest-thermostat"
};
var nestThermostatIds = Object.keys(providerSchemas.thermostats);
nestThermostatIds.forEach((nestThermostatId) => {
// set the opent2t info for the Nest Device
var deviceInfo = {};
deviceInfo.opent2t = {};
deviceInfo.opent2t.controlId = nestThermostatId;
// Create a translator for this device and get the platform information, possibly expanded
platformPromises.push(OpenT2T.createTranslatorAsync(opent2tInfo.translator, { 'deviceInfo': deviceInfo, 'hub': this })
.then((translator) => {
// Use get to translate the Nest formatted device that we already got in the previous request.
// We already have this data, so no need to make an unnecesary request over the wire.
var deviceSchema = providerSchemas.thermostats[nestThermostatId];
return this._getAwayStatus(deviceSchema['structure_id']).then((result) => {
deviceSchema.away = result;
return OpenT2T.invokeMethodAsync(translator, opent2tInfo.schema, 'get', [expand, deviceSchema ])
.then((platformResponse) => {
return platformResponse;
});
});
}));
});
}
return Promise.all(platformPromises)
.then((platforms) => {
var toReturn = {};
toReturn.schema = "opent2t.p.hub";
toReturn.platforms = platforms;
return toReturn;
});
}
/**
* Get the name of the hub. Ties to the n property from oic.core
*/
getN() {
return this._name;
}
/**
* Gets device details (all fields), response formatted per nest api
*/
getDeviceDetailsAsync(deviceType, deviceId) {
return this._firebaseRef.child(this._devicesPath + deviceType + '/' +deviceId).once('value').then((snapshot) => {
var deviceSchema = snapshot.val();
return this._getAwayStatus(deviceSchema['structure_id']).then((result) => {
deviceSchema.away = result;
return deviceSchema;
});
});
}
/**
* Puts device details (all fields) payload formatted per nest api
*/
putDeviceDetailsAsync(deviceType, deviceId, putPayload) {
var propertyName = Object.keys(putPayload);
var path = this._devicesPath + deviceType + '/' + deviceId + '/' + propertyName[0];
return this._firebaseRef.child(path).set(putPayload[propertyName[0]]).then((response) => {
if (response === undefined) { //success
var result = {
device_id:deviceId
};
result[propertyName] = putPayload[propertyName[0]];
//get temperature scale
if (propertyName[0].includes('_temperature_')) {
result['temperature_scale'] = propertyName[0].charAt(propertyName[0].length -1);
}
return result;
}
}).catch(function (err) {
var str = err.toString();
var startInd = str.indexOf('{');
var endInd = str.lastIndexOf('}');
var errorMsg = JSON.parse(str.substring(startInd, endInd + 1));
throw new Error(errorMsg.error);
});
}
/**
* Internal Helper function to get the away status for structure with structureId
*/
_getAwayStatus(structureId) {
return this._firebaseRef.child(this._structPath + structureId + '/away').once('value').then((snapshot) => {
return snapshot.val();
});
}
}
module.exports = Translator; | fix CI errors.
| org.opent2t.sample.hub.superpopular/com.nest.hub/js/thingTranslator.js | fix CI errors. | <ide><path>rg.opent2t.sample.hub.superpopular/com.nest.hub/js/thingTranslator.js
<ide> getPlatforms(expand, payload) {
<ide> if(payload !== undefined){
<ide> return this._providerSchemaToPlatformSchema( payload, expand );
<del> } else {
<add> } else {
<ide> return this._firebaseRef.child(this._devicesPath).once('value').then((snapshot) => {
<ide> return this._providerSchemaToPlatformSchema(snapshot.val(), expand);
<ide> });
<del> }
<add> }
<ide> }
<ide>
<ide> /* eslint no-unused-vars: "off" */ |
|
Java | apache-2.0 | 30ef1f8637d8a6b7d526b6689dc342918641d763 | 0 | opencb/hpg-bigdata,opencb/hpg-bigdata,opencb/hpg-bigdata | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.hpg.bigdata.app.cli.local;
import htsjdk.samtools.*;
import htsjdk.samtools.util.LineReader;
import htsjdk.samtools.util.StringLineReader;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.sql.SparkSession;
import org.ga4gh.models.ReadAlignment;
import org.opencb.biodata.models.alignment.RegionCoverage;
import org.opencb.biodata.models.core.Region;
import org.opencb.biodata.tools.alignment.AlignmentOptions;
import org.opencb.biodata.tools.alignment.BamManager;
import org.opencb.biodata.tools.alignment.BamUtils;
import org.opencb.biodata.tools.alignment.stats.AlignmentGlobalStats;
import org.opencb.commons.utils.FileUtils;
import org.opencb.hpg.bigdata.app.cli.CommandExecutor;
import org.opencb.hpg.bigdata.core.avro.AlignmentAvroSerializer;
import org.opencb.hpg.bigdata.core.converters.SAMRecord2ReadAlignmentConverter;
import org.opencb.hpg.bigdata.core.lib.AlignmentDataset;
import org.opencb.hpg.bigdata.core.lib.SparkConfCreator;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
/**
* Created by imedina on 16/03/15.
*/
public class AlignmentCommandExecutor extends CommandExecutor {
private LocalCliOptionsParser.AlignmentCommandOptions alignmentCommandOptions;
public static final String BAM_HEADER_SUFFIX = ".header";
public AlignmentCommandExecutor(LocalCliOptionsParser.AlignmentCommandOptions alignmentCommandOptions) {
this.alignmentCommandOptions = alignmentCommandOptions;
}
/*
* Parse specific 'alignment' command options
*/
public void execute() throws Exception {
String subCommand = alignmentCommandOptions.getParsedSubCommand();
switch (subCommand) {
case "convert":
init(alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.conf);
convert();
break;
case "stats":
init(alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.conf);
stats();
break;
case "coverage":
init(alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.conf);
coverage();
break;
case "query":
init(alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.conf);
query();
break;
/*
case "align":
System.out.println("Sub-command 'align': Not yet implemented for the command 'alignment' !");
break;
*/
default:
break;
}
}
private void convert() throws IOException {
String input = alignmentCommandOptions.convertAlignmentCommandOptions.input;
String output = alignmentCommandOptions.convertAlignmentCommandOptions.output;
String compressionCodecName = alignmentCommandOptions.convertAlignmentCommandOptions.compression;
// sanity check
if (compressionCodecName.equals("null")) {
compressionCodecName = "deflate";
}
if (alignmentCommandOptions.convertAlignmentCommandOptions.toBam) {
// conversion: GA4GH/Avro model -> BAM
// header management: read it from a separate file
File file = new File(input + BAM_HEADER_SUFFIX);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
InputStream is = new FileInputStream(input);
String textHeader = new String(data);
LineReader lineReader = new StringLineReader(textHeader);
SAMFileHeader header = new SAMTextHeaderCodec().decode(lineReader, textHeader);
// reader
DataFileStream<ReadAlignment> reader = new DataFileStream<ReadAlignment>(is, new SpecificDatumReader<>(ReadAlignment.class));
// writer
OutputStream os = new FileOutputStream(new File(output));
SAMFileWriter writer = new SAMFileWriterFactory().makeBAMWriter(header, false, new File(output));
// main loop
int reads = 0;
SAMRecord samRecord;
SAMRecord2ReadAlignmentConverter converter = new SAMRecord2ReadAlignmentConverter();
for (ReadAlignment readAlignment : reader) {
samRecord = converter.backward(readAlignment);
samRecord.setHeader(header);
writer.addAlignment(samRecord);
if (++reads % 100_000 == 0) {
System.out.println("Converted " + reads + " reads");
}
}
// close
reader.close();
writer.close();
os.close();
is.close();
} else {
// conversion: BAM -> GA4GH/Avro model
/* System.out.println("Loading library hpgbigdata...");
System.out.println("\tjava.libary.path = " + System.getProperty("java.library.path"));
System.loadLibrary("hpgbigdata");
System.out.println("...done!");
new NativeSupport().bam2ga(input, output, compressionCodecName == null
? "snappy"
: compressionCodecName, alignmentCommandOptions.convertAlignmentCommandOptions.adjustQuality);
try {
// header management: saved it in a separate file
SamReader reader = SamReaderFactory.makeDefault().open(new File(input));
SAMFileHeader header = reader.getFileHeader();
PrintWriter pwriter = null;
pwriter = new PrintWriter(new FileWriter(output + BAM_HEADER_SUFFIX));
pwriter.write(header.getTextHeader());
pwriter.close();
} catch (IOException e) {
throw e;
}
*/
boolean adjustQuality = alignmentCommandOptions.convertAlignmentCommandOptions.adjustQuality;
AlignmentAvroSerializer avroSerializer = new AlignmentAvroSerializer(compressionCodecName);
avroSerializer.toAvro(input, output);
}
}
private void stats() throws IOException {
// get input parameters
String input = alignmentCommandOptions.statsAlignmentCommandOptions.input;
String output = alignmentCommandOptions.statsAlignmentCommandOptions.output;
try {
// compute stats using the BamManager
BamManager alignmentManager = new BamManager(Paths.get(input));
AlignmentGlobalStats stats = alignmentManager.stats();
// write results
PrintWriter writer = new PrintWriter(new File(output + "/stats.json"));
writer.write(stats.toJSON());
writer.close();
} catch (Exception e) {
throw e;
}
}
private void coverage() throws IOException {
final int chunkSize = 10000;
// get input parameters
String input = alignmentCommandOptions.coverageAlignmentCommandOptions.input;
String output = alignmentCommandOptions.coverageAlignmentCommandOptions.output;
Path filePath = Paths.get(input);
// writer
PrintWriter writer = new PrintWriter(new File(output + "/" + filePath.getFileName() + ".coverage"));
SAMFileHeader fileHeader = BamUtils.getFileHeader(filePath);
AlignmentOptions options = new AlignmentOptions();
options.setContained(false);
short[] values;
BamManager alignmentManager = new BamManager(filePath);
Iterator<SAMSequenceRecord> iterator = fileHeader.getSequenceDictionary().getSequences().iterator();
while (iterator.hasNext()) {
SAMSequenceRecord next = iterator.next();
for (int i = 0; i < next.getSequenceLength(); i += chunkSize) {
Region region = new Region(next.getSequenceName(), i + 1,
Math.min(i + chunkSize, next.getSequenceLength()));
RegionCoverage regionCoverage = alignmentManager.coverage(region, options, null);
// write coverages to file (only values greater than 0)
values = regionCoverage.getValues();
for (int j=0, start = region.getStart(); j < values.length; j++, start++) {
if (values[j] > 0) {
writer.write(next.getSequenceName() + "\t" + start + "\t" + values[j] + "\n");
}
}
}
}
// close
writer.close();
//
// HashMap<String, Integer> regionLength = new HashMap<>();
//
// //TODO: fix using the new RegionCoverage, JT
// try {
// // header management
// BufferedReader br = new BufferedReader(new FileReader(input + BAM_HEADER_SUFFIX));
// String line, fieldName, fieldLength;
// String[] fields;
// String[] subfields;
// while ((line = br.readLine()) != null) {
// if (line.startsWith("@SQ")) {
// fields = line.split("\t");
// subfields = fields[1].split(":");
// fieldName = subfields[1];
// subfields = fields[2].split(":");
// fieldLength = subfields[1];
//
// regionLength.put(fieldName, Integer.parseInt(fieldLength));
// }
// }
// br.close();
//
// // reader
// InputStream is = new FileInputStream(input);
// DataFileStream<ReadAlignment> reader = new DataFileStream<>(is, new SpecificDatumReader<>(ReadAlignment.class));
//
// // writer
// PrintWriter writer = new PrintWriter(new File(output + "/depth.txt"));
//
// String chromName = "";
// int[] chromDepth;
//
// RegionDepth regionDepth;
// RegionDepthCalculator calculator = new RegionDepthCalculator();
//
// int pos;
// long prevPos = 0L;
//
// // main loop
// chromDepth = null;
// for (ReadAlignment readAlignment : reader) {
// if (readAlignment.getAlignment() != null) {
// regionDepth = calculator.compute(readAlignment);
// if (chromDepth == null) {
// chromName = regionDepth.chrom;
// chromDepth = new int[regionLength.get(regionDepth.chrom)];
// }
// if (!chromName.equals(regionDepth.chrom)) {
// // write depth
// int length = chromDepth.length;
// for (int i = 0; i < length; i++) {
// writer.write(chromName + "\t" + (i + 1) + "\t" + chromDepth[i] + "\n");
// }
//
// // init
// prevPos = 0L;
// chromName = regionDepth.chrom;
// chromDepth = new int[regionLength.get(regionDepth.chrom)];
// }
// if (prevPos > regionDepth.position) {
// throw new IOException("Error: the input file (" + input + ") is not sorted (reads out of order).");
// }
//
// pos = (int) regionDepth.position;
// for (int i: regionDepth.array) {
// chromDepth[pos] += regionDepth.array[i];
// pos++;
// }
// prevPos = regionDepth.position;
// }
// }
// // write depth
// int length = chromDepth.length;
// for (int i = 0; i < length; i++) {
// if (chromDepth[i] > 0) {
// writer.write(chromName + "\t" + (i + 1) + "\t" + chromDepth[i] + "\n");
// }
// }
//
// // close
// reader.close();
// is.close();
// writer.close();
// } catch (Exception e) {
// throw e;
// }
}
public void query() throws Exception {
// check mandatory parameter 'input file'
Path inputPath = Paths.get(alignmentCommandOptions.queryAlignmentCommandOptions.input);
FileUtils.checkFile(inputPath);
// TODO: to take the spark home from somewhere else
SparkConf sparkConf = SparkConfCreator.getConf("variant query", "local", 1,
true, "/home/jtarraga/soft/spark-2.0.0/");
System.out.println("sparkConf = " + sparkConf.toDebugString());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
// SparkConf sparkConf = SparkConfCreator.getConf("MyTest", "local", 1, true, "/home/jtarraga/soft/spark-2.0.0/");
// SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
AlignmentDataset ad = new AlignmentDataset();
ad.load(alignmentCommandOptions.queryAlignmentCommandOptions.input, sparkSession);
ad.createOrReplaceTempView("alignment");
// query for region
List<Region> regions = null;
if (StringUtils.isNotEmpty(alignmentCommandOptions.queryAlignmentCommandOptions.regions)) {
regions = Region.parseRegions(alignmentCommandOptions.queryAlignmentCommandOptions.regions);
ad.regionFilter(regions);
}
// query for region file
if (StringUtils.isNotEmpty(alignmentCommandOptions.queryAlignmentCommandOptions.regionFile)) {
logger.warn("Query for region file, not yet implemented.");
}
// query for minimun mapping quality
if (alignmentCommandOptions.queryAlignmentCommandOptions.minMapQ > 0) {
ad.mappingQualityFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minMapQ);
}
// query for flags
if (alignmentCommandOptions.queryAlignmentCommandOptions.requireFlags != Integer.MAX_VALUE) {
ad.flagFilter("" + alignmentCommandOptions.queryAlignmentCommandOptions.requireFlags, false);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.filteringFlags != 0) {
ad.flagFilter("" + alignmentCommandOptions.queryAlignmentCommandOptions.filteringFlags, true);
}
// query for template length
if (alignmentCommandOptions.queryAlignmentCommandOptions.minTLen != 0) {
ad.templateLengthFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minTLen);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.maxTLen != Integer.MAX_VALUE) {
ad.templateLengthFilter("<=" + alignmentCommandOptions.queryAlignmentCommandOptions.maxTLen);
}
// query for alignment length
if (alignmentCommandOptions.queryAlignmentCommandOptions.minALen != 0) {
ad.alignmentLengthFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minALen);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.maxALen != Integer.MAX_VALUE) {
ad.alignmentLengthFilter("<=" + alignmentCommandOptions.queryAlignmentCommandOptions.maxALen);
}
// apply previous filters
ad.update();
// save the dataset
logger.warn("The current query implementation saves the resulting dataset in Avro format.");
ad.write().format("com.databricks.spark.avro").save(alignmentCommandOptions.queryAlignmentCommandOptions.output);
}
}
| hpg-bigdata-app/src/main/java/org/opencb/hpg/bigdata/app/cli/local/AlignmentCommandExecutor.java | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.hpg.bigdata.app.cli.local;
import htsjdk.samtools.*;
import htsjdk.samtools.util.LineReader;
import htsjdk.samtools.util.StringLineReader;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.sql.SparkSession;
import org.ga4gh.models.ReadAlignment;
import org.opencb.biodata.models.alignment.RegionCoverage;
import org.opencb.biodata.models.core.Region;
import org.opencb.biodata.tools.alignment.AlignmentManager;
import org.opencb.biodata.tools.alignment.AlignmentOptions;
import org.opencb.biodata.tools.alignment.AlignmentUtils;
import org.opencb.biodata.tools.alignment.stats.AlignmentGlobalStats;
import org.opencb.commons.utils.FileUtils;
import org.opencb.hpg.bigdata.app.cli.CommandExecutor;
import org.opencb.hpg.bigdata.core.avro.AlignmentAvroSerializer;
import org.opencb.hpg.bigdata.core.converters.SAMRecord2ReadAlignmentConverter;
import org.opencb.hpg.bigdata.core.lib.AlignmentDataset;
import org.opencb.hpg.bigdata.core.lib.SparkConfCreator;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
/**
* Created by imedina on 16/03/15.
*/
public class AlignmentCommandExecutor extends CommandExecutor {
private LocalCliOptionsParser.AlignmentCommandOptions alignmentCommandOptions;
public static final String BAM_HEADER_SUFFIX = ".header";
public AlignmentCommandExecutor(LocalCliOptionsParser.AlignmentCommandOptions alignmentCommandOptions) {
this.alignmentCommandOptions = alignmentCommandOptions;
}
/*
* Parse specific 'alignment' command options
*/
public void execute() throws Exception {
String subCommand = alignmentCommandOptions.getParsedSubCommand();
switch (subCommand) {
case "convert":
init(alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.convertAlignmentCommandOptions.commonOptions.conf);
convert();
break;
case "stats":
init(alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.statsAlignmentCommandOptions.commonOptions.conf);
stats();
break;
case "coverage":
init(alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.coverageAlignmentCommandOptions.commonOptions.conf);
coverage();
break;
case "query":
init(alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.logLevel,
alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.verbose,
alignmentCommandOptions.queryAlignmentCommandOptions.commonOptions.conf);
query();
break;
/*
case "align":
System.out.println("Sub-command 'align': Not yet implemented for the command 'alignment' !");
break;
*/
default:
break;
}
}
private void convert() throws IOException {
String input = alignmentCommandOptions.convertAlignmentCommandOptions.input;
String output = alignmentCommandOptions.convertAlignmentCommandOptions.output;
String compressionCodecName = alignmentCommandOptions.convertAlignmentCommandOptions.compression;
// sanity check
if (compressionCodecName.equals("null")) {
compressionCodecName = "deflate";
}
if (alignmentCommandOptions.convertAlignmentCommandOptions.toBam) {
// conversion: GA4GH/Avro model -> BAM
// header management: read it from a separate file
File file = new File(input + BAM_HEADER_SUFFIX);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
InputStream is = new FileInputStream(input);
String textHeader = new String(data);
LineReader lineReader = new StringLineReader(textHeader);
SAMFileHeader header = new SAMTextHeaderCodec().decode(lineReader, textHeader);
// reader
DataFileStream<ReadAlignment> reader = new DataFileStream<ReadAlignment>(is, new SpecificDatumReader<>(ReadAlignment.class));
// writer
OutputStream os = new FileOutputStream(new File(output));
SAMFileWriter writer = new SAMFileWriterFactory().makeBAMWriter(header, false, new File(output));
// main loop
int reads = 0;
SAMRecord samRecord;
SAMRecord2ReadAlignmentConverter converter = new SAMRecord2ReadAlignmentConverter();
for (ReadAlignment readAlignment : reader) {
samRecord = converter.backward(readAlignment);
samRecord.setHeader(header);
writer.addAlignment(samRecord);
if (++reads % 100_000 == 0) {
System.out.println("Converted " + reads + " reads");
}
}
// close
reader.close();
writer.close();
os.close();
is.close();
} else {
// conversion: BAM -> GA4GH/Avro model
/* System.out.println("Loading library hpgbigdata...");
System.out.println("\tjava.libary.path = " + System.getProperty("java.library.path"));
System.loadLibrary("hpgbigdata");
System.out.println("...done!");
new NativeSupport().bam2ga(input, output, compressionCodecName == null
? "snappy"
: compressionCodecName, alignmentCommandOptions.convertAlignmentCommandOptions.adjustQuality);
try {
// header management: saved it in a separate file
SamReader reader = SamReaderFactory.makeDefault().open(new File(input));
SAMFileHeader header = reader.getFileHeader();
PrintWriter pwriter = null;
pwriter = new PrintWriter(new FileWriter(output + BAM_HEADER_SUFFIX));
pwriter.write(header.getTextHeader());
pwriter.close();
} catch (IOException e) {
throw e;
}
*/
boolean adjustQuality = alignmentCommandOptions.convertAlignmentCommandOptions.adjustQuality;
AlignmentAvroSerializer avroSerializer = new AlignmentAvroSerializer(compressionCodecName);
avroSerializer.toAvro(input, output);
}
}
private void stats() throws IOException {
// get input parameters
String input = alignmentCommandOptions.statsAlignmentCommandOptions.input;
String output = alignmentCommandOptions.statsAlignmentCommandOptions.output;
try {
// compute stats using the AlignmentManager
AlignmentManager alignmentManager = new AlignmentManager(Paths.get(input));
AlignmentGlobalStats stats = alignmentManager.stats();
// write results
PrintWriter writer = new PrintWriter(new File(output + "/stats.json"));
writer.write(stats.toJSON());
writer.close();
} catch (Exception e) {
throw e;
}
}
private void coverage() throws IOException {
final int chunkSize = 10000;
// get input parameters
String input = alignmentCommandOptions.coverageAlignmentCommandOptions.input;
String output = alignmentCommandOptions.coverageAlignmentCommandOptions.output;
Path filePath = Paths.get(input);
// writer
PrintWriter writer = new PrintWriter(new File(output + "/" + filePath.getFileName() + ".coverage"));
SAMFileHeader fileHeader = AlignmentUtils.getFileHeader(filePath);
AlignmentOptions options = new AlignmentOptions();
options.setContained(false);
short[] values;
AlignmentManager alignmentManager = new AlignmentManager(filePath);
Iterator<SAMSequenceRecord> iterator = fileHeader.getSequenceDictionary().getSequences().iterator();
while (iterator.hasNext()) {
SAMSequenceRecord next = iterator.next();
for (int i = 0; i < next.getSequenceLength(); i += chunkSize) {
Region region = new Region(next.getSequenceName(), i + 1,
Math.min(i + chunkSize, next.getSequenceLength()));
RegionCoverage regionCoverage = alignmentManager.coverage(region, options, null);
// write coverages to file (only values greater than 0)
values = regionCoverage.getValues();
for (int j=0, start = region.getStart(); j < values.length; j++, start++) {
if (values[j] > 0) {
writer.write(next.getSequenceName() + "\t" + start + "\t" + values[j] + "\n");
}
}
}
}
// close
writer.close();
//
// HashMap<String, Integer> regionLength = new HashMap<>();
//
// //TODO: fix using the new RegionCoverage, JT
// try {
// // header management
// BufferedReader br = new BufferedReader(new FileReader(input + BAM_HEADER_SUFFIX));
// String line, fieldName, fieldLength;
// String[] fields;
// String[] subfields;
// while ((line = br.readLine()) != null) {
// if (line.startsWith("@SQ")) {
// fields = line.split("\t");
// subfields = fields[1].split(":");
// fieldName = subfields[1];
// subfields = fields[2].split(":");
// fieldLength = subfields[1];
//
// regionLength.put(fieldName, Integer.parseInt(fieldLength));
// }
// }
// br.close();
//
// // reader
// InputStream is = new FileInputStream(input);
// DataFileStream<ReadAlignment> reader = new DataFileStream<>(is, new SpecificDatumReader<>(ReadAlignment.class));
//
// // writer
// PrintWriter writer = new PrintWriter(new File(output + "/depth.txt"));
//
// String chromName = "";
// int[] chromDepth;
//
// RegionDepth regionDepth;
// RegionDepthCalculator calculator = new RegionDepthCalculator();
//
// int pos;
// long prevPos = 0L;
//
// // main loop
// chromDepth = null;
// for (ReadAlignment readAlignment : reader) {
// if (readAlignment.getAlignment() != null) {
// regionDepth = calculator.compute(readAlignment);
// if (chromDepth == null) {
// chromName = regionDepth.chrom;
// chromDepth = new int[regionLength.get(regionDepth.chrom)];
// }
// if (!chromName.equals(regionDepth.chrom)) {
// // write depth
// int length = chromDepth.length;
// for (int i = 0; i < length; i++) {
// writer.write(chromName + "\t" + (i + 1) + "\t" + chromDepth[i] + "\n");
// }
//
// // init
// prevPos = 0L;
// chromName = regionDepth.chrom;
// chromDepth = new int[regionLength.get(regionDepth.chrom)];
// }
// if (prevPos > regionDepth.position) {
// throw new IOException("Error: the input file (" + input + ") is not sorted (reads out of order).");
// }
//
// pos = (int) regionDepth.position;
// for (int i: regionDepth.array) {
// chromDepth[pos] += regionDepth.array[i];
// pos++;
// }
// prevPos = regionDepth.position;
// }
// }
// // write depth
// int length = chromDepth.length;
// for (int i = 0; i < length; i++) {
// if (chromDepth[i] > 0) {
// writer.write(chromName + "\t" + (i + 1) + "\t" + chromDepth[i] + "\n");
// }
// }
//
// // close
// reader.close();
// is.close();
// writer.close();
// } catch (Exception e) {
// throw e;
// }
}
public void query() throws Exception {
// check mandatory parameter 'input file'
Path inputPath = Paths.get(alignmentCommandOptions.queryAlignmentCommandOptions.input);
FileUtils.checkFile(inputPath);
// TODO: to take the spark home from somewhere else
SparkConf sparkConf = SparkConfCreator.getConf("variant query", "local", 1,
true, "/home/jtarraga/soft/spark-2.0.0/");
System.out.println("sparkConf = " + sparkConf.toDebugString());
SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
// SparkConf sparkConf = SparkConfCreator.getConf("MyTest", "local", 1, true, "/home/jtarraga/soft/spark-2.0.0/");
// SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf));
AlignmentDataset ad = new AlignmentDataset();
ad.load(alignmentCommandOptions.queryAlignmentCommandOptions.input, sparkSession);
ad.createOrReplaceTempView("alignment");
// query for region
List<Region> regions = null;
if (StringUtils.isNotEmpty(alignmentCommandOptions.queryAlignmentCommandOptions.regions)) {
regions = Region.parseRegions(alignmentCommandOptions.queryAlignmentCommandOptions.regions);
ad.regionFilter(regions);
}
// query for region file
if (StringUtils.isNotEmpty(alignmentCommandOptions.queryAlignmentCommandOptions.regionFile)) {
logger.warn("Query for region file, not yet implemented.");
}
// query for minimun mapping quality
if (alignmentCommandOptions.queryAlignmentCommandOptions.minMapQ > 0) {
ad.mappingQualityFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minMapQ);
}
// query for flags
if (alignmentCommandOptions.queryAlignmentCommandOptions.requireFlags != Integer.MAX_VALUE) {
ad.flagFilter("" + alignmentCommandOptions.queryAlignmentCommandOptions.requireFlags, false);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.filteringFlags != 0) {
ad.flagFilter("" + alignmentCommandOptions.queryAlignmentCommandOptions.filteringFlags, true);
}
// query for template length
if (alignmentCommandOptions.queryAlignmentCommandOptions.minTLen != 0) {
ad.templateLengthFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minTLen);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.maxTLen != Integer.MAX_VALUE) {
ad.templateLengthFilter("<=" + alignmentCommandOptions.queryAlignmentCommandOptions.maxTLen);
}
// query for alignment length
if (alignmentCommandOptions.queryAlignmentCommandOptions.minALen != 0) {
ad.alignmentLengthFilter(">=" + alignmentCommandOptions.queryAlignmentCommandOptions.minALen);
}
if (alignmentCommandOptions.queryAlignmentCommandOptions.maxALen != Integer.MAX_VALUE) {
ad.alignmentLengthFilter("<=" + alignmentCommandOptions.queryAlignmentCommandOptions.maxALen);
}
// apply previous filters
ad.update();
// save the dataset
logger.warn("The current query implementation saves the resulting dataset in Avro format.");
ad.write().format("com.databricks.spark.avro").save(alignmentCommandOptions.queryAlignmentCommandOptions.output);
}
}
| app: Fix compilation issues using Alignment classes from biodata
| hpg-bigdata-app/src/main/java/org/opencb/hpg/bigdata/app/cli/local/AlignmentCommandExecutor.java | app: Fix compilation issues using Alignment classes from biodata | <ide><path>pg-bigdata-app/src/main/java/org/opencb/hpg/bigdata/app/cli/local/AlignmentCommandExecutor.java
<ide> import org.ga4gh.models.ReadAlignment;
<ide> import org.opencb.biodata.models.alignment.RegionCoverage;
<ide> import org.opencb.biodata.models.core.Region;
<del>import org.opencb.biodata.tools.alignment.AlignmentManager;
<ide> import org.opencb.biodata.tools.alignment.AlignmentOptions;
<del>import org.opencb.biodata.tools.alignment.AlignmentUtils;
<add>import org.opencb.biodata.tools.alignment.BamManager;
<add>import org.opencb.biodata.tools.alignment.BamUtils;
<ide> import org.opencb.biodata.tools.alignment.stats.AlignmentGlobalStats;
<ide> import org.opencb.commons.utils.FileUtils;
<ide> import org.opencb.hpg.bigdata.app.cli.CommandExecutor;
<ide> String output = alignmentCommandOptions.statsAlignmentCommandOptions.output;
<ide>
<ide> try {
<del> // compute stats using the AlignmentManager
<del> AlignmentManager alignmentManager = new AlignmentManager(Paths.get(input));
<add> // compute stats using the BamManager
<add> BamManager alignmentManager = new BamManager(Paths.get(input));
<ide> AlignmentGlobalStats stats = alignmentManager.stats();
<ide>
<ide> // write results
<ide> // writer
<ide> PrintWriter writer = new PrintWriter(new File(output + "/" + filePath.getFileName() + ".coverage"));
<ide>
<del> SAMFileHeader fileHeader = AlignmentUtils.getFileHeader(filePath);
<add> SAMFileHeader fileHeader = BamUtils.getFileHeader(filePath);
<ide>
<ide> AlignmentOptions options = new AlignmentOptions();
<ide> options.setContained(false);
<ide>
<ide> short[] values;
<ide>
<del> AlignmentManager alignmentManager = new AlignmentManager(filePath);
<add> BamManager alignmentManager = new BamManager(filePath);
<ide> Iterator<SAMSequenceRecord> iterator = fileHeader.getSequenceDictionary().getSequences().iterator();
<ide> while (iterator.hasNext()) {
<ide> SAMSequenceRecord next = iterator.next(); |
|
JavaScript | bsd-3-clause | d36c09af7b7fe852d63d40ed6476f762cb1c9afe | 0 | Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js | import macro from 'vtk.js/Sources/macro';
import vtkCellArray from 'vtk.js/Sources/Common/Core/CellArray';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkMath from 'vtk.js/Sources/Common/Core/Math';
import vtkPoints from 'vtk.js/Sources/Common/Core/Points';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import { DesiredOutputPrecision } from 'vtk.js/Sources/Common/DataModel/DataSetAttributes/Constants';
import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import Constants from './Constants';
const { VaryRadius, GenerateTCoords } = Constants;
const { vtkDebugMacro, vtkErrorMacro, vtkWarningMacro } = macro;
// ----------------------------------------------------------------------------
// vtkTubeFilter methods
// ----------------------------------------------------------------------------
function vtkTubeFilter(publicAPI, model) {
// Set our classname
model.classHierarchy.push('vtkTubeFilter');
function computeOffset(offset, npts) {
let newOffset = offset;
if (model.sidesShareVertices) {
newOffset += model.numberOfSides * npts;
} else {
// points are duplicated
newOffset += 2 * model.numberOfSides * npts;
}
if (model.capping) {
// cap points are duplicated
newOffset += 2 * model.numberOfSides;
}
return newOffset;
}
function findNextValidSegment(points, pointIds, start) {
const ptId = pointIds[start];
const ps = points.slice(3 * ptId, 3 * (ptId + 1));
let end = start + 1;
while (end < pointIds.length) {
const endPtId = pointIds[end];
const pe = points.slice(3 * endPtId, 3 * (endPtId + 1));
if (ps !== pe) {
return end - 1;
}
++end;
}
return pointIds.length;
}
function generateSlidingNormals(pts, lines, normals, firstNormal = null) {
let normal = [0.0, 0.0, 1.0];
const lineData = lines;
// lid = 0;
let npts = lineData[0];
for (let i = 0; i < lineData.length; i += npts + 1) {
npts = lineData[i];
if (npts === 1) {
// return arbitary
normals.setTuple(lineData[i + 1], normal);
} else if (npts > 1) {
let sNextId = 0;
let sPrev = [0, 0, 0];
const sNext = [0, 0, 0];
const linePts = lineData.slice(i + 1, i + 1 + npts);
sNextId = findNextValidSegment(pts, linePts, 0);
if (sNextId !== npts) {
// atleast one valid segment
let pt1Id = linePts[sNextId];
let pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
let pt2Id = linePts[sNextId + 1];
let pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
sPrev = pt2.map((elem, idx) => elem - pt1[idx]);
vtkMath.normalize(sPrev);
// compute first normal
if (firstNormal) {
normal = firstNormal;
} else {
// find the next valid, non-parallel segment
while (++sNextId < npts) {
sNextId = findNextValidSegment(pts, linePts, sNextId);
if (sNextId !== npts) {
pt1Id = linePts[sNextId];
pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
pt2Id = linePts[sNextId + 1];
pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
for (let j = 0; j < 3; ++j) {
sNext[j] = pt2[j] - pt1[j];
}
vtkMath.normalize(sNext);
// now the starting normal should simply be the cross product.
// In the following if statement, we check for the case where
// the two segments are parallel, in which case, continue
// searching for the next valid segment
const n = [0.0, 0.0, 0.0];
vtkMath.cross(sPrev, sNext, n);
if (vtkMath.norm(n) > 1.0e-3) {
normal = n;
sPrev = sNext;
break;
}
}
}
if (sNextId >= npts) {
// only one valid segment
// a little trick to find orthogonal normal
for (let j = 0; j < 3; ++j) {
if (sPrev[j] !== 0.0) {
normal[(j + 2) % 3] = 0.0;
normal[(j + 1) % 3] = 1.0;
normal[j] = -sPrev[(j + 1) % 3] / sPrev[j];
break;
}
}
}
}
vtkMath.normalize(normal);
// compute remaining normals
let lastNormalId = 0;
while (++sNextId < npts) {
sNextId = findNextValidSegment(pts, linePts, sNextId);
if (sNextId === npts) {
break;
}
pt1Id = linePts[sNextId];
pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
pt2Id = linePts[sNextId + 1];
pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
for (let j = 0; j < 3; ++j) {
sNext[j] = pt2[j] - pt1[j];
}
vtkMath.normalize(sNext);
// compute rotation vector
const w = [0.0, 0.0, 0.0];
vtkMath.cross(sPrev, normal, w);
if (vtkMath.normalize(w) !== 0.0) {
// can't use this segment otherwise
const q = [0.0, 0.0, 0.0];
vtkMath.cross(sNext, sPrev, q);
if (vtkMath.normalize(q) !== 0.0) {
// can't use this segment otherwise
const f1 = vtkMath.dot(q, normal);
let f2 = 1.0 - f1 * f1;
if (f2 > 0.0) {
f2 = Math.sqrt(f2);
} else {
f2 = 0.0;
}
const c = [0, 0, 0];
for (let j = 0; j < 3; ++j) {
c[j] = sNext[j] + sPrev[j];
}
vtkMath.normalize(c);
vtkMath.cross(c, q, w);
vtkMath.cross(sPrev, q, c);
if (vtkMath.dot(normal, c) * vtkMath.dot(w, c) < 0.0) {
f2 *= -1.0;
}
// insert current normal before updating
for (let j = lastNormalId; j < sNextId; ++j) {
normals.setTuple(linePts[j], normal);
}
lastNormalId = sNextId;
sPrev = sNext;
// compute next normal
normal = f1 * q + f2 * w;
}
}
}
// insert last normal for the remaining points
for (let j = lastNormalId; j < npts; ++j) {
normals.setTuple(linePts[j], normal);
}
} else {
// no valid segments
for (let j = 0; j < npts; ++j) {
normals.setTuple(linePts[j], normal);
}
}
}
}
return 1;
}
function generatePoints(
offset,
npts,
pts,
inPts,
newPts,
pd,
outPD,
newNormals,
inScalars,
range,
inVectors,
maxSpeed,
inNormals,
theta
) {
// Use averaged segment to create beveled effect.
const sNext = [0.0, 0.0, 0.0];
const sPrev = [0.0, 0.0, 0.0];
const startCapNorm = [0.0, 0.0, 0.0];
const endCapNorm = [0.0, 0.0, 0.0];
let p = [0.0, 0.0, 0.0];
let pNext = [0.0, 0.0, 0.0];
let s = [0.0, 0.0, 0.0];
let n = [0.0, 0.0, 0.0];
const w = [0.0, 0.0, 0.0];
const nP = [0.0, 0.0, 0.0];
const normal = [0.0, 0.0, 0.0];
let sFactor = 1.0;
let ptId = offset;
for (let j = 0; j < npts; ++j) {
// First point
if (j === 0) {
p = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
pNext = inPts.slice(3 * pts[1], 3 * (pts[1] + 1));
for (let i = 0; i < 3; ++i) {
sNext[i] = pNext[i] - p[i];
sPrev[i] = sNext[i];
startCapNorm[i] = -sPrev[i];
}
vtkMath.normalize(startCapNorm);
} else if (j === npts - 1) {
for (let i = 0; i < 3; ++i) {
sPrev[i] = sNext[i];
p[i] = pNext[i];
endCapNorm[i] = sNext[i];
}
vtkMath.normalize(endCapNorm);
} else {
for (let i = 0; i < 3; ++i) {
p[i] = pNext[i];
}
pNext = inPts.slice(3 * pts[j + 1], 3 * (pts[j + 1] + 1));
for (let i = 0; i < 3; ++i) {
sPrev[i] = sNext[i];
sNext[i] = pNext[i] - p[i];
}
}
if (vtkMath.normalize(sNext) === 0.0) {
vtkWarningMacro('Coincident points!');
return 0;
}
for (let i = 0; i < 3; ++i) {
s[i] = (sPrev[i] + sNext[i]) / 2.0; // average vector
}
n = inNormals.slice(3 * pts[j], 3 * (pts[j] + 1));
// if s is zero then just use sPrev cross n
if (vtkMath.normalize(s) === 0.0) {
vtkMath.cross(sPrev, n, s);
if (vtkMath.normalize(s) === 0.0) {
vtkDebugMacro('Using alternate bevel vector');
}
}
vtkMath.cross(s, n, w);
if (vtkMath.normalize(w) === 0.0) {
let msg = 'Bad normal: s = ';
msg += `${s[0]}, ${s[1]}, ${s[2]}`;
msg += ` n = ${n[0]}, ${n[1]}, ${n[2]}`;
vtkWarningMacro(msg);
return 0;
}
vtkMath.cross(w, s, nP); // create orthogonal coordinate system
vtkMath.normalize(nP);
// Compute a scalar factor based on scalars or vectors
if (inScalars && model.varyRadius === VaryRadius.VARY_RADIUS_BY_SCALAR) {
sFactor =
1.0 +
(model.radiusFactor - 1.0) *
(inScalars.getComponent(pts[j], 0) - range[0]) /
(range[1] - range[0]);
} else if (
inVectors &&
model.varyRadius === VaryRadius.VARY_RADIUS_BY_VECTOR
) {
sFactor = Math.sqrt(
maxSpeed / vtkMath.norm(inVectors.getTuple(pts[j]))
);
if (sFactor > model.radiusFactor) {
sFactor = model.radiusFactor;
}
} else if (
inScalars &&
model.varyRadius === VaryRadius.VARY_RADIUS_BY_ABSOLUTE_SCALAR
) {
sFactor = inScalars.getComponent(pts[j], 0);
if (sFactor < 0.0) {
vtkWarningMacro('Scalar value less than zero, skipping line');
return 0;
}
}
// create points around line
if (model.sidesShareVertices) {
for (let k = 0; k < model.numberOfSides; ++k) {
for (let i = 0; i < 3; ++i) {
normal[i] =
w[i] * Math.cos(k * theta) + nP[i] * Math.sin(k * theta);
s[i] = p[i] + model.radius * sFactor * normal[i];
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = normal[i];
}
outPD.passData(pd, pts[j], ptId);
ptId++;
} // for each side
} else {
const nRight = [0, 0, 0];
const nLeft = [0, 0, 0];
for (let k = 0; k < model.numberOfSides; ++k) {
for (let i = 0; i < 3; ++i) {
// Create duplicate vertices at each point
// and adjust the associated normals so that they are
// oriented with the facets. This preserves the tube's
// polygonal appearance, as if by flat-shading around the tube,
// while still allowing smooth (gouraud) shading along the
// tube as it bends.
normal[i] =
w[i] * Math.cos(k * theta) + nP[i] * Math.sin(k * theta);
nRight[i] =
w[i] * Math.cos((k - 0.5) * theta) +
nP[i] * Math.sin((k - 0.5) * theta);
nLeft[i] =
w[i] * Math.cos((k + 0.5) * theta) +
nP[i] * Math.sin((k + 0.5) * theta);
s[i] = p[i] + model.radius * sFactor * normal[i];
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = nRight[i];
newPts[3 * (ptId + 1) + i] = s[i];
newNormals[3 * (ptId + 1) + i] = nLeft[i];
}
outPD.passData(pd, pts[j], ptId + 1);
ptId += 2;
} // for each side
} // else separate vertices
} // for all points in the polyline
// Produce end points for cap. They are placed at tail end of points.
if (model.capping) {
let numCapSides = model.numberOfSides;
let capIncr = 1;
if (!model.sidesShareVertices) {
numCapSides = 2 * model.numberOfSides;
capIncr = 2;
}
// the start cap
for (let k = 0; k < numCapSides; k += capIncr) {
s = newPts.slice(3 * (offset + k), 3 * (offset + k + 1));
for (let i = 0; i < 3; ++i) {
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = startCapNorm[i];
}
outPD.passData(pd, pts[0], ptId);
ptId++;
}
// the end cap
let endOffset = offset + (npts - 1) * model.numberOfSides;
if (!model.sidesShareVertices) {
endOffset = offset + 2 * (npts - 1) * model.numberOfSides;
}
for (let k = 0; k < numCapSides; k += capIncr) {
s = newPts.slice(3 * (endOffset + k), 3 * (endOffset + k + 1));
for (let i = 0; i < 3; ++i) {
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = endCapNorm[i];
}
outPD.passData(pd, pts[npts - 1], ptId);
ptId++;
}
} // if capping
return 1;
}
function generateStrips(
offset,
npts,
inCellId,
outCellId,
inCD,
outCD,
newStrips
) {
let i1 = 0;
let i2 = 0;
let i3 = 0;
let newOutCellId = outCellId;
let outCellIdx = 0;
const newStripsData = newStrips.getData();
let cellId = 0;
while (outCellIdx < newStripsData.length) {
if (cellId === outCellId) {
break;
}
outCellIdx += newStripsData[outCellIdx] + 1;
cellId++;
}
if (model.sidesShareVertices) {
for (
let k = offset;
k < model.numberOfSides + offset;
k += model.onRatio
) {
i1 = k % model.numberOfSides;
i2 = (k + 1) % model.numberOfSides;
newStripsData[outCellIdx++] = npts * 2;
for (let i = 0; i < npts; ++i) {
i3 = i * model.numberOfSides;
newStripsData[outCellIdx++] = offset + i2 + i3;
newStripsData[outCellIdx++] = offset + i1 + i3;
}
outCD.passData(inCD, inCellId, newOutCellId++);
} // for each side of the tube
} else {
for (
let k = offset;
k < model.numberOfSides + offset;
k += model.onRatio
) {
i1 = 2 * (k % model.numberOfSides) + 1;
i2 = 2 * ((k + 1) % model.numberOfSides);
// outCellId = newStrips.getNumberOfCells(true);
newStripsData[outCellIdx] = npts * 2;
outCellIdx++;
for (let i = 0; i < npts; ++i) {
i3 = i * 2 * model.numberOfSides;
newStripsData[outCellIdx++] = offset + i2 + i3;
newStripsData[outCellIdx++] = offset + i1 + i3;
}
outCD.passData(inCD, inCellId, newOutCellId++);
} // for each side of the tube
}
// Take care of capping. The caps are n-sided polygons that can be easily
// triangle stripped.
if (model.capping) {
let startIdx = offset + npts * model.numberOfSides;
let idx = 0;
if (!model.sidesShareVertices) {
startIdx = offset + 2 * npts * model.numberOfSides;
}
// The start cap
newStripsData[outCellIdx++] = model.numberOfSides;
newStripsData[outCellIdx++] = startIdx;
newStripsData[outCellIdx++] = startIdx + 1;
let k = 0;
for (
i1 = model.numberOfSides - 1, i2 = 2, k = 0;
k < model.numberOfSides - 2;
++k
) {
if (k % 2) {
idx = startIdx + i2;
newStripsData[outCellIdx++] = idx;
i2++;
} else {
idx = startIdx + i1;
newStripsData[outCellIdx++] = idx;
i1--;
}
}
outCD.passData(inCD, inCellId, newOutCellId++);
// The end cap - reversed order to be consistent with normal
startIdx += model.numberOfSides;
newStripsData[outCellIdx++] = model.numberOfSides;
newStripsData[outCellIdx++] = startIdx;
newStripsData[outCellIdx++] = startIdx + model.numberOfSides - 1;
for (
i1 = model.numberOfSides - 2, i2 = 1, k = 0;
k < model.numberOfSides - 2;
++k
) {
if (k % 2) {
idx = startIdx + i1;
newStripsData[outCellIdx++] = idx;
i1--;
} else {
idx = startIdx + i2;
newStripsData[outCellIdx++] = idx;
i2++;
}
}
outCD.passData(inCD, inCellId, newOutCellId++);
}
return newOutCellId;
}
function generateTCoords(offset, npts, pts, inPts, inScalars, newTCoords) {
let numSides = model.numberOfSides;
if (!model.sidesShareVertices) {
numSides = 2 * model.numberOfSides;
}
let tc = 0.0;
let s0 = 0.0;
let s = 0.0;
const inScalarsData = inScalars.getData();
if (model.generateTCoords === GenerateTCoords.TCOORDS_FROM_SCALARS) {
s0 = inScalarsData[pts[0]];
for (let i = 0; i < npts; ++i) {
s = inScalarsData[pts[i]];
tc = (s - s0) / model.textureLength;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
}
} else if (model.generateTCoords === GenerateTCoords.TCOORDS_FROM_LENGTH) {
let len = 0.0;
const xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
tc = len / model.textureLength;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
} else if (
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_NORMALIZED_LENGTH
) {
let len = 0.0;
let len1 = 0.0;
let xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len1 += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
tc = len / len1;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
}
// Capping, set the endpoints as appropriate
if (model.capping) {
const startIdx = offset + npts * numSides;
// start cap
for (let ik = 0; ik < model.numberOfSides; ++ik) {
const tcId = 2 * (startIdx + ik);
newTCoords[tcId] = 0.0;
newTCoords[tcId + 1] = 0.0;
}
// end cap
for (let ik = 0; ik < model.numberOfSides; ++ik) {
const tcId = 2 * (startIdx + model.numberOfSides + ik);
newTCoords[tcId] = 0.0;
newTCoords[tcId + 1] = 0.0;
}
}
}
publicAPI.requestData = (inData, outData) => {
// implement requestData
// pass through for now
const output = vtkPolyData.newInstance();
output.shallowCopy(inData[0]);
outData[0] = output;
const input = inData[0];
if (!input) {
vtkErrorMacro('Invalid or missing input');
return;
}
// Allocate output
const inPts = input.getPoints();
if (!inPts) {
return;
}
const numPts = inPts.getNumberOfPoints();
if (numPts < 1) {
return;
}
const inLines = input.getLines();
if (!inLines) {
return;
}
const numLines = inLines.getNumberOfCells();
if (numLines < 1) {
return;
}
let numNewPts = numPts * model.numberOfSides;
if (model.capping) {
numNewPts = (numPts + 2 * numLines) * model.numberOfSides;
}
let pointType = inPts.getDataType();
if (model.outputPointsPrecision === DesiredOutputPrecision.SINGLE) {
pointType = VtkDataTypes.FLOAT;
} else if (model.outputPointsPrecision === DesiredOutputPrecision.DOUBLE) {
pointType = VtkDataTypes.DOUBLE;
}
const newPts = vtkPoints.newInstance({
dataType: pointType,
size: numNewPts * 3,
numberOfComponents: 3,
});
let numNormals = 3 * numNewPts;
if (model.capping) {
numNormals = 3 * (numNewPts + 2 * model.numberOfSides);
}
const newNormalsData = new Float32Array(numNormals);
const newNormals = vtkDataArray.newInstance({
numberOfComponents: 3,
values: newNormalsData,
name: 'TubeNormals',
});
let numStrips = 0;
const inLinesData = inLines.getData();
let npts = inLinesData[0];
for (let i = 0; i < inLinesData.length; i += npts + 1) {
npts = inLinesData[i];
numStrips +=
(2 * npts + 1) * Math.ceil(model.numberOfSides / model.onRatio);
if (model.capping) {
numStrips += 2 * (model.numberOfSides + 1);
}
}
const newStripsData = new Uint32Array(numStrips);
const newStrips = vtkCellArray.newInstance({ values: newStripsData });
let newStripId = 0;
let inNormals = input.getPointData().getNormals();
let inNormalsData = null;
let generateNormals = false;
if (!inNormals || model.useDefaultNormal) {
inNormalsData = new Float32Array(3 * numPts);
inNormals = vtkDataArray.newInstance({
numberOfComponents: 3,
values: inNormalsData,
name: 'Normals',
});
if (model.useDefaultNormal) {
inNormalsData = inNormalsData.map((elem, index) => {
const i = index % 3;
return model.defaultNormal[i];
});
} else {
generateNormals = true;
}
}
const inScalars = publicAPI.getInputArrayToProcess(0);
let outScalars = null;
let range = [];
if (inScalars) {
// allocate output scalar array
// assuming point scalars for now
outScalars = vtkDataArray.newInstance({
name: inScalars.getName(),
dataType: inScalars.getDataType(),
numberOfComponents: inScalars.getNumberOfComponents(),
size: numNewPts * inScalars.getNumberOfComponents(),
});
range = inScalars.getRange();
if (range[1] - range[0] === 0.0) {
if (model.varyRadius === VaryRadius.VARY_RADIUS_BY_SCALAR) {
vtkWarningMacro('Scalar range is zero!');
}
range[1] = range[0] + 1.0;
}
}
const inVectors = publicAPI.getInputArrayToProcess(1);
let maxSpeed = 0;
if (inVectors) {
maxSpeed = inVectors.getMaxNorm();
}
const outCD = output.getCellData();
outCD.copyNormalsOff();
outCD.passData(input.getCellData());
const outPD = output.getPointData();
outPD.copyNormalsOff();
if (inScalars && outScalars) {
outPD.setScalars(outScalars);
}
// TCoords
let newTCoords = null;
if (
(model.generateTCoords === GenerateTCoords.TCOORDS_FROM_SCALARS &&
inScalars) ||
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_LENGTH ||
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_NORMALIZED_LENGTH
) {
const newTCoordsData = new Float32Array(2 * numNewPts);
newTCoords = vtkDataArray.newInstance({
numberOfComponents: 2,
values: newTCoordsData,
name: 'TCoords',
});
outPD.copyTCoordsOff();
}
outPD.passData(input.getPointData());
// Create points along each polyline that are connected into numberOfSides
// triangle strips.
const theta = 2.0 * Math.PI / model.numberOfSides;
npts = inLinesData[0];
let offset = 0;
let inCellId = input.getVerts().getNumberOfCells();
for (let i = 0; i < inLinesData.length; i += npts + 1) {
npts = inLinesData[i];
const pts = inLinesData.slice(i + 1, i + 1 + npts);
if (npts > 1) {
// if not, skip tubing this line
if (generateNormals) {
const polyLine = inLinesData.slice(i, i + npts + 1);
generateSlidingNormals(inPts.getData(), polyLine, inNormals);
}
}
// generate points
if (
generatePoints(
offset,
npts,
pts,
inPts.getData(),
newPts.getData(),
input.getPointData(),
outPD,
newNormalsData,
inScalars,
range,
inVectors,
maxSpeed,
inNormalsData,
theta
)
) {
// generate strips for the polyline
newStripId = generateStrips(
offset,
npts,
inCellId,
newStripId,
input.getCellData(),
outCD,
newStrips
);
// generate texture coordinates for the polyline
if (newTCoords) {
generateTCoords(
offset,
npts,
pts,
inPts.getData(),
inScalars,
newTCoords.getData()
);
}
} else {
// skip tubing this line
vtkWarningMacro('Could not generate points');
}
// lineIdx += npts;
// Compute the new offset for the next polyline
offset = computeOffset(offset, npts);
inCellId++;
}
output.setPoints(newPts);
output.setStrips(newStrips);
output.setPointData(outPD);
outPD.setNormals(newNormals);
outData[0] = output;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
outputPointsPrecision: DesiredOutputPrecision.DEFAULT,
radius: 0.5,
varyRadius: VaryRadius.VARY_RADIUS_OFF,
numberOfSides: 3,
radiusFactor: 10,
defaultNormal: [0, 0, 1],
useDefaultNormal: false,
sidesShareVertices: true,
capping: false,
onRatio: 1,
offset: 0,
generateTCoords: GenerateTCoords.TCOORDS_OFF,
textureLength: 1.0,
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
macro.setGet(publicAPI, model, [
'outputPointsPrecision',
'radius',
'varyRadius',
'numberOfSides',
'radiusFactor',
'defaultNormal',
'useDefaultNormal',
'sidesShareVertices',
'capping',
'onRatio',
'offset',
'generateTCoords',
'textureLength',
]);
// Make this a VTK object
macro.obj(publicAPI, model);
// Also make it an algorithm with one input and one output
macro.algo(publicAPI, model, 1, 1);
// Object specific methods
vtkTubeFilter(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = macro.newInstance(extend, 'vtkTubeFilter');
// ----------------------------------------------------------------------------
export default Object.assign({ newInstance, extend });
| Sources/Filters/General/TubeFilter/index.js | import macro from 'vtk.js/Sources/macro';
import vtkCellArray from 'vtk.js/Sources/Common/Core/CellArray';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkMath from 'vtk.js/Sources/Common/Core/Math';
import vtkPoints from 'vtk.js/Sources/Common/Core/Points';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import { DesiredOutputPrecision } from 'vtk.js/Sources/Common/DataModel/DataSetAttributes/Constants';
import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import Constants from './Constants';
const { VaryRadius, GenerateTCoords } = Constants;
const { vtkDebugMacro, vtkErrorMacro, vtkWarningMacro } = macro;
// ----------------------------------------------------------------------------
// vtkTubeFilter methods
// ----------------------------------------------------------------------------
function vtkTubeFilter(publicAPI, model) {
// Set our classname
model.classHierarchy.push('vtkTubeFilter');
function computeOffset(offset, npts) {
let newOffset = offset;
if (model.sidesShareVertices) {
newOffset += model.numberOfSides * npts;
} else {
// points are duplicated
newOffset += 2 * model.numberOfSides * npts;
}
if (model.capping) {
// cap points are duplicated
newOffset += 2 * model.numberOfSides;
}
return newOffset;
}
function findNextValidSegment(points, pointIds, start) {
const ptId = pointIds[start];
const ps = points.slice(3 * ptId, 3 * (ptId + 1));
let end = start + 1;
while (end < pointIds.length) {
const endPtId = pointIds[end];
const pe = points.slice(3 * endPtId, 3 * (endPtId + 1));
if (ps !== pe) {
return end - 1;
}
++end;
}
return pointIds.length;
}
function generateSlidingNormals(pts, lines, normals, firstNormal = null) {
let normal = [0.0, 0.0, 1.0];
const lineData = lines;
// lid = 0;
let npts = lineData[0];
for (let i = 0; i < lineData.length; i += npts + 1) {
npts = lineData[i];
if (npts === 1) {
// return arbitary
normals.setTuple(lineData[i + 1], normal);
} else if (npts > 1) {
let sNextId = 0;
let sPrev = [0, 0, 0];
const sNext = [0, 0, 0];
const linePts = lineData.slice(i + 1, i + 1 + npts);
sNextId = findNextValidSegment(pts, linePts, 0);
if (sNextId !== npts) {
// atleast one valid segment
let pt1Id = linePts[sNextId];
let pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
let pt2Id = linePts[sNextId + 1];
let pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
sPrev = pt2.map((elem, idx) => elem - pt1[idx]);
vtkMath.normalize(sPrev);
// compute first normal
if (firstNormal) {
normal = firstNormal;
} else {
// find the next valid, non-parallel segment
while (++sNextId < npts) {
sNextId = findNextValidSegment(pts, linePts, sNextId);
if (sNextId !== npts) {
pt1Id = linePts[sNextId];
pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
pt2Id = linePts[sNextId + 1];
pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
for (let j = 0; j < 3; ++j) {
sNext[j] = pt2[j] - pt1[j];
}
vtkMath.normalize(sNext);
// now the starting normal should simply be the cross product.
// In the following if statement, we check for the case where
// the two segments are parallel, in which case, continue
// searching for the next valid segment
const n = [0.0, 0.0, 0.0];
vtkMath.cross(sPrev, sNext, n);
if (vtkMath.norm(n) > 1.0e-3) {
normal = n;
sPrev = sNext;
break;
}
}
}
if (sNextId >= npts) {
// only one valid segment
// a little trick to find orthogonal normal
for (let j = 0; j < 3; ++j) {
if (sPrev[j] !== 0.0) {
normal[(j + 2) % 3] = 0.0;
normal[(j + 1) % 3] = 1.0;
normal[j] = -sPrev[(j + 1) % 3] / sPrev[j];
break;
}
}
}
}
vtkMath.normalize(normal);
// compute remaining normals
let lastNormalId = 0;
while (++sNextId < npts) {
sNextId = findNextValidSegment(pts, linePts, sNextId);
if (sNextId === npts) {
break;
}
pt1Id = linePts[sNextId];
pt1 = pts.slice(3 * pt1Id, 3 * (pt1Id + 1));
pt2Id = linePts[sNextId + 1];
pt2 = pts.slice(3 * pt2Id, 3 * (pt2Id + 1));
for (let j = 0; j < 3; ++j) {
sNext[j] = pt2[j] - pt1[j];
}
vtkMath.normalize(sNext);
// compute rotation vector
const w = [0.0, 0.0, 0.0];
vtkMath.cross(sPrev, normal, w);
if (vtkMath.normalize(w) !== 0.0) {
// can't use this segment otherwise
const q = [0.0, 0.0, 0.0];
vtkMath.cross(sNext, sPrev, q);
if (vtkMath.normalize(q) !== 0.0) {
// can't use this segment otherwise
const f1 = vtkMath.dot(q, normal);
let f2 = 1.0 - f1 * f1;
if (f2 > 0.0) {
f2 = Math.sqrt(f2);
} else {
f2 = 0.0;
}
const c = [0, 0, 0];
for (let j = 0; j < 3; ++j) {
c[j] = sNext[j] + sPrev[j];
}
vtkMath.normalize(c);
vtkMath.cross(c, q, w);
vtkMath.cross(sPrev, q, c);
if (vtkMath.dot(normal, c) * vtkMath.dot(w, c) < 0.0) {
f2 *= -1.0;
}
// insert current normal before updating
for (let j = lastNormalId; j < sNextId; ++j) {
normals.setTuple(linePts[j], normal);
}
lastNormalId = sNextId;
sPrev = sNext;
// compute next normal
normal = f1 * q + f2 * w;
}
}
}
// insert last normal for the remaining points
for (let j = lastNormalId; j < npts; ++j) {
normals.setTuple(linePts[j], normal);
}
} else {
// no valid segments
for (let j = 0; j < npts; ++j) {
normals.setTuple(linePts[j], normal);
}
}
}
}
return 1;
}
function generatePoints(
offset,
npts,
pts,
inPts,
newPts,
pd,
outPD,
newNormals,
inScalars,
range,
inVectors,
maxSpeed,
inNormals,
theta
) {
// Use averaged segment to create beveled effect.
const sNext = [0.0, 0.0, 0.0];
const sPrev = [0.0, 0.0, 0.0];
const startCapNorm = [0.0, 0.0, 0.0];
const endCapNorm = [0.0, 0.0, 0.0];
let p = [0.0, 0.0, 0.0];
let pNext = [0.0, 0.0, 0.0];
let s = [0.0, 0.0, 0.0];
let n = [0.0, 0.0, 0.0];
const w = [0.0, 0.0, 0.0];
const nP = [0.0, 0.0, 0.0];
const normal = [0.0, 0.0, 0.0];
let sFactor = 1.0;
let ptId = offset;
for (let j = 0; j < npts; ++j) {
// First point
if (j === 0) {
p = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
pNext = inPts.slice(3 * pts[1], 3 * (pts[1] + 1));
for (let i = 0; i < 3; ++i) {
sNext[i] = pNext[i] - p[i];
sPrev[i] = sNext[i];
startCapNorm[i] = -sPrev[i];
}
vtkMath.normalize(startCapNorm);
} else if (j === npts - 1) {
for (let i = 0; i < 3; ++i) {
sPrev[i] = sNext[i];
p[i] = pNext[i];
endCapNorm[i] = sNext[i];
}
vtkMath.normalize(endCapNorm);
} else {
for (let i = 0; i < 3; ++i) {
p[i] = pNext[i];
}
pNext = inPts.slice(3 * pts[j + 1], 3 * (pts[j + 1] + 1));
for (let i = 0; i < 3; ++i) {
sPrev[i] = sNext[i];
sNext[i] = pNext[i] - p[i];
}
}
if (vtkMath.normalize(sNext) === 0.0) {
vtkWarningMacro('Coincident points!');
return 0;
}
for (let i = 0; i < 3; ++i) {
s[i] = (sPrev[i] + sNext[i]) / 2.0; // average vector
}
n = inNormals.slice(3 * pts[j], 3 * (pts[j] + 1));
// if s is zero then just use sPrev cross n
if (vtkMath.normalize(s) === 0.0) {
vtkMath.cross(sPrev, n, s);
if (vtkMath.normalize(s) === 0.0) {
vtkDebugMacro('Using alternate bevel vector');
}
}
vtkMath.cross(s, n, w);
if (vtkMath.normalize(w) === 0.0) {
let msg = 'Bad normal: s = ';
msg += `${s[0]}, ${s[1]}, ${s[2]}`;
msg += ` n = ${n[0]}, ${n[1]}, ${n[2]}`;
vtkWarningMacro(msg);
return 0;
}
vtkMath.cross(w, s, nP); // create orthogonal coordinate system
vtkMath.normalize(nP);
// Compute a scalar factor based on scalars or vectors
if (inScalars && model.varyRadius === VaryRadius.VARY_RADIUS_BY_SCALAR) {
sFactor =
1.0 +
(model.radiusFactor - 1.0) *
(inScalars.getComponent(pts[j], 0) - range[0]) /
(range[1] - range[0]);
} else if (
inVectors &&
model.varyRadius === VaryRadius.VARY_RADIUS_BY_VECTOR
) {
sFactor = Math.sqrt(
maxSpeed / vtkMath.norm(inVectors.getTuple(pts[j]))
);
if (sFactor > model.radiusFactor) {
sFactor = model.radiusFactor;
}
} else if (
inScalars &&
model.varyRadius === VaryRadius.VARY_RADIUS_BY_ABSOLUTE_SCALAR
) {
sFactor = inScalars.getComponent(pts[j], 0);
if (sFactor < 0.0) {
vtkWarningMacro('Scalar value less than zero, skipping line');
return 0;
}
}
// create points around line
if (model.sidesShareVertices) {
for (let k = 0; k < model.numberOfSides; ++k) {
for (let i = 0; i < 3; ++i) {
normal[i] =
w[i] * Math.cos(k * theta) + nP[i] * Math.sin(k * theta);
s[i] = p[i] + model.radius * sFactor * normal[i];
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = normal[i];
}
outPD.passData(pd, pts[j], ptId);
ptId++;
} // for each side
} else {
const nRight = [0, 0, 0];
const nLeft = [0, 0, 0];
for (let k = 0; k < model.numberOfSides; ++k) {
for (let i = 0; i < 3; ++i) {
// Create duplicate vertices at each point
// and adjust the associated normals so that they are
// oriented with the facets. This preserves the tube's
// polygonal appearance, as if by flat-shading around the tube,
// while still allowing smooth (gouraud) shading along the
// tube as it bends.
normal[i] =
w[i] * Math.cos(k * theta) + nP[i] * Math.sin(k * theta);
nRight[i] =
w[i] * Math.cos((k - 0.5) * theta) +
nP[i] * Math.sin((k - 0.5) * theta);
nLeft[i] =
w[i] * Math.cos((k + 0.5) * theta) +
nP[i] * Math.sin((k + 0.5) * theta);
s[i] = p[i] + model.radius * sFactor * normal[i];
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = nRight[i];
newPts[3 * (ptId + 1) + i] = s[i];
newNormals[3 * (ptId + 1) + i] = nLeft[i];
}
outPD.passData(pd, pts[j], ptId + 1);
ptId += 2;
} // for each side
} // else separate vertices
} // for all points in the polyline
// Produce end points for cap. They are placed at tail end of points.
if (model.capping) {
let numCapSides = model.numberOfSides;
let capIncr = 1;
if (!model.sidesShareVertices) {
numCapSides = 2 * model.numberOfSides;
capIncr = 2;
}
// the start cap
for (let k = 0; k < numCapSides; k += capIncr) {
s = newPts.slice(3 * (offset + k), 3 * (offset + k + 1));
for (let i = 0; i < 3; ++i) {
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = startCapNorm[i];
}
outPD.passData(pd, pts[0], ptId);
ptId++;
}
// the end cap
let endOffset = offset + (npts - 1) * model.numberOfSides;
if (!model.sidesShareVertices) {
endOffset = offset + 2 * (npts - 1) * model.numberOfSides;
}
for (let k = 0; k < numCapSides; k += capIncr) {
s = newPts.slice(3 * (endOffset + k), 3 * (endOffset + k + 1));
for (let i = 0; i < 3; ++i) {
newPts[3 * ptId + i] = s[i];
newNormals[3 * ptId + i] = endCapNorm[i];
}
outPD.passData(pd, pts[npts - 1], ptId);
ptId++;
}
} // if capping
return 1;
}
function generateStrips(
offset,
npts,
inCellId,
outCellId,
inCD,
outCD,
newStrips
) {
let i1 = 0;
let i2 = 0;
let i3 = 0;
let newOutCellId = outCellId;
let outCellIdx = 0;
const newStripsData = newStrips.getData();
let cellId = 0;
while (outCellIdx < newStripsData.length) {
if (cellId === outCellId) {
break;
}
outCellIdx += newStripsData[outCellIdx] + 1;
cellId++;
}
if (model.sidesShareVertices) {
for (
let k = offset;
k < model.numberOfSides + offset;
k += model.onRatio
) {
i1 = k % model.numberOfSides;
i2 = (k + 1) % model.numberOfSides;
newStripsData[outCellIdx++] = npts * 2;
for (let i = 0; i < npts; ++i) {
i3 = i * model.numberOfSides;
newStripsData[outCellIdx++] = offset + i2 + i3;
newStripsData[outCellIdx++] = offset + i1 + i3;
}
outCD.passData(inCD, inCellId, newOutCellId++);
} // for each side of the tube
} else {
for (
let k = offset;
k < model.numberOfSides + offset;
k += model.onRatio
) {
i1 = 2 * (k % model.numberOfSides) + 1;
i2 = 2 * ((k + 1) % model.numberOfSides);
// outCellId = newStrips.getNumberOfCells(true);
newStripsData[outCellIdx] = npts * 2;
outCellIdx++;
for (let i = 0; i < npts; ++i) {
i3 = i * 2 * model.numberOfSides;
newStripsData[outCellIdx++] = offset + i2 + i3;
newStripsData[outCellIdx++] = offset + i1 + i3;
}
outCD.passData(inCD, inCellId, newOutCellId++);
} // for each side of the tube
}
// Take care of capping. The caps are n-sided polygons that can be easily
// triangle stripped.
if (model.capping) {
let startIdx = offset + npts * model.numberOfSides;
let idx = 0;
if (!model.sidesShareVertices) {
startIdx = offset + 2 * npts * model.numberOfSides;
}
// The start cap
newStripsData[outCellIdx++] = model.numberOfSides;
newStripsData[outCellIdx++] = startIdx;
newStripsData[outCellIdx++] = startIdx + 1;
let k = 0;
for (
i1 = model.numberOfSides - 1, i2 = 2, k = 0;
k < model.numberOfSides - 2;
++k
) {
if (k % 2) {
idx = startIdx + i2;
newStripsData[outCellIdx++] = idx;
i2++;
} else {
idx = startIdx + i1;
newStripsData[outCellIdx++] = idx;
i1--;
}
}
outCD.passData(inCD, inCellId, newOutCellId++);
// The end cap - reversed order to be consistent with normal
startIdx += model.numberOfSides;
newStripsData[outCellIdx++] = model.numberOfSides;
newStripsData[outCellIdx++] = startIdx;
newStripsData[outCellIdx++] = startIdx + model.numberOfSides - 1;
for (
i1 = model.numberOfSides - 2, i2 = 1, k = 0;
k < model.numberOfSides - 2;
++k
) {
if (k % 2) {
idx = startIdx + i1;
newStripsData[outCellIdx++] = idx;
i1--;
} else {
idx = startIdx + i2;
newStripsData[outCellIdx++] = idx;
i2++;
}
}
outCD.passData(inCD, inCellId, newOutCellId++);
}
return newOutCellId;
}
function generateTCoords(offset, npts, pts, inPts, inScalars, newTCoords) {
let numSides = model.numberOfSides;
if (!model.sidesShareVertices) {
numSides = 2 * model.numberOfSides;
}
let tc = 0.0;
let s0 = 0.0;
let s = 0.0;
const inScalarsData = inScalars.getData();
if (model.generateTCoords === GenerateTCoords.TCOORDS_FROM_SCALARS) {
s0 = inScalarsData[pts[0]];
for (let i = 0; i < npts; ++i) {
s = inScalarsData[pts[i]];
tc = (s - s0) / model.textureLength;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
}
} else if (model.generateTCoords === GenerateTCoords.TCOORDS_FROM_LENGTH) {
let len = 0.0;
const xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
tc = len / model.textureLength;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
} else if (
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_NORMALIZED_LENGTH
) {
let len = 0.0;
let len1 = 0.0;
let xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len1 += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
xPrev = inPts.slice(3 * pts[0], 3 * (pts[0] + 1));
for (let i = 0; i < npts; ++i) {
const x = inPts.slice(3 * pts[i], 3 * (pts[i] + 1));
len += Math.sqrt(vtkMath.distance2BetweenPoints(x, xPrev));
tc = len / len1;
for (let k = 0; k < numSides; ++k) {
const tcy = k / (numSides - 1);
const tcId = 2 * (offset + i * numSides + k);
newTCoords[tcId] = tc;
newTCoords[tcId + 1] = tcy;
}
for (let k = 0; k < 3; ++k) {
xPrev[k] = x[k];
}
}
}
// Capping, set the endpoints as appropriate
if (model.capping) {
const startIdx = offset + npts * numSides;
// start cap
for (let ik = 0; ik < model.numberOfSides; ++ik) {
const tcId = 2 * (startIdx + ik);
newTCoords[tcId] = 0.0;
newTCoords[tcId + 1] = 0.0;
}
// end cap
for (let ik = 0; ik < model.numberOfSides; ++ik) {
const tcId = 2 * (startIdx + model.numberOfSides + ik);
newTCoords[tcId] = 0.0;
newTCoords[tcId + 1] = 0.0;
}
}
}
publicAPI.requestData = (inData, outData) => {
// implement requestData
// pass through for now
outData[0] = inData[0];
const input = inData[0];
if (!input) {
vtkErrorMacro('Invalid or missing input');
return;
}
// Allocate output
const output = vtkPolyData.newInstance();
const inPts = input.getPoints();
if (!inPts) {
return;
}
const numPts = inPts.getNumberOfPoints();
if (numPts < 1) {
return;
}
const inLines = input.getLines();
if (!inLines) {
return;
}
const numLines = inLines.getNumberOfCells();
if (numLines < 1) {
return;
}
let numNewPts = numPts * model.numberOfSides;
if (model.capping) {
numNewPts = (numPts + 2 * numLines) * model.numberOfSides;
}
let pointType = inPts.getDataType();
if (model.outputPointsPrecision === DesiredOutputPrecision.SINGLE) {
pointType = VtkDataTypes.FLOAT;
} else if (model.outputPointsPrecision === DesiredOutputPrecision.DOUBLE) {
pointType = VtkDataTypes.DOUBLE;
}
const newPts = vtkPoints.newInstance({
dataType: pointType,
size: numNewPts * 3,
numberOfComponents: 3,
});
let numNormals = 3 * numNewPts;
if (model.capping) {
numNormals = 3 * (numNewPts + 2 * model.numberOfSides);
}
const newNormalsData = new Float32Array(numNormals);
const newNormals = vtkDataArray.newInstance({
numberOfComponents: 3,
values: newNormalsData,
name: 'TubeNormals',
});
let numStrips = 0;
const inLinesData = inLines.getData();
let npts = inLinesData[0];
for (let i = 0; i < inLinesData.length; i += npts + 1) {
npts = inLinesData[i];
numStrips +=
(2 * npts + 1) * Math.ceil(model.numberOfSides / model.onRatio);
if (model.capping) {
numStrips += 2 * (model.numberOfSides + 1);
}
}
const newStripsData = new Uint32Array(numStrips);
const newStrips = vtkCellArray.newInstance({ values: newStripsData });
let newStripId = 0;
let inNormals = input.getPointData().getNormals();
let inNormalsData = null;
let generateNormals = false;
if (!inNormals || model.useDefaultNormal) {
inNormalsData = new Float32Array(3 * numPts);
inNormals = vtkDataArray.newInstance({
numberOfComponents: 3,
values: inNormalsData,
name: 'Normals',
});
if (model.useDefaultNormal) {
inNormalsData = inNormalsData.map((elem, index) => {
const i = index % 3;
return model.defaultNormal[i];
});
} else {
generateNormals = true;
}
}
const inScalars = publicAPI.getInputArrayToProcess(0);
let outScalars = null;
let range = [];
if (inScalars) {
// allocate output scalar array
// assuming point scalars for now
outScalars = vtkDataArray.newInstance({
name: inScalars.getName(),
dataType: inScalars.getDataType(),
numberOfComponents: inScalars.getNumberOfComponents(),
size: numNewPts * inScalars.getNumberOfComponents(),
});
range = inScalars.getRange();
if (range[1] - range[0] === 0.0) {
if (model.varyRadius === VaryRadius.VARY_RADIUS_BY_SCALAR) {
vtkWarningMacro('Scalar range is zero!');
}
range[1] = range[0] + 1.0;
}
}
const inVectors = publicAPI.getInputArrayToProcess(1);
let maxSpeed = 0;
if (inVectors) {
maxSpeed = inVectors.getMaxNorm();
}
const outCD = output.getCellData();
outCD.copyNormalsOff();
outCD.passData(input.getCellData());
const outPD = output.getPointData();
outPD.copyNormalsOff();
if (inScalars && outScalars) {
outPD.setScalars(outScalars);
}
// TCoords
let newTCoords = null;
if (
(model.generateTCoords === GenerateTCoords.TCOORDS_FROM_SCALARS &&
inScalars) ||
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_LENGTH ||
model.generateTCoords === GenerateTCoords.TCOORDS_FROM_NORMALIZED_LENGTH
) {
const newTCoordsData = new Float32Array(2 * numNewPts);
newTCoords = vtkDataArray.newInstance({
numberOfComponents: 2,
values: newTCoordsData,
name: 'TCoords',
});
outPD.copyTCoordsOff();
}
outPD.passData(input.getPointData());
// Create points along each polyline that are connected into numberOfSides
// triangle strips.
const theta = 2.0 * Math.PI / model.numberOfSides;
npts = inLinesData[0];
let offset = 0;
let inCellId = input.getVerts().getNumberOfCells();
for (let i = 0; i < inLinesData.length; i += npts + 1) {
npts = inLinesData[i];
const pts = inLinesData.slice(i + 1, i + 1 + npts);
if (npts > 1) {
// if not, skip tubing this line
if (generateNormals) {
const polyLine = inLinesData.slice(i, i + npts + 1);
generateSlidingNormals(inPts.getData(), polyLine, inNormals);
}
}
// generate points
if (
generatePoints(
offset,
npts,
pts,
inPts.getData(),
newPts.getData(),
input.getPointData(),
outPD,
newNormalsData,
inScalars,
range,
inVectors,
maxSpeed,
inNormalsData,
theta
)
) {
// generate strips for the polyline
newStripId = generateStrips(
offset,
npts,
inCellId,
newStripId,
input.getCellData(),
outCD,
newStrips
);
// generate texture coordinates for the polyline
if (newTCoords) {
generateTCoords(
offset,
npts,
pts,
inPts.getData(),
inScalars,
newTCoords.getData()
);
}
} else {
// skip tubing this line
vtkWarningMacro('Could not generate points');
}
// lineIdx += npts;
// Compute the new offset for the next polyline
offset = computeOffset(offset, npts);
inCellId++;
}
output.setPoints(newPts);
output.setStrips(newStrips);
output.setPointData(outPD);
outPD.setNormals(newNormals);
outData[0] = output;
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
outputPointsPrecision: DesiredOutputPrecision.DEFAULT,
radius: 0.5,
varyRadius: VaryRadius.VARY_RADIUS_OFF,
numberOfSides: 3,
radiusFactor: 10,
defaultNormal: [0, 0, 1],
useDefaultNormal: false,
sidesShareVertices: true,
capping: false,
onRatio: 1,
offset: 0,
generateTCoords: GenerateTCoords.TCOORDS_OFF,
textureLength: 1.0,
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
// Build VTK API
macro.setGet(publicAPI, model, [
'outputPointsPrecision',
'radius',
'varyRadius',
'numberOfSides',
'radiusFactor',
'defaultNormal',
'useDefaultNormal',
'sidesShareVertices',
'capping',
'onRatio',
'offset',
'generateTCoords',
'textureLength',
]);
// Make this a VTK object
macro.obj(publicAPI, model);
// Also make it an algorithm with one input and one output
macro.algo(publicAPI, model, 1, 1);
// Object specific methods
vtkTubeFilter(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = macro.newInstance(extend, 'vtkTubeFilter');
// ----------------------------------------------------------------------------
export default Object.assign({ newInstance, extend });
| fix(TubeFilter): Properly use shallow copy inside filter
| Sources/Filters/General/TubeFilter/index.js | fix(TubeFilter): Properly use shallow copy inside filter | <ide><path>ources/Filters/General/TubeFilter/index.js
<ide> publicAPI.requestData = (inData, outData) => {
<ide> // implement requestData
<ide> // pass through for now
<del> outData[0] = inData[0];
<add> const output = vtkPolyData.newInstance();
<add> output.shallowCopy(inData[0]);
<add> outData[0] = output;
<ide>
<ide> const input = inData[0];
<ide> if (!input) {
<ide> }
<ide>
<ide> // Allocate output
<del> const output = vtkPolyData.newInstance();
<del>
<ide> const inPts = input.getPoints();
<ide> if (!inPts) {
<ide> return; |
|
Java | apache-2.0 | 4317740c5d450d62d6918909f0eff283e007f5a0 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandLine;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.hosted.node.admin.task.util.process.Terminal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* @author hakonhall
*/
public class Yum {
// Note: "(?dm)" makes newline be \n (only), and enables multiline mode where ^$ match lines with find()
private static final Pattern CHECKING_FOR_UPDATE_PATTERN =
Pattern.compile("(?dm)^Package matching [^ ]+ already installed\\. Checking for update\\.$");
private static final Pattern NOTHING_TO_DO_PATTERN = Pattern.compile("(?dm)^Nothing to do$");
private static final Pattern INSTALL_NOOP_PATTERN = NOTHING_TO_DO_PATTERN;
private static final Pattern UPGRADE_NOOP_PATTERN = Pattern.compile("(?dm)^No packages marked for update$");
private static final Pattern REMOVE_NOOP_PATTERN = Pattern.compile("(?dm)^No Packages marked for removal$");
private static final Pattern UNKNOWN_PACKAGE_PATTERN = Pattern.compile(
"(?dm)^No package ([^ ]+) available\\.$");
// WARNING: These must be in the same order as the supplier below
private static final String RPM_QUERYFORMAT = Stream.of("NAME", "EPOCH", "VERSION", "RELEASE", "ARCH")
.map(formatter -> "%{" + formatter + "}")
.collect(Collectors.joining("\\n"));
private static final Function<YumPackageName.Builder, List<Function<String, YumPackageName.Builder>>>
PACKAGE_NAME_BUILDERS_GENERATOR = builder -> List.of(
builder::setName, builder::setEpoch, builder::setVersion, builder::setRelease, builder::setArchitecture);
private final Terminal terminal;
public Yum(Terminal terminal) {
this.terminal = terminal;
}
public Optional<YumPackageName> queryInstalled(TaskContext context, String packageName) {
CommandResult commandResult = terminal.newCommandLine(context)
.add("rpm", "-q", packageName, "--queryformat", RPM_QUERYFORMAT)
.ignoreExitCode()
.executeSilently();
if (commandResult.getExitCode() != 0) return Optional.empty();
YumPackageName.Builder builder = new YumPackageName.Builder();
List<Function<String, YumPackageName.Builder>> builders = PACKAGE_NAME_BUILDERS_GENERATOR.apply(builder);
List<Optional<String>> lines = commandResult.mapEachLine(line -> Optional.of(line).filter(s -> !"(none)".equals(s)));
if (lines.size() != builders.size()) throw new IllegalStateException(String.format(
"Unexpected response from rpm, expected %d lines, got %s", builders.size(), commandResult.getOutput()));
IntStream.range(0, builders.size()).forEach(i -> lines.get(i).ifPresent(builders.get(i)::apply));
return Optional.of(builder.build());
}
/**
* Lock and install, or if necessary downgrade, a package to a given version.
*
* @return false only if the package was already locked and installed at the given version (no-op)
*/
public boolean installFixedVersion(TaskContext context, YumPackageName yumPackage, String... repos) {
String targetVersionLockName = yumPackage.toVersionLockName();
boolean alreadyLocked = terminal
.newCommandLine(context)
.add("yum", "--quiet", "versionlock", "list")
.executeSilently()
.getOutputLinesStream()
.map(YumPackageName::parseString)
.filter(Optional::isPresent) // removes garbage first lines, even with --quiet
.map(Optional::get)
.anyMatch(packageName -> {
// Ignore lines for other packages
if (packageName.getName().equals(yumPackage.getName())) {
// If existing lock doesn't exactly match the full package name,
// it means it's locked to another version and we must remove that lock.
String versionLockName = packageName.toVersionLockName();
if (versionLockName.equals(targetVersionLockName)) {
return true;
} else {
terminal.newCommandLine(context)
.add("yum", "versionlock", "delete", versionLockName)
.execute();
}
}
return false;
});
boolean modified = false;
if (!alreadyLocked) {
CommandLine commandLine = terminal.newCommandLine(context).add("yum", "versionlock", "add");
// If the targetVersionLockName refers to a package in a by-default-disabled repo,
// we must enable the repo unless targetVersionLockName is already installed.
// The other versionlock commands (list, delete) does not require --enablerepo.
for (String repo : repos) commandLine.add("--enablerepo=" + repo);
commandLine.add(targetVersionLockName).execute();
modified = true;
}
// The following 3 things may happen with yum install:
// 1. The package is installed or upgraded to the target version, in case we'd return
// true from converge()
// 2. The package is already installed at target version, in case
// "Nothing to do" is printed in the last line and we may return false from converge()
// 3. The package is already installed but at a later version than the target version,
// in case the last 2 lines of the output is:
// - "Package matching yakl-client-0.10-654.el7.x86_64 already installed. Checking for update."
// - "Nothing to do"
// And in case we need to downgrade and return true from converge()
var installCommand = terminal.newCommandLine(context).add("yum", "install");
for (String repo : repos) installCommand.add("--enablerepo=" + repo);
installCommand.add("--assumeyes", yumPackage.toName());
String output = installCommand.executeSilently().getUntrimmedOutput();
if (NOTHING_TO_DO_PATTERN.matcher(output).find()) {
if (CHECKING_FOR_UPDATE_PATTERN.matcher(output).find()) {
// case 3.
var upgradeCommand = terminal.newCommandLine(context).add("yum", "downgrade", "--assumeyes");
for (String repo : repos) upgradeCommand.add("--enablerepo=" + repo);
upgradeCommand.add(yumPackage.toName()).execute();
modified = true;
} else {
// case 2.
}
} else {
// case 1.
installCommand.recordSilentExecutionAsSystemModification();
modified = true;
}
return modified;
}
public GenericYumCommand install(YumPackageName... packages) {
return newYumCommand("install", packages, INSTALL_NOOP_PATTERN);
}
public GenericYumCommand install(String package1, String... packages) {
return install(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand install(List<String> packages) {
return install(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
public GenericYumCommand upgrade(YumPackageName... packages) {
return newYumCommand("upgrade", packages, UPGRADE_NOOP_PATTERN);
}
public GenericYumCommand upgrade(String package1, String... packages) {
return upgrade(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand upgrade(List<String> packages) {
return upgrade(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
public GenericYumCommand remove(YumPackageName... packages) {
return newYumCommand("remove", packages, REMOVE_NOOP_PATTERN);
}
public GenericYumCommand remove(String package1, String... packages) {
return remove(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand remove(List<String> packages) {
return remove(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
static YumPackageName[] toYumPackageNameArray(String package1, String... packages) {
YumPackageName[] array = new YumPackageName[1 + packages.length];
array[0] = YumPackageName.fromString(package1);
for (int i = 0; i < packages.length; ++i) {
array[1 + i] = YumPackageName.fromString(packages[i]);
}
return array;
}
private GenericYumCommand newYumCommand(String yumCommand, YumPackageName[] packages, Pattern noopPattern) {
return new GenericYumCommand(terminal, yumCommand, List.of(packages), noopPattern);
}
public static class GenericYumCommand {
private final Terminal terminal;
private final String yumCommand;
private final List<YumPackageName> packages;
private final Pattern commandOutputNoopPattern;
private final List<String> enabledRepo = new ArrayList<>();
private GenericYumCommand(Terminal terminal,
String yumCommand,
List<YumPackageName> packages,
Pattern commandOutputNoopPattern) {
this.terminal = terminal;
this.yumCommand = yumCommand;
this.packages = packages;
this.commandOutputNoopPattern = commandOutputNoopPattern;
if (packages.isEmpty() && ! "upgrade".equals(yumCommand)) {
throw new IllegalArgumentException("No packages specified");
}
}
public GenericYumCommand enableRepos(String... repos) {
enabledRepo.addAll(List.of(repos));
return this;
}
public boolean converge(TaskContext context) {
CommandLine commandLine = terminal.newCommandLine(context);
commandLine.add("yum", yumCommand, "--assumeyes");
enabledRepo.forEach(repo -> commandLine.add("--enablerepo=" + repo));
commandLine.add(packages.stream().map(YumPackageName::toName).collect(Collectors.toList()));
// There's no way to figure out whether a yum command would have been a no-op.
// Therefore, run the command and parse the output to decide.
boolean modifiedSystem = commandLine
.executeSilently()
.mapOutput(this::mapOutput);
if (modifiedSystem) {
commandLine.recordSilentExecutionAsSystemModification();
}
return modifiedSystem;
}
private boolean mapOutput(String output) {
Matcher unknownPackageMatcher = UNKNOWN_PACKAGE_PATTERN.matcher(output);
if (unknownPackageMatcher.find()) {
throw new IllegalArgumentException("Unknown package: " + unknownPackageMatcher.group(1));
}
return !commandOutputNoopPattern.matcher(output).find();
}
}
}
| node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/Yum.java | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandLine;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.hosted.node.admin.task.util.process.Terminal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* @author hakonhall
*/
public class Yum {
// Note: "(?dm)" makes newline be \n (only), and enables multiline mode where ^$ match lines with find()
private static final Pattern CHECKING_FOR_UPDATE_PATTERN =
Pattern.compile("(?dm)^Package matching [^ ]+ already installed\\. Checking for update\\.$");
private static final Pattern NOTHING_TO_DO_PATTERN = Pattern.compile("(?dm)^Nothing to do$");
private static final Pattern INSTALL_NOOP_PATTERN = NOTHING_TO_DO_PATTERN;
private static final Pattern UPGRADE_NOOP_PATTERN = Pattern.compile("(?dm)^No packages marked for update$");
private static final Pattern REMOVE_NOOP_PATTERN = Pattern.compile("(?dm)^No Packages marked for removal$");
private static final Pattern UNKNOWN_PACKAGE_PATTERN = Pattern.compile(
"(?dm)^No package ([^ ]+) available\\.$");
// WARNING: These must be in the same order as the supplier below
private static final String RPM_QUERYFORMAT = Stream.of("NAME", "EPOCH", "VERSION", "RELEASE", "ARCH")
.map(formatter -> "%{" + formatter + "}")
.collect(Collectors.joining("\\n"));
private static final Function<YumPackageName.Builder, List<Function<String, YumPackageName.Builder>>>
PACKAGE_NAME_BUILDERS_GENERATOR = builder -> List.of(
builder::setName, builder::setEpoch, builder::setVersion, builder::setRelease, builder::setArchitecture);
private final Terminal terminal;
public Yum(Terminal terminal) {
this.terminal = terminal;
}
public Optional<YumPackageName> queryInstalled(TaskContext context, String packageName) {
CommandResult commandResult = terminal.newCommandLine(context)
.add("rpm", "-q", packageName, "--queryformat", RPM_QUERYFORMAT)
.ignoreExitCode()
.executeSilently();
if (commandResult.getExitCode() != 0) return Optional.empty();
YumPackageName.Builder builder = new YumPackageName.Builder();
List<Function<String, YumPackageName.Builder>> builders = PACKAGE_NAME_BUILDERS_GENERATOR.apply(builder);
List<Optional<String>> lines = commandResult.mapEachLine(line -> Optional.of(line).filter(s -> !"(none)".equals(s)));
if (lines.size() != builders.size()) throw new IllegalStateException(String.format(
"Unexpected response from rpm, expected %d lines, got %s", builders.size(), commandResult.getOutput()));
IntStream.range(0, builders.size()).forEach(i -> lines.get(i).ifPresent(builders.get(i)::apply));
return Optional.of(builder.build());
}
/**
* Lock and install, or if necessary downgrade, a package to a given version.
*
* @return false only if the package was already locked and installed at the given version (no-op)
*/
public boolean installFixedVersion(TaskContext context, YumPackageName yumPackage, String... repos) {
String targetVersionLockName = yumPackage.toVersionLockName();
boolean alreadyLocked = terminal
.newCommandLine(context)
.add("yum", "--quiet", "versionlock", "list")
.executeSilently()
.getOutputLinesStream()
.map(YumPackageName::parseString)
.filter(Optional::isPresent) // removes garbage first lines, even with --quiet
.map(Optional::get)
.anyMatch(packageName -> {
// Ignore lines for other packages
if (packageName.getName().equals(yumPackage.getName())) {
// If existing lock doesn't exactly match the full package name,
// it means it's locked to another version and we must remove that lock.
String versionLockName = packageName.toVersionLockName();
if (versionLockName.equals(targetVersionLockName)) {
return true;
} else {
terminal.newCommandLine(context)
.add("yum", "versionlock", "delete", versionLockName)
.execute();
}
}
return false;
});
boolean modified = false;
if (!alreadyLocked) {
CommandLine commandLine = terminal.newCommandLine(context).add("yum", "versionlock", "add");
// If the targetVersionLockName refers to a package in a by-default-disabled repo,
// we must enable the repo unless targetVersionLockName is already installed.
for (String repo : repos) commandLine.add("--enablerepo=" + repo);
commandLine.add(targetVersionLockName).execute();
modified = true;
}
// The following 3 things may happen with yum install:
// 1. The package is installed or upgraded to the target version, in case we'd return
// true from converge()
// 2. The package is already installed at target version, in case
// "Nothing to do" is printed in the last line and we may return false from converge()
// 3. The package is already installed but at a later version than the target version,
// in case the last 2 lines of the output is:
// - "Package matching yakl-client-0.10-654.el7.x86_64 already installed. Checking for update."
// - "Nothing to do"
// And in case we need to downgrade and return true from converge()
var installCommand = terminal.newCommandLine(context).add("yum", "install");
for (String repo : repos) installCommand.add("--enablerepo=" + repo);
installCommand.add("--assumeyes", yumPackage.toName());
String output = installCommand.executeSilently().getUntrimmedOutput();
if (NOTHING_TO_DO_PATTERN.matcher(output).find()) {
if (CHECKING_FOR_UPDATE_PATTERN.matcher(output).find()) {
// case 3.
var upgradeCommand = terminal.newCommandLine(context).add("yum", "downgrade", "--assumeyes");
for (String repo : repos) upgradeCommand.add("--enablerepo=" + repo);
upgradeCommand.add(yumPackage.toName()).execute();
modified = true;
} else {
// case 2.
}
} else {
// case 1.
installCommand.recordSilentExecutionAsSystemModification();
modified = true;
}
return modified;
}
public GenericYumCommand install(YumPackageName... packages) {
return newYumCommand("install", packages, INSTALL_NOOP_PATTERN);
}
public GenericYumCommand install(String package1, String... packages) {
return install(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand install(List<String> packages) {
return install(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
public GenericYumCommand upgrade(YumPackageName... packages) {
return newYumCommand("upgrade", packages, UPGRADE_NOOP_PATTERN);
}
public GenericYumCommand upgrade(String package1, String... packages) {
return upgrade(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand upgrade(List<String> packages) {
return upgrade(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
public GenericYumCommand remove(YumPackageName... packages) {
return newYumCommand("remove", packages, REMOVE_NOOP_PATTERN);
}
public GenericYumCommand remove(String package1, String... packages) {
return remove(toYumPackageNameArray(package1, packages));
}
public GenericYumCommand remove(List<String> packages) {
return remove(packages.stream().map(YumPackageName::fromString).toArray(YumPackageName[]::new));
}
static YumPackageName[] toYumPackageNameArray(String package1, String... packages) {
YumPackageName[] array = new YumPackageName[1 + packages.length];
array[0] = YumPackageName.fromString(package1);
for (int i = 0; i < packages.length; ++i) {
array[1 + i] = YumPackageName.fromString(packages[i]);
}
return array;
}
private GenericYumCommand newYumCommand(String yumCommand, YumPackageName[] packages, Pattern noopPattern) {
return new GenericYumCommand(terminal, yumCommand, List.of(packages), noopPattern);
}
public static class GenericYumCommand {
private final Terminal terminal;
private final String yumCommand;
private final List<YumPackageName> packages;
private final Pattern commandOutputNoopPattern;
private final List<String> enabledRepo = new ArrayList<>();
private GenericYumCommand(Terminal terminal,
String yumCommand,
List<YumPackageName> packages,
Pattern commandOutputNoopPattern) {
this.terminal = terminal;
this.yumCommand = yumCommand;
this.packages = packages;
this.commandOutputNoopPattern = commandOutputNoopPattern;
if (packages.isEmpty() && ! "upgrade".equals(yumCommand)) {
throw new IllegalArgumentException("No packages specified");
}
}
public GenericYumCommand enableRepos(String... repos) {
enabledRepo.addAll(List.of(repos));
return this;
}
public boolean converge(TaskContext context) {
CommandLine commandLine = terminal.newCommandLine(context);
commandLine.add("yum", yumCommand, "--assumeyes");
enabledRepo.forEach(repo -> commandLine.add("--enablerepo=" + repo));
commandLine.add(packages.stream().map(YumPackageName::toName).collect(Collectors.toList()));
// There's no way to figure out whether a yum command would have been a no-op.
// Therefore, run the command and parse the output to decide.
boolean modifiedSystem = commandLine
.executeSilently()
.mapOutput(this::mapOutput);
if (modifiedSystem) {
commandLine.recordSilentExecutionAsSystemModification();
}
return modifiedSystem;
}
private boolean mapOutput(String output) {
Matcher unknownPackageMatcher = UNKNOWN_PACKAGE_PATTERN.matcher(output);
if (unknownPackageMatcher.find()) {
throw new IllegalArgumentException("Unknown package: " + unknownPackageMatcher.group(1));
}
return !commandOutputNoopPattern.matcher(output).find();
}
}
}
| Document other versionlock commands
| node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/Yum.java | Document other versionlock commands | <ide><path>ode-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/Yum.java
<ide> CommandLine commandLine = terminal.newCommandLine(context).add("yum", "versionlock", "add");
<ide> // If the targetVersionLockName refers to a package in a by-default-disabled repo,
<ide> // we must enable the repo unless targetVersionLockName is already installed.
<add> // The other versionlock commands (list, delete) does not require --enablerepo.
<ide> for (String repo : repos) commandLine.add("--enablerepo=" + repo);
<ide> commandLine.add(targetVersionLockName).execute();
<ide> modified = true; |
|
Java | apache-2.0 | c080cfc6324958544b0c7b7bb14c9ef7060b82f9 | 0 | jeffpc/voldemort,stotch/voldemort,LeoYao/voldemort,gnb/voldemort,cshaxu/voldemort,birendraa/voldemort,PratikDeshpande/voldemort,stotch/voldemort,gnb/voldemort,null-exception/voldemort,birendraa/voldemort,mabh/voldemort,arunthirupathi/voldemort,voldemort/voldemort,bhasudha/voldemort,squarY/voldemort,FelixGV/voldemort,arunthirupathi/voldemort,bitti/voldemort,arunthirupathi/voldemort,voldemort/voldemort,stotch/voldemort,jwlent55/voldemort,bitti/voldemort,FelixGV/voldemort,squarY/voldemort,stotch/voldemort,LeoYao/voldemort,rickbw/voldemort,HB-SI/voldemort,bhasudha/voldemort,birendraa/voldemort,bhasudha/voldemort,mabh/voldemort,FelixGV/voldemort,jeffpc/voldemort,dallasmarlow/voldemort,gnb/voldemort,dallasmarlow/voldemort,PratikDeshpande/voldemort,bitti/voldemort,PratikDeshpande/voldemort,voldemort/voldemort,dallasmarlow/voldemort,PratikDeshpande/voldemort,jeffpc/voldemort,LeoYao/voldemort,squarY/voldemort,jalkjaer/voldemort,voldemort/voldemort,null-exception/voldemort,bhasudha/voldemort,dallasmarlow/voldemort,bitti/voldemort,FelixGV/voldemort,mabh/voldemort,dallasmarlow/voldemort,jwlent55/voldemort,jwlent55/voldemort,null-exception/voldemort,LeoYao/voldemort,null-exception/voldemort,squarY/voldemort,stotch/voldemort,HB-SI/voldemort,stotch/voldemort,arunthirupathi/voldemort,squarY/voldemort,FelixGV/voldemort,LeoYao/voldemort,voldemort/voldemort,voldemort/voldemort,rickbw/voldemort,jwlent55/voldemort,arunthirupathi/voldemort,cshaxu/voldemort,FelixGV/voldemort,voldemort/voldemort,jwlent55/voldemort,dallasmarlow/voldemort,jwlent55/voldemort,HB-SI/voldemort,birendraa/voldemort,arunthirupathi/voldemort,cshaxu/voldemort,rickbw/voldemort,rickbw/voldemort,null-exception/voldemort,PratikDeshpande/voldemort,rickbw/voldemort,mabh/voldemort,cshaxu/voldemort,bhasudha/voldemort,squarY/voldemort,PratikDeshpande/voldemort,bhasudha/voldemort,jalkjaer/voldemort,arunthirupathi/voldemort,jalkjaer/voldemort,jeffpc/voldemort,squarY/voldemort,LeoYao/voldemort,birendraa/voldemort,jalkjaer/voldemort,bitti/voldemort,mabh/voldemort,cshaxu/voldemort,FelixGV/voldemort,gnb/voldemort,rickbw/voldemort,bitti/voldemort,jalkjaer/voldemort,jeffpc/voldemort,cshaxu/voldemort,HB-SI/voldemort,gnb/voldemort,HB-SI/voldemort,gnb/voldemort,mabh/voldemort,HB-SI/voldemort,jeffpc/voldemort,jalkjaer/voldemort,null-exception/voldemort,jalkjaer/voldemort,birendraa/voldemort,bitti/voldemort | /*
* Copyright 2012 LinkedIn, 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 voldemort.store.stats;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* Some convenient statistics to track about the store
*
*
*/
public class StoreStats {
private final Map<Tracked, RequestCounter> counters;
private static final Logger logger = Logger.getLogger(StoreStats.class.getName());
private String storeName;
// RequestCounter config
private static final boolean useHistogram = true;
private static final long timeWindow = 60000;
public StoreStats(String storeName) {
this(storeName, null);
}
/**
* @param parent An optional parent stats object that will maintain
* aggregate data across many stores
*/
public StoreStats(String storeName, StoreStats parent) {
if (storeName == null) {
throw new IllegalArgumentException("StoreStats.storeName cannot be null !!");
}
this.storeName = storeName;
counters = new EnumMap<Tracked, RequestCounter>(Tracked.class);
for(Tracked tracked: Tracked.values()) {
String requestCounterName = "store-stats" + "." + storeName + "." + tracked.toString();
RequestCounter requestCounter;
if (parent == null) {
requestCounter = new RequestCounter(requestCounterName, timeWindow, useHistogram);
} else {
requestCounterName = parent.storeName + "." + requestCounterName;
requestCounter =
new RequestCounter(requestCounterName, timeWindow, useHistogram, parent.counters.get(tracked));
}
counters.put(tracked, requestCounter);
}
if(logger.isDebugEnabled()) {
logger.debug("Constructed StoreStats object (" + System.identityHashCode(this)
+ ") with parent object (" + System.identityHashCode(parent) + ")");
}
}
/**
* Record the duration of specified op. For PUT, GET and GET_ALL use
* specific methods for those ops.
*/
public void recordTime(Tracked op, long timeNS) {
recordTime(op, timeNS, 0, 0, 0, 0);
}
/**
* Record the duration of specified op. For PUT, GET and GET_ALL use
* specific methods for those ops.
*/
public void recordDeleteTime(long timeNS, long keySize) {
recordTime(Tracked.DELETE, timeNS, 0, 0, keySize, 0);
}
/**
* Record the duration of a put operation, along with the size of the values
* returned.
*/
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {
recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);
}
/**
* Record the duration of a get operation, along with whether or not an
* empty response (ie no values matched) and the size of the values
* returned.
*/
public void recordGetTime(long timeNS, boolean emptyResponse, long totalBytes, long keyBytes) {
recordTime(Tracked.GET, timeNS, emptyResponse ? 1 : 0, totalBytes, keyBytes, 0);
}
/**
* Record the duration of a get versions operation, along with whether or
* not an empty response (ie no values matched) was returned.
*/
public void recordGetVersionsTime(long timeNS, boolean emptyResponse) {
recordTime(Tracked.GET_VERSIONS, timeNS, emptyResponse ? 1 : 0, 0, 0, 0);
}
/**
* Record the duration of a get_all operation, along with how many values
* were requested, how may were actually returned and the size of the values
* returned.
*/
public void recordGetAllTime(long timeNS,
int requested,
int returned,
long totalValueBytes,
long totalKeyBytes) {
recordTime(Tracked.GET_ALL,
timeNS,
requested - returned,
totalValueBytes,
totalKeyBytes,
requested);
}
/**
* Method to service public recording APIs
*
* @param op Operation being tracked
* @param timeNS Duration of operation
* @param numEmptyResponses GET and GET_ALL: number of empty responses being
* sent back, ie requested keys for which there were no values
* @param size Total size of response payload, ie sum of lengths of bytes in
* all versions of values
* @param getAllAggregateRequests Total of key-values requested in
* aggregatee from get_all operations
*/
private void recordTime(Tracked op,
long timeNS,
long numEmptyResponses,
long valueSize,
long keySize,
long getAllAggregateRequests) {
counters.get(op).addRequest(timeNS,
numEmptyResponses,
valueSize,
keySize,
getAllAggregateRequests);
if (logger.isTraceEnabled() && !storeName.contains("aggregate") && !storeName.contains("voldsys$"))
logger.trace("Store '" + storeName + "' logged a " + op.toString() + " request taking " +
((double) timeNS / voldemort.utils.Time.NS_PER_MS) + " ms");
}
public long getCount(Tracked op) {
return counters.get(op).getCount();
}
public float getThroughput(Tracked op) {
return counters.get(op).getThroughput();
}
public float getThroughputInBytes(Tracked op) {
return counters.get(op).getThroughputInBytes();
}
public double getAvgTimeInMs(Tracked op) {
return counters.get(op).getAverageTimeInMs();
}
public long getNumEmptyResponses(Tracked op) {
return counters.get(op).getNumEmptyResponses();
}
public long getMaxLatencyInMs(Tracked op) {
return counters.get(op).getMaxLatencyInMs();
}
public double getQ95LatencyInMs(Tracked op) {
return counters.get(op).getQ95LatencyMs();
}
public double getQ99LatencyInMs(Tracked op) {
return counters.get(op).getQ99LatencyMs();
}
public Map<Tracked, RequestCounter> getCounters() {
return Collections.unmodifiableMap(counters);
}
public long getMaxValueSizeInBytes(Tracked op) {
return counters.get(op).getMaxValueSizeInBytes();
}
public long getMaxKeySizeInBytes(Tracked op) {
return counters.get(op).getMaxKeySizeInBytes();
}
public double getAvgValueSizeinBytes(Tracked op) {
return counters.get(op).getAverageValueSizeInBytes();
}
public double getAvgKeySizeinBytes(Tracked op) {
return counters.get(op).getAverageKeySizeInBytes();
}
public double getGetAllAverageCount() {
long total = getGetAllAggregatedCount();
return total == 0 ? 0.0d : total / counters.get(Tracked.GET_ALL).getCount();
}
public long getGetAllAggregatedCount() {
return counters.get(Tracked.GET_ALL).getGetAllAggregatedCount();
}
public long getGetAllMaxCount() {
return counters.get(Tracked.GET_ALL).getGetAllMaxCount();
}
}
| src/java/voldemort/store/stats/StoreStats.java | /*
* Copyright 2012 LinkedIn, 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 voldemort.store.stats;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* Some convenient statistics to track about the store
*
*
*/
public class StoreStats {
private final StoreStats parent;
private final Map<Tracked, RequestCounter> counters;
private static final Logger logger = Logger.getLogger(StoreStats.class.getName());
private String storeName;
// RequestCounter config
private static final boolean useHistogram = true;
private static final long timeWindow = 60000;
public StoreStats(String storeName) {
this(storeName, null);
}
/**
* @param parent An optional parent stats object that will maintain
* aggregate data across many stores
*/
public StoreStats(String storeName, StoreStats parent) {
if (storeName == null) {
throw new IllegalArgumentException("StoreStats.storeName cannot be null !!");
}
this.storeName = storeName;
counters = new EnumMap<Tracked, RequestCounter>(Tracked.class);
for(Tracked tracked: Tracked.values()) {
String requestCounterName = "store-stats" + "." + storeName + "." + tracked.toString();
RequestCounter requestCounter;
if (parent == null) {
requestCounter = new RequestCounter(requestCounterName, timeWindow, useHistogram);
} else {
requestCounterName = parent.storeName + "." + requestCounterName;
requestCounter =
new RequestCounter(requestCounterName, timeWindow, useHistogram, parent.counters.get(tracked));
}
counters.put(tracked, requestCounter);
}
this.parent = parent;
if(logger.isDebugEnabled()) {
logger.debug("Constructed StoreStats object (" + System.identityHashCode(this)
+ ") with parent object (" + System.identityHashCode(parent) + ")");
}
}
/**
* Record the duration of specified op. For PUT, GET and GET_ALL use
* specific methods for those ops.
*/
public void recordTime(Tracked op, long timeNS) {
recordTime(op, timeNS, 0, 0, 0, 0);
}
/**
* Record the duration of specified op. For PUT, GET and GET_ALL use
* specific methods for those ops.
*/
public void recordDeleteTime(long timeNS, long keySize) {
recordTime(Tracked.DELETE, timeNS, 0, 0, keySize, 0);
}
/**
* Record the duration of a put operation, along with the size of the values
* returned.
*/
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {
recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);
}
/**
* Record the duration of a get operation, along with whether or not an
* empty response (ie no values matched) and the size of the values
* returned.
*/
public void recordGetTime(long timeNS, boolean emptyResponse, long totalBytes, long keyBytes) {
recordTime(Tracked.GET, timeNS, emptyResponse ? 1 : 0, totalBytes, keyBytes, 0);
}
/**
* Record the duration of a get versions operation, along with whether or
* not an empty response (ie no values matched) was returned.
*/
public void recordGetVersionsTime(long timeNS, boolean emptyResponse) {
recordTime(Tracked.GET_VERSIONS, timeNS, emptyResponse ? 1 : 0, 0, 0, 0);
}
/**
* Record the duration of a get_all operation, along with how many values
* were requested, how may were actually returned and the size of the values
* returned.
*/
public void recordGetAllTime(long timeNS,
int requested,
int returned,
long totalValueBytes,
long totalKeyBytes) {
recordTime(Tracked.GET_ALL,
timeNS,
requested - returned,
totalValueBytes,
totalKeyBytes,
requested);
}
/**
* Method to service public recording APIs
*
* @param op Operation being tracked
* @param timeNS Duration of operation
* @param numEmptyResponses GET and GET_ALL: number of empty responses being
* sent back, ie requested keys for which there were no values
* @param size Total size of response payload, ie sum of lengths of bytes in
* all versions of values
* @param getAllAggregateRequests Total of key-values requested in
* aggregatee from get_all operations
*/
private void recordTime(Tracked op,
long timeNS,
long numEmptyResponses,
long valueSize,
long keySize,
long getAllAggregateRequests) {
counters.get(op).addRequest(timeNS,
numEmptyResponses,
valueSize,
keySize,
getAllAggregateRequests);
if(parent != null)
parent.recordTime(op,
timeNS,
numEmptyResponses,
valueSize,
keySize,
getAllAggregateRequests);
if (logger.isTraceEnabled() && !storeName.contains("aggregate") && !storeName.contains("voldsys$"))
logger.trace("Store '" + storeName + "' logged a " + op.toString() + " request taking " +
((double) timeNS / voldemort.utils.Time.NS_PER_MS) + " ms");
}
public long getCount(Tracked op) {
return counters.get(op).getCount();
}
public float getThroughput(Tracked op) {
return counters.get(op).getThroughput();
}
public float getThroughputInBytes(Tracked op) {
return counters.get(op).getThroughputInBytes();
}
public double getAvgTimeInMs(Tracked op) {
return counters.get(op).getAverageTimeInMs();
}
public long getNumEmptyResponses(Tracked op) {
return counters.get(op).getNumEmptyResponses();
}
public long getMaxLatencyInMs(Tracked op) {
return counters.get(op).getMaxLatencyInMs();
}
public double getQ95LatencyInMs(Tracked op) {
return counters.get(op).getQ95LatencyMs();
}
public double getQ99LatencyInMs(Tracked op) {
return counters.get(op).getQ99LatencyMs();
}
public Map<Tracked, RequestCounter> getCounters() {
return Collections.unmodifiableMap(counters);
}
public long getMaxValueSizeInBytes(Tracked op) {
return counters.get(op).getMaxValueSizeInBytes();
}
public long getMaxKeySizeInBytes(Tracked op) {
return counters.get(op).getMaxKeySizeInBytes();
}
public double getAvgValueSizeinBytes(Tracked op) {
return counters.get(op).getAverageValueSizeInBytes();
}
public double getAvgKeySizeinBytes(Tracked op) {
return counters.get(op).getAverageKeySizeInBytes();
}
public double getGetAllAverageCount() {
long total = getGetAllAggregatedCount();
return total == 0 ? 0.0d : total / counters.get(Tracked.GET_ALL).getCount();
}
public long getGetAllAggregatedCount() {
return counters.get(Tracked.GET_ALL).getGetAllAggregatedCount();
}
public long getGetAllMaxCount() {
return counters.get(Tracked.GET_ALL).getGetAllMaxCount();
}
}
| Removed old parent delegating code in StoreStats which would cause double counting.
Conflicts:
src/java/voldemort/store/stats/StoreStats.java
| src/java/voldemort/store/stats/StoreStats.java | Removed old parent delegating code in StoreStats which would cause double counting. | <ide><path>rc/java/voldemort/store/stats/StoreStats.java
<ide> */
<ide> public class StoreStats {
<ide>
<del> private final StoreStats parent;
<ide> private final Map<Tracked, RequestCounter> counters;
<ide>
<ide> private static final Logger logger = Logger.getLogger(StoreStats.class.getName());
<ide>
<ide> counters.put(tracked, requestCounter);
<ide> }
<del> this.parent = parent;
<ide>
<ide> if(logger.isDebugEnabled()) {
<ide> logger.debug("Constructed StoreStats object (" + System.identityHashCode(this)
<ide> valueSize,
<ide> keySize,
<ide> getAllAggregateRequests);
<del> if(parent != null)
<del> parent.recordTime(op,
<del> timeNS,
<del> numEmptyResponses,
<del> valueSize,
<del> keySize,
<del> getAllAggregateRequests);
<ide>
<ide> if (logger.isTraceEnabled() && !storeName.contains("aggregate") && !storeName.contains("voldsys$"))
<ide> logger.trace("Store '" + storeName + "' logged a " + op.toString() + " request taking " + |
|
Java | agpl-3.0 | 62071d1d41aa79331c977812842e46c5fb6282ad | 0 | lampeh/FooPing,lampeh/FooPing,lampeh/FooPing | package org.openchaos.android.fooping.service;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.preference.PreferenceManager;
import android.util.Log;
public class PingService extends IntentService {
private static final String tag = "PingService";
private SharedPreferences prefs;
private LocationManager lm;
private WifiManager wm;
private SensorManager sm;
private static final double roundValue(double value, int scale) {
return BigDecimal.valueOf(value).setScale(scale, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().doubleValue();
}
public PingService() {
super(tag);
}
@Override
public void onCreate() {
Log.d(tag, "onCreate()");
super.onCreate();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onHandleIntent(Intent intent) {
String clientID = prefs.getString("ClientID", "unknown");
long ts = System.currentTimeMillis();
// always send ping
if (true) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "ping");
json.put("ts", ts);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseBattery", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "battery");
json.put("ts", ts);
JSONObject bat_data = new JSONObject();
Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (batteryStatus != null) {
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level >= 0 && scale > 0) {
bat_data.put("pct", roundValue(((double)level / (double)scale)*100, 2));
} else {
Log.w(tag, "Battery level unknown");
bat_data.put("pct", -1);
}
bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
// bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));
}
json.put("battery", bat_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseGPS", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "loc_gps");
json.put("ts", ts);
if (lm == null) {
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
JSONObject loc_data = new JSONObject();
Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (last_loc != null) {
loc_data.put("ts", last_loc.getTime());
loc_data.put("lat", last_loc.getLatitude());
loc_data.put("lon", last_loc.getLongitude());
if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));
}
json.put("loc_gps", loc_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseNetwork", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "loc_net");
json.put("ts", ts);
if (lm == null) {
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
JSONObject loc_data = new JSONObject();
Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (last_loc != null) {
loc_data.put("ts", last_loc.getTime());
loc_data.put("lat", last_loc.getLatitude());
loc_data.put("lon", last_loc.getLongitude());
if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));
}
json.put("loc_net", loc_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseWIFI", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "wifi");
json.put("ts", ts);
if (wm == null) {
wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
}
JSONArray wifi_list = new JSONArray();
List<ScanResult> wifiScan = wm.getScanResults();
if (wifiScan != null) {
for (ScanResult wifi : wifiScan) {
JSONObject wifi_data = new JSONObject();
wifi_data.put("BSSID", wifi.BSSID);
wifi_data.put("SSID", wifi.SSID);
wifi_data.put("freq", wifi.frequency);
wifi_data.put("level", wifi.level);
// wifi_data.put("cap", wifi.capabilities);
// wifi_data.put("ts", wifi.timestamp);
wifi_list.put(wifi_data);
}
}
json.put("wifi", wifi_list);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
// TODO: cannot poll sensors. register receiver to cache sensor data
if (prefs.getBoolean("UseSensors", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "sensors");
json.put("ts", ts);
if (sm == null) {
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
}
JSONArray sensor_list = new JSONArray();
List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
if (sensors != null) {
for (Sensor sensor : sensors) {
JSONObject sensor_info = new JSONObject();
sensor_info.put("name", sensor.getName());
sensor_info.put("type", sensor.getType());
sensor_info.put("vendor", sensor.getVendor());
sensor_info.put("version", sensor.getVersion());
sensor_info.put("power", roundValue(sensor.getPower(), 4));
sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));
sensor_list.put(sensor_info);
}
}
json.put("sensors", sensor_list);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
}
private class _sendUDP extends AsyncTask <byte[], Void, Void> {
private SecretKeySpec skeySpec;
private Cipher cipher;
@Override
protected Void doInBackground(final byte[]... msgBuf) {
boolean encrypt = prefs.getBoolean("SendAES", false);
boolean compress = prefs.getBoolean("SendGZIP", false);
String exchangeHost = prefs.getString("ExchangeHost", null);
int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));
if (encrypt) {
try {
// TODO: SHA256(ExchangeKey)
skeySpec = new SecretKeySpec(prefs.getString("ExchangeKey", null).getBytes("US-ASCII"), "AES");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
try {
cipher = Cipher.getInstance("AES/CFB8/NoPadding");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
assert !encrypt || (skeySpec != null && cipher != null);
assert exchangeHost != null && exchangePort > 0 && exchangePort < 65536;
final int count = msgBuf.length;
for (int i = 0; i < count; i++) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = null;
GZIPOutputStream zos = null;
// TODO: send protocol header to signal compression & encryption
if (encrypt) {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
final byte[] iv = cipher.getIV();
// iv.length == cipher block size
// first byte in stream: (iv.length/16)-1
// TODO: pointless. AES uses fixed 128bit blocks
assert iv.length <= 4096 && (iv.length & 0x0f) == 0;
baos.write((iv.length >> 4)-1);
// write iv block
baos.write(iv);
cos = new CipherOutputStream(baos, cipher);
}
if (compress) {
zos = new GZIPOutputStream((encrypt)?(cos):(baos));
zos.write(msgBuf[i]);
zos.finish();
zos.close();
if (encrypt) {
cos.close();
}
} else if (encrypt) {
cos.write(msgBuf[i]);
cos.close();
} else {
baos.write(msgBuf[i]);
}
baos.flush();
final byte[] message = baos.toByteArray();
baos.close();
// path MTU is the actual limit here, not only local MTU
// TODO: make packet fragmentable (clear DF flag)
if (message.length > 1500) {
Log.w(tag, "Message probably too long: " + message.length + " bytes");
}
DatagramPacket packet = new DatagramPacket(message, message.length, InetAddress.getByName(exchangeHost), exchangePort);
DatagramSocket socket = new DatagramSocket();
// socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
socket.send(packet);
socket.close();
Log.d(tag, "message sent: " + message.length + " bytes (raw: " + msgBuf[i].length + " bytes)");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
return null;
}
}
}
| src/org/openchaos/android/fooping/service/PingService.java | package org.openchaos.android.fooping.service;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.preference.PreferenceManager;
import android.util.Log;
public class PingService extends IntentService {
private static final String tag = "PingService";
private SharedPreferences prefs;
private LocationManager lm;
private WifiManager wm;
private SensorManager sm;
private static final double roundValue(double value, int scale) {
return BigDecimal.valueOf(value).setScale(scale, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().doubleValue();
}
public PingService() {
super(tag);
}
@Override
public void onCreate() {
Log.d(tag, "onCreate()");
super.onCreate();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onHandleIntent(Intent intent) {
String clientID = prefs.getString("ClientID", "unknown");
long ts = System.currentTimeMillis();
// always send ping
if (true) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "ping");
json.put("ts", ts);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseBattery", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "battery");
json.put("ts", ts);
JSONObject bat_data = new JSONObject();
Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (batteryStatus != null) {
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level > 0 && scale > 0) {
bat_data.put("pct", roundValue(((double)level / (double)scale)*100, 2));
} else {
Log.w(tag, "Battery level unknown");
bat_data.put("pct", -1);
}
bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
// bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));
}
json.put("battery", bat_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseGPS", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "loc_gps");
json.put("ts", ts);
if (lm == null) {
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
JSONObject loc_data = new JSONObject();
Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (last_loc != null) {
loc_data.put("ts", last_loc.getTime());
loc_data.put("lat", last_loc.getLatitude());
loc_data.put("lon", last_loc.getLongitude());
if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));
}
json.put("loc_gps", loc_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseNetwork", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "loc_net");
json.put("ts", ts);
if (lm == null) {
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
JSONObject loc_data = new JSONObject();
Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (last_loc != null) {
loc_data.put("ts", last_loc.getTime());
loc_data.put("lat", last_loc.getLatitude());
loc_data.put("lon", last_loc.getLongitude());
if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));
}
json.put("loc_net", loc_data);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
if (prefs.getBoolean("UseWIFI", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "wifi");
json.put("ts", ts);
if (wm == null) {
wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
}
JSONArray wifi_list = new JSONArray();
List<ScanResult> wifiScan = wm.getScanResults();
if (wifiScan != null) {
for (ScanResult wifi : wifiScan) {
JSONObject wifi_data = new JSONObject();
wifi_data.put("BSSID", wifi.BSSID);
wifi_data.put("SSID", wifi.SSID);
wifi_data.put("freq", wifi.frequency);
wifi_data.put("level", wifi.level);
// wifi_data.put("cap", wifi.capabilities);
// wifi_data.put("ts", wifi.timestamp);
wifi_list.put(wifi_data);
}
}
json.put("wifi", wifi_list);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
// TODO: cannot poll sensors. register receiver to cache sensor data
if (prefs.getBoolean("UseSensors", false)) {
try {
JSONObject json = new JSONObject();
json.put("client", clientID);
json.put("type", "sensors");
json.put("ts", ts);
if (sm == null) {
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
}
JSONArray sensor_list = new JSONArray();
List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
if (sensors != null) {
for (Sensor sensor : sensors) {
JSONObject sensor_info = new JSONObject();
sensor_info.put("name", sensor.getName());
sensor_info.put("type", sensor.getType());
sensor_info.put("vendor", sensor.getVendor());
sensor_info.put("version", sensor.getVersion());
sensor_info.put("power", roundValue(sensor.getPower(), 4));
sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));
sensor_list.put(sensor_info);
}
}
json.put("sensors", sensor_list);
new _sendUDP().execute(new JSONArray().put(json).toString().getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
}
private class _sendUDP extends AsyncTask <byte[], Void, Void> {
private SecretKeySpec skeySpec;
private Cipher cipher;
@Override
protected Void doInBackground(final byte[]... msgBuf) {
boolean encrypt = prefs.getBoolean("SendAES", false);
boolean compress = prefs.getBoolean("SendGZIP", false);
String exchangeHost = prefs.getString("ExchangeHost", null);
int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));
if (encrypt) {
try {
// TODO: SHA256(ExchangeKey)
skeySpec = new SecretKeySpec(prefs.getString("ExchangeKey", null).getBytes("US-ASCII"), "AES");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
try {
cipher = Cipher.getInstance("AES/CFB8/NoPadding");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
assert !encrypt || (skeySpec != null && cipher != null);
assert exchangeHost != null && exchangePort > 0 && exchangePort < 65536;
final int count = msgBuf.length;
for (int i = 0; i < count; i++) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = null;
GZIPOutputStream zos = null;
// TODO: send protocol header to signal compression & encryption
if (encrypt) {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
final byte[] iv = cipher.getIV();
// iv.length == cipher block size
// first byte in stream: (iv.length/16)-1
// TODO: pointless. AES uses fixed 128bit blocks
assert iv.length <= 4096 && (iv.length & 0x0f) == 0;
baos.write((iv.length >> 4)-1);
// write iv block
baos.write(iv);
cos = new CipherOutputStream(baos, cipher);
}
if (compress) {
zos = new GZIPOutputStream((encrypt)?(cos):(baos));
zos.write(msgBuf[i]);
zos.finish();
zos.close();
if (encrypt) {
cos.close();
}
} else if (encrypt) {
cos.write(msgBuf[i]);
cos.close();
} else {
baos.write(msgBuf[i]);
}
baos.flush();
final byte[] message = baos.toByteArray();
baos.close();
// path MTU is the actual limit here, not only local MTU
// TODO: make packet fragmentable (clear DF flag) or handle ICMP errors and re-send packet
if (message.length > 1500) {
Log.w(tag, "Message probably too long: " + message.length + " bytes");
}
DatagramPacket packet = new DatagramPacket(message, message.length, InetAddress.getByName(exchangeHost), exchangePort);
DatagramSocket socket = new DatagramSocket();
// socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
socket.send(packet);
socket.close();
Log.d(tag, "message sent: " + message.length + " bytes (raw: " + msgBuf[i].length + " bytes)");
} catch (Exception e) {
Log.e(tag, e.toString());
e.printStackTrace();
}
}
return null;
}
}
}
| don't reject battery level == 0
| src/org/openchaos/android/fooping/service/PingService.java | don't reject battery level == 0 | <ide><path>rc/org/openchaos/android/fooping/service/PingService.java
<ide> if (batteryStatus != null) {
<ide> int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
<ide> int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
<del> if (level > 0 && scale > 0) {
<add> if (level >= 0 && scale > 0) {
<ide> bat_data.put("pct", roundValue(((double)level / (double)scale)*100, 2));
<ide> } else {
<ide> Log.w(tag, "Battery level unknown");
<ide> baos.close();
<ide>
<ide> // path MTU is the actual limit here, not only local MTU
<del> // TODO: make packet fragmentable (clear DF flag) or handle ICMP errors and re-send packet
<add> // TODO: make packet fragmentable (clear DF flag)
<ide> if (message.length > 1500) {
<ide> Log.w(tag, "Message probably too long: " + message.length + " bytes");
<ide> } |
|
JavaScript | mit | e0a6bfd085ab83fb80f10d21b354c893276da891 | 0 | ConsenSys/truffle | var Web3 = require("web3");
var ethers = require("ethers");
var abi = require("web3-eth-abi");
var reformat = require("./reformat");
var web3 = new Web3();
var Utils = {
is_object: function(val) {
return typeof val == "object" && !Array.isArray(val);
},
is_big_number: function(val) {
if (typeof val != "object") return false;
return web3.utils.isBN(val) || web3.utils.isBigNumber(val);
},
is_tx_params: function(val) {
if (!Utils.is_object(val)) return false;
if (Utils.is_big_number(val)) return false;
const allowed_fields = {
from: true,
to: true,
gas: true,
gasPrice: true,
value: true,
data: true,
nonce: true
};
for (field_name of Object.keys(val)) {
if (allowed_fields[field_name]) return true;
}
return false;
},
decodeLogs: function(_logs, isSingle) {
var constructor = this;
var logs = Utils.toTruffleLog(_logs, isSingle);
return logs
.map(function(log) {
var logABI = constructor.events[log.topics[0]];
if (logABI == null) {
return null;
}
var copy = Utils.merge({}, log);
copy.event = logABI.name;
copy.topics = logABI.anonymous ? copy.topics : copy.topics.slice(1);
const logArgs = abi.decodeLog(logABI.inputs, copy.data, copy.topics);
copy.args = reformat.numbers.call(constructor, logArgs, logABI.inputs);
delete copy.data;
delete copy.topics;
return copy;
})
.filter(function(log) {
return log != null;
});
},
toTruffleLog: function(events, isSingle) {
// Transform singletons (from event listeners) to the kind of
// object we find on the receipt
if (isSingle && typeof isSingle === "boolean") {
var temp = [];
temp.push(events);
return temp.map(function(log) {
log.data = log.raw.data;
log.topics = log.raw.topics;
return log;
});
}
// Or reformat items in the existing array
events.forEach(event => {
if (event.raw) {
event.data = event.raw.data;
event.topics = event.raw.topics;
}
});
return events;
},
merge: function() {
var merged = {};
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
var object = args[i];
var keys = Object.keys(object);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = object[key];
merged[key] = value;
}
}
return merged;
},
parallel: function(arr, callback) {
callback = callback || function() {};
if (!arr.length) {
return callback(null, []);
}
var index = 0;
var results = new Array(arr.length);
arr.forEach(function(fn, position) {
fn(function(err, result) {
if (err) {
callback(err);
callback = function() {};
} else {
index++;
results[position] = result;
if (index >= arr.length) {
callback(null, results);
}
}
});
});
},
linkBytecode: function(bytecode, links) {
Object.keys(links).forEach(function(library_name) {
var library_address = links[library_name];
var regex = new RegExp("__" + library_name + "_+", "g");
bytecode = bytecode.replace(regex, library_address.replace("0x", ""));
});
return bytecode;
},
// Extracts optional tx params from a list of fn arguments
getTxParams: function(methodABI, args) {
var constructor = this;
var expected_arg_count = methodABI ? methodABI.inputs.length : 0;
tx_params = {};
var last_arg = args[args.length - 1];
if (
args.length === expected_arg_count + 1 &&
Utils.is_tx_params(last_arg)
) {
tx_params = args.pop();
}
return Utils.merge(constructor.class_defaults, tx_params);
},
// Verifies that a contracts libraries have been linked correctly.
// Throws on error
checkLibraries: function() {
var constructor = this;
var regex = /__[^_]+_+/g;
var unlinked_libraries = constructor.binary.match(regex);
if (unlinked_libraries != null) {
unlinked_libraries = unlinked_libraries
.map(function(name) {
// Remove underscores
return name.replace(/_/g, "");
})
.sort()
.filter(function(name, index, arr) {
// Remove duplicates
if (index + 1 >= arr.length) {
return true;
}
return name != arr[index + 1];
})
.join(", ");
var error =
constructor.contractName +
" contains unresolved libraries. You must deploy and link" +
" the following libraries before you can deploy a new version of " +
constructor.contractName +
": " +
unlinked_libraries;
throw new Error(error);
}
},
convertToEthersBN: function(original) {
const converted = [];
original.forEach(item => {
// Recurse for arrays
if (Array.isArray(item)) {
converted.push(Utils.convertToEthersBN(item));
// Convert Web3 BN / BigNumber
} else if (Utils.is_big_number(item)) {
const ethersBN = ethers.utils.bigNumberify(item.toString());
converted.push(ethersBN);
} else {
converted.push(item);
}
});
return converted;
}
};
module.exports = Utils;
| packages/truffle-contract/lib/utils.js | var Web3 = require("web3");
var ethers = require("ethers");
var abi = require("web3-eth-abi");
var reformat = require("./reformat");
var web3 = new Web3();
var Utils = {
is_object: function(val) {
return typeof val == "object" && !Array.isArray(val);
},
is_big_number: function(val) {
if (typeof val != "object") return false;
return web3.utils.isBN(val) || web3.utils.isBigNumber(val);
},
is_tx_params: function(val) {
if (!Utils.is_object(val)) return false;
if (Utils.is_big_number(val)) return false;
const allowed_fields = {
from: true,
to: true,
gas: true,
gasPrice: true,
value: true,
data: true,
nonce: true
};
for (field_name of Object.keys(val)) {
if (!allowed_fields[field_name]) return false;
}
return true;
},
decodeLogs: function(_logs, isSingle) {
var constructor = this;
var logs = Utils.toTruffleLog(_logs, isSingle);
return logs
.map(function(log) {
var logABI = constructor.events[log.topics[0]];
if (logABI == null) {
return null;
}
var copy = Utils.merge({}, log);
copy.event = logABI.name;
copy.topics = logABI.anonymous ? copy.topics : copy.topics.slice(1);
const logArgs = abi.decodeLog(logABI.inputs, copy.data, copy.topics);
copy.args = reformat.numbers.call(constructor, logArgs, logABI.inputs);
delete copy.data;
delete copy.topics;
return copy;
})
.filter(function(log) {
return log != null;
});
},
toTruffleLog: function(events, isSingle) {
// Transform singletons (from event listeners) to the kind of
// object we find on the receipt
if (isSingle && typeof isSingle === "boolean") {
var temp = [];
temp.push(events);
return temp.map(function(log) {
log.data = log.raw.data;
log.topics = log.raw.topics;
return log;
});
}
// Or reformat items in the existing array
events.forEach(event => {
if (event.raw) {
event.data = event.raw.data;
event.topics = event.raw.topics;
}
});
return events;
},
merge: function() {
var merged = {};
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
var object = args[i];
var keys = Object.keys(object);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = object[key];
merged[key] = value;
}
}
return merged;
},
parallel: function(arr, callback) {
callback = callback || function() {};
if (!arr.length) {
return callback(null, []);
}
var index = 0;
var results = new Array(arr.length);
arr.forEach(function(fn, position) {
fn(function(err, result) {
if (err) {
callback(err);
callback = function() {};
} else {
index++;
results[position] = result;
if (index >= arr.length) {
callback(null, results);
}
}
});
});
},
linkBytecode: function(bytecode, links) {
Object.keys(links).forEach(function(library_name) {
var library_address = links[library_name];
var regex = new RegExp("__" + library_name + "_+", "g");
bytecode = bytecode.replace(regex, library_address.replace("0x", ""));
});
return bytecode;
},
// Extracts optional tx params from a list of fn arguments
getTxParams: function(methodABI, args) {
var constructor = this;
var expected_arg_count = methodABI ? methodABI.inputs.length : 0;
tx_params = {};
var last_arg = args[args.length - 1];
if (
args.length === expected_arg_count + 1 &&
Utils.is_tx_params(last_arg)
) {
tx_params = args.pop();
}
return Utils.merge(constructor.class_defaults, tx_params);
},
// Verifies that a contracts libraries have been linked correctly.
// Throws on error
checkLibraries: function() {
var constructor = this;
var regex = /__[^_]+_+/g;
var unlinked_libraries = constructor.binary.match(regex);
if (unlinked_libraries != null) {
unlinked_libraries = unlinked_libraries
.map(function(name) {
// Remove underscores
return name.replace(/_/g, "");
})
.sort()
.filter(function(name, index, arr) {
// Remove duplicates
if (index + 1 >= arr.length) {
return true;
}
return name != arr[index + 1];
})
.join(", ");
var error =
constructor.contractName +
" contains unresolved libraries. You must deploy and link" +
" the following libraries before you can deploy a new version of " +
constructor.contractName +
": " +
unlinked_libraries;
throw new Error(error);
}
},
convertToEthersBN: function(original) {
const converted = [];
original.forEach(item => {
// Recurse for arrays
if (Array.isArray(item)) {
converted.push(Utils.convertToEthersBN(item));
// Convert Web3 BN / BigNumber
} else if (Utils.is_big_number(item)) {
const ethersBN = ethers.utils.bigNumberify(item.toString());
converted.push(ethersBN);
} else {
converted.push(item);
}
});
return converted;
}
};
module.exports = Utils;
| truffle-contract: don't strict validate txParams
The logic which this commit removes would have broken compatibility with
enterprise clients which require extra tx params, such as Quorum.
| packages/truffle-contract/lib/utils.js | truffle-contract: don't strict validate txParams | <ide><path>ackages/truffle-contract/lib/utils.js
<ide> is_tx_params: function(val) {
<ide> if (!Utils.is_object(val)) return false;
<ide> if (Utils.is_big_number(val)) return false;
<add>
<ide> const allowed_fields = {
<ide> from: true,
<ide> to: true,
<ide> };
<ide>
<ide> for (field_name of Object.keys(val)) {
<del> if (!allowed_fields[field_name]) return false;
<del> }
<del>
<del> return true;
<add> if (allowed_fields[field_name]) return true;
<add> }
<add>
<add> return false;
<ide> },
<ide>
<ide> decodeLogs: function(_logs, isSingle) { |
|
Java | apache-2.0 | 398e585e2df5d103439435d3c13bd2130fb8e120 | 0 | kubernetes-client/java,kubernetes-client/java | package io.kubernetes.client.util;
import io.kubernetes.client.ApiClient;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.IOException;
public class Config {
private static final String SERVICEACCOUNT_ROOT =
"/var/run/secrets/kubernetes.io/serviceaccount";
private static final String SERVICEACCOUNT_CA_PATH =
SERVICEACCOUNT_ROOT + "/ca.crt";
private static final String SERVICEACCOUNT_TOKEN_PATH =
SERVICEACCOUNT_ROOT + "/token";
public static ApiClient fromCluster() throws IOException {
String host = System.getenv("KUBERNETES_SERVICE_HOST");
String port = System.getenv("KUBERNETES_SERVICE_PORT");
FileInputStream caCert = new FileInputStream(SERVICEACCOUNT_CA_PATH);
BufferedReader tokenReader = new BufferedReader(new FileReader(SERVICEACCOUNT_TOKEN_PATH));
StringBuilder builder = new StringBuilder();
for (String line = tokenReader.readLine(); line != null; line = tokenReader.readLine()) {
builder.append(line);
}
ApiClient result = new ApiClient();
result.setBasePath("https://" + host + ":" + port);
result.setSslCaCert(caCert);
result.setAccessToken(builder.toString());
return result;
}
public static ApiClient fromUrl(String url) {
return fromUrl(url, true);
}
public static ApiClient fromUrl(String url, boolean validateSSL) {
return new ApiClient()
.setBasePath(url)
.setVerifyingSsl(validateSSL);
}
public static ApiClient fromUserPassword(String url, String user, String password) {
return fromUserPassword(url, user, password, true);
}
public static ApiClient fromUserPassword(String url, String user, String password, boolean validateSSL) {
ApiClient client = fromUrl(url, validateSSL);
client.setUsername(user);
client.setPassword(password);
return client;
}
public static ApiClient fromToken(String url, String token) {
return fromToken(url, token, true);
}
public static ApiClient fromToken(String url, String token, boolean validateSSL) {
ApiClient client = fromUrl(url, validateSSL);
client.setAccessToken(token);
return client;
}
} | util/src/main/java/io/kubernetes/client/util/Config.java | package io.kubernetes.client.util;
import io.kubernetes.client.ApiClient;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.IOException;
public class Config {
private static final String SERVICEACCOUNT_ROOT =
"/var/run/secrets/kubernetes.io/serviceaccount";
private static final String SERVICEACCOUNT_CA_PATH =
SERVICEACCOUNT_ROOT + "/ca.crt";
private static final String SERVICEACCOUNT_TOKEN_PATH =
SERVICEACCOUNT_ROOT + "/token";
public static ApiClient fromCluster() throws IOException {
String host = System.getenv("KUBERNETES_SERVICE_HOST");
String port = System.getenv("KUBERNETES_SERVICE_PORT");
FileInputStream caCert = new FileInputStream(SERVICEACCOUNT_CA_PATH);
BufferedReader tokenReader = new BufferedReader(new FileReader(SERVICEACCOUNT_TOKEN_PATH));
StringBuilder builder = new StringBuilder();
for (String line = tokenReader.readLine(); line != null; line = tokenReader.readLine()) {
builder.append(line);
}
ApiClient result = new ApiClient();
result.setBasePath("https://" + host + ":" + port);
result.setSslCaCert(caCert);
result.setAccessToken(builder.toString());
return result;
}
} | Add a bunch of simplified helper methods for creating clients from
different information.
| util/src/main/java/io/kubernetes/client/util/Config.java | Add a bunch of simplified helper methods for creating clients from different information. | <ide><path>til/src/main/java/io/kubernetes/client/util/Config.java
<ide>
<ide> return result;
<ide> }
<add>
<add> public static ApiClient fromUrl(String url) {
<add> return fromUrl(url, true);
<add> }
<add>
<add> public static ApiClient fromUrl(String url, boolean validateSSL) {
<add> return new ApiClient()
<add> .setBasePath(url)
<add> .setVerifyingSsl(validateSSL);
<add> }
<add>
<add> public static ApiClient fromUserPassword(String url, String user, String password) {
<add> return fromUserPassword(url, user, password, true);
<add> }
<add>
<add> public static ApiClient fromUserPassword(String url, String user, String password, boolean validateSSL) {
<add> ApiClient client = fromUrl(url, validateSSL);
<add> client.setUsername(user);
<add> client.setPassword(password);
<add> return client;
<add> }
<add>
<add> public static ApiClient fromToken(String url, String token) {
<add> return fromToken(url, token, true);
<add> }
<add>
<add> public static ApiClient fromToken(String url, String token, boolean validateSSL) {
<add> ApiClient client = fromUrl(url, validateSSL);
<add> client.setAccessToken(token);
<add> return client;
<add> }
<ide> } |
|
JavaScript | mit | 3380390b3cbff4f9b95f8aeeebfb8f2e6514da20 | 0 | richardgirges/express-fileupload,richardgirges/express-fileupload | const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const {
debugLog,
checkAndMakeDir,
getTempFilename,
deleteFile
} = require('./utilities');
module.exports = (options, fieldname, filename) => {
const dir = path.normalize(options.tempFileDir);
const tempFilePath = path.join(dir, getTempFilename());
checkAndMakeDir({createParentPath: true}, tempFilePath);
debugLog(options, `Temporary file path is ${tempFilePath}`);
const hash = crypto.createHash('md5');
const writeStream = fs.createWriteStream(tempFilePath);
let fileSize = 0; // eslint-disable-line
return {
dataHandler: (data) => {
writeStream.write(data);
hash.update(data);
fileSize += data.length;
debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`);
},
getFilePath: () => tempFilePath,
getFileSize: () => fileSize,
getHash: () => hash.digest('hex'),
complete: () => {
writeStream.end();
// Return empty buff since data was uploaded into a temp file.
return Buffer.concat([]);
},
cleanup: () => {
debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
writeStream.end();
deleteFile(tempFilePath, (err) => { if (err) throw err; });
}
};
};
| lib/tempFileHandler.js | const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const {
debugLog,
checkAndMakeDir,
getTempFilename,
deleteFile
} = require('./utilities');
module.exports = (options, fieldname, filename) => {
const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
const tempFilePath = path.join(dir, getTempFilename());
checkAndMakeDir({createParentPath: true}, tempFilePath);
debugLog(options, `Temporary file path is ${tempFilePath}`);
const hash = crypto.createHash('md5');
const writeStream = fs.createWriteStream(tempFilePath);
let fileSize = 0; // eslint-disable-line
return {
dataHandler: (data) => {
writeStream.write(data);
hash.update(data);
fileSize += data.length;
debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`);
},
getFilePath: () => tempFilePath,
getFileSize: () => fileSize,
getHash: () => hash.digest('hex'),
complete: () => {
writeStream.end();
// Return empty buff since data was uploaded into a temp file.
return Buffer.concat([]);
},
cleanup: () => {
debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
writeStream.end();
deleteFile(tempFilePath, (err) => { if (err) throw err; });
}
};
};
| upd:remove default tmp path
Remove default tempDir path, since it set in default options. | lib/tempFileHandler.js | upd:remove default tmp path | <ide><path>ib/tempFileHandler.js
<ide> } = require('./utilities');
<ide>
<ide> module.exports = (options, fieldname, filename) => {
<del> const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
<add> const dir = path.normalize(options.tempFileDir);
<ide> const tempFilePath = path.join(dir, getTempFilename());
<ide> checkAndMakeDir({createParentPath: true}, tempFilePath);
<ide> |
|
JavaScript | mit | e7e46ba782215819cac303e77b1628724d03218f | 0 | apparatus/fuge-runner,apparatus/fuge-runner,microbial-lab/fuge-runner | /*
* 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 THE AUTHOR 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.
*/
'use strict';
var _ = require('lodash');
var async = require('async');
var spawn = require('child_process').spawn;
var execSync = require('child_process').execSync;
var psTree = require('ps-tree');
var winPsTree = require('winpstree');
var fs = require('fs');
var path = require('path');
var dotenv = require('dotenv');
module.exports = function() {
var isWin = /^win/.test(process.platform);
var handleIpAddress = function(container, cmd) {
var ipAddress;
ipAddress = container.specific.ipAddress || '127.0.0.1';
cmd = cmd.replace(/__TARGETIP__/g, ipAddress);
return cmd;
};
var generateEnvironment = function(containerEnv) {
var envArgs = ' ';
_.each(_.keys(containerEnv), function(key) {
if (isWin) {
envArgs += 'set ' + key + '=' + containerEnv[key] + '&&';
}
else {
envArgs += key + '=' + containerEnv[key] + ' ';
}
});
return envArgs;
};
var run = function(mode, container, exitCb, cb) {
var cmd = container.specific.execute.exec;
var cwd = container.specific.path;
var envFile = getEnvFile(container);
var env;
var toExec;
var child = {};
var envArgs = '';
var called = false;
if (cmd.slice(0, 5) === 'node ' && cmd.slice(0, 7) !== 'node -r') {
// use same node running fuge
var fugePath = process.mainModule.filename;
cmd = process.argv[0] + ' -r ' + fugePath + ' ' + cmd.slice(5);
container.type = 'node';
}
if (envFile && !fs.existsSync(envFile)) {
return cb('Error: ' + envFile + ' does not exist');
}
if (container.specific && container.specific.environment) {
envArgs = generateEnvironment(container.specific.environment);
}
if (envFile) {
var envFileData = dotenv.parse(fs.readFileSync(envFile));
envArgs += ' ' + generateEnvironment(envFileData || {});
}
if (isWin) {
toExec = envArgs + ' ' + cmd;
}
else {
toExec = envArgs + ' exec ' + cmd;
}
toExec = handleIpAddress(container, toExec);
console.log('running: ' + toExec);
env = Object.create(process.env);
if (mode !== 'preview') {
var options = {cwd: cwd, env: env, stdio: [0, 'pipe', 'pipe'], detached: false};
if (container.type === 'node') {
options.stdio[3] = 'ipc';
}
if (isWin) {
child = spawn(process.env.comspec, ['/c', toExec], options);
}
else {
child = spawn('/bin/bash', ['-c', toExec], options);
}
child.unref();
child.on('error', function(err) {
if (!called) {
called = true;
exitCb(child.pid, container.name, err);
}
});
child.on('exit', function(code) {
if (!called) {
called = true;
exitCb(child.pid, container.name, code);
}
});
}
else {
child.detail = { cmd: cmd,
environment: container.specific.environment,
cwd: cwd };
}
cb(null, child);
function getEnvFile(container) {
/* jshint ignore:start */
var envFile = container.specific.source.env_file;
/* jshint ignore:end */
var yamlPath = container.specific.yamlPath;
return envFile && path.resolve(path.dirname(yamlPath), envFile);
}
};
var start = function(mode, container, config, exitCb, cb) {
if (container && container.specific && container.specific.execute && container.specific.execute.exec) {
if (container.type === 'docker' && !config.runDocker) {
console.log('docker disabled, skipping: ' + container.specific.execute.exec);
cb();
}
else {
run(mode, container, exitCb, cb);
}
}
else {
if (container.name !== '__proxy') {
console.log('warning: ' + container.name + ' not started, missing execute statement');
}
cb();
}
};
var getContainerId = function(psOutput, container) {
var lines = psOutput.split('\n');
var re = new RegExp('^([a-f0-9]+)\\s+' + container.specific.execute.image + '.*');
var id = null;
var match;
_.each(lines, function(line) {
match = re.exec(line);
if (match) {
id = match[1];
}
});
return id;
};
var kill = function kill(container, pid, signal, cb) {
var psOutput;
var id;
if (pid) {
try {
if (container.type === 'docker') {
if (!psOutput) {
psOutput = execSync('docker ps').toString();
}
id = getContainerId(psOutput, container);
if (id) {
execSync('docker kill ' + id);
}
cb(null);
}
else {
if (isWin) {
winPsTree(pid, function(err, childPids) {
async.eachSeries(childPids, function(childPid, next) {
console.log('sending ' + signal + ' to child process: ' + childPid);
try { process.kill(childPid, signal); } catch(e) {}
next();
}, function() {
console.log('sending ' + signal + ' to parent process: ' + pid);
try { process.kill(pid, signal); } catch(e) {}
cb(null);
});
});
}
else {
psTree(pid, function(err, children) {
async.eachSeries(children, function(child, next) {
console.log('sending ' + signal + ' to child process: ' + child.PID);
try { process.kill(child.PID, signal); } catch(e) {}
next();
}, function() {
console.log('sending ' + signal + ' to parent process: ' + pid);
try { process.kill(pid, signal); } catch(e) {}
cb(null);
});
});
}
}
}
catch (e) {
console.log(e);
}
}
};
var stop = function stop(container, pid, cb) {
kill(container, pid, 'SIGKILL', cb);
};
return {
kill: kill,
start: start,
stop: stop
};
};
| lib/processRunner.js | /*
* 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 THE AUTHOR 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.
*/
'use strict';
var _ = require('lodash');
var async = require('async');
var spawn = require('child_process').spawn;
var execSync = require('child_process').execSync;
var psTree = require('ps-tree');
var winPsTree = require('winpstree');
var fs = require('fs');
var path = require('path');
var dotenv = require('dotenv');
module.exports = function() {
var isWin = /^win/.test(process.platform);
var handleIpAddress = function(container, cmd) {
var ipAddress;
ipAddress = container.specific.ipAddress || '127.0.0.1';
cmd = cmd.replace(/__TARGETIP__/g, ipAddress);
return cmd;
};
var generateEnvironment = function(containerEnv) {
var envArgs = ' ';
_.each(_.keys(containerEnv), function(key) {
if (isWin) {
envArgs += 'set ' + key + '=' + containerEnv[key] + '&&';
}
else {
envArgs += key + '=' + containerEnv[key] + ' ';
}
});
return envArgs;
};
var run = function(mode, container, exitCb, cb) {
var cmd = container.specific.execute.exec;
var cwd = container.specific.path;
var envFile = getEnvFile(container);
var env;
var toExec;
var child = {};
var envArgs = '';
var called = false;
if (cmd.slice(0, 5) === 'node ' && cmd.slice(0, 7) !== 'node -r') {
// use same node running fuge
cmd = process.argv[0] + ' -r fuge ' + cmd.slice(5);
container.type = 'node';
}
if (envFile && !fs.existsSync(envFile)) {
return cb('Error: ' + envFile + ' does not exist');
}
if (container.specific && container.specific.environment) {
envArgs = generateEnvironment(container.specific.environment);
}
if (envFile) {
var envFileData = dotenv.parse(fs.readFileSync(envFile));
envArgs += ' ' + generateEnvironment(envFileData || {});
}
if (isWin) {
toExec = envArgs + ' ' + cmd;
}
else {
toExec = envArgs + ' exec ' + cmd;
}
toExec = handleIpAddress(container, toExec);
console.log('running: ' + toExec);
env = Object.create(process.env);
if (mode !== 'preview') {
var options = {cwd: cwd, env: env, stdio: [0, 'pipe', 'pipe'], detached: false};
if (container.type === 'node') {
options.stdio[3] = 'ipc';
}
if (isWin) {
child = spawn(process.env.comspec, ['/c', toExec], options);
}
else {
child = spawn('/bin/bash', ['-c', toExec], options);
}
child.unref();
child.on('error', function(err) {
if (!called) {
called = true;
exitCb(child.pid, container.name, err);
}
});
child.on('exit', function(code) {
if (!called) {
called = true;
exitCb(child.pid, container.name, code);
}
});
}
else {
child.detail = { cmd: cmd,
environment: container.specific.environment,
cwd: cwd };
}
cb(null, child);
function getEnvFile(container) {
/* jshint ignore:start */
var envFile = container.specific.source.env_file;
/* jshint ignore:end */
var yamlPath = container.specific.yamlPath;
return envFile && path.resolve(path.dirname(yamlPath), envFile);
}
};
var start = function(mode, container, config, exitCb, cb) {
if (container && container.specific && container.specific.execute && container.specific.execute.exec) {
if (container.type === 'docker' && !config.runDocker) {
console.log('docker disabled, skipping: ' + container.specific.execute.exec);
cb();
}
else {
run(mode, container, exitCb, cb);
}
}
else {
if (container.name !== '__proxy') {
console.log('warning: ' + container.name + ' not started, missing execute statement');
}
cb();
}
};
var getContainerId = function(psOutput, container) {
var lines = psOutput.split('\n');
var re = new RegExp('^([a-f0-9]+)\\s+' + container.specific.execute.image + '.*');
var id = null;
var match;
_.each(lines, function(line) {
match = re.exec(line);
if (match) {
id = match[1];
}
});
return id;
};
var kill = function kill(container, pid, signal, cb) {
var psOutput;
var id;
if (pid) {
try {
if (container.type === 'docker') {
if (!psOutput) {
psOutput = execSync('docker ps').toString();
}
id = getContainerId(psOutput, container);
if (id) {
execSync('docker kill ' + id);
}
cb(null);
}
else {
if (isWin) {
winPsTree(pid, function(err, childPids) {
async.eachSeries(childPids, function(childPid, next) {
console.log('sending ' + signal + ' to child process: ' + childPid);
try { process.kill(childPid, signal); } catch(e) {}
next();
}, function() {
console.log('sending ' + signal + ' to parent process: ' + pid);
try { process.kill(pid, signal); } catch(e) {}
cb(null);
});
});
}
else {
psTree(pid, function(err, children) {
async.eachSeries(children, function(child, next) {
console.log('sending ' + signal + ' to child process: ' + child.PID);
try { process.kill(child.PID, signal); } catch(e) {}
next();
}, function() {
console.log('sending ' + signal + ' to parent process: ' + pid);
try { process.kill(pid, signal); } catch(e) {}
cb(null);
});
});
}
}
}
catch (e) {
console.log(e);
}
}
};
var stop = function stop(container, pid, cb) {
kill(container, pid, 'SIGKILL', cb);
};
return {
kill: kill,
start: start,
stop: stop
};
};
| Use full path to fuge
| lib/processRunner.js | Use full path to fuge | <ide><path>ib/processRunner.js
<ide>
<ide> if (cmd.slice(0, 5) === 'node ' && cmd.slice(0, 7) !== 'node -r') {
<ide> // use same node running fuge
<del> cmd = process.argv[0] + ' -r fuge ' + cmd.slice(5);
<add> var fugePath = process.mainModule.filename;
<add> cmd = process.argv[0] + ' -r ' + fugePath + ' ' + cmd.slice(5);
<ide> container.type = 'node';
<ide> }
<ide> |
|
Java | agpl-3.0 | f83ec7a66d11f03d6a36479210bb11cebcebbe0b | 0 | USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis | package org.openlmis.vaccine.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.openlmis.core.domain.Facility;
import org.openlmis.core.domain.SupervisoryNode;
import org.openlmis.core.utils.DateUtil;
import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
public class OrderRequisitionDTO extends SupervisoryNode{
Long id;
Long periodId;
Long programId;
Long facilityId;
String status;
String periodName;
String programName;
String facilityType;
String districtName;
private Date submittedDate;
private Date modifiedDate;
private Date periodStartDate;
private Date periodEndDate;
private String stringModifiedDate;
private String stringPeriodStartDate;
private String stringPeriodEndDate;
private String requisitionStatus;
//Used to view pending requisition
String facilityName;
String orderDate;
Long orderId;
//Used to join order requisition and stock Card
@JsonIgnore
Facility facility;
Long productId;
Long quantityRequested ;
String productCategory;
Boolean emergency;
String productName;
String productCode;
public static List<OrderRequisitionDTO> prepareForView(List<VaccineOrderRequisition> requisitions) {
List<OrderRequisitionDTO> result = new ArrayList<>();
for (VaccineOrderRequisition requisition : requisitions) {
OrderRequisitionDTO requisitionDTO = populateDTOWithRequisition(requisition);
requisitionDTO.requisitionStatus = requisition.getStatus().name();
result.add(requisitionDTO);
}
return result;
}
private static OrderRequisitionDTO populateDTOWithRequisition(VaccineOrderRequisition requisition) {
OrderRequisitionDTO rnrDTO = new OrderRequisitionDTO();
rnrDTO.id = requisition.getId();
rnrDTO.programId = requisition.getProgram().getId();
rnrDTO.facilityId = requisition.getFacility().getId();
rnrDTO.programName = requisition.getProgram().getName();
rnrDTO.facilityName = requisition.getFacility().getName();
rnrDTO.facilityType = requisition.getFacility().getFacilityType().getName();
rnrDTO.districtName = requisition.getFacility().getGeographicZone().getName();
rnrDTO.modifiedDate = requisition.getModifiedDate();
rnrDTO.periodStartDate = requisition.getPeriod().getStartDate();
rnrDTO.periodEndDate = requisition.getPeriod().getEndDate();
rnrDTO.stringModifiedDate = formatDate(requisition.getModifiedDate());
rnrDTO.stringPeriodStartDate = formatDate(requisition.getPeriod().getStartDate());
rnrDTO.stringPeriodEndDate = formatDate(requisition.getPeriod().getEndDate());
rnrDTO.emergency = requisition.isEmergency();
return rnrDTO;
}
private void formatDates(){
stringModifiedDate = formatDate(modifiedDate);
stringPeriodStartDate = formatDate(periodStartDate);
stringPeriodEndDate = formatDate(periodEndDate);
}
private static String formatDate(Date date) {
return DateUtil.getFormattedDate(date, "dd/MM/yyyy");
}
}
| modules/vaccine/src/main/java/org/openlmis/vaccine/dto/OrderRequisitionDTO.java | package org.openlmis.vaccine.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.openlmis.core.domain.Facility;
import org.openlmis.core.utils.DateUtil;
import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
public class OrderRequisitionDTO {
Long id;
Long periodId;
Long programId;
Long facilityId;
String status;
String periodName;
String programName;
String facilityType;
String districtName;
private Date submittedDate;
private Date modifiedDate;
private Date periodStartDate;
private Date periodEndDate;
private String stringModifiedDate;
private String stringPeriodStartDate;
private String stringPeriodEndDate;
private String requisitionStatus;
//Used to view pending requisition
String facilityName;
Date orderDate;
//Used to join order requisition and stock Card
@JsonIgnore
Facility facility;
Long productId;
Long quantityRequested ;
String productCategory;
Boolean emergency;
public static List<OrderRequisitionDTO> prepareForView(List<VaccineOrderRequisition> requisitions) {
List<OrderRequisitionDTO> result = new ArrayList<>();
for (VaccineOrderRequisition requisition : requisitions) {
OrderRequisitionDTO requisitionDTO = populateDTOWithRequisition(requisition);
requisitionDTO.requisitionStatus = requisition.getStatus().name();
result.add(requisitionDTO);
}
return result;
}
private static OrderRequisitionDTO populateDTOWithRequisition(VaccineOrderRequisition requisition) {
OrderRequisitionDTO rnrDTO = new OrderRequisitionDTO();
rnrDTO.id = requisition.getId();
rnrDTO.programId = requisition.getProgram().getId();
rnrDTO.facilityId = requisition.getFacility().getId();
rnrDTO.programName = requisition.getProgram().getName();
rnrDTO.facilityName = requisition.getFacility().getName();
rnrDTO.facilityType = requisition.getFacility().getFacilityType().getName();
rnrDTO.districtName = requisition.getFacility().getGeographicZone().getName();
rnrDTO.modifiedDate = requisition.getModifiedDate();
rnrDTO.periodStartDate = requisition.getPeriod().getStartDate();
rnrDTO.periodEndDate = requisition.getPeriod().getEndDate();
rnrDTO.stringModifiedDate = formatDate(requisition.getModifiedDate());
rnrDTO.stringPeriodStartDate = formatDate(requisition.getPeriod().getStartDate());
rnrDTO.stringPeriodEndDate = formatDate(requisition.getPeriod().getEndDate());
rnrDTO.emergency = requisition.isEmergency();
return rnrDTO;
}
private void formatDates(){
stringModifiedDate = formatDate(modifiedDate);
stringPeriodStartDate = formatDate(periodStartDate);
stringPeriodEndDate = formatDate(periodEndDate);
}
private static String formatDate(Date date) {
return DateUtil.getFormattedDate(date, "dd/MM/yyyy");
}
}
| VIMS-330 : Add java code for Vaccine consolidated report
| modules/vaccine/src/main/java/org/openlmis/vaccine/dto/OrderRequisitionDTO.java | VIMS-330 : Add java code for Vaccine consolidated report | <ide><path>odules/vaccine/src/main/java/org/openlmis/vaccine/dto/OrderRequisitionDTO.java
<ide> import lombok.Data;
<ide> import lombok.EqualsAndHashCode;
<ide> import org.openlmis.core.domain.Facility;
<add>import org.openlmis.core.domain.SupervisoryNode;
<ide> import org.openlmis.core.utils.DateUtil;
<ide> import org.openlmis.vaccine.domain.VaccineOrderRequisition.VaccineOrderRequisition;
<ide>
<ide>
<ide> @Data
<ide> @EqualsAndHashCode(callSuper = false)
<del>public class OrderRequisitionDTO {
<add>public class OrderRequisitionDTO extends SupervisoryNode{
<ide>
<ide> Long id;
<ide> Long periodId;
<ide> //Used to view pending requisition
<ide>
<ide> String facilityName;
<del> Date orderDate;
<add> String orderDate;
<add> Long orderId;
<ide>
<ide>
<ide>
<ide> String productCategory;
<ide>
<ide> Boolean emergency;
<add>
<add> String productName;
<add>
<add> String productCode;
<ide>
<ide>
<ide> |
|
Java | mit | error: pathspec 'fltstr/Test.java' did not match any file(s) known to git
| d213ee23c1b7ff26624a5ea05fe57c904ad4f912 | 1 | malzev/java-core-ex | public class Test {
public static void main(String[] args) {
float number = -895.25f;
String numberAsString = Float.toString(number);
}
}
| fltstr/Test.java | Update and rename fltstr to fltstr/Test.java | fltstr/Test.java | Update and rename fltstr to fltstr/Test.java | <ide><path>ltstr/Test.java
<add>public class Test {
<add> public static void main(String[] args) {
<add> float number = -895.25f;
<add> String numberAsString = Float.toString(number);
<add> }
<add>} |
|
Java | mit | 36d292ef4caf95d7fd7f89728e6c521601099ba3 | 0 | IgorGee/3D-Image-Creator,IgorGee/PendantCreator3D,IgorGee/Carbonizr | package xyz.igorgee.pendantcreator3d;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.github.scribejava.core.model.Token;
import java.io.File;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xyz.igorgee.shapwaysapi.Client;
import static xyz.igorgee.utilities.UIUtilities.makeAlertDialog;
import static xyz.igorgee.utilities.UIUtilities.makeSnackbar;
public class HomePageFragment extends ListFragment {
private final static int SELECT_PHOTO = 46243;
@Bind(android.R.id.list) ListView list;
@Bind(R.id.empty_home_page_text) TextView textView;
Client client;
String imageTitle;
ArrayList<String> files;
ArrayAdapter<String> adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_homepage, container, false);
ButterKnife.bind(this, view);
initializeClient();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
files = new ArrayList<>();
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, files);
setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
makeSnackbar(v, ((TextView) v).getText().toString());
}
private void initializeClient() {
client = new Client();
SharedPreferences preferences = getActivity().
getSharedPreferences(MainActivity.MY_PREF_NAME, Context.MODE_PRIVATE);
String accessTokenValue = preferences.getString(MainActivity.ACCESS_TOKEN_VALUE, null);
String accessTokenSecret = preferences.getString(MainActivity.ACCESS_TOKEN_SECRET, null);
client.setAccessToken(new Token(accessTokenValue, accessTokenSecret));
new connectToClient().execute();
}
private class connectToClient extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d("TEST", client.getCart());
return null;
}
}
@OnClick(R.id.selectImageButton)
public void selectImage(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == Activity.RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
imageTitle = new File(imagePath).getName();
String info = "Title: " + imageTitle + "\n";
info += "Height: " + height + "\n" + "Width: " + width;
makeAlertDialog(getActivity(), info, android.R.drawable.ic_menu_report_image);
if (height > 2000 || width > 2000) {
makeSnackbar(getActivity().findViewById(R.id.rootLayout),
"Image too big.\nMax: 2000px x 2000px");
} else {
files.add(imageTitle);
adapter.notifyDataSetChanged();
}
cursor.close();
textView.setVisibility(View.GONE);
}
}
}
}
| app/src/main/java/xyz/igorgee/pendantcreator3d/HomePageFragment.java | package xyz.igorgee.pendantcreator3d;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.github.scribejava.core.model.Token;
import java.io.File;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xyz.igorgee.shapwaysapi.Client;
import static xyz.igorgee.utilities.UIUtilities.makeAlertDialog;
import static xyz.igorgee.utilities.UIUtilities.makeSnackbar;
public class HomePageFragment extends ListFragment {
private final static int SELECT_PHOTO = 46243;
@Bind(android.R.id.list) ListView list;
@Bind(R.id.empty_home_page_text) TextView textView;
Client client;
String imageTitle;
ArrayList<String> files;
ArrayAdapter<String> adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_homepage, container, false);
ButterKnife.bind(this, view);
initializeClient();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
files = new ArrayList<>();
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, files);
setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
makeSnackbar(v, ((TextView) v).getText().toString());
}
private void initializeClient() {
client = new Client();
SharedPreferences preferences = getActivity().
getSharedPreferences(MainActivity.MY_PREF_NAME, Context.MODE_PRIVATE);
String accessTokenValue = preferences.getString(MainActivity.ACCESS_TOKEN_VALUE, null);
String accessTokenSecret = preferences.getString(MainActivity.ACCESS_TOKEN_SECRET, null);
client.setAccessToken(new Token(accessTokenValue, accessTokenSecret));
new connectToClient().execute();
}
private class connectToClient extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d("TEST", client.getCart());
return null;
}
}
@OnClick(R.id.selectImageButton)
public void selectImage(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == Activity.RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
imageTitle = new File(imagePath).getName();
String info = "Title: " + imageTitle + "\n";
info += "Height: " + height + "\n" + "Width: " + width;
makeAlertDialog(getActivity(), info, android.R.drawable.ic_menu_report_image);
if (height > 2000 || width > 2000) {
makeSnackbar(getActivity().findViewById(R.id.rootLayout),
"Image too big.\nMax: 2000px x 2000px");
} else {
files.add(imageTitle);
adapter.notifyDataSetChanged();
}
cursor.close();
textView.setVisibility(View.GONE);
}
}
}
}
| Optimize imports
| app/src/main/java/xyz/igorgee/pendantcreator3d/HomePageFragment.java | Optimize imports | <ide><path>pp/src/main/java/xyz/igorgee/pendantcreator3d/HomePageFragment.java
<ide> package xyz.igorgee.pendantcreator3d;
<ide>
<ide> import android.app.Activity;
<del>import android.app.AlertDialog;
<del>import android.app.Fragment;
<ide> import android.app.ListFragment;
<ide> import android.content.Context;
<del>import android.content.DialogInterface;
<ide> import android.content.Intent;
<ide> import android.content.SharedPreferences;
<ide> import android.database.Cursor;
<ide> import android.os.Bundle;
<ide> import android.provider.MediaStore;
<ide> import android.support.annotation.Nullable;
<del>import android.support.v4.widget.DrawerLayout;
<ide> import android.util.Log;
<ide> import android.view.LayoutInflater;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import android.widget.ArrayAdapter;
<del>import android.widget.LinearLayout;
<ide> import android.widget.ListView;
<ide> import android.widget.TextView;
<ide> |
|
Java | epl-1.0 | 36802a37181d16ee0aa2b3fa49982abcba465f1c | 0 | floralvikings/jenjin | package com.jenjinstudios.core.message;
import com.jenjinstudios.core.Connection;
import com.jenjinstudios.core.io.Message;
import com.jenjinstudios.core.io.MessageType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The {@code ExecutableMessage} class should be extended to create self-handling messages on the server.
* @author Caleb Brinkman
*/
@SuppressWarnings("unused")
public abstract class ExecutableMessage
{
/** The logger for this class. */
private static final Logger LOGGER = Logger.getLogger(ExecutableMessage.class.getName());
/** The Message for this ExecutableMessage. */
private final Message message;
/**
* Construct an ExecutableMessage with the given Message.
* @param message The Message.
*/
protected ExecutableMessage(Message message) {
this.message = message;
}
/** Run the synced portion of this message. */
public abstract void runDelayed();
/** Run asynchronous portion of this message. */
public abstract void runImmediate();
/**
* The Message for this ExecutableMessage.
* @return The Message used by this ExecutableMessage
*/
public Message getMessage() {
return message;
}
/**
* Get an executable message for the given connection and message.
* @param connection The connection.
* @param message The Message.
* @return The ExecutableMessage appropriate to the given message.
*/
@SuppressWarnings("unchecked")
public static ExecutableMessage getExecutableMessageFor(Connection connection, Message message) {
ExecutableMessage executableMessage = null;
MessageType messageType = connection.getMessageRegistry().getMessageType(message.getID());
List<Class<? extends ExecutableMessage>> execClasses = messageType.getExecutableMessageClasses();
try
{
Constructor<? extends ExecutableMessage> execConstructor = null;
for (Class<? extends ExecutableMessage> execClass : execClasses)
{
if (execClass == null) continue;
Constructor<? extends ExecutableMessage>[] execConstructors;
execConstructors = (Constructor<? extends ExecutableMessage>[]) execClass.getConstructors();
execConstructor = getAppropriateConstructor(connection, execConstructors);
}
if (execConstructor != null)
{
executableMessage = execConstructor.newInstance(connection, message);
} else
{
LOGGER.log(Level.SEVERE, "No constructor containing Connection or {0} as first argument type found for {1}",
new Object[]{connection.getClass().getName(), message.name});
}
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e)
{
LOGGER.log(Level.SEVERE, "Constructor not correct", e);
} catch (NullPointerException e)
{
LOGGER.log(Level.SEVERE, "No executable message found for: " + message, e);
}
return executableMessage;
}
private static Constructor getAppropriateConstructor(Connection connection, Constructor[] execConstructors) {
// TODO Make this more specific.
Constructor correctConstructor = null;
for (Constructor constructor : execConstructors)
{
Class<?> firstParam = constructor.getParameterTypes()[0];
if (firstParam.isAssignableFrom(connection.getClass()))
correctConstructor = constructor;
}
return correctConstructor;
}
}
| jenjin-core/src/main/java/com/jenjinstudios/core/message/ExecutableMessage.java | package com.jenjinstudios.core.message;
import com.jenjinstudios.core.Connection;
import com.jenjinstudios.core.io.Message;
import com.jenjinstudios.core.io.MessageType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The {@code ExecutableMessage} class should be extended to create self-handling messages on the server.
* @author Caleb Brinkman
*/
@SuppressWarnings("unused")
public abstract class ExecutableMessage
{
/** The logger for this class. */
private static final Logger LOGGER = Logger.getLogger(ExecutableMessage.class.getName());
/** The Message for this ExecutableMessage. */
private final Message message;
/**
* Construct an ExecutableMessage with the given Message.
* @param message The Message.
*/
protected ExecutableMessage(Message message) {
this.message = message;
}
/** Run the synced portion of this message. */
public abstract void runDelayed();
/** Run asynchronous portion of this message. */
public abstract void runImmediate();
/**
* The Message for this ExecutableMessage.
* @return The Message used by this ExecutableMessage
*/
public Message getMessage() {
return message;
}
/**
* Get an executable message for the given connection and message.
* @param connection The connection.
* @param message The Message.
* @return The ExecutableMessage appropriate to the given message.
*/
@SuppressWarnings("unchecked")
public static ExecutableMessage getExecutableMessageFor(Connection connection, Message message) {
ExecutableMessage executableMessage = null;
MessageType messageType = connection.getMessageRegistry().getMessageType(message.getID());
List<Class<? extends ExecutableMessage>> execClasses = messageType.getExecutableMessageClasses();
try
{
Constructor<? extends ExecutableMessage> execConstructor = null;
for (Class<? extends ExecutableMessage> execClass : execClasses)
{
if (execClass == null) continue;
Constructor<? extends ExecutableMessage>[] execConstructors;
execConstructors = (Constructor<? extends ExecutableMessage>[]) execClass.getConstructors();
execConstructor = getAppropriateConstructor(connection, execConstructors);
}
if (execConstructor != null)
{
executableMessage = execConstructor.newInstance(connection, message);
} else
{
LOGGER.log(Level.SEVERE, "No constructor containing Connection or {0} as first argument type found for {1}",
new Object[]{connection.getClass().getName(), message.name});
}
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e)
{
LOGGER.log(Level.SEVERE, "Constructor not correct", e);
} catch (NullPointerException e)
{
LOGGER.log(Level.SEVERE, "No executable message found for: " + message, e);
}
return executableMessage;
}
private static Constructor getAppropriateConstructor(Connection connection, Constructor[] execConstructors) {
Constructor correctConstructor = null;
for (Constructor constructor : execConstructors)
{
Class<?> firstParam = constructor.getParameterTypes()[0];
if (firstParam.isAssignableFrom(connection.getClass()))
correctConstructor = constructor;
}
return correctConstructor;
}
}
| Added TODO comment
| jenjin-core/src/main/java/com/jenjinstudios/core/message/ExecutableMessage.java | Added TODO comment | <ide><path>enjin-core/src/main/java/com/jenjinstudios/core/message/ExecutableMessage.java
<ide> }
<ide>
<ide> private static Constructor getAppropriateConstructor(Connection connection, Constructor[] execConstructors) {
<add> // TODO Make this more specific.
<ide> Constructor correctConstructor = null;
<ide> for (Constructor constructor : execConstructors)
<ide> { |
|
Java | apache-2.0 | ebd376e7df5f5f5f7c4594897d969179547ddf26 | 0 | SSEHUB/EASyProducer,SSEHUB/EASyProducer,SSEHUB/EASyProducer | package de.uni_hildesheim.sse.easy.java.artifacts;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import de.uni_hildesheim.sse.easy.java.JavaSettings;
import de.uni_hildesheim.sse.easy.java.JavaSettingsInitializer;
import de.uni_hildesheim.sse.easy_producer.instantiator.Bundle;
import de.uni_hildesheim.sse.easy_producer.instantiator.JavaUtilities;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactCreator;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactFactory;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactModel;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.FileArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.FragmentArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.IFileSystemArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.Path;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.representation.Text;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.common.VilException;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.ArraySet;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Conversion;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Invisible;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.OperationMeta;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Set;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeDescriptor;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeRegistry;
import de.uni_hildesheim.sse.utils.logger.EASyLoggerFactory;
import de.uni_hildesheim.sse.utils.logger.EASyLoggerFactory.EASyLogger;
/**
* Represents a Java source code file artifact.
*
* @author Holger Eichelberger, Sass
*/
@ArtifactCreator(DefaultJavaFileArtifactCreator.class)
public class JavaFileArtifact extends FileArtifact implements IJavaParent {
private static EASyLogger logger = EASyLoggerFactory.INSTANCE.getLogger(JavaFileArtifact.class, Bundle.ID);
private File file;
private CompilationUnit unitNode;
private List<JavaClass> classList;
private boolean changed = false;
/**
* Creates a new class file artifact.
*
* @param file
* the file to read the artifact contents from
* @param model
* the artifact model to create this folder artifact within
*/
JavaFileArtifact(File file, ArtifactModel model) {
super(file, model);
this.file = file;
// parse lazy on request
}
/**
* Returns the annotation value.
*
* @param annotation
* the name of the annotation type
* @param field
* the field to be returned
* @return the field or <b>null</b> if not found
*/
@Invisible
public String annotationValue(String annotation, String field) {
return ""; // TODO implement, if done, remove @Invisible annotation
}
/**
* Return whether one of the classes, the methods or attributes has this
* annotation.
*
* @param annotation
* the (qualified) name of the annotation
* @param field
* the name of the annotation field (if <b>null</b> or empty the
* {@link JavaAnnotation#DEFAULT_FIELD default name "value"} is
* used
* @param value
* the name of the annotation value
* @return <code>true</code> if this annotation is present,
* <code>false</code> else
*/
public boolean hasAnnotation(String annotation, String field, String value) {
Set<JavaClass> classes = this.classes();
boolean hasAnnotation = false;
if (null == field || 0 == field.length()) {
field = JavaAnnotation.DEFAULT_FIELD;
}
// TODO efficiency: directly rely on classList and cached structures in
// JavaAttribute and JavaMethod
for (JavaClass javaClass : classes) {
// Check the classes
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, javaClass.annotations());
if (hasAnnotation) {
break;
}
// Check attributes
Set<JavaAttribute> attributes = javaClass.attributes();
for (JavaAttribute javaAttribute : attributes) {
Set<JavaAnnotation> attributeAnnotations = javaAttribute.annotations();
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, attributeAnnotations);
if (hasAnnotation) {
break;
}
}
// Check methods
Set<JavaMethod> methods = javaClass.methods();
for (JavaMethod javaMethod : methods) {
Set<JavaAnnotation> methodAnnotation = javaMethod.annotations();
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, methodAnnotation);
if (hasAnnotation) {
break;
}
}
}
return hasAnnotation;
}
/**
* Checks if a Set of JavaAnnotations contains a specific annotation.
*
* @param annotation
* The annotation name
* @param field
* the name of the field
* @param value
* The annotation value
* @param hasAnnotation
* indicates if annotation is present
* @param annotations
* Set with JavaAnnotations
* @return hasAnnotation true of false
*/
private boolean checkAnnotation(String annotation, String field, String value, boolean hasAnnotation,
Set<JavaAnnotation> annotations) {
String simpleName = JavaAnnotation.toSimpleName(annotation); // as we do
// not
// resolve,
// we must
// be lazy
for (JavaAnnotation javaAnnotation : annotations) {
try {
if ((javaAnnotation.getQualifiedName().equals(annotation)
|| javaAnnotation.getName().equals(simpleName))
&& javaAnnotation.getAnnotationValue(field).equals(value)) {
hasAnnotation = true;
break;
}
} catch (VilException e) {
logger.exception(e);
}
}
return hasAnnotation;
}
@Override
public void artifactChanged(Object cause) throws VilException {
super.artifactChanged(cause);
if (cause instanceof Text && null != getText()) {
initialize(getText().getText().toCharArray());
} else {
initialize();
}
changed = false;
}
@Override
public void store() throws VilException {
// store changes in the representation if there are some, store tree
// afterwards
// both changes shall not overlap...
super.store();
if (changed) {
// Check if file exists
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
logger.exception(e);
}
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
String code = unitNode.toString();
Map<String, String> options = new HashMap<String, String>();
options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR,
JavaCore.INSERT);
options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR,
JavaCore.INSERT);
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0,
System.getProperty("line.separator"));
IDocument doc = new Document(code);
try {
if (null != textEdit) {
textEdit.apply(doc);
}
} catch (MalformedTreeException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
} catch (BadLocationException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
}
// Save output
try {
writer.write(doc.get());
} catch (IOException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
}
} catch (IOException e) {
throw new VilException(e, VilException.ID_IO);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new VilException(e, VilException.ID_IO);
}
}
changed = false;
}
}
/**
* Returns the classes of this java file.
*
* @return the annotations
*/
@OperationMeta(returnGenerics = JavaClass.class)
public Set<JavaClass> classes() {
if (null == classList) {
initialize();
}
return new ArraySet<JavaClass>(classList.toArray(new JavaClass[classList.size()]), JavaClass.class);
}
/**
* Returns the specified classes of this java file.
*
* @param name
* the name of the class
* @return the specified class or <b>null</b>
*/
public JavaClass getClassByName(String name) {
JavaClass result = null;
if (null == classList) {
initialize();
}
for (int c = 0; null == result && c < classList.size(); c++) {
JavaClass cls = classList.get(c);
try {
if (cls.getName().equals(name)) {
result = cls;
}
} catch (VilException e) {
logger.exception(e);
}
}
return result;
}
/**
* Returns the default class of this Java File artifact, i.e., the class
* corresponding to the name of this artifact.
*
* @return the default class or <b>null</b> if there is none
*/
public JavaClass getDefaultClass() {
JavaClass result;
try {
String name = getName();
if (name.endsWith(".java")) {
name = name.substring(0, name.length() - 5);
}
result = getClassByName(name);
} catch (VilException e) {
logger.exception(e);
result = null;
}
return result;
}
/**
* Initializes the parse tree / classes from {@link #file}.
*/
private void initialize() {
initialize(readFileToString(file).toCharArray());
}
/**
* Initializes the parse tree / classes.
*
* @param data
* the data to initialize from (source code as characters)
*/
private void initialize(char[] data) {
// TODO separate inner classes
classList = new ArrayList<JavaClass>();
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(data);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
// Set options to resolve bindings
parser.setBindingsRecovery(true);
parser.setResolveBindings(true);
Hashtable<String, String> options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
parser.setCompilerOptions(options);
String unitName = FilenameUtils.getBaseName(file.getName());
parser.setUnitName(unitName);
String[] classpath = JavaUtilities.JRE_CLASS_PATH;
String sourcePath;
boolean isClasspathFromScript = false;
if (null != getArtifactModel()) {
Object classPathFromScript = getArtifactModel().getSettings(JavaSettings.CLASSPATH);
if (null != classPathFromScript) {
isClasspathFromScript = true;
sourcePath = JavaSettingsInitializer.determineClasspath(classPathFromScript);
} else {
// if no classpath is given via VIL
sourcePath = JavaSettingsInitializer.determineClasspath(null);
}
} else {
sourcePath = JavaSettingsInitializer.determineClasspath(null);
}
// WORKAROUND! FIX IT!
if (sourcePath.contains("//")) {
sourcePath = sourcePath.replaceAll("//", "/");
}
String[] sources = {sourcePath};
logger.warn("CLASSPATH: " + sources);
parser.setEnvironment(classpath, sources, new String[] {"UTF-8" }, true);
// Create AST
unitNode = (CompilationUnit) parser.createAST(null);
// Check for problems but only if the classpath was set via VIL
if (isClasspathFromScript) {
IProblem[] problems = unitNode.getProblems();
if (problems != null && problems.length > 0) {
logger.warn("Got " + problems.length + " problems compiling the source file: "
+ file.getAbsolutePath());
for (IProblem problem : problems) {
logger.warn(problem.getMessage());
}
}
}
unitNode.accept(new ASTVisitor() {
public boolean visit(TypeDeclaration typeDeclaration) {
// The below code is used to check if it is not a top-level
// class
if (typeDeclaration.isPackageMemberTypeDeclaration()) {
classList.add(new JavaClass(typeDeclaration, JavaFileArtifact.this));
}
return true;
}
});
unitNode.recordModifications();
}
/**
* Reads a file to String.
*
* @param filePath
* The file path as String.
* @return File as String.
*/
@Invisible
public static String readFileToString(File filePath) {
// TODO check whether this can be replaced by related apache.commons
// method
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (FileNotFoundException fnf) {
logger.exception(fnf);
} catch (IOException ioe) {
logger.exception(ioe);
}
return fileData.toString();
}
@Override
public void notifyChildChanged(FragmentArtifact child) {
changed = true;
}
@Override
public void deleteChild(FragmentArtifact child) throws VilException {
// implement if substructures are stored / cached
}
/**
* Returns all imports.
*
* @return all imports
*/
@SuppressWarnings("unchecked")
@OperationMeta(returnGenerics = JavaImport.class)
public Set<JavaImport> imports() {
if (null == unitNode) {
initialize();
}
List<JavaImport> imports = new ArrayList<JavaImport>();
List<ImportDeclaration> unitNodeImports = unitNode.imports();
for (ImportDeclaration importDeclaration : unitNodeImports) {
JavaImport javaImport = new JavaImport(importDeclaration, JavaFileArtifact.this);
imports.add(javaImport);
}
return new ArraySet<JavaImport>(imports.toArray(new JavaImport[imports.size()]), JavaImport.class);
}
/**
* Returns the package declaration.
*
* @return {@link JavaPackage} representing the package declaration
*/
public JavaPackage javaPackage() {
if (null == unitNode) {
initialize();
}
JavaPackage javaPackage = new JavaPackage(unitNode.getPackage(), JavaFileArtifact.this);
return javaPackage;
}
/**
* Returns all qualified names.
*
* @return all qualified names.
*/
public Set<JavaQualifiedName> qualifiedNames() {
if (null == classList) {
initialize();
}
List<JavaQualifiedName> qualifiedNames = new ArrayList<JavaQualifiedName>();
for (JavaClass javaClass : classList) {
for (JavaQualifiedName javaQualifiedName : javaClass.qualifiedNames()) {
qualifiedNames.add(javaQualifiedName);
}
}
return new ArraySet<JavaQualifiedName>(qualifiedNames.toArray(new JavaQualifiedName[qualifiedNames.size()]),
JavaQualifiedName.class);
}
/**
* Renames all (qualified) package names, imports and packages in this Java
* artifact from <code>oldName</code> to <code>newName</code>. Nothing
* happens, if <code>oldName</code> cannot be found. However, the caller is
* responsible for potential name clashes due to the execution of this
* operation.
*
* @param oldName
* the old package name
* @param newName
* the new package name
*/
public void modifyNamespace(String oldName, String newName) {
try {
renameImports(oldName, newName);
renameQualifiedNames(oldName, newName);
renamePackages(oldName, newName);
store();
} catch (VilException e) {
logger.exception(e);
}
}
/**
* Renames all (qualified) package names, imports and packages in this Java
* artifact as stated by <code>nameMapping</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param nameMapping
* pairs of old and new package names (key = old, value = new)
*/
public void modifiyNamespace(Map<String, String> nameMapping) {
try {
renameImports(nameMapping);
renameQualifiedNames(nameMapping);
renamePackages(nameMapping);
store();
} catch (VilException e) {
logger.exception(e);
}
}
/**
* Renames all (qualified) package names in this Java artifact from
* <code>oldName</code> to <code>newName</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param oldName
* the old package name
* @param newName
* the new package name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renamePackages(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renamePackages(tmp);
}
/**
* Renames all (qualified) package names in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new package names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renamePackages(Map<String, String> nameMapping) throws VilException {
JavaPackage javaPackage = this.javaPackage();
String path = javaPackage.getName();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
javaPackage.rename(path.replace(entry.getKey(), entry.getValue()));
}
}
/**
* Renames all imports in this Java artifact from <code>oldName</code> to
* <code>newName</code>. Nothing happens, if <code>oldName</code> cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param oldName
* the old import name
* @param newName
* the new import name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameImports(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renameImports(tmp);
}
/**
* Renames all imports in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new import names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameImports(Map<String, String> nameMapping) throws VilException {
Set<JavaImport> imports = this.imports();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
for (JavaImport javaImport : imports) {
if (javaImport.getName().contains(entry.getKey())) {
javaImport.rename(javaImport.getName().replace(entry.getKey(), entry.getValue()));
}
}
}
}
/**
* Renames all qualified names in this Java artifact from
* <code>oldName</code> to <code>newName</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param oldName
* the old qualified name
* @param newName
* the new qualified name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameQualifiedNames(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renameQualifiedNames(tmp);
}
/**
* Renames all qualified names in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new qualified names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameQualifiedNames(Map<String, String> nameMapping) throws VilException {
Set<JavaClass> classes = this.classes();
for (JavaClass javaClass : classes) {
Set<JavaQualifiedName> qualifiedNames = javaClass.qualifiedNames();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
for (JavaQualifiedName javaQualifiedName : qualifiedNames) {
javaQualifiedName.rename(javaQualifiedName.getName().replace(entry.getKey(), entry.getValue()));
}
}
}
}
/**
* Conversion operation.
*
* @param val
* the value to be converted
* @return the converted value or null
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(IFileSystemArtifact val) {
JavaFileArtifact convertedValue = null;
if (val instanceof JavaFileArtifact) {
convertedValue = (JavaFileArtifact) val;
}
return convertedValue;
}
/**
* Conversion operation.
*
* @param val
* the value to be converted
* @return the converted value
* @throws VilException
* in case that creating the artifact fails
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(String val) throws VilException {
Path path = Path.convert(val);
return convert(path);
}
/**
* Conversion operation.
*
* @param path
* the path to be converted
* @return the converted value
* @throws VilException
* in case that creating the artifact fails
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(Path path) throws VilException {
return ArtifactFactory.createArtifact(JavaFileArtifact.class, path.getAbsolutePath(), path.getArtifactModel());
}
}
| Plugins/Instantiation/Instantiator.Java/src/de/uni_hildesheim/sse/easy/java/artifacts/JavaFileArtifact.java | package de.uni_hildesheim.sse.easy.java.artifacts;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import de.uni_hildesheim.sse.easy.java.JavaSettings;
import de.uni_hildesheim.sse.easy.java.JavaSettingsInitializer;
import de.uni_hildesheim.sse.easy_producer.instantiator.Bundle;
import de.uni_hildesheim.sse.easy_producer.instantiator.JavaUtilities;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactCreator;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactFactory;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.ArtifactModel;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.FileArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.FragmentArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.IFileSystemArtifact;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.Path;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.artifactModel.representation.Text;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.common.VilException;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.ArraySet;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Conversion;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Invisible;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.OperationMeta;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Set;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeDescriptor;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeRegistry;
import de.uni_hildesheim.sse.utils.logger.EASyLoggerFactory;
import de.uni_hildesheim.sse.utils.logger.EASyLoggerFactory.EASyLogger;
/**
* Represents a Java source code file artifact.
*
* @author Holger Eichelberger, Sass
*/
@ArtifactCreator(DefaultJavaFileArtifactCreator.class)
public class JavaFileArtifact extends FileArtifact implements IJavaParent {
private static EASyLogger logger = EASyLoggerFactory.INSTANCE.getLogger(JavaFileArtifact.class, Bundle.ID);
private File file;
private CompilationUnit unitNode;
private List<JavaClass> classList;
private boolean changed = false;
/**
* Creates a new class file artifact.
*
* @param file
* the file to read the artifact contents from
* @param model
* the artifact model to create this folder artifact within
*/
JavaFileArtifact(File file, ArtifactModel model) {
super(file, model);
this.file = file;
// parse lazy on request
}
/**
* Returns the annotation value.
*
* @param annotation
* the name of the annotation type
* @param field
* the field to be returned
* @return the field or <b>null</b> if not found
*/
@Invisible
public String annotationValue(String annotation, String field) {
return ""; // TODO implement, if done, remove @Invisible annotation
}
/**
* Return whether one of the classes, the methods or attributes has this
* annotation.
*
* @param annotation
* the (qualified) name of the annotation
* @param field
* the name of the annotation field (if <b>null</b> or empty the
* {@link JavaAnnotation#DEFAULT_FIELD default name "value"} is
* used
* @param value
* the name of the annotation value
* @return <code>true</code> if this annotation is present,
* <code>false</code> else
*/
public boolean hasAnnotation(String annotation, String field, String value) {
Set<JavaClass> classes = this.classes();
boolean hasAnnotation = false;
if (null == field || 0 == field.length()) {
field = JavaAnnotation.DEFAULT_FIELD;
}
// TODO efficiency: directly rely on classList and cached structures in
// JavaAttribute and JavaMethod
for (JavaClass javaClass : classes) {
// Check the classes
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, javaClass.annotations());
if (hasAnnotation) {
break;
}
// Check attributes
Set<JavaAttribute> attributes = javaClass.attributes();
for (JavaAttribute javaAttribute : attributes) {
Set<JavaAnnotation> attributeAnnotations = javaAttribute.annotations();
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, attributeAnnotations);
if (hasAnnotation) {
break;
}
}
// Check methods
Set<JavaMethod> methods = javaClass.methods();
for (JavaMethod javaMethod : methods) {
Set<JavaAnnotation> methodAnnotation = javaMethod.annotations();
hasAnnotation = checkAnnotation(annotation, field, value, hasAnnotation, methodAnnotation);
if (hasAnnotation) {
break;
}
}
}
return hasAnnotation;
}
/**
* Checks if a Set of JavaAnnotations contains a specific annotation.
*
* @param annotation
* The annotation name
* @param field
* the name of the field
* @param value
* The annotation value
* @param hasAnnotation
* indicates if annotation is present
* @param annotations
* Set with JavaAnnotations
* @return hasAnnotation true of false
*/
private boolean checkAnnotation(String annotation, String field, String value, boolean hasAnnotation,
Set<JavaAnnotation> annotations) {
String simpleName = JavaAnnotation.toSimpleName(annotation); // as we do
// not
// resolve,
// we must
// be lazy
for (JavaAnnotation javaAnnotation : annotations) {
try {
if ((javaAnnotation.getQualifiedName().equals(annotation)
|| javaAnnotation.getName().equals(simpleName))
&& javaAnnotation.getAnnotationValue(field).equals(value)) {
hasAnnotation = true;
break;
}
} catch (VilException e) {
logger.exception(e);
}
}
return hasAnnotation;
}
@Override
public void artifactChanged(Object cause) throws VilException {
super.artifactChanged(cause);
if (cause instanceof Text && null != getText()) {
initialize(getText().getText().toCharArray());
} else {
initialize();
}
changed = false;
}
@Override
public void store() throws VilException {
// store changes in the representation if there are some, store tree
// afterwards
// both changes shall not overlap...
super.store();
if (changed) {
// Check if file exists
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
logger.exception(e);
}
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
String code = unitNode.toString();
Map<String, String> options = new HashMap<String, String>();
options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR,
JavaCore.INSERT);
options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR,
JavaCore.INSERT);
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0,
System.getProperty("line.separator"));
IDocument doc = new Document(code);
try {
if (null != textEdit) {
textEdit.apply(doc);
}
} catch (MalformedTreeException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
} catch (BadLocationException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
}
// Save output
try {
writer.write(doc.get());
} catch (IOException e) {
throw new VilException(e, VilException.ID_ARTIFACT_INTERNAL);
}
} catch (IOException e) {
throw new VilException(e, VilException.ID_IO);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new VilException(e, VilException.ID_IO);
}
}
changed = false;
}
}
/**
* Returns the classes of this java file.
*
* @return the annotations
*/
@OperationMeta(returnGenerics = JavaClass.class)
public Set<JavaClass> classes() {
if (null == classList) {
initialize();
}
return new ArraySet<JavaClass>(classList.toArray(new JavaClass[classList.size()]), JavaClass.class);
}
/**
* Returns the specified classes of this java file.
*
* @param name
* the name of the class
* @return the specified class or <b>null</b>
*/
public JavaClass getClassByName(String name) {
JavaClass result = null;
if (null == classList) {
initialize();
}
for (int c = 0; null == result && c < classList.size(); c++) {
JavaClass cls = classList.get(c);
try {
if (cls.getName().equals(name)) {
result = cls;
}
} catch (VilException e) {
logger.exception(e);
}
}
return result;
}
/**
* Returns the default class of this Java File artifact, i.e., the class
* corresponding to the name of this artifact.
*
* @return the default class or <b>null</b> if there is none
*/
public JavaClass getDefaultClass() {
JavaClass result;
try {
String name = getName();
if (name.endsWith(".java")) {
name = name.substring(0, name.length() - 5);
}
result = getClassByName(name);
} catch (VilException e) {
logger.exception(e);
result = null;
}
return result;
}
/**
* Initializes the parse tree / classes from {@link #file}.
*/
private void initialize() {
initialize(readFileToString(file).toCharArray());
}
/**
* Initializes the parse tree / classes.
*
* @param data
* the data to initialize from (source code as characters)
*/
private void initialize(char[] data) {
// TODO separate inner classes
classList = new ArrayList<JavaClass>();
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(data);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
// Set options to resolve bindings
parser.setBindingsRecovery(true);
parser.setResolveBindings(true);
Hashtable<String, String> options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
parser.setCompilerOptions(options);
String unitName = FilenameUtils.getBaseName(file.getName());
parser.setUnitName(unitName);
String[] classpath = JavaUtilities.JRE_CLASS_PATH;
String sourcePath;
boolean isClasspathFromScript = false;
if (null != getArtifactModel()) {
Object classPathFromScript = getArtifactModel().getSettings(JavaSettings.CLASSPATH);
if (null != classPathFromScript) {
isClasspathFromScript = true;
sourcePath = JavaSettingsInitializer.determineClasspath(classPathFromScript);
} else {
// if no classpath is given via VIL
sourcePath = JavaSettingsInitializer.determineClasspath(null);
}
} else {
sourcePath = JavaSettingsInitializer.determineClasspath(null);
}
// WORKAROUND! FIX IT!
if (sourcePath.contains("//")) {
sourcePath = sourcePath.replaceAll("//", "/");
}
String[] sources = {sourcePath};
System.out.println("CLASSPATH: " + sources);
parser.setEnvironment(classpath, sources, new String[] {"UTF-8" }, true);
// Create AST
unitNode = (CompilationUnit) parser.createAST(null);
// Check for problems but only if the classpath was set via VIL
if (isClasspathFromScript) {
IProblem[] problems = unitNode.getProblems();
if (problems != null && problems.length > 0) {
logger.warn("Got " + problems.length + " problems compiling the source file: "
+ file.getAbsolutePath());
for (IProblem problem : problems) {
logger.warn(problem.getMessage());
}
}
}
unitNode.accept(new ASTVisitor() {
public boolean visit(TypeDeclaration typeDeclaration) {
// The below code is used to check if it is not a top-level
// class
if (typeDeclaration.isPackageMemberTypeDeclaration()) {
classList.add(new JavaClass(typeDeclaration, JavaFileArtifact.this));
}
return true;
}
});
unitNode.recordModifications();
}
/**
* Reads a file to String.
*
* @param filePath
* The file path as String.
* @return File as String.
*/
@Invisible
public static String readFileToString(File filePath) {
// TODO check whether this can be replaced by related apache.commons
// method
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (FileNotFoundException fnf) {
logger.exception(fnf);
} catch (IOException ioe) {
logger.exception(ioe);
}
return fileData.toString();
}
@Override
public void notifyChildChanged(FragmentArtifact child) {
changed = true;
}
@Override
public void deleteChild(FragmentArtifact child) throws VilException {
// implement if substructures are stored / cached
}
/**
* Returns all imports.
*
* @return all imports
*/
@SuppressWarnings("unchecked")
@OperationMeta(returnGenerics = JavaImport.class)
public Set<JavaImport> imports() {
if (null == unitNode) {
initialize();
}
List<JavaImport> imports = new ArrayList<JavaImport>();
List<ImportDeclaration> unitNodeImports = unitNode.imports();
for (ImportDeclaration importDeclaration : unitNodeImports) {
JavaImport javaImport = new JavaImport(importDeclaration, JavaFileArtifact.this);
imports.add(javaImport);
}
return new ArraySet<JavaImport>(imports.toArray(new JavaImport[imports.size()]), JavaImport.class);
}
/**
* Returns the package declaration.
*
* @return {@link JavaPackage} representing the package declaration
*/
public JavaPackage javaPackage() {
if (null == unitNode) {
initialize();
}
JavaPackage javaPackage = new JavaPackage(unitNode.getPackage(), JavaFileArtifact.this);
return javaPackage;
}
/**
* Returns all qualified names.
*
* @return all qualified names.
*/
public Set<JavaQualifiedName> qualifiedNames() {
if (null == classList) {
initialize();
}
List<JavaQualifiedName> qualifiedNames = new ArrayList<JavaQualifiedName>();
for (JavaClass javaClass : classList) {
for (JavaQualifiedName javaQualifiedName : javaClass.qualifiedNames()) {
qualifiedNames.add(javaQualifiedName);
}
}
return new ArraySet<JavaQualifiedName>(qualifiedNames.toArray(new JavaQualifiedName[qualifiedNames.size()]),
JavaQualifiedName.class);
}
/**
* Renames all (qualified) package names, imports and packages in this Java
* artifact from <code>oldName</code> to <code>newName</code>. Nothing
* happens, if <code>oldName</code> cannot be found. However, the caller is
* responsible for potential name clashes due to the execution of this
* operation.
*
* @param oldName
* the old package name
* @param newName
* the new package name
*/
public void modifyNamespace(String oldName, String newName) {
try {
renameImports(oldName, newName);
renameQualifiedNames(oldName, newName);
renamePackages(oldName, newName);
store();
} catch (VilException e) {
logger.exception(e);
}
}
/**
* Renames all (qualified) package names, imports and packages in this Java
* artifact as stated by <code>nameMapping</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param nameMapping
* pairs of old and new package names (key = old, value = new)
*/
public void modifiyNamespace(Map<String, String> nameMapping) {
try {
renameImports(nameMapping);
renameQualifiedNames(nameMapping);
renamePackages(nameMapping);
store();
} catch (VilException e) {
logger.exception(e);
}
}
/**
* Renames all (qualified) package names in this Java artifact from
* <code>oldName</code> to <code>newName</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param oldName
* the old package name
* @param newName
* the new package name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renamePackages(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renamePackages(tmp);
}
/**
* Renames all (qualified) package names in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new package names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renamePackages(Map<String, String> nameMapping) throws VilException {
JavaPackage javaPackage = this.javaPackage();
String path = javaPackage.getName();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
javaPackage.rename(path.replace(entry.getKey(), entry.getValue()));
}
}
/**
* Renames all imports in this Java artifact from <code>oldName</code> to
* <code>newName</code>. Nothing happens, if <code>oldName</code> cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param oldName
* the old import name
* @param newName
* the new import name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameImports(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renameImports(tmp);
}
/**
* Renames all imports in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new import names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameImports(Map<String, String> nameMapping) throws VilException {
Set<JavaImport> imports = this.imports();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
for (JavaImport javaImport : imports) {
if (javaImport.getName().contains(entry.getKey())) {
javaImport.rename(javaImport.getName().replace(entry.getKey(), entry.getValue()));
}
}
}
}
/**
* Renames all qualified names in this Java artifact from
* <code>oldName</code> to <code>newName</code>. Nothing happens, if
* <code>oldName</code> cannot be found. However, the caller is responsible
* for potential name clashes due to the execution of this operation.
*
* @param oldName
* the old qualified name
* @param newName
* the new qualified name
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameQualifiedNames(String oldName, String newName) throws VilException {
Map<String, String> tmp = new HashMap<String, String>();
tmp.put(oldName, newName);
renameQualifiedNames(tmp);
}
/**
* Renames all qualified names in this Java artifact as stated by
* <code>nameMapping</code>. Nothing happens, if package names cannot be
* found. However, the caller is responsible for potential name clashes due
* to the execution of this operation.
*
* @param nameMapping
* pairs of old and new qualified names (key = old, value = new)
* @throws VilException
* in case that the operation cannot be executed due to syntax
* or I/O problems
*/
public void renameQualifiedNames(Map<String, String> nameMapping) throws VilException {
Set<JavaClass> classes = this.classes();
for (JavaClass javaClass : classes) {
Set<JavaQualifiedName> qualifiedNames = javaClass.qualifiedNames();
for (Map.Entry<String, String> entry : nameMapping.entrySet()) {
for (JavaQualifiedName javaQualifiedName : qualifiedNames) {
javaQualifiedName.rename(javaQualifiedName.getName().replace(entry.getKey(), entry.getValue()));
}
}
}
}
/**
* Conversion operation.
*
* @param val
* the value to be converted
* @return the converted value or null
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(IFileSystemArtifact val) {
JavaFileArtifact convertedValue = null;
if (val instanceof JavaFileArtifact) {
convertedValue = (JavaFileArtifact) val;
}
return convertedValue;
}
/**
* Conversion operation.
*
* @param val
* the value to be converted
* @return the converted value
* @throws VilException
* in case that creating the artifact fails
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(String val) throws VilException {
Path path = Path.convert(val);
return convert(path);
}
/**
* Conversion operation.
*
* @param path
* the path to be converted
* @return the converted value
* @throws VilException
* in case that creating the artifact fails
*/
@Invisible
@Conversion
public static JavaFileArtifact convert(Path path) throws VilException {
return ArtifactFactory.createArtifact(JavaFileArtifact.class, path.getAbsolutePath(), path.getArtifactModel());
}
}
| changed sysout to logger.warn | Plugins/Instantiation/Instantiator.Java/src/de/uni_hildesheim/sse/easy/java/artifacts/JavaFileArtifact.java | changed sysout to logger.warn | <ide><path>lugins/Instantiation/Instantiator.Java/src/de/uni_hildesheim/sse/easy/java/artifacts/JavaFileArtifact.java
<ide> sourcePath = sourcePath.replaceAll("//", "/");
<ide> }
<ide> String[] sources = {sourcePath};
<del> System.out.println("CLASSPATH: " + sources);
<add> logger.warn("CLASSPATH: " + sources);
<ide> parser.setEnvironment(classpath, sources, new String[] {"UTF-8" }, true);
<ide> // Create AST
<ide> unitNode = (CompilationUnit) parser.createAST(null); |
|
JavaScript | mit | e781a3940d8e073ad7fe65b436ea8fe8e9df1101 | 0 | johniek/meteor-rock,johniek/meteor-rock | a019046e-306c-11e5-9929-64700227155b | helloWorld.js | a0168eb4-306c-11e5-9929-64700227155b | a019046e-306c-11e5-9929-64700227155b | helloWorld.js | a019046e-306c-11e5-9929-64700227155b | <ide><path>elloWorld.js
<del>a0168eb4-306c-11e5-9929-64700227155b
<add>a019046e-306c-11e5-9929-64700227155b |
|
JavaScript | agpl-3.0 | a5f69fdee2e253a3355937f7246ea01ddd45b563 | 0 | pyraxo/haru | module.exports = {
type: 'role',
resolve: (content, { includeEveryone = true }, msg) => {
const guild = msg.guild
content = String(content).toLowerCase()
let role = content.match(/^<@&(\d{17,18})>$/)
if (!role) {
let roles = guild.roles.filter(r => {
const name = r.name.toLowerCase()
return (name === content || name.includes(content)) && (name === '@everyone' ? includeEveryone : true)
})
if (roles.length) {
return Promise.resolve(roles)
} else {
return Promise.reject('role.NOT_FOUND')
}
} else {
let r = guild.roles.get(role[1])
if (!r) return Promise.reject('role.NOT_FOUND')
return Promise.resolve([r])
}
}
}
| src/core/managers/resolvers/role.js | module.exports = {
type: 'role',
resolve: (content, { includeEveryone = true }, msg) => {
const guild = msg.guild
content = String(content).toLowerCase()
let role = content.match(/^<@&(\d{17,18})>$/)
if (!role) {
let roles = guild.roles.filter(r => {
const name = r.name.toLowerCase()
return name === content || name.includes(content) && name === '@everyone' ? includeEveryone : true
})
if (roles.length) {
return Promise.resolve(roles)
} else {
return Promise.reject('role.NOT_FOUND')
}
} else {
let r = guild.roles.get(role[1])
if (!r) return Promise.reject('role.NOT_FOUND')
return Promise.resolve([r])
}
}
}
| :bug: Fix role resolver
| src/core/managers/resolvers/role.js | :bug: Fix role resolver | <ide><path>rc/core/managers/resolvers/role.js
<ide> if (!role) {
<ide> let roles = guild.roles.filter(r => {
<ide> const name = r.name.toLowerCase()
<del> return name === content || name.includes(content) && name === '@everyone' ? includeEveryone : true
<add> return (name === content || name.includes(content)) && (name === '@everyone' ? includeEveryone : true)
<ide> })
<ide> if (roles.length) {
<ide> return Promise.resolve(roles) |
|
Java | mit | f56885330b2da68983ddec33d777dcf313908b32 | 0 | phdelodder/SubTools | package org.lodder.subtools.multisubdownloader.gui.dialog.progress.search;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
import org.lodder.subtools.multisubdownloader.gui.dialog.Cancelable;
import org.lodder.subtools.multisubdownloader.gui.dialog.MultiSubDialog;
import org.lodder.subtools.multisubdownloader.subtitleproviders.SubtitleProvider;
import org.lodder.subtools.sublibrary.model.Release;
public class SearchProgressDialog extends MultiSubDialog implements SearchProgressListener {
private final Cancelable searchAction;
private SearchProgressTableModel tableModel;
private JProgressBar progressBar;
public SearchProgressDialog(JFrame frame, Cancelable searchAction) {
super(frame, "Searching", false);
this.searchAction = searchAction;
initialize_ui();
setDialogLocation(frame);
repaint();
this.setVisible(true);
}
@Override
public void progress(SubtitleProvider provider, int jobsLeft, Release release) {
this.tableModel.update(provider.getName(), jobsLeft, (release == null ? "Done" : release.getFilename()));
}
@Override
public void progress(int progress) {
if (progress == 0) {
this.progressBar.setIndeterminate(true);
} else {
this.progressBar.setIndeterminate(false);
this.progressBar.setValue(progress);
this.progressBar.setString(Integer.toString(progress));
}
}
private void initialize_ui() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
searchAction.cancel(true);
}
});
setBounds(100, 100, 601, 300);
getContentPane().setLayout(new MigLayout("", "[grow,fill][]", "[][][]"));
this.tableModel = new SearchProgressTableModel();
JTable table = new JTable(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(150);
table.getColumnModel().getColumn(1).setMaxWidth(50);
JScrollPane tablePane = new JScrollPane(table);
tablePane.setViewportView(table);
getContentPane().add(tablePane, "cell 0 0 2 1");
progressBar = new JProgressBar(0, 100);
progressBar.setIndeterminate(true);
getContentPane().add(progressBar, "cell 0 1 2 1,grow");
JButton btnStop = new JButton("Stop!");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
searchAction.cancel(true);
}
});
getContentPane().add(btnStop, "cell 1 2,alignx left");
}
}
| MultiSubDownloader/src/main/java/org/lodder/subtools/multisubdownloader/gui/dialog/progress/search/SearchProgressDialog.java | package org.lodder.subtools.multisubdownloader.gui.dialog.progress.search;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
import org.lodder.subtools.multisubdownloader.gui.dialog.Cancelable;
import org.lodder.subtools.multisubdownloader.gui.dialog.MultiSubDialog;
import org.lodder.subtools.multisubdownloader.subtitleproviders.SubtitleProvider;
import org.lodder.subtools.sublibrary.model.Release;
public class SearchProgressDialog extends MultiSubDialog implements SearchProgressListener {
private final Cancelable searchAction;
private SearchProgressTableModel tableModel;
private JProgressBar progressBar;
public SearchProgressDialog(JFrame frame, Cancelable searchAction) {
super(frame, "Searching", false);
this.searchAction = searchAction;
initialize_ui();
setDialogLocation(frame);
repaint();
this.setVisible(true);
}
@Override
public void progress(SubtitleProvider provider, int jobsLeft, Release release) {
this.tableModel.update(provider.getName(), jobsLeft, (release == null ? "Done" : release.getFilename()));
}
@Override
public void progress(int progress) {
if (progress == 0) {
this.progressBar.setIndeterminate(true);
} else {
this.progressBar.setIndeterminate(false);
this.progressBar.setValue(progress);
this.progressBar.setString(Integer.toString(progress));
}
}
private void initialize_ui() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
searchAction.cancel(true);
}
});
setBounds(100, 100, 601, 300);
getContentPane().setLayout(new MigLayout());
this.tableModel = new SearchProgressTableModel();
JTable table = new JTable(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(150);
table.getColumnModel().getColumn(1).setMaxWidth(50);
JScrollPane tablePane = new JScrollPane(table);
tablePane.setViewportView(table);
getContentPane().add(tablePane, "wrap");
progressBar = new JProgressBar(0, 100);
progressBar.setIndeterminate(true);
getContentPane().add(progressBar, "grow, wrap");
JButton btnStop = new JButton("Stop!");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
searchAction.cancel(true);
}
});
getContentPane().add(btnStop, "alignx left");
}
}
| Small adjustment to the UI, stop button to right and table fill the
complete dialog | MultiSubDownloader/src/main/java/org/lodder/subtools/multisubdownloader/gui/dialog/progress/search/SearchProgressDialog.java | Small adjustment to the UI, stop button to right and table fill the complete dialog | <ide><path>ultiSubDownloader/src/main/java/org/lodder/subtools/multisubdownloader/gui/dialog/progress/search/SearchProgressDialog.java
<ide> }
<ide> });
<ide> setBounds(100, 100, 601, 300);
<del> getContentPane().setLayout(new MigLayout());
<add> getContentPane().setLayout(new MigLayout("", "[grow,fill][]", "[][][]"));
<ide>
<ide> this.tableModel = new SearchProgressTableModel();
<ide> JTable table = new JTable(tableModel);
<ide>
<ide> JScrollPane tablePane = new JScrollPane(table);
<ide> tablePane.setViewportView(table);
<del> getContentPane().add(tablePane, "wrap");
<add> getContentPane().add(tablePane, "cell 0 0 2 1");
<ide>
<ide> progressBar = new JProgressBar(0, 100);
<ide> progressBar.setIndeterminate(true);
<del> getContentPane().add(progressBar, "grow, wrap");
<del>
<del> JButton btnStop = new JButton("Stop!");
<del> btnStop.addActionListener(new ActionListener() {
<del> public void actionPerformed(ActionEvent arg0) {
<del> searchAction.cancel(true);
<del> }
<del> });
<del> getContentPane().add(btnStop, "alignx left");
<add> getContentPane().add(progressBar, "cell 0 1 2 1,grow");
<add>
<add> JButton btnStop = new JButton("Stop!");
<add> btnStop.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent arg0) {
<add> searchAction.cancel(true);
<add> }
<add> });
<add> getContentPane().add(btnStop, "cell 1 2,alignx left");
<ide> }
<ide> } |
|
JavaScript | mit | 90932fcfecb3a58cdc38eae1edae9d2e70269a7b | 0 | bobbybee/scratch-llvm,trumank/scratch-llvm,bobbybee/scratch-llvm,trumank/scratch-llvm,bobbybee/scratch-llvm,trumank/scratch-llvm | // takes an IR function object and returns a list of Scratch blocks
module.exports.ffi = {};
module.exports.generateFunctionHat = function(functionContext, func) {
var spec = func.funcName;
var inputs = [];
var defaults = [];
functionContext.params = [];
for(var i = 0; i < func.paramList.length; ++i) {
var pName = "param" + i;
if(func.paramList[i][1])
pName = func.paramList[i][1];
inputs.push(pName);
functionContext.params.push(pName);
defaults.push(defaultForType(func.paramList[i][0]));
spec += " "+specifierForType(func.paramList[i][0]);
}
return ["procDef", spec, inputs, defaults, false];
}
module.exports.compileFunction = function(func, IR) {
console.log("Compiling "+JSON.stringify(func)+"...");
var functionContext = {
locals: {},
globalLocalDepth: 0,
scopedLocalDepth: 0,
params: [],
gotoInit: false,
globalToFree: 0,
scopeToFree: 0,
scoped: false,
globals: IR.globals,
rootGlobal: IR.rootGlobal
}
var blockList = [module.exports.generateFunctionHat(functionContext, func)];
if(func.inGotoComplex) {
blockList = blockList.concat(initGotoComplex());
}
for(var i = 0; i < func.code.length;) {
console.log(func.code[i]);
var iGain = 1;
var hasGotoComplex = functionContext.gotoComplex && functionContext.gotoComplex.okToUse && functionContext.gotoComplex.active; // this MUST be before compileInstruction for branching to work
// optimize out alloca calls
if(func.code[i].type == "set" && func.code[i].computation == [] && func.code[i].value == 0 &&
func.code[i+1].type == "store" && func.code[i+1].destination.value == func.code[i].name) {
func.code[i].value = func.code[i+1].src.value;
iGain++;
}
// optimize out icmp in conditional branch
if(func.code[i].type == "set" && func.code[i].val.type == "comparison" &&
func.code[i+1].type == "branch" && func.code[i+1].conditional && func.code[i+1].condition == func.code[i].name) {
func.code[i] = {
type: "branch",
conditional: true,
dest: func.code[i+1].dest,
falseDest: func.code[i+1].falseDest,
condition: icmpBlock(functionContext, func.code[i]),
rawCondition: true
};
iGain++;
}
var instruction = compileInstruction(functionContext, func.code[i]);
if(!functionContext.gotoInit && functionContext.gotoComplex && functionContext.gotoComplex.okToUse) {
blockList = blockList.concat([functionContext.gotoComplex.forever]);
functionContext.gotoInit = true;
}
if(hasGotoComplex) {
if(functionContext.gotoComplex.currentContext[2]) {
functionContext.gotoComplex.currentContext[2] =
functionContext.gotoComplex.currentContext[2].concat(instruction);
} else {
functionContext.gotoComplex.currentContext[2] = instruction;
}
} else {
blockList = blockList.concat(instruction);
}
i += iGain;
}
//blockList = blockList.concat(returnBlock());
return blockList;
}
function compileInstruction(ctx, block) {
if(block.type == "call") {
// calling a (potentially foreign) function
return callBlock(ctx, block);
} else if(block.type == "ffi") {
// FFI block
// load the code from the options
return module.exports.ffi[block.ffiBlock];
} else if(block.type == "set") {
var val = 0;
console.log("SET: "+JSON.stringify(block));
if(block.val.type == "return value") {
val = ["readVariable", "return value"];
} else if(block.val.type == "variable") {
val = fetchByName(ctx, block.val.name);
} else if(block.val.type == "arithmetic") {
val = [block.val.operation, fetchByName(ctx, block.val.operand1), fetchByName(ctx, block.val.operand2)];
} else if(block.val.type == "comparison") {
val = icmpBlock(ctx, val);
} else if(block.val.type == "sext") {
val = signExtend(ctx, block.val);
} else if(block.val.type == "addressOf") { // todo: full getelementptr implementation
val = addressOf(ctx, block.val.base.name);
}
return compileInstruction(ctx, block.computation)
.concat(allocateLocal(ctx, val, block.name));
} else if(block.type == "ret") {
return returnBlock(ctx, block.value);
} else if(block.type == "store") {
return dereferenceAndSet(ctx, block.destination.value, block.src.value);
} else if(block.type == "gotoComplex") {
ctx.gotoComplex = {
context: [],
okToUse: false,
forever: ["doForever", []],
active: true
}
//return [ctx.gotoComplex.forever];
} else if(block.type == "label") {
if(ctx.scoped) {
ctx.gotoComplex.currentContext[2] =
ctx.gotoComplex.currentContext[2].concat(freeLocals(ctx));
}
ctx.scoped = true;
var chunk = ["doIfElse", ["=", getCurrentLabel(), block.label], [], []];
ctx.gotoComplex.okToUse = true;
ctx.gotoComplex.active = true;
if(ctx.gotoComplex.currentContext) {
ctx.gotoComplex.currentContext[3] = [chunk];
ctx.gotoComplex.currentContext = ctx.gotoComplex.currentContext[3][0];
} else {
ctx.gotoComplex.currentContext = chunk;
ctx.gotoComplex.context = ctx.gotoComplex.currentContext;
ctx.gotoComplex.forever[1] = [ctx.gotoComplex.context];
}
} else if(block.type == "branch") {
ctx.gotoComplex.active = false;
if(block.conditional) {
var cond = block.rawCondition ? block.condition : ["=", fetchByName(ctx, block.condition), 1];
return [
["doIfElse", cond, absoluteBranch(block.dest.slice(1)), absoluteBranch(block.falseDest.slice(1))]
];
} else {
return absoluteBranch(block.dest);
}
}
return [];
}
// fixme: stub
function defaultForType(type) {
console.log(type);
return 0;
}
// fixme: stub
function specifierForType(type) {
return "%s";
}
// fixme: stub
function formatValue(ctx, type, value) {
console.log("FORMAT: "+type+","+value);
if(typeof value == "object") {
if(value.type == "getelementptr") {
// fixme: necessary and proper implementation
return addressOf(ctx, value.base.val);
}
}
if(value[0] == '%') {
return fetchByName(ctx, value);
}
return value;
}
function getOffset(ctx, value) {
return ctx.globalLocalDepth + ctx.scopedLocalDepth - ctx.locals[value];
}
function stackPtr() {
return ["readVariable", "sp"];
}
function stackPosFromOffset(offset) {
// optimize zero-index
/*if(offset == 0) {
return stackPtr();
}*/
return ["+", stackPtr(), offset + 1];
}
// higher-level code generation
function allocateLocal(ctx, val, name) {
if(name) {
console.log(name+","+val);
var depth = 0;
if(ctx.scoped) {
depth = ctx.globalLocalDepth + (++ctx.scopedLocalDepth);
} else {
depth = ctx.globalLocalDepth;
}
ctx.locals[name] = depth;
}
ctx.globalToFree++;
if(ctx.scoped) {
ctx.scopeToFree++;
}
return [
["setLine:ofList:to:", stackPtr(), "DATA", val],
["changeVar:by:", "sp", -1]
];
}
function freeStack(num) {
console.log("Freeing stack");
return [
["changeVar:by:", "sp", num]
//["doRepeat", num, [["deleteLine:ofList:", "last", "Stack"]]],
];
}
function freeLocals(ctx) {
var numToFree = ctx.globalToFree;
if(ctx.scoped) {
numToFree = ctx.scopeToFree;
ctx.scopeToFree = 0;
ctx.scopedLocalDepth = 0;
}
return freeStack(numToFree);
}
function fetchByName(ctx, n) {
if(ctx.locals[n] !== undefined)
return ["getLine:ofList:", stackPosFromOffset(getOffset(ctx, n)), "DATA"];
else if(ctx.params.indexOf(n) > -1)
return ["getParam", n, "r"];
else if( (n * 1) == n)
return n
else
console.log("fetchByName undefined "+n);
console.log(ctx.locals);
return ["undefined"];
}
function addressOf(ctx, n) {
console.log(ctx.rootGlobal[n.slice(1)]);
if(ctx.rootGlobal[n.slice(1)])
return ctx.rootGlobal[n.slice(1)].ptr;
else
console.log("addressOf undefined "+n);
return ["undefined"];
}
function returnBlock(ctx, val) {
var proc = freeLocals(ctx);
if(ctx.gotoComplex) {
proc = proc.concat(cleanGotoComplex());
}
if(val) {
proc.push(["setVar:to:", "return value", formatValue(ctx, val[0], val[1])]);
}
proc.push(["stopScripts", "this script"]);
return proc;
}
function callBlock(ctx, block) {
var spec = block.funcName;
var args = [];
for(var a = 0; a < block.paramList.length; ++a) {
args.push(formatValue(ctx, block.paramList[a][0], block.paramList[a][1]));
spec += " "+specifierForType(block.paramList[a][0]);
}
return [
["call", spec].concat(args)
];
}
// TODO: more robust implementation to support heap
function dereferenceAndSet(ctx, ptr, content) {
return [
[
"setLine:ofList:to:",
stackPosFromOffset(getOffset(ctx, ptr)),
"DATA",
fetchByName(ctx, content)
]
];
}
function specForComparison(comp) {
if(comp == "eq") {
return "=";
} else if(comp == "ne") {
return "!=";
} else if(comp == "slt" || comp == "ult") {
return "<";
} else if(comp == "sgt" || comp == "ugt") {
return ">";
}
return "undefined";
}
function initGotoComplex() {
return [
["append:toList:", 0, "Label Stack"]
];
}
function getCurrentLabel() {
return ["getLine:ofList:", "last", "Label Stack"];
}
function cleanGotoComplex() {
return [
["deleteLine:ofList:", "last", "Label Stack"]
];
}
function absoluteBranch(dest) {
return [
["setLine:ofList:to:", "last", "Label Stack", dest]
];
}
function castToNumber(b) {
return ["*", b, 1];
}
function icmpBlock(ctx, block) {
var spec = specForComparison(block.val.operation);
var negate = false;
if(spec[0] == "!") {
negate = true;
spec = spec.slice(1);
}
var b = [spec, fetchByName(ctx, block.val.left), fetchByName(ctx, block.val.right)];
if(negate) {
b = ["not", b];
}
return castToNumber(b);
}
function signExtend(ctx, block) {
// TODO: once we support typing correctly, sign extend will need a proper implementation too
return [fetchByName(block.source)];
} | backend.js | // takes an IR function object and returns a list of Scratch blocks
module.exports.ffi = {};
module.exports.generateFunctionHat = function(functionContext, func) {
var spec = func.funcName;
var inputs = [];
var defaults = [];
functionContext.params = [];
for(var i = 0; i < func.paramList.length; ++i) {
var pName = "param" + i;
if(func.paramList[i][1])
pName = func.paramList[i][1];
inputs.push(pName);
functionContext.params.push(pName);
defaults.push(defaultForType(func.paramList[i][0]));
spec += " "+specifierForType(func.paramList[i][0]);
}
return ["procDef", spec, inputs, defaults, false];
}
module.exports.compileFunction = function(func, IR) {
console.log("Compiling "+JSON.stringify(func)+"...");
var functionContext = {
locals: {},
globalLocalDepth: 0,
scopedLocalDepth: 0,
params: [],
gotoInit: false,
globalToFree: 0,
scopeToFree: 0,
scoped: false,
globals: IR.globals,
rootGlobal: IR.rootGlobal
}
var blockList = [module.exports.generateFunctionHat(functionContext, func)];
if(func.inGotoComplex) {
blockList = blockList.concat(initGotoComplex());
}
for(var i = 0; i < func.code.length;) {
console.log(func.code[i]);
var iGain = 1;
var hasGotoComplex = functionContext.gotoComplex && functionContext.gotoComplex.okToUse && functionContext.gotoComplex.active; // this MUST be before compileInstruction for branching to work
// optimize out alloca calls
if(func.code[i].type == "set" && func.code[i].computation == [] && func.code[i].value == 0 &&
func.code[i+1].type == "store" && func.code[i+1].destination.value == func.code[i].name) {
func.code[i].value = func.code[i+1].src.value;
iGain++;
}
// optimize out icmp in conditional branch
if(func.code[i].type == "set" && func.code[i].val.type == "comparison" &&
func.code[i+1].type == "branch" && func.code[i+1].conditional && func.code[i+1].condition == func.code[i].name) {
func.code[i] = {
type: "branch",
conditional: true,
dest: func.code[i+1].dest,
falseDest: func.code[i+1].falseDest,
condition: icmpBlock(functionContext, func.code[i]),
rawCondition: true
};
iGain++;
}
var instruction = compileInstruction(functionContext, func.code[i]);
if(!functionContext.gotoInit && functionContext.gotoComplex && functionContext.gotoComplex.okToUse) {
blockList = blockList.concat([functionContext.gotoComplex.forever]);
functionContext.gotoInit = true;
}
if(hasGotoComplex) {
if(functionContext.gotoComplex.currentContext[2]) {
functionContext.gotoComplex.currentContext[2] =
functionContext.gotoComplex.currentContext[2].concat(instruction);
} else {
functionContext.gotoComplex.currentContext[2] = instruction;
}
} else {
blockList = blockList.concat(instruction);
}
i += iGain;
}
//blockList = blockList.concat(returnBlock());
return blockList;
}
function compileInstruction(ctx, block) {
if(block.type == "call") {
// calling a (potentially foreign) function
return callBlock(ctx, block);
} else if(block.type == "ffi") {
// FFI block
// load the code from the options
return module.exports.ffi[block.ffiBlock];
} else if(block.type == "set") {
var val = 0;
console.log("SET: "+JSON.stringify(block));
if(block.val.type == "return value") {
val = ["readVariable", "return value"];
} else if(block.val.type == "variable") {
val = fetchByName(ctx, block.val.name);
} else if(block.val.type == "arithmetic") {
val = [block.val.operation, fetchByName(ctx, block.val.operand1), fetchByName(ctx, block.val.operand2)];
} else if(block.val.type == "comparison") {
val = icmpBlock(ctx, val);
} else if(block.val.type == "sext") {
val = signExtend(ctx, block.val);
}
return compileInstruction(ctx, block.computation)
.concat(allocateLocal(ctx, val, block.name));
} else if(block.type == "ret") {
return returnBlock(ctx, block.value);
} else if(block.type == "store") {
return dereferenceAndSet(ctx, block.destination.value, block.src.value);
} else if(block.type == "gotoComplex") {
ctx.gotoComplex = {
context: [],
okToUse: false,
forever: ["doForever", []],
active: true
}
//return [ctx.gotoComplex.forever];
} else if(block.type == "label") {
if(ctx.scoped) {
ctx.gotoComplex.currentContext[2] =
ctx.gotoComplex.currentContext[2].concat(freeLocals(ctx));
}
ctx.scoped = true;
var chunk = ["doIfElse", ["=", getCurrentLabel(), block.label], [], []];
ctx.gotoComplex.okToUse = true;
ctx.gotoComplex.active = true;
if(ctx.gotoComplex.currentContext) {
ctx.gotoComplex.currentContext[3] = [chunk];
ctx.gotoComplex.currentContext = ctx.gotoComplex.currentContext[3][0];
} else {
ctx.gotoComplex.currentContext = chunk;
ctx.gotoComplex.context = ctx.gotoComplex.currentContext;
ctx.gotoComplex.forever[1] = [ctx.gotoComplex.context];
}
} else if(block.type == "branch") {
ctx.gotoComplex.active = false;
if(block.conditional) {
var cond = block.rawCondition ? block.condition : ["=", fetchByName(ctx, block.condition), 1];
return [
["doIfElse", cond, absoluteBranch(block.dest.slice(1)), absoluteBranch(block.falseDest.slice(1))]
];
} else {
return absoluteBranch(block.dest);
}
}
return [];
}
// fixme: stub
function defaultForType(type) {
console.log(type);
return 0;
}
// fixme: stub
function specifierForType(type) {
return "%s";
}
// fixme: stub
function formatValue(ctx, type, value) {
console.log("FORMAT: "+type+","+value);
if(typeof value == "object") {
if(value.type == "getelementptr") {
// fixme: necessary and proper implementation
return addressOf(ctx, value.base.val);
}
}
if(value[0] == '%') {
return fetchByName(ctx, value);
}
return value;
}
function getOffset(ctx, value) {
return ctx.globalLocalDepth + ctx.scopedLocalDepth - ctx.locals[value];
}
function stackPtr() {
return ["readVariable", "sp"];
}
function stackPosFromOffset(offset) {
// optimize zero-index
/*if(offset == 0) {
return stackPtr();
}*/
return ["+", stackPtr(), offset + 1];
}
// higher-level code generation
function allocateLocal(ctx, val, name) {
if(name) {
console.log(name+","+val);
var depth = 0;
if(ctx.scoped) {
depth = ctx.globalLocalDepth + (++ctx.scopedLocalDepth);
} else {
depth = ctx.globalLocalDepth;
}
ctx.locals[name] = depth;
}
ctx.globalToFree++;
if(ctx.scoped) {
ctx.scopeToFree++;
}
return [
["setLine:ofList:to:", stackPtr(), "DATA", val],
["changeVar:by:", "sp", -1]
];
}
function freeStack(num) {
console.log("Freeing stack");
return [
["changeVar:by:", "sp", num]
//["doRepeat", num, [["deleteLine:ofList:", "last", "Stack"]]],
];
}
function freeLocals(ctx) {
var numToFree = ctx.globalToFree;
if(ctx.scoped) {
numToFree = ctx.scopeToFree;
ctx.scopeToFree = 0;
ctx.scopedLocalDepth = 0;
}
return freeStack(numToFree);
}
function fetchByName(ctx, n) {
if(ctx.locals[n] !== undefined)
return ["getLine:ofList:", stackPosFromOffset(getOffset(ctx, n)), "DATA"];
else if(ctx.params.indexOf(n) > -1)
return ["getParam", n, "r"];
else if( (n * 1) == n)
return n
else
console.log("fetchByName undefined "+n);
console.log(ctx.locals);
return ["undefined"];
}
function addressOf(ctx, n) {
console.log(ctx.rootGlobal[n.slice(1)]);
if(ctx.rootGlobal[n.slice(1)])
return ctx.rootGlobal[n.slice(1)].ptr;
else
console.log("addressOf undefined "+n);
return ["undefined"];
}
function returnBlock(ctx, val) {
var proc = freeLocals(ctx);
if(ctx.gotoComplex) {
proc = proc.concat(cleanGotoComplex());
}
if(val) {
proc.push(["setVar:to:", "return value", formatValue(ctx, val[0], val[1])]);
}
proc.push(["stopScripts", "this script"]);
return proc;
}
function callBlock(ctx, block) {
var spec = block.funcName;
var args = [];
for(var a = 0; a < block.paramList.length; ++a) {
args.push(formatValue(ctx, block.paramList[a][0], block.paramList[a][1]));
spec += " "+specifierForType(block.paramList[a][0]);
}
return [
["call", spec].concat(args)
];
}
// TODO: more robust implementation to support heap
function dereferenceAndSet(ctx, ptr, content) {
return [
[
"setLine:ofList:to:",
stackPosFromOffset(getOffset(ctx, ptr)),
"DATA",
fetchByName(ctx, content)
]
];
}
function specForComparison(comp) {
if(comp == "eq") {
return "=";
} else if(comp == "ne") {
return "!=";
} else if(comp == "slt" || comp == "ult") {
return "<";
} else if(comp == "sgt" || comp == "ugt") {
return ">";
}
return "undefined";
}
function initGotoComplex() {
return [
["append:toList:", 0, "Label Stack"]
];
}
function getCurrentLabel() {
return ["getLine:ofList:", "last", "Label Stack"];
}
function cleanGotoComplex() {
return [
["deleteLine:ofList:", "last", "Label Stack"]
];
}
function absoluteBranch(dest) {
return [
["setLine:ofList:to:", "last", "Label Stack", dest]
];
}
function castToNumber(b) {
return ["*", b, 1];
}
function icmpBlock(ctx, block) {
var spec = specForComparison(block.val.operation);
var negate = false;
if(spec[0] == "!") {
negate = true;
spec = spec.slice(1);
}
var b = [spec, fetchByName(ctx, block.val.left), fetchByName(ctx, block.val.right)];
if(negate) {
b = ["not", b];
}
return castToNumber(b);
}
function signExtend(ctx, block) {
// TODO: once we support typing correctly, sign extend will need a proper implementation too
return [fetchByName(block.source)];
} | Main getelementptr backend
| backend.js | Main getelementptr backend | <ide><path>ackend.js
<ide> val = icmpBlock(ctx, val);
<ide> } else if(block.val.type == "sext") {
<ide> val = signExtend(ctx, block.val);
<add> } else if(block.val.type == "addressOf") { // todo: full getelementptr implementation
<add> val = addressOf(ctx, block.val.base.name);
<ide> }
<ide>
<ide> return compileInstruction(ctx, block.computation) |
|
Java | apache-2.0 | 284a6c07dfac5849cd7f8d0c488be29abd666b30 | 0 | apache/derby,apache/derby,apache/derby,apache/derby,trejkaz/derby,trejkaz/derby,trejkaz/derby | /*
Derby - Class org.apache.derby.iapi.types.SQLChar
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.derby.iapi.types;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.io.Storable;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.services.io.StreamStorable;
import org.apache.derby.iapi.services.io.FormatIdInputStream;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derby.iapi.types.NumberDataValue;
import org.apache.derby.iapi.types.BooleanDataValue;
import org.apache.derby.iapi.types.ConcatableDataValue;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.jdbc.CharacterStreamDescriptor;
import org.apache.derby.iapi.services.cache.ClassSize;
import org.apache.derby.iapi.services.io.ArrayInputStream;
import org.apache.derby.iapi.services.io.InputStreamUtil;
import org.apache.derby.iapi.util.StringUtil;
import org.apache.derby.iapi.util.UTF8Util;
import org.apache.derby.iapi.services.i18n.LocaleFinder;
import org.apache.derby.iapi.db.DatabaseContext;
import org.apache.derby.iapi.types.SQLInteger;
import org.apache.derby.iapi.types.SQLDate;
import org.apache.derby.iapi.types.SQLTime;
import org.apache.derby.iapi.types.SQLTimestamp;
import java.io.InputStream;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import java.io.UTFDataFormatException;
import java.io.EOFException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.RuleBasedCollator;
import java.text.CollationKey;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Calendar;
/**
The SQLChar represents a CHAR value with UCS_BASIC collation.
SQLChar may be used directly by any code when it is guaranteed
that the required collation is UCS_BASIC, e.g. system columns.
<p>
The state may be in char[], a String, a Clob, or an unread stream, depending
on how the datatype was created.
<p>
Stream notes:
<p>
When the datatype comes from the database layer and the length of the bytes
necessary to store the datatype on disk exceeds the size of a page of the
container holding the data then the store returns a stream rather than reading
all the bytes into a char[] or String. The hope is that the usual usage case
is that data never need be expanded in the derby layer, and that client can
just be given a stream that can be read a char at a time through the jdbc
layer. Even though SQLchar's can't ever be this big, this code is shared
by all the various character datatypes including SQLClob which is expected
to usually larger than a page.
<p>
The state can also be a stream in the case of insert/update where the client
has used a jdbc interface to set the value as a stream rather than char[].
In this case the hope is that the usual usage case is that stream never need
be read until it is passed to store, read once, and inserted into the database.
**/
public class SQLChar
extends DataType implements StringDataValue, StreamStorable
{
/**************************************************************************
* static fields of the class
**************************************************************************
*/
/**
* The pad character (space).
*/
private static final char PAD = '\u0020';
/**
* threshold, that decides when we return space back to the VM
* see getString() where it is used
*/
protected final static int RETURN_SPACE_THRESHOLD = 4096;
/**
* when we know that the array needs to grow by at least
* one byte, it is not performant to grow by just one byte
* instead this amount is used to provide a reasonable growby size.
*/
private final static int GROWBY_FOR_CHAR = 64;
private static final int BASE_MEMORY_USAGE =
ClassSize.estimateBaseFromCatalog( SQLChar.class);
/**
Static array that can be used for blank padding.
*/
private static final char[] BLANKS = new char[40];
static {
for (int i = 0; i < BLANKS.length; i++) {
BLANKS[i] = ' ';
}
}
/**
* Stream header generator for CHAR, VARCHAR and LONG VARCHAR. Currently,
* only one header format is used for these data types.
*/
protected static final StreamHeaderGenerator CHAR_HEADER_GENERATOR =
new CharStreamHeaderGenerator();
/**************************************************************************
* Fields of the class
**************************************************************************
*/
/*
* object state
*/
// Don't use value directly in most situations. Use getString()
// OR use the rawData array if rawLength != -1.
private String value;
// rawData holds the reusable array for reading in SQLChars. It contains a
// valid value if rawLength is greater than or equal to 0. See getString()
// to see how it is converted to a String. Even when converted to a String
// object the rawData array remains for potential future use, unless
// rawLength is > 4096. In this case the rawData is set to null to avoid
// huge memory use.
private char[] rawData;
private int rawLength = -1;
// For null strings, cKey = null.
private CollationKey cKey;
/**
* The value as a user-created Clob
*/
protected Clob _clobValue;
/**
* The value as a stream in the on-disk format.
*/
InputStream stream;
/* Locale info (for International support) */
private LocaleFinder localeFinder;
/**************************************************************************
* Constructors for This class:
**************************************************************************
*/
/**
* no-arg constructor, required by Formattable.
**/
public SQLChar()
{
}
public SQLChar(String val)
{
value = val;
}
public SQLChar(Clob val)
{
setValue( val );
}
/**************************************************************************
* Private/Protected methods of This class:
**************************************************************************
*/
private static void appendBlanks(char[] ca, int offset, int howMany)
{
while (howMany > 0)
{
int count = howMany > BLANKS.length ? BLANKS.length : howMany;
System.arraycopy(BLANKS, 0, ca, offset, count);
howMany -= count;
offset += count;
}
}
/**************************************************************************
* Public Methods of This class:
**************************************************************************
*/
/**************************************************************************
* Public Methods of DataValueDescriptor interface:
* Mostly implemented in Datatype.
**************************************************************************
*/
/**
* Get Boolean from a SQLChar.
*
* <p>
* Return false for only "0" or "false" for false. No case insensitivity.
* Everything else is true.
* <p>
* The above matches JCC.
*
*
* @see DataValueDescriptor#getBoolean
*
* @exception StandardException Thrown on error
**/
public boolean getBoolean()
throws StandardException
{
if (isNull())
return false;
// match JCC, match only "0" or "false" for false. No case
// insensitivity. everything else is true.
String cleanedValue = getString().trim();
return !(cleanedValue.equals("0") || cleanedValue.equals("false"));
}
/**
* Get Byte from a SQLChar.
*
* <p>
* Uses java standard Byte.parseByte() to perform coercion.
*
* @see DataValueDescriptor#getByte
*
* @exception StandardException thrown on failure to convert
**/
public byte getByte() throws StandardException
{
if (isNull())
return (byte)0;
try
{
return Byte.parseByte(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "byte");
}
}
/**
* Get Short from a SQLChar.
*
* <p>
* Uses java standard Short.parseShort() to perform coercion.
*
* @see DataValueDescriptor#getShort
*
* @exception StandardException thrown on failure to convert
**/
public short getShort() throws StandardException
{
if (isNull())
return (short)0;
try
{
return Short.parseShort(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "short");
}
}
/**
* Get int from a SQLChar.
*
* <p>
* Uses java standard Short.parseInt() to perform coercion.
*
* @see DataValueDescriptor#getInt
*
* @exception StandardException thrown on failure to convert
**/
public int getInt() throws StandardException
{
if (isNull())
return 0;
try
{
return Integer.parseInt(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "int");
}
}
/**
* Get long from a SQLChar.
*
* <p>
* Uses java standard Short.parseLong() to perform coercion.
*
* @see DataValueDescriptor#getLong
*
* @exception StandardException thrown on failure to convert
**/
public long getLong() throws StandardException
{
if (isNull())
return 0;
try
{
return Long.parseLong(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "long");
}
}
/**
* Get float from a SQLChar.
*
* <p>
* Uses java standard Float.floatValue() to perform coercion.
*
* @see DataValueDescriptor#getFloat
*
* @exception StandardException thrown on failure to convert
**/
public float getFloat() throws StandardException
{
if (isNull())
return 0;
try
{
return new Float(getString().trim()).floatValue();
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "float");
}
}
/**
* Get double from a SQLChar.
*
* <p>
* Uses java standard Double.doubleValue() to perform coercion.
*
* @see DataValueDescriptor#getDouble
*
* @exception StandardException thrown on failure to convert
**/
public double getDouble() throws StandardException
{
if (isNull())
return 0;
try
{
return new Double(getString().trim()).doubleValue();
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "double");
}
}
/**
* Get date from a SQLChar.
*
* @see DataValueDescriptor#getDate
*
* @exception StandardException thrown on failure to convert
**/
public Date getDate(Calendar cal)
throws StandardException
{
return getDate(cal, getString(), getLocaleFinder());
}
/**
* Static function to Get date from a string.
*
* @see DataValueDescriptor#getDate
*
* @exception StandardException thrown on failure to convert
**/
public static Date getDate(
java.util.Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLDate internalDate = new SQLDate(str, false, localeFinder);
return internalDate.getDate(cal);
}
/**
* Get time from a SQLChar.
*
* @see DataValueDescriptor#getTime
*
* @exception StandardException thrown on failure to convert
**/
public Time getTime(Calendar cal) throws StandardException
{
return getTime( cal, getString(), getLocaleFinder());
}
/**
* Static function to Get Time from a string.
*
* @see DataValueDescriptor#getTime
*
* @exception StandardException thrown on failure to convert
**/
public static Time getTime(
Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLTime internalTime = new SQLTime( str, false, localeFinder, cal);
return internalTime.getTime( cal);
}
/**
* Get Timestamp from a SQLChar.
*
* @see DataValueDescriptor#getTimestamp
*
* @exception StandardException thrown on failure to convert
**/
public Timestamp getTimestamp( Calendar cal) throws StandardException
{
return getTimestamp( cal, getString(), getLocaleFinder());
}
/**
* Static function to Get Timestamp from a string.
*
* @see DataValueDescriptor#getTimestamp
*
* @exception StandardException thrown on failure to convert
**/
public static Timestamp getTimestamp(
java.util.Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLTimestamp internalTimestamp =
new SQLTimestamp( str, false, localeFinder, cal);
return internalTimestamp.getTimestamp( cal);
}
/**************************************************************************
* Public Methods of StreamStorable interface:
**************************************************************************
*/
public InputStream returnStream()
{
return stream;
}
/**
* Set this value to the on-disk format stream.
*/
public void setStream(InputStream newStream) {
this.value = null;
this.rawLength = -1;
this.stream = newStream;
cKey = null;
_clobValue = null;
}
public void loadStream() throws StandardException
{
getString();
}
/**
* @exception StandardException Thrown on error
*/
public Object getObject() throws StandardException
{
if ( _clobValue != null ) { return _clobValue; }
else { return getString(); }
}
/**
* @exception StandardException Thrown on error
*/
public InputStream getStream() throws StandardException
{
return stream;
}
/**
* Returns a descriptor for the input stream for this character data value.
*
* @return Unless the method is overridden, {@code null} is returned.
* @throws StandardException if obtaining the descriptor fails
* @see SQLClob#getStreamWithDescriptor()
*/
public CharacterStreamDescriptor getStreamWithDescriptor()
throws StandardException {
// For now return null for all non-Clob types.
// TODO: Is this what we want, or do we want to treat some of the other
// string types as streams as well?
return null;
}
/**
* CHAR/VARCHAR/LONG VARCHAR implementation.
* Convert to a BigDecimal using getString.
*/
public int typeToBigDecimal() throws StandardException
{
return java.sql.Types.CHAR;
}
/**
* @exception StandardException Thrown on error
*/
public int getLength() throws StandardException {
if ( _clobValue != null ) { return getClobLength(); }
if (rawLength != -1)
return rawLength;
if (stream != null) {
if (stream instanceof Resetable && stream instanceof ObjectInput) {
try {
// Skip the encoded byte length.
InputStreamUtil.skipFully(stream, 2);
// Decode the whole stream to find the character length.
return (int)UTF8Util.skipUntilEOF(stream);
} catch (IOException ioe) {
throwStreamingIOException(ioe);
} finally {
try {
((Resetable) stream).resetStream();
} catch (IOException ioe) {
throwStreamingIOException(ioe);
}
}
}
}
String tmpString = getString();
if (tmpString == null) {
return 0;
} else {
int clobLength = tmpString.length();
return clobLength;
}
}
private int readCharacterLength(ObjectInput in) throws IOException {
int utflen = in.readUnsignedShort();
return utflen;
}
/**
* Wraps an {@code IOException} in a {@code StandardException} then throws
* the wrapping exception.
*
* @param ioe the {@code IOException} to wrap
* @throws StandardException the wrapping exception
*/
protected void throwStreamingIOException(IOException ioe)
throws StandardException {
throw StandardException.
newException(SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION,
ioe, getTypeName());
}
public String getTypeName()
{
return TypeId.CHAR_NAME;
}
/**
* If possible, use getCharArray() if you don't really
* need a string. getString() will cause an extra
* char array to be allocated when it calls the the String()
* constructor (the first time through), so may be
* cheaper to use getCharArray().
*
* @exception StandardException Thrown on error
*/
public String getString() throws StandardException
{
if (value == null) {
int len = rawLength;
if (len != -1) {
// data is stored in the char[] array
value = new String(rawData, 0, len);
if (len > RETURN_SPACE_THRESHOLD) {
// free up this char[] array to reduce memory usage
rawData = null;
rawLength = -1;
cKey = null;
}
} else if (_clobValue != null) {
try {
value = _clobValue.getSubString( 1L, getClobLength() );
_clobValue = null;
}
catch (SQLException se) { throw StandardException.plainWrapException( se ); }
} else if (stream != null) {
// data stored as a stream
try {
if (stream instanceof FormatIdInputStream) {
readExternal((FormatIdInputStream) stream);
} else {
readExternal(new FormatIdInputStream(stream));
}
stream = null;
// at this point the value is only in the char[]
// so call again to convert to a String
return getString();
} catch (IOException ioe) {
throw StandardException.newException(
SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION,
ioe,
String.class.getName());
}
}
}
return value;
}
/**
* Get a char array. Typically, this is a simple
* getter that is cheaper than getString() because
* we always need to create a char array when
* doing I/O. Use this instead of getString() where
* reasonable.
* <p>
* <b>WARNING</b>: may return a character array that has spare
* characters at the end. MUST be used in conjunction
* with getLength() to be safe.
*
* @exception StandardException Thrown on error
*/
public char[] getCharArray() throws StandardException
{
if (isNull())
{
return (char[])null;
}
else if (rawLength != -1)
{
return rawData;
}
else
{
// this is expensive -- we are getting a
// copy of the char array that the
// String wrapper uses.
getString();
rawData = value.toCharArray();
rawLength = rawData.length;
cKey = null;
return rawData;
}
}
/*
* Storable interface, implies Externalizable, TypedFormat
*/
/**
Return my format identifier.
@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId
*/
public int getTypeFormatId() {
return StoredFormatIds.SQL_CHAR_ID;
}
/**
* see if the String value is null.
@see Storable#isNull
*/
public boolean isNull()
{
return ((value == null) && (rawLength == -1) && (stream == null) && (_clobValue == null));
}
/**
Writes a non-Clob data value to the modified UTF-8 format used by Derby.
The maximum stored size is based upon the UTF format
used to stored the String. The format consists of
a two byte length field and a maximum number of three
bytes for each character.
<BR>
This puts an upper limit on the length of a stored
String. The maximum stored length is 65535, these leads to
the worse case of a maximum string length of 21844 ((65535 - 2) / 3).
<BR>
Strings with stored length longer than 64K is handled with
the following format:
(1) 2 byte length: will be assigned 0.
(2) UTF formated string data.
(3) terminate the string with the following 3 bytes:
first byte is:
+---+---+---+---+---+---+---+---+
| 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
second byte is:
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
third byte is:
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
The UTF format:
Writes a string to the underlying output stream using UTF-8
encoding in a machine-independent manner.
<p>
First, two bytes are written to the output stream as if by the
<code>writeShort</code> method giving the number of bytes to
follow. This value is the number of bytes actually written out,
not the length of the string. Following the length, each character
of the string is output, in sequence, using the UTF-8 encoding
for the character.
@exception IOException if an I/O error occurs.
@since JDK1.0
@exception IOException thrown by writeUTF
@see java.io.DataInputStream
*/
public void writeExternal(ObjectOutput out) throws IOException
{
// never called when value is null
if (SanityManager.DEBUG)
SanityManager.ASSERT(!isNull());
//
// This handles the case that a CHAR or VARCHAR value was populated from
// a user Clob.
//
if ( _clobValue != null )
{
writeClobUTF( out );
return;
}
String lvalue = null;
char[] data = null;
int strlen = rawLength;
boolean isRaw;
if (strlen < 0) {
lvalue = value;
strlen = lvalue.length();
isRaw = false;
} else {
data = rawData;
isRaw = true;
}
// byte length will always be at least string length
int utflen = strlen;
for (int i = 0 ; (i < strlen) && (utflen <= 65535); i++)
{
int c = isRaw ? data[i] : lvalue.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F))
{
// 1 byte for character
}
else if (c > 0x07FF)
{
utflen += 2; // 3 bytes for character
}
else
{
utflen += 1; // 2 bytes for character
}
}
StreamHeaderGenerator header = getStreamHeaderGenerator();
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!header.expectsCharCount());
}
// Generate the header, write it to the destination stream, write the
// user data and finally write an EOF-marker is required.
header.generateInto(out, utflen);
writeUTF(out, strlen, isRaw, null );
header.writeEOF(out, utflen);
}
/**
* Writes the user data value to a stream in the modified UTF-8 format.
*
* @param out destination stream
* @param strLen string length of the value
* @param isRaw {@code true} if the source is {@code rawData}, {@code false}
* if the source is {@code value}
* @param characterReader Reader from _clobValue if it exists
* @throws IOException if writing to the destination stream fails
*/
private final void writeUTF(ObjectOutput out, int strLen,
final boolean isRaw, Reader characterReader)
throws IOException {
// Copy the source reference into a local variable (optimization).
final char[] data = isRaw ? rawData : null;
final String lvalue = isRaw ? null : value;
// Iterate through the value and write it as modified UTF-8.
for (int i = 0 ; i < strLen ; i++) {
int c;
if ( characterReader != null ) { c = characterReader.read(); }
else { c = isRaw ? data[i] : lvalue.charAt(i); }
if ((c >= 0x0001) && (c <= 0x007F))
{
out.write(c);
}
else if (c > 0x07FF)
{
out.write(0xE0 | ((c >> 12) & 0x0F));
out.write(0x80 | ((c >> 6) & 0x3F));
out.write(0x80 | ((c >> 0) & 0x3F));
}
else
{
out.write(0xC0 | ((c >> 6) & 0x1F));
out.write(0x80 | ((c >> 0) & 0x3F));
}
}
}
/**
* Writes the header and the user data for a CLOB to the destination stream.
*
* @param out destination stream
* @throws IOException if writing to the destination stream fails
*/
protected final void writeClobUTF(ObjectOutput out)
throws IOException {
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!isNull());
SanityManager.ASSERT(stream == null, "Stream not null!");
}
boolean isUserClob = ( _clobValue != null );
try {
boolean isRaw = rawLength >= 0;
// Assume isRaw, update afterwards if required.
int strLen = rawLength;
if (!isRaw) {
if ( isUserClob ) { strLen = rawGetClobLength(); }
else { strLen = value.length(); }
}
// Generate the header and invoke the encoding routine.
StreamHeaderGenerator header = getStreamHeaderGenerator();
int toEncodeLen = header.expectsCharCount() ? strLen : -1;
header.generateInto(out, toEncodeLen);
Reader characterReader = null;
if ( isUserClob ) { characterReader = _clobValue.getCharacterStream(); }
writeUTF(out, strLen, isRaw, characterReader );
header.writeEOF(out, toEncodeLen);
if ( isUserClob ) { characterReader.close(); }
}
catch (SQLException se)
{
IOException ioe = new IOException( se.getMessage() );
ioe.initCause( se );
throw ioe;
}
}
/**
* Reads in a string from the specified data input stream. The
* string has been encoded using a modified UTF-8 format.
* <p>
* The first two bytes are read as if by
* <code>readUnsignedShort</code>. This value gives the number of
* following bytes that are in the encoded string, not
* the length of the resulting string. The following bytes are then
* interpreted as bytes encoding characters in the UTF-8 format
* and are converted into characters.
* <p>
* This method blocks until all the bytes are read, the end of the
* stream is detected, or an exception is thrown.
*
* @param in a data input stream.
* @exception EOFException if the input stream reaches the end
* before all the bytes.
* @exception IOException if an I/O error occurs.
* @exception UTFDataFormatException if the bytes do not represent a
* valid UTF-8 encoding of a Unicode string.
* @see java.io.DataInputStream#readUnsignedShort()
* @see java.io.Externalizable#readExternal
*/
public void readExternalFromArray(ArrayInputStream in)
throws IOException
{
resetForMaterialization();
int utfLen = (((in.read() & 0xFF) << 8) | (in.read() & 0xFF));
if (rawData == null || rawData.length < utfLen) {
// This array may be as much as three times too big. This happens
// if the content is only 3-byte characters (i.e. CJK).
// TODO: Decide if a threshold should be introduced, where the
// content is copied to a smaller array if the number of
// unused array positions exceeds the threshold.
rawData = new char[utfLen];
}
arg_passer[0] = rawData;
rawLength = in.readDerbyUTF(arg_passer, utfLen);
rawData = arg_passer[0];
}
char[][] arg_passer = new char[1][];
/**
* Reads a CLOB from the source stream and materializes the value in a
* character array.
*
* @param in source stream
* @param charLen the char length of the value, or {@code 0} if unknown
* @throws IOException if reading from the source fails
*/
protected void readExternalClobFromArray(ArrayInputStream in, int charLen)
throws IOException {
resetForMaterialization();
if (rawData == null || rawData.length < charLen) {
rawData = new char[charLen];
}
arg_passer[0] = rawData;
rawLength = in.readDerbyUTF(arg_passer, 0);
rawData = arg_passer[0];
}
/**
* Resets state after materializing value from an array.
*/
private void resetForMaterialization() {
value = null;
stream = null;
cKey = null;
}
public void readExternal(ObjectInput in) throws IOException
{
// Read the stored length in the stream header.
int utflen = in.readUnsignedShort();
readExternal(in, utflen, 0);
}
/**
* Restores the data value from the source stream, materializing the value
* in memory.
*
* @param in the source stream
* @param utflen the byte length, or {@code 0} if unknown
* @param knownStrLen the char length, or {@code 0} if unknown
* @throws UTFDataFormatException if an encoding error is detected
* @throws IOException if reading the stream fails
*/
protected void readExternal(ObjectInput in, int utflen,
final int knownStrLen)
throws IOException {
int requiredLength;
// minimum amount that is reasonable to grow the array
// when we know the array needs to growby at least one
// byte but we dont want to grow by one byte as that
// is not performant
int minGrowBy = growBy();
if (utflen != 0)
{
// the object was not stored as a streaming column
// we know exactly how long it is
requiredLength = utflen;
}
else
{
// the object was stored as a streaming column
// and we have a clue how much we can read unblocked
// OR
// The original string was a 0 length string.
requiredLength = in.available();
if (requiredLength < minGrowBy)
requiredLength = minGrowBy;
}
char str[];
if ((rawData == null) || (requiredLength > rawData.length)) {
str = new char[requiredLength];
} else {
str = rawData;
}
int arrayLength = str.length;
// Set these to null to allow GC of the array if required.
rawData = null;
resetForMaterialization();
int count = 0;
int strlen = 0;
readingLoop:
while (((strlen < knownStrLen) || (knownStrLen == 0)) &&
((count < utflen) || (utflen == 0)))
{
int c;
try {
c = in.readUnsignedByte();
} catch (EOFException eof) {
if (utflen != 0)
throw new EOFException();
// This is the case for a 0 length string.
// OR the string was originally streamed in
// which puts a 0 for utflen but no trailing
// E0,0,0 markers.
break readingLoop;
}
//if (c == -1) // read EOF
//{
// if (utflen != 0)
// throw new EOFException();
// break;
//}
// change it to an unsigned byte
//c &= 0xFF;
if (strlen >= arrayLength) // the char array needs to be grown
{
int growby = in.available();
// We know that the array needs to be grown by at least one.
// However, even if the input stream wants to block on every
// byte, we don't want to grow by a byte at a time.
// Note, for large data (clob > 32k), it is performant
// to grow the array by atleast 4k rather than a small amount
// Even better maybe to grow by 32k but then may be
// a little excess(?) for small data.
// hopefully in.available() will give a fair
// estimate of how much data can be read to grow the
// array by larger and necessary chunks.
// This performance issue due to
// the slow growth of this array was noticed since inserts
// on clobs was taking a really long time as
// the array here grew previously by 64 bytes each time
// till stream was drained. (Derby-302)
// for char, growby 64 seems reasonable, but for varchar
// clob 4k or 32k is performant and hence
// growBy() is override correctly to ensure this
if (growby < minGrowBy)
growby = minGrowBy;
int newstrlength = arrayLength + growby;
char oldstr[] = str;
str = new char[newstrlength];
System.arraycopy(oldstr, 0, str, 0, arrayLength);
arrayLength = newstrlength;
}
/// top fours bits of the first unsigned byte that maps to a
// 1,2 or 3 byte character
//
// 0000xxxx - 0 - 1 byte char
// 0001xxxx - 1 - 1 byte char
// 0010xxxx - 2 - 1 byte char
// 0011xxxx - 3 - 1 byte char
// 0100xxxx - 4 - 1 byte char
// 0101xxxx - 5 - 1 byte char
// 0110xxxx - 6 - 1 byte char
// 0111xxxx - 7 - 1 byte char
// 1000xxxx - 8 - error
// 1001xxxx - 9 - error
// 1010xxxx - 10 - error
// 1011xxxx - 11 - error
// 1100xxxx - 12 - 2 byte char
// 1101xxxx - 13 - 2 byte char
// 1110xxxx - 14 - 3 byte char
// 1111xxxx - 15 - error
int char2, char3;
char actualChar;
if ((c & 0x80) == 0x00)
{
// one byte character
count++;
actualChar = (char) c;
}
else if ((c & 0x60) == 0x40) // we know the top bit is set here
{
// two byte character
count += 2;
if (utflen != 0 && count > utflen)
throw new UTFDataFormatException();
char2 = in.readUnsignedByte();
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException();
actualChar = (char)(((c & 0x1F) << 6) | (char2 & 0x3F));
}
else if ((c & 0x70) == 0x60) // we know the top bit is set here
{
// three byte character
count += 3;
if (utflen != 0 && count > utflen)
throw new UTFDataFormatException();
char2 = in.readUnsignedByte();
char3 = in.readUnsignedByte();
if ((c == 0xE0) && (char2 == 0) && (char3 == 0)
&& (utflen == 0))
{
// we reached the end of a long string,
// that was terminated with
// (11100000, 00000000, 00000000)
break readingLoop;
}
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException();
actualChar = (char)(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
}
else {
throw new UTFDataFormatException(
"Invalid code point: " + Integer.toHexString(c));
}
str[strlen++] = actualChar;
}
rawData = str;
rawLength = strlen;
}
/**
* returns the reasonable minimum amount by
* which the array can grow . See readExternal.
* when we know that the array needs to grow by at least
* one byte, it is not performant to grow by just one byte
* instead this amount is used to provide a resonable growby size.
* @return minimum reasonable growby size
*/
protected int growBy()
{
return GROWBY_FOR_CHAR; //seems reasonable for a char
}
/**
* @see Storable#restoreToNull
*
*/
public void restoreToNull()
{
value = null;
stream = null;
rawLength = -1;
cKey = null;
}
/**
@exception StandardException thrown on error
*/
public boolean compare(int op,
DataValueDescriptor other,
boolean orderedNulls,
boolean unknownRV)
throws StandardException
{
if (!orderedNulls) // nulls are unordered
{
if (this.isNull() || ((DataValueDescriptor) other).isNull())
return unknownRV;
}
/* When comparing String types to non-string types, we always
* convert the string type to the non-string type.
*/
if (! (other instanceof SQLChar))
{
return other.compare(flip(op), this, orderedNulls, unknownRV);
}
/* Do the comparison */
return super.compare(op, other, orderedNulls, unknownRV);
}
/**
@exception StandardException thrown on error
*/
public int compare(DataValueDescriptor other) throws StandardException
{
/* Use compare method from dominant type, negating result
* to reflect flipping of sides.
*/
if (typePrecedence() < other.typePrecedence())
{
return - (other.compare(this));
}
// stringCompare deals with null as comparable and smallest
return stringCompare(this, (SQLChar)other);
}
/*
* CloneableObject interface
*/
/** From CloneableObject
* Shallow clone a StreamStorable without objectifying. This is used to
* avoid unnecessary objectifying of a stream object. The only
* difference of this method from getClone is this method does not
* objectify a stream.
*/
public Object cloneObject()
{
if ((stream == null) && (_clobValue == null)) { return getClone(); }
SQLChar self = (SQLChar) getNewNull();
self.copyState(this);
return self;
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#getClone */
public DataValueDescriptor getClone()
{
try
{
return new SQLChar(getString());
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
SanityManager.THROWASSERT("Unexpected exception", se);
return null;
}
}
/**
* @see DataValueDescriptor#getNewNull
*
*/
public DataValueDescriptor getNewNull()
{
return new SQLChar();
}
/** @see StringDataValue#getValue(RuleBasedCollator) */
public StringDataValue getValue(RuleBasedCollator collatorForComparison)
{
if (collatorForComparison == null)
{//null collatorForComparison means use UCS_BASIC for collation
return this;
} else {
//non-null collatorForComparison means use collator sensitive
//implementation of SQLChar
CollatorSQLChar s = new CollatorSQLChar(collatorForComparison);
s.copyState(this);
return s;
}
}
/**
* @see DataValueDescriptor#setValueFromResultSet
*
* @exception SQLException Thrown on error
*/
public final void setValueFromResultSet(ResultSet resultSet, int colNumber,
boolean isNullable)
throws SQLException
{
setValue(resultSet.getString(colNumber));
}
/**
Set the value into a PreparedStatement.
*/
public final void setInto(
PreparedStatement ps,
int position)
throws SQLException, StandardException
{
ps.setString(position, getString());
}
public void setValue(Clob theValue)
{
stream = null;
rawLength = -1;
cKey = null;
value = null;
_clobValue = theValue;
}
public void setValue(String theValue)
{
stream = null;
rawLength = -1;
cKey = null;
_clobValue = null;
value = theValue;
}
public void setValue(boolean theValue) throws StandardException
{
// match JCC.
setValue(theValue ? "1" : "0");
}
public void setValue(int theValue) throws StandardException
{
setValue(Integer.toString(theValue));
}
public void setValue(double theValue) throws StandardException
{
setValue(Double.toString(theValue));
}
public void setValue(float theValue) throws StandardException
{
setValue(Float.toString(theValue));
}
public void setValue(short theValue) throws StandardException
{
setValue(Short.toString(theValue));
}
public void setValue(long theValue) throws StandardException
{
setValue(Long.toString(theValue));
}
public void setValue(byte theValue) throws StandardException
{
setValue(Byte.toString(theValue));
}
public void setValue(byte[] theValue) throws StandardException
{
if (theValue == null)
{
restoreToNull();
return;
}
/*
** We can't just do a new String(theValue)
** because that method assumes we are converting
** ASCII and it will take on char per byte.
** So we need to convert the byte array to a
** char array and go from there.
**
** If we have an odd number of bytes pad out.
*/
int mod = (theValue.length % 2);
int len = (theValue.length/2) + mod;
char[] carray = new char[len];
int cindex = 0;
int bindex = 0;
/*
** If we have a left over byte, then get
** that now.
*/
if (mod == 1)
{
carray[--len] = (char)(theValue[theValue.length - 1] << 8);
}
for (; cindex < len; bindex+=2, cindex++)
{
carray[cindex] = (char)((theValue[bindex] << 8) |
(theValue[bindex+1] & 0x00ff));
}
setValue(new String(carray));
}
/**
Only to be called when an application through JDBC is setting a
SQLChar to a java.math.BigDecimal.
*/
public void setBigDecimal(Number bigDecimal) throws StandardException
{
if (bigDecimal == null)
setToNull();
else
setValue(bigDecimal.toString());
}
/** @exception StandardException Thrown on error */
public void setValue(Date theValue, Calendar cal) throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCDate( cal, sb);
strValue= sb.toString();
}
}
setValue( strValue);
}
/** @exception StandardException Thrown on error */
public void setValue(Time theValue, Calendar cal) throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCTime( cal, sb);
strValue= sb.toString();
}
}
setValue( strValue);
}
/** @exception StandardException Thrown on error */
public void setValue(
Timestamp theValue,
Calendar cal)
throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCDate( cal, sb);
sb.append( ' ');
formatJDBCTime( cal, sb);
int micros =
(theValue.getNanos() + SQLTimestamp.FRACTION_TO_NANO/2) /
SQLTimestamp.FRACTION_TO_NANO;
if( micros > 0)
{
sb.append( '.');
String microsStr = Integer.toString( micros);
if(microsStr.length() > SQLTimestamp.MAX_FRACTION_DIGITS)
{
sb.append(
microsStr.substring(
0, SQLTimestamp.MAX_FRACTION_DIGITS));
}
else
{
for(int i = microsStr.length();
i < SQLTimestamp.MAX_FRACTION_DIGITS ; i++)
{
sb.append( '0');
}
sb.append( microsStr);
}
}
strValue= sb.toString();
}
}
setValue( strValue);
}
private void formatJDBCDate( Calendar cal, StringBuffer sb)
{
SQLDate.dateToString( cal.get( Calendar.YEAR),
cal.get( Calendar.MONTH) - Calendar.JANUARY + 1,
cal.get( Calendar.DAY_OF_MONTH),
sb);
}
private void formatJDBCTime( Calendar cal, StringBuffer sb)
{
SQLTime.timeToString(
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND),
sb);
}
/**
* Set the value from the stream which is in the on-disk format.
* @param theStream On disk format of the stream
* @param valueLength length of the logical value in characters.
*/
public final void setValue(InputStream theStream, int valueLength)
{
setStream(theStream);
}
/**
* Allow any Java type to be cast to a character type using
* Object.toString.
* @see DataValueDescriptor#setObjectForCast
*
* @exception StandardException
* thrown on failure
*/
public void setObjectForCast(
Object theValue,
boolean instanceOfResultType,
String resultTypeClassName)
throws StandardException
{
if (theValue == null)
{
setToNull();
return;
}
if ("java.lang.String".equals(resultTypeClassName))
setValue(theValue.toString());
else
super.setObjectForCast(
theValue, instanceOfResultType, resultTypeClassName);
}
protected void setFrom(DataValueDescriptor theValue)
throws StandardException
{
if ( theValue instanceof SQLChar )
{
SQLChar that = (SQLChar) theValue;
if ( that._clobValue != null )
{
setValue( that._clobValue );
return;
}
}
setValue(theValue.getString());
}
/**
* Normalization method - this method may be called when putting
* a value into a SQLChar, for example, when inserting into a SQLChar
* column. See NormalizeResultSet in execution.
*
* @param desiredType The type to normalize the source column to
* @param source The value to normalize
*
*
* @exception StandardException Thrown for null into
* non-nullable column, and for
* truncation error
*/
public void normalize(
DataTypeDescriptor desiredType,
DataValueDescriptor source)
throws StandardException
{
normalize(desiredType, source.getString());
}
protected void normalize(DataTypeDescriptor desiredType, String sourceValue)
throws StandardException
{
int desiredWidth = desiredType.getMaximumWidth();
int sourceWidth = sourceValue.length();
/*
** If the input is already the right length, no normalization is
** necessary - just return the source.
*/
if (sourceWidth == desiredWidth) {
setValue(sourceValue);
return;
}
/*
** If the input is shorter than the desired type, construct a new
** SQLChar padded with blanks to the right length.
*/
if (sourceWidth < desiredWidth)
{
setToNull();
char[] ca;
if ((rawData == null) || (desiredWidth > rawData.length)) {
ca = rawData = new char[desiredWidth];
} else {
ca = rawData;
}
sourceValue.getChars(0, sourceWidth, ca, 0);
SQLChar.appendBlanks(ca, sourceWidth, desiredWidth - sourceWidth);
rawLength = desiredWidth;
return;
}
/*
** Check whether any non-blank characters will be truncated.
*/
hasNonBlankChars(sourceValue, desiredWidth, sourceWidth);
/*
** No non-blank characters will be truncated. Truncate the blanks
** to the desired width.
*/
String truncatedString = sourceValue.substring(0, desiredWidth);
setValue(truncatedString);
}
/*
** Method to check for truncation of non blank chars.
*/
protected final void hasNonBlankChars(String source, int start, int end)
throws StandardException
{
/*
** Check whether any non-blank characters will be truncated.
*/
for (int posn = start; posn < end; posn++)
{
if (source.charAt(posn) != ' ')
{
throw StandardException.newException(
SQLState.LANG_STRING_TRUNCATION,
getTypeName(),
StringUtil.formatForPrint(source),
String.valueOf(start));
}
}
}
///////////////////////////////////////////////////////////////
//
// VariableSizeDataValue INTERFACE
//
///////////////////////////////////////////////////////////////
/**
* Set the width of the to the desired value. Used
* when CASTing. Ideally we'd recycle normalize(), but
* the behavior is different (we issue a warning instead
* of an error, and we aren't interested in nullability).
*
* @param desiredWidth the desired length
* @param desiredScale the desired scale (ignored)
* @param errorOnTrunc throw an error on truncation
*
* @exception StandardException Thrown when errorOnTrunc
* is true and when a shrink will truncate non-white
* spaces.
*/
public void setWidth(int desiredWidth,
int desiredScale, // Ignored
boolean errorOnTrunc)
throws StandardException
{
int sourceWidth;
/*
** If the input is NULL, nothing to do.
*/
if ( (_clobValue == null ) && (getString() == null) )
{
return;
}
sourceWidth = getLength();
/*
** If the input is shorter than the desired type, construct a new
** SQLChar padded with blanks to the right length. Only
** do this if we have a SQLChar -- SQLVarchars don't
** pad.
*/
if (sourceWidth < desiredWidth)
{
if (!(this instanceof SQLVarchar))
{
StringBuffer strbuf;
strbuf = new StringBuffer(getString());
for ( ; sourceWidth < desiredWidth; sourceWidth++)
{
strbuf.append(' ');
}
setValue(new String(strbuf));
}
}
else if (sourceWidth > desiredWidth && desiredWidth > 0)
{
/*
** Check whether any non-blank characters will be truncated.
*/
if (errorOnTrunc)
hasNonBlankChars(getString(), desiredWidth, sourceWidth);
//RESOLVE: should issue a warning instead
/*
** Truncate to the desired width.
*/
setValue(getString().substring(0, desiredWidth));
}
return;
}
/*
** SQL Operators
*/
/**
* The = operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the =
* @param right The value on the right side of the =
*
* @return A SQL boolean value telling whether the two parameters are equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue equals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) == 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) == 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The <> operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <>
* @param right The value on the right side of the <>
*
* @return A SQL boolean value telling whether the two parameters
* are not equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue notEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) != 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) != 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The < operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <
* @param right The value on the right side of the <
*
* @return A SQL boolean value telling whether the first operand is
* less than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) < 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) < 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The > operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >
* @param right The value on the right side of the >
*
* @return A SQL boolean value telling whether the first operand is
* greater than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) > 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) > 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The <= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <=
* @param right The value on the right side of the <=
*
* @return A SQL boolean value telling whether the first operand is
* less than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) <= 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) <= 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The >= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >=
* @param right The value on the right side of the >=
*
* @return A SQL boolean value telling whether the first operand is
* greater than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) >= 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) >= 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/*
** Concatable interface
*/
/**
* This method implements the char_length function for char.
*
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLInteger containing the length of the char value
*
* @exception StandardException Thrown on error
*
* @see ConcatableDataValue#charLength(NumberDataValue)
*/
public NumberDataValue charLength(NumberDataValue result)
throws StandardException
{
if (result == null)
{
result = new SQLInteger();
}
if (this.isNull())
{
result.setToNull();
return result;
}
result.setValue(this.getLength());
return result;
}
/**
* @see StringDataValue#concatenate
*
* @exception StandardException Thrown on error
*/
public StringDataValue concatenate(
StringDataValue leftOperand,
StringDataValue rightOperand,
StringDataValue result)
throws StandardException
{
if (leftOperand.isNull() || leftOperand.getString() == null ||
rightOperand.isNull() || rightOperand.getString() == null)
{
result.setToNull();
return result;
}
result.setValue(
leftOperand.getString().concat(rightOperand.getString()));
return result;
}
/**
* This method implements the like function for char (with no escape value).
*
* @param pattern The pattern to use
*
* @return A SQL boolean value telling whether the first operand is
* like the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue like(DataValueDescriptor pattern)
throws StandardException
{
Boolean likeResult;
// note that we call getLength() because the length
// of the char array may be different than the
// length we should be using (i.e. getLength()).
// see getCharArray() for more info
char[] evalCharArray = getCharArray();
char[] patternCharArray = ((SQLChar)pattern).getCharArray();
likeResult = Like.like(evalCharArray,
getLength(),
patternCharArray,
pattern.getLength(),
null);
return SQLBoolean.truthValue(this,
pattern,
likeResult);
}
/**
* This method implements the like function for char with an escape value.
*
* @param pattern The pattern to use
*
* @return A SQL boolean value telling whether the first operand is
* like the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue like(
DataValueDescriptor pattern,
DataValueDescriptor escape)
throws StandardException
{
Boolean likeResult;
if (SanityManager.DEBUG)
SanityManager.ASSERT(
pattern instanceof StringDataValue &&
escape instanceof StringDataValue,
"All three operands must be instances of StringDataValue");
// ANSI states a null escape yields 'unknown' results
//
// This method is only called when we have an escape clause, so this
// test is valid
if (escape.isNull())
{
throw StandardException.newException(SQLState.LANG_ESCAPE_IS_NULL);
}
// note that we call getLength() because the length
// of the char array may be different than the
// length we should be using (i.e. getLength()).
// see getCharArray() for more info
char[] evalCharArray = getCharArray();
char[] patternCharArray = ((SQLChar)pattern).getCharArray();
char[] escapeCharArray = (((SQLChar) escape).getCharArray());
int escapeLength = escape.getLength();
if (escapeCharArray != null && escapeLength != 1 )
{
throw StandardException.newException(
SQLState.LANG_INVALID_ESCAPE_CHARACTER,
new String(escapeCharArray));
}
likeResult = Like.like(evalCharArray,
getLength(),
patternCharArray,
pattern.getLength(),
escapeCharArray,
escapeLength,
null);
return SQLBoolean.truthValue(this,
pattern,
likeResult);
}
/**
* This method implements the locate function for char.
* @param searchFrom - The string to search from
* @param start - The position to search from in string searchFrom
* @param result - The object to return
*
* Note: use getString() to get the string to search for.
*
* @return The position in searchFrom the fist occurrence of this.value.
* 0 is returned if searchFrom does not contain this.value.
* @exception StandardException Thrown on error
*/
public NumberDataValue locate( StringDataValue searchFrom,
NumberDataValue start,
NumberDataValue result)
throws StandardException
{
int startVal;
if( result == null )
{
result = new SQLInteger();
}
if( start.isNull() )
{
startVal = 1;
}
else
{
startVal = start.getInt();
}
if( isNull() || searchFrom.isNull() )
{
result.setToNull();
return result;
}
String mySearchFrom = searchFrom.getString();
String mySearchFor = this.getString();
/* the below 2 if conditions are to emulate DB2's behavior */
if( startVal < 1 )
{
throw StandardException.newException(
SQLState.LANG_INVALID_PARAMETER_FOR_SEARCH_POSITION,
new String(getString()), new String(mySearchFrom),
new Integer(startVal));
}
if( mySearchFor.length() == 0 )
{
result.setValue( startVal );
return result;
}
result.setValue( mySearchFrom.indexOf(mySearchFor, startVal - 1) + 1);
return result;
}
/**
* The SQL substr() function.
*
* @param start Start of substr
* @param length Length of substr
* @param result The result of a previous call to this method,
* null if not called yet.
* @param maxLen Maximum length of the result
*
* @return A ConcatableDataValue containing the result of the substr()
*
* @exception StandardException Thrown on error
*/
public ConcatableDataValue substring(
NumberDataValue start,
NumberDataValue length,
ConcatableDataValue result,
int maxLen)
throws StandardException
{
int startInt;
int lengthInt;
StringDataValue stringResult;
if (result == null)
{
result = getNewVarchar();
}
stringResult = (StringDataValue) result;
/* The result is null if the receiver (this) is null or if the length
* is negative.
* We will return null, which is the only sensible thing to do.
* (If user did not specify a length then length is not a user null.)
*/
if (this.isNull() || start.isNull() ||
(length != null && length.isNull()))
{
stringResult.setToNull();
return stringResult;
}
startInt = start.getInt();
// If length is not specified, make it till end of the string
if (length != null)
{
lengthInt = length.getInt();
}
else lengthInt = maxLen - startInt + 1;
/* DB2 Compatibility: Added these checks to match DB2. We currently
* enforce these limits in both modes. We could do these checks in DB2
* mode only, if needed, so leaving earlier code for out of range in
* for now, though will not be exercised
*/
if ((startInt <= 0 || lengthInt < 0 || startInt > maxLen ||
lengthInt > maxLen - startInt + 1))
{
throw StandardException.newException(
SQLState.LANG_SUBSTR_START_OR_LEN_OUT_OF_RANGE);
}
// Return null if length is non-positive
if (lengthInt < 0)
{
stringResult.setToNull();
return stringResult;
}
/* If startInt < 0 then we count from the right of the string */
if (startInt < 0)
{
// Return '' if window is to left of string.
if (startInt + getLength() < 0 &&
(startInt + getLength() + lengthInt <= 0))
{
stringResult.setValue("");
return stringResult;
}
// Convert startInt to positive to get substring from right
startInt += getLength();
while (startInt < 0)
{
startInt++;
lengthInt--;
}
}
else if (startInt > 0)
{
/* java substring() is 0 based */
startInt--;
}
/* Oracle docs don't say what happens if the window is to the
* left of the string. Return "" if the window
* is to the left or right.
*/
if (lengthInt == 0 ||
lengthInt <= 0 - startInt ||
startInt > getLength())
{
stringResult.setValue("");
return stringResult;
}
if (lengthInt >= getLength() - startInt)
{
stringResult.setValue(getString().substring(startInt));
}
else
{
stringResult.setValue(
getString().substring(startInt, startInt + lengthInt));
}
return stringResult;
}
/**
* This function public for testing purposes.
*
* @param trimType Type of trim (LEADING, TRAILING, or BOTH)
* @param trimChar Character to trim
* @param source String from which to trim trimChar
*
* @return A String containing the result of the trim.
*/
private String trimInternal(int trimType, char trimChar, String source)
{
if (source == null) {
return null;
}
int len = source.length();
int start = 0;
if (trimType == LEADING || trimType == BOTH)
{
for (; start < len; start++)
if (trimChar != source.charAt(start))
break;
}
if (start == len)
return "";
int end = len - 1;
if (trimType == TRAILING || trimType == BOTH)
{
for (; end >= 0; end--)
if (trimChar != source.charAt(end))
break;
}
if (end == -1)
return "";
return source.substring(start, end + 1);
}
/**
* @param trimType Type of trim (LEADING, TRAILING, or BOTH)
* @param trimChar Character to trim from this SQLChar (may be null)
* @param result The result of a previous call to this method,
* null if not called yet.
*
* @return A StringDataValue containing the result of the trim.
*/
public StringDataValue ansiTrim(
int trimType,
StringDataValue trimChar,
StringDataValue result)
throws StandardException
{
if (result == null)
{
result = getNewVarchar();
}
if (trimChar == null || trimChar.getString() == null)
{
result.setToNull();
return result;
}
if (trimChar.getString().length() != 1)
{
throw StandardException.newException(
SQLState.LANG_INVALID_TRIM_CHARACTER, trimChar.getString());
}
char trimCharacter = trimChar.getString().charAt(0);
result.setValue(trimInternal(trimType, trimCharacter, getString()));
return result;
}
/** @see StringDataValue#upper
*
* @exception StandardException Thrown on error
*/
public StringDataValue upper(StringDataValue result)
throws StandardException
{
if (result == null)
{
result = (StringDataValue) getNewNull();
}
if (this.isNull())
{
result.setToNull();
return result;
}
String upper = getString();
upper = upper.toUpperCase(getLocale());
result.setValue(upper);
return result;
}
/** @see StringDataValue#lower
*
* @exception StandardException Thrown on error
*/
public StringDataValue lower(StringDataValue result)
throws StandardException
{
if (result == null)
{
result = (StringDataValue) getNewNull();
}
if (this.isNull())
{
result.setToNull();
return result;
}
String lower = getString();
lower = lower.toLowerCase(getLocale());
result.setValue(lower);
return result;
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#typePrecedence */
public int typePrecedence()
{
return TypeId.CHAR_PRECEDENCE;
}
/**
* Compare two Strings using standard SQL semantics.
*
* @param op1 The first String
* @param op2 The second String
*
* @return -1 - op1 < op2
* 0 - op1 == op2
* 1 - op1 > op2
*/
protected static int stringCompare(String op1, String op2)
{
int posn;
char leftchar;
char rightchar;
int leftlen;
int rightlen;
int retvalIfLTSpace;
String remainingString;
int remainingLen;
/*
** By convention, nulls sort High, and null == null
*/
if (op1 == null || op2 == null)
{
if (op1 != null) // op2 == null
return -1;
if (op2 != null) // op1 == null
return 1;
return 0; // both null
}
/*
** Compare characters until we find one that isn't equal, or until
** one String or the other runs out of characters.
*/
leftlen = op1.length();
rightlen = op2.length();
int shorterLen = leftlen < rightlen ? leftlen : rightlen;
for (posn = 0; posn < shorterLen; posn++)
{
leftchar = op1.charAt(posn);
rightchar = op2.charAt(posn);
if (leftchar != rightchar)
{
if (leftchar < rightchar)
return -1;
else
return 1;
}
}
/*
** All the characters are equal up to the length of the shorter
** string. If the two strings are of equal length, the values are
** equal.
*/
if (leftlen == rightlen)
return 0;
/*
** One string is shorter than the other. Compare the remaining
** characters in the longer string to spaces (the SQL standard says
** that in this case the comparison is as if the shorter string is
** padded with blanks to the length of the longer string.
*/
if (leftlen > rightlen)
{
/*
** Remaining characters are on the left.
*/
/* If a remaining character is less than a space,
* return -1 (op1 < op2) */
retvalIfLTSpace = -1;
remainingString = op1;
posn = rightlen;
remainingLen = leftlen;
}
else
{
/*
** Remaining characters are on the right.
*/
/* If a remaining character is less than a space,
* return 1 (op1 > op2) */
retvalIfLTSpace = 1;
remainingString = op2;
posn = leftlen;
remainingLen = rightlen;
}
/* Look at the remaining characters in the longer string */
for ( ; posn < remainingLen; posn++)
{
char remainingChar;
/*
** Compare the characters to spaces, and return the appropriate
** value, depending on which is the longer string.
*/
remainingChar = remainingString.charAt(posn);
if (remainingChar < ' ')
return retvalIfLTSpace;
else if (remainingChar > ' ')
return -retvalIfLTSpace;
}
/* The remaining characters in the longer string were all spaces,
** so the strings are equal.
*/
return 0;
}
/**
* Compare two SQLChars.
*
* @exception StandardException Thrown on error
*/
protected int stringCompare(SQLChar char1, SQLChar char2)
throws StandardException
{
return stringCompare(char1.getCharArray(), char1.getLength(),
char2.getCharArray(), char2.getLength());
}
/**
* Compare two Strings using standard SQL semantics.
*
* @param op1 The first String
* @param op2 The second String
*
* @return -1 - op1 < op2
* 0 - op1 == op2
* 1 - op1 > op2
*/
protected static int stringCompare(
char[] op1,
int leftlen,
char[] op2,
int rightlen)
{
int posn;
char leftchar;
char rightchar;
int retvalIfLTSpace;
char[] remainingString;
int remainingLen;
/*
** By convention, nulls sort High, and null == null
*/
if (op1 == null || op2 == null)
{
if (op1 != null) // op2 == null
return -1;
if (op2 != null) // op1 == null
return 1;
return 0; // both null
}
/*
** Compare characters until we find one that isn't equal, or until
** one String or the other runs out of characters.
*/
int shorterLen = leftlen < rightlen ? leftlen : rightlen;
for (posn = 0; posn < shorterLen; posn++)
{
leftchar = op1[posn];
rightchar = op2[posn];
if (leftchar != rightchar)
{
if (leftchar < rightchar)
return -1;
else
return 1;
}
}
/*
** All the characters are equal up to the length of the shorter
** string. If the two strings are of equal length, the values are
** equal.
*/
if (leftlen == rightlen)
return 0;
/*
** One string is shorter than the other. Compare the remaining
** characters in the longer string to spaces (the SQL standard says
** that in this case the comparison is as if the shorter string is
** padded with blanks to the length of the longer string.
*/
if (leftlen > rightlen)
{
/*
** Remaining characters are on the left.
*/
/* If a remaining character is less than a space,
* return -1 (op1 < op2) */
retvalIfLTSpace = -1;
remainingString = op1;
posn = rightlen;
remainingLen = leftlen;
}
else
{
/*
** Remaining characters are on the right.
*/
/* If a remaining character is less than a space,
* return 1 (op1 > op2) */
retvalIfLTSpace = 1;
remainingString = op2;
posn = leftlen;
remainingLen = rightlen;
}
/* Look at the remaining characters in the longer string */
for ( ; posn < remainingLen; posn++)
{
char remainingChar;
/*
** Compare the characters to spaces, and return the appropriate
** value, depending on which is the longer string.
*/
remainingChar = remainingString[posn];
if (remainingChar < ' ')
return retvalIfLTSpace;
else if (remainingChar > ' ')
return -retvalIfLTSpace;
}
/* The remaining characters in the longer string were all spaces,
** so the strings are equal.
*/
return 0;
}
/**
* This method gets called for the collation sensitive char classes ie
* CollatorSQLChar, CollatorSQLVarchar, CollatorSQLLongvarchar,
* CollatorSQLClob. These collation sensitive chars need to have the
* collation key in order to do string comparison. And the collation key
* is obtained using the Collator object that these classes already have.
*
* @return CollationKey obtained using Collator on the string
* @throws StandardException
*/
protected CollationKey getCollationKey() throws StandardException
{
char tmpCharArray[];
if (cKey != null)
return cKey;
if (rawLength == -1)
{
/* materialize the string if input is a stream */
tmpCharArray = getCharArray();
if (tmpCharArray == null)
return null;
}
int lastNonspaceChar = rawLength;
while (lastNonspaceChar > 0 &&
rawData[lastNonspaceChar - 1] == '\u0020')
lastNonspaceChar--; // count off the trailing spaces.
RuleBasedCollator rbc = getCollatorForCollation();
cKey = rbc.getCollationKey(new String(rawData, 0, lastNonspaceChar));
return cKey;
}
/*
* String display of value
*/
public String toString()
{
if (isNull()) {
return "NULL";
}
if ((value == null) && (rawLength != -1)) {
return new String(rawData, 0, rawLength);
}
if (stream != null) {
try {
return getString();
} catch (Exception e) {
return e.toString();
}
}
return value;
}
/*
* Hash code
*/
public int hashCode()
{
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!(this instanceof CollationElementsInterface),
"SQLChar.hashCode() does not work with collation");
}
try {
if (getString() == null)
{
return 0;
}
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
SanityManager.THROWASSERT("Unexpected exception", se);
return 0;
}
/* value.hashCode() doesn't work because of the SQL blank padding
* behavior.
* We want the hash code to be based on the value after the
* trailing blanks have been trimmed. Calling trim() is too expensive
* since it will create a new object, so here's what we do:
* o Walk from the right until we've found the 1st
* non-blank character.
* o Calculate the hash code based on the characters from the
* start up to the first non-blank character from the right.
*/
// value will have been set by the getString() above
String lvalue = value;
// Find 1st non-blank from the right
int lastNonPadChar = lvalue.length() - 1;
while (lastNonPadChar >= 0 && lvalue.charAt(lastNonPadChar) == PAD) {
lastNonPadChar--;
}
// Build the hash code. It should be identical to what we get from
// lvalue.substring(0, lastNonPadChar+1).hashCode(), but it should be
// cheaper this way since we don't allocate a new string.
int hashcode = 0;
for (int i = 0; i <= lastNonPadChar; i++) {
hashcode = hashcode * 31 + lvalue.charAt(i);
}
return hashcode;
}
/**
* Hash code implementation for collator sensitive subclasses.
*/
int hashCodeForCollation() {
CollationKey key = null;
try {
key = getCollationKey();
} catch (StandardException se) {
// ignore exceptions, like we do in hashCode()
if (SanityManager.DEBUG) {
SanityManager.THROWASSERT("Unexpected exception", se);
}
}
return key == null ? 0 : key.hashCode();
}
/**
* Get a SQLVarchar for a built-in string function.
*
* @return a SQLVarchar.
*
* @exception StandardException Thrown on error
*/
protected StringDataValue getNewVarchar() throws StandardException
{
return new SQLVarchar();
}
protected void setLocaleFinder(LocaleFinder localeFinder)
{
this.localeFinder = localeFinder;
}
/** @exception StandardException Thrown on error */
private Locale getLocale() throws StandardException
{
return getLocaleFinder().getCurrentLocale();
}
protected RuleBasedCollator getCollatorForCollation()
throws StandardException
{
return getLocaleFinder().getCollator();
}
protected LocaleFinder getLocaleFinder()
{
// This is not very satisfactory, as it creates a dependency on
// the DatabaseContext. It's the best I could do on short notice,
// though. - Jeff
if (localeFinder == null)
{
DatabaseContext dc = (DatabaseContext)
ContextService.getContext(DatabaseContext.CONTEXT_ID);
if( dc != null)
localeFinder = dc.getDatabase();
}
return localeFinder;
}
protected DateFormat getDateFormat() throws StandardException {
return getLocaleFinder().getDateFormat();
}
protected DateFormat getTimeFormat() throws StandardException {
return getLocaleFinder().getTimeFormat();
}
protected DateFormat getTimestampFormat() throws StandardException {
return getLocaleFinder().getTimestampFormat();
}
protected DateFormat getDateFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar( getLocaleFinder().getDateFormat(), cal);
}
protected DateFormat getTimeFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar( getLocaleFinder().getTimeFormat(), cal);
}
protected DateFormat getTimestampFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar(
getLocaleFinder().getTimestampFormat(), cal);
}
private DateFormat setDateFormatCalendar( DateFormat df, Calendar cal)
{
if( cal != null && df.getTimeZone() != cal.getTimeZone())
{
// The DateFormat returned by getDateFormat may be cached and used
// by other threads. Therefore we cannot change its calendar.
df = (DateFormat) df.clone();
df.setCalendar( cal);
}
return df;
}
public int estimateMemoryUsage()
{
int sz = BASE_MEMORY_USAGE + ClassSize.estimateMemoryUsage( value);
if( null != rawData)
sz += 2*rawData.length;
// Assume that cKey, stream, and localFinder are shared,
// so do not count their memory usage
return sz;
} // end of estimateMemoryUsage
protected void copyState(SQLChar other) {
this.value = other.value;
this.rawData = other.rawData;
this.rawLength = other.rawLength;
this.cKey = other.cKey;
this.stream = other.stream;
this._clobValue = other._clobValue;
this.localeFinder = localeFinder;
}
/**
* Gets a trace representation for debugging.
*
* @return a trace representation of this SQL Type.
*/
public String getTraceString() throws StandardException {
// Check if the value is SQL NULL.
if (isNull()) {
return "NULL";
}
return (toString());
}
/**
* Returns the default stream header generator for the string data types.
*
* @return A stream header generator.
*/
public StreamHeaderGenerator getStreamHeaderGenerator() {
return CHAR_HEADER_GENERATOR;
}
/**
* Sets the mode for the database being accessed.
*
* @param inSoftUpgradeMode {@code true} if the database is being accessed
* in soft upgrade mode, {@code false} if not, and {@code null} if
* unknown
*/
public void setSoftUpgradeMode(Boolean inSoftUpgradeMode) {
// Ignore this for CHAR, VARCHAR and LONG VARCHAR.
}
private int getClobLength() throws StandardException
{
try {
return rawGetClobLength();
}
catch (SQLException se) { throw StandardException.plainWrapException( se ); }
}
private int rawGetClobLength() throws SQLException
{
long maxLength = Integer.MAX_VALUE;
long length = _clobValue.length();
if ( length > Integer.MAX_VALUE )
{
StandardException se = StandardException.newException
( SQLState.BLOB_TOO_LARGE_FOR_CLIENT, Long.toString( length ), Long.toString( maxLength ) );
throw new SQLException( se.getMessage() );
}
return (int) length;
}
}
| java/engine/org/apache/derby/iapi/types/SQLChar.java | /*
Derby - Class org.apache.derby.iapi.types.SQLChar
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.derby.iapi.types;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.io.Storable;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.services.io.StreamStorable;
import org.apache.derby.iapi.services.io.FormatIdInputStream;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derby.iapi.types.NumberDataValue;
import org.apache.derby.iapi.types.BooleanDataValue;
import org.apache.derby.iapi.types.ConcatableDataValue;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.jdbc.CharacterStreamDescriptor;
import org.apache.derby.iapi.services.cache.ClassSize;
import org.apache.derby.iapi.services.io.ArrayInputStream;
import org.apache.derby.iapi.services.io.InputStreamUtil;
import org.apache.derby.iapi.util.StringUtil;
import org.apache.derby.iapi.util.UTF8Util;
import org.apache.derby.iapi.services.i18n.LocaleFinder;
import org.apache.derby.iapi.db.DatabaseContext;
import org.apache.derby.iapi.types.SQLInteger;
import org.apache.derby.iapi.types.SQLDate;
import org.apache.derby.iapi.types.SQLTime;
import org.apache.derby.iapi.types.SQLTimestamp;
import java.io.InputStream;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import java.io.UTFDataFormatException;
import java.io.EOFException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.RuleBasedCollator;
import java.text.CollationKey;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Calendar;
/**
The SQLChar represents a CHAR value with UCS_BASIC collation.
SQLChar may be used directly by any code when it is guaranteed
that the required collation is UCS_BASIC, e.g. system columns.
<p>
The state may be in char[], a String, a Clob, or an unread stream, depending
on how the datatype was created.
<p>
Stream notes:
<p>
When the datatype comes from the database layer and the length of the bytes
necessary to store the datatype on disk exceeds the size of a page of the
container holding the data then the store returns a stream rather than reading
all the bytes into a char[] or String. The hope is that the usual usage case
is that data never need be expanded in the derby layer, and that client can
just be given a stream that can be read a char at a time through the jdbc
layer. Even though SQLchar's can't ever be this big, this code is shared
by all the various character datatypes including SQLClob which is expected
to usually larger than a page.
<p>
The state can also be a stream in the case of insert/update where the client
has used a jdbc interface to set the value as a stream rather than char[].
In this case the hope is that the usual usage case is that stream never need
be read until it is passed to store, read once, and inserted into the database.
**/
public class SQLChar
extends DataType implements StringDataValue, StreamStorable
{
/**************************************************************************
* static fields of the class
**************************************************************************
*/
/**
* The pad character (space).
*/
private static final char PAD = '\u0020';
/**
* threshold, that decides when we return space back to the VM
* see getString() where it is used
*/
protected final static int RETURN_SPACE_THRESHOLD = 4096;
/**
* when we know that the array needs to grow by at least
* one byte, it is not performant to grow by just one byte
* instead this amount is used to provide a reasonable growby size.
*/
private final static int GROWBY_FOR_CHAR = 64;
private static final int BASE_MEMORY_USAGE =
ClassSize.estimateBaseFromCatalog( SQLChar.class);
/**
Static array that can be used for blank padding.
*/
private static final char[] BLANKS = new char[40];
static {
for (int i = 0; i < BLANKS.length; i++) {
BLANKS[i] = ' ';
}
}
/**
* Stream header generator for CHAR, VARCHAR and LONG VARCHAR. Currently,
* only one header format is used for these data types.
*/
protected static final StreamHeaderGenerator CHAR_HEADER_GENERATOR =
new CharStreamHeaderGenerator();
/**************************************************************************
* Fields of the class
**************************************************************************
*/
/*
* object state
*/
// Don't use value directly in most situations. Use getString()
// OR use the rawData array if rawLength != -1.
private String value;
// rawData holds the reusable array for reading in SQLChars. It contains a
// valid value if rawLength is greater than or equal to 0. See getString()
// to see how it is converted to a String. Even when converted to a String
// object the rawData array remains for potential future use, unless
// rawLength is > 4096. In this case the rawData is set to null to avoid
// huge memory use.
private char[] rawData;
private int rawLength = -1;
// For null strings, cKey = null.
private CollationKey cKey;
/**
* The value as a user-created Clob
*/
protected Clob _clobValue;
/**
* The value as a stream in the on-disk format.
*/
InputStream stream;
/* Locale info (for International support) */
private LocaleFinder localeFinder;
/**************************************************************************
* Constructors for This class:
**************************************************************************
*/
/**
* no-arg constructor, required by Formattable.
**/
public SQLChar()
{
}
public SQLChar(String val)
{
value = val;
}
public SQLChar(Clob val)
{
setValue( val );
}
/**************************************************************************
* Private/Protected methods of This class:
**************************************************************************
*/
private static void appendBlanks(char[] ca, int offset, int howMany)
{
while (howMany > 0)
{
int count = howMany > BLANKS.length ? BLANKS.length : howMany;
System.arraycopy(BLANKS, 0, ca, offset, count);
howMany -= count;
offset += count;
}
}
/**************************************************************************
* Public Methods of This class:
**************************************************************************
*/
/**************************************************************************
* Public Methods of DataValueDescriptor interface:
* Mostly implemented in Datatype.
**************************************************************************
*/
/**
* Get Boolean from a SQLChar.
*
* <p>
* Return false for only "0" or "false" for false. No case insensitivity.
* Everything else is true.
* <p>
* The above matches JCC.
*
*
* @see DataValueDescriptor#getBoolean
*
* @exception StandardException Thrown on error
**/
public boolean getBoolean()
throws StandardException
{
if (isNull())
return false;
// match JCC, match only "0" or "false" for false. No case
// insensitivity. everything else is true.
String cleanedValue = getString().trim();
return !(cleanedValue.equals("0") || cleanedValue.equals("false"));
}
/**
* Get Byte from a SQLChar.
*
* <p>
* Uses java standard Byte.parseByte() to perform coercion.
*
* @see DataValueDescriptor#getByte
*
* @exception StandardException thrown on failure to convert
**/
public byte getByte() throws StandardException
{
if (isNull())
return (byte)0;
try
{
return Byte.parseByte(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "byte");
}
}
/**
* Get Short from a SQLChar.
*
* <p>
* Uses java standard Short.parseShort() to perform coercion.
*
* @see DataValueDescriptor#getShort
*
* @exception StandardException thrown on failure to convert
**/
public short getShort() throws StandardException
{
if (isNull())
return (short)0;
try
{
return Short.parseShort(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "short");
}
}
/**
* Get int from a SQLChar.
*
* <p>
* Uses java standard Short.parseInt() to perform coercion.
*
* @see DataValueDescriptor#getInt
*
* @exception StandardException thrown on failure to convert
**/
public int getInt() throws StandardException
{
if (isNull())
return 0;
try
{
return Integer.parseInt(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "int");
}
}
/**
* Get long from a SQLChar.
*
* <p>
* Uses java standard Short.parseLong() to perform coercion.
*
* @see DataValueDescriptor#getLong
*
* @exception StandardException thrown on failure to convert
**/
public long getLong() throws StandardException
{
if (isNull())
return 0;
try
{
return Long.parseLong(getString().trim());
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "long");
}
}
/**
* Get float from a SQLChar.
*
* <p>
* Uses java standard Float.floatValue() to perform coercion.
*
* @see DataValueDescriptor#getFloat
*
* @exception StandardException thrown on failure to convert
**/
public float getFloat() throws StandardException
{
if (isNull())
return 0;
try
{
return new Float(getString().trim()).floatValue();
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "float");
}
}
/**
* Get double from a SQLChar.
*
* <p>
* Uses java standard Double.doubleValue() to perform coercion.
*
* @see DataValueDescriptor#getDouble
*
* @exception StandardException thrown on failure to convert
**/
public double getDouble() throws StandardException
{
if (isNull())
return 0;
try
{
return new Double(getString().trim()).doubleValue();
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(
SQLState.LANG_FORMAT_EXCEPTION, "double");
}
}
/**
* Get date from a SQLChar.
*
* @see DataValueDescriptor#getDate
*
* @exception StandardException thrown on failure to convert
**/
public Date getDate(Calendar cal)
throws StandardException
{
return getDate(cal, getString(), getLocaleFinder());
}
/**
* Static function to Get date from a string.
*
* @see DataValueDescriptor#getDate
*
* @exception StandardException thrown on failure to convert
**/
public static Date getDate(
java.util.Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLDate internalDate = new SQLDate(str, false, localeFinder);
return internalDate.getDate(cal);
}
/**
* Get time from a SQLChar.
*
* @see DataValueDescriptor#getTime
*
* @exception StandardException thrown on failure to convert
**/
public Time getTime(Calendar cal) throws StandardException
{
return getTime( cal, getString(), getLocaleFinder());
}
/**
* Static function to Get Time from a string.
*
* @see DataValueDescriptor#getTime
*
* @exception StandardException thrown on failure to convert
**/
public static Time getTime(
Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLTime internalTime = new SQLTime( str, false, localeFinder, cal);
return internalTime.getTime( cal);
}
/**
* Get Timestamp from a SQLChar.
*
* @see DataValueDescriptor#getTimestamp
*
* @exception StandardException thrown on failure to convert
**/
public Timestamp getTimestamp( Calendar cal) throws StandardException
{
return getTimestamp( cal, getString(), getLocaleFinder());
}
/**
* Static function to Get Timestamp from a string.
*
* @see DataValueDescriptor#getTimestamp
*
* @exception StandardException thrown on failure to convert
**/
public static Timestamp getTimestamp(
java.util.Calendar cal,
String str,
LocaleFinder localeFinder)
throws StandardException
{
if( str == null)
return null;
SQLTimestamp internalTimestamp =
new SQLTimestamp( str, false, localeFinder, cal);
return internalTimestamp.getTimestamp( cal);
}
/**************************************************************************
* Public Methods of StreamStorable interface:
**************************************************************************
*/
public InputStream returnStream()
{
return stream;
}
/**
* Set this value to the on-disk format stream.
*/
public void setStream(InputStream newStream) {
this.value = null;
this.rawLength = -1;
this.stream = newStream;
cKey = null;
_clobValue = null;
}
public void loadStream() throws StandardException
{
getString();
}
/**
* @exception StandardException Thrown on error
*/
public Object getObject() throws StandardException
{
if ( _clobValue != null ) { return _clobValue; }
else { return getString(); }
}
/**
* @exception StandardException Thrown on error
*/
public InputStream getStream() throws StandardException
{
return stream;
}
/**
* Returns a descriptor for the input stream for this character data value.
*
* @return Unless the method is overridden, {@code null} is returned.
* @throws StandardException if obtaining the descriptor fails
* @see SQLClob#getStreamWithDescriptor()
*/
public CharacterStreamDescriptor getStreamWithDescriptor()
throws StandardException {
// For now return null for all non-Clob types.
// TODO: Is this what we want, or do we want to treat some of the other
// string types as streams as well?
return null;
}
/**
* CHAR/VARCHAR/LONG VARCHAR implementation.
* Convert to a BigDecimal using getString.
*/
public int typeToBigDecimal() throws StandardException
{
return java.sql.Types.CHAR;
}
/**
* @exception StandardException Thrown on error
*/
public int getLength() throws StandardException {
if ( _clobValue != null ) { return getClobLength(); }
if (rawLength != -1)
return rawLength;
if (stream != null) {
if (stream instanceof Resetable && stream instanceof ObjectInput) {
try {
// Skip the encoded byte length.
InputStreamUtil.skipFully(stream, 2);
// Decode the whole stream to find the character length.
return (int)UTF8Util.skipUntilEOF(stream);
} catch (IOException ioe) {
throwStreamingIOException(ioe);
} finally {
try {
((Resetable) stream).resetStream();
} catch (IOException ioe) {
throwStreamingIOException(ioe);
}
}
}
}
String tmpString = getString();
if (tmpString == null) {
return 0;
} else {
int clobLength = tmpString.length();
return clobLength;
}
}
private int readCharacterLength(ObjectInput in) throws IOException {
int utflen = in.readUnsignedShort();
return utflen;
}
/**
* Wraps an {@code IOException} in a {@code StandardException} then throws
* the wrapping exception.
*
* @param ioe the {@code IOException} to wrap
* @throws StandardException the wrapping exception
*/
protected void throwStreamingIOException(IOException ioe)
throws StandardException {
throw StandardException.
newException(SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION,
ioe, getTypeName());
}
public String getTypeName()
{
return TypeId.CHAR_NAME;
}
/**
* If possible, use getCharArray() if you don't really
* need a string. getString() will cause an extra
* char array to be allocated when it calls the the String()
* constructor (the first time through), so may be
* cheaper to use getCharArray().
*
* @exception StandardException Thrown on error
*/
public String getString() throws StandardException
{
if (value == null) {
int len = rawLength;
if (len != -1) {
// data is stored in the char[] array
value = new String(rawData, 0, len);
if (len > RETURN_SPACE_THRESHOLD) {
// free up this char[] array to reduce memory usage
rawData = null;
rawLength = -1;
cKey = null;
}
} else if (_clobValue != null) {
try {
value = _clobValue.getSubString( 1L, getClobLength() );
_clobValue = null;
}
catch (SQLException se) { throw StandardException.plainWrapException( se ); }
} else if (stream != null) {
// data stored as a stream
try {
if (stream instanceof FormatIdInputStream) {
readExternal((FormatIdInputStream) stream);
} else {
readExternal(new FormatIdInputStream(stream));
}
stream = null;
// at this point the value is only in the char[]
// so call again to convert to a String
return getString();
} catch (IOException ioe) {
throw StandardException.newException(
SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION,
ioe,
"java.sql.String");
}
}
}
return value;
}
/**
* Get a char array. Typically, this is a simple
* getter that is cheaper than getString() because
* we always need to create a char array when
* doing I/O. Use this instead of getString() where
* reasonable.
* <p>
* <b>WARNING</b>: may return a character array that has spare
* characters at the end. MUST be used in conjunction
* with getLength() to be safe.
*
* @exception StandardException Thrown on error
*/
public char[] getCharArray() throws StandardException
{
if (isNull())
{
return (char[])null;
}
else if (rawLength != -1)
{
return rawData;
}
else
{
// this is expensive -- we are getting a
// copy of the char array that the
// String wrapper uses.
getString();
rawData = value.toCharArray();
rawLength = rawData.length;
cKey = null;
return rawData;
}
}
/*
* Storable interface, implies Externalizable, TypedFormat
*/
/**
Return my format identifier.
@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId
*/
public int getTypeFormatId() {
return StoredFormatIds.SQL_CHAR_ID;
}
/**
* see if the String value is null.
@see Storable#isNull
*/
public boolean isNull()
{
return ((value == null) && (rawLength == -1) && (stream == null) && (_clobValue == null));
}
/**
Writes a non-Clob data value to the modified UTF-8 format used by Derby.
The maximum stored size is based upon the UTF format
used to stored the String. The format consists of
a two byte length field and a maximum number of three
bytes for each character.
<BR>
This puts an upper limit on the length of a stored
String. The maximum stored length is 65535, these leads to
the worse case of a maximum string length of 21844 ((65535 - 2) / 3).
<BR>
Strings with stored length longer than 64K is handled with
the following format:
(1) 2 byte length: will be assigned 0.
(2) UTF formated string data.
(3) terminate the string with the following 3 bytes:
first byte is:
+---+---+---+---+---+---+---+---+
| 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
second byte is:
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
third byte is:
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
The UTF format:
Writes a string to the underlying output stream using UTF-8
encoding in a machine-independent manner.
<p>
First, two bytes are written to the output stream as if by the
<code>writeShort</code> method giving the number of bytes to
follow. This value is the number of bytes actually written out,
not the length of the string. Following the length, each character
of the string is output, in sequence, using the UTF-8 encoding
for the character.
@exception IOException if an I/O error occurs.
@since JDK1.0
@exception IOException thrown by writeUTF
@see java.io.DataInputStream
*/
public void writeExternal(ObjectOutput out) throws IOException
{
// never called when value is null
if (SanityManager.DEBUG)
SanityManager.ASSERT(!isNull());
//
// This handles the case that a CHAR or VARCHAR value was populated from
// a user Clob.
//
if ( _clobValue != null )
{
writeClobUTF( out );
return;
}
String lvalue = null;
char[] data = null;
int strlen = rawLength;
boolean isRaw;
if (strlen < 0) {
lvalue = value;
strlen = lvalue.length();
isRaw = false;
} else {
data = rawData;
isRaw = true;
}
// byte length will always be at least string length
int utflen = strlen;
for (int i = 0 ; (i < strlen) && (utflen <= 65535); i++)
{
int c = isRaw ? data[i] : lvalue.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F))
{
// 1 byte for character
}
else if (c > 0x07FF)
{
utflen += 2; // 3 bytes for character
}
else
{
utflen += 1; // 2 bytes for character
}
}
StreamHeaderGenerator header = getStreamHeaderGenerator();
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!header.expectsCharCount());
}
// Generate the header, write it to the destination stream, write the
// user data and finally write an EOF-marker is required.
header.generateInto(out, utflen);
writeUTF(out, strlen, isRaw, null );
header.writeEOF(out, utflen);
}
/**
* Writes the user data value to a stream in the modified UTF-8 format.
*
* @param out destination stream
* @param strLen string length of the value
* @param isRaw {@code true} if the source is {@code rawData}, {@code false}
* if the source is {@code value}
* @param characterReader Reader from _clobValue if it exists
* @throws IOException if writing to the destination stream fails
*/
private final void writeUTF(ObjectOutput out, int strLen,
final boolean isRaw, Reader characterReader)
throws IOException {
// Copy the source reference into a local variable (optimization).
final char[] data = isRaw ? rawData : null;
final String lvalue = isRaw ? null : value;
// Iterate through the value and write it as modified UTF-8.
for (int i = 0 ; i < strLen ; i++) {
int c;
if ( characterReader != null ) { c = characterReader.read(); }
else { c = isRaw ? data[i] : lvalue.charAt(i); }
if ((c >= 0x0001) && (c <= 0x007F))
{
out.write(c);
}
else if (c > 0x07FF)
{
out.write(0xE0 | ((c >> 12) & 0x0F));
out.write(0x80 | ((c >> 6) & 0x3F));
out.write(0x80 | ((c >> 0) & 0x3F));
}
else
{
out.write(0xC0 | ((c >> 6) & 0x1F));
out.write(0x80 | ((c >> 0) & 0x3F));
}
}
}
/**
* Writes the header and the user data for a CLOB to the destination stream.
*
* @param out destination stream
* @throws IOException if writing to the destination stream fails
*/
protected final void writeClobUTF(ObjectOutput out)
throws IOException {
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!isNull());
SanityManager.ASSERT(stream == null, "Stream not null!");
}
boolean isUserClob = ( _clobValue != null );
try {
boolean isRaw = rawLength >= 0;
// Assume isRaw, update afterwards if required.
int strLen = rawLength;
if (!isRaw) {
if ( isUserClob ) { strLen = rawGetClobLength(); }
else { strLen = value.length(); }
}
// Generate the header and invoke the encoding routine.
StreamHeaderGenerator header = getStreamHeaderGenerator();
int toEncodeLen = header.expectsCharCount() ? strLen : -1;
header.generateInto(out, toEncodeLen);
Reader characterReader = null;
if ( isUserClob ) { characterReader = _clobValue.getCharacterStream(); }
writeUTF(out, strLen, isRaw, characterReader );
header.writeEOF(out, toEncodeLen);
if ( isUserClob ) { characterReader.close(); }
}
catch (SQLException se)
{
IOException ioe = new IOException( se.getMessage() );
ioe.initCause( se );
throw ioe;
}
}
/**
* Reads in a string from the specified data input stream. The
* string has been encoded using a modified UTF-8 format.
* <p>
* The first two bytes are read as if by
* <code>readUnsignedShort</code>. This value gives the number of
* following bytes that are in the encoded string, not
* the length of the resulting string. The following bytes are then
* interpreted as bytes encoding characters in the UTF-8 format
* and are converted into characters.
* <p>
* This method blocks until all the bytes are read, the end of the
* stream is detected, or an exception is thrown.
*
* @param in a data input stream.
* @exception EOFException if the input stream reaches the end
* before all the bytes.
* @exception IOException if an I/O error occurs.
* @exception UTFDataFormatException if the bytes do not represent a
* valid UTF-8 encoding of a Unicode string.
* @see java.io.DataInputStream#readUnsignedShort()
* @see java.io.Externalizable#readExternal
*/
public void readExternalFromArray(ArrayInputStream in)
throws IOException
{
resetForMaterialization();
int utfLen = (((in.read() & 0xFF) << 8) | (in.read() & 0xFF));
if (rawData == null || rawData.length < utfLen) {
// This array may be as much as three times too big. This happens
// if the content is only 3-byte characters (i.e. CJK).
// TODO: Decide if a threshold should be introduced, where the
// content is copied to a smaller array if the number of
// unused array positions exceeds the threshold.
rawData = new char[utfLen];
}
arg_passer[0] = rawData;
rawLength = in.readDerbyUTF(arg_passer, utfLen);
rawData = arg_passer[0];
}
char[][] arg_passer = new char[1][];
/**
* Reads a CLOB from the source stream and materializes the value in a
* character array.
*
* @param in source stream
* @param charLen the char length of the value, or {@code 0} if unknown
* @throws IOException if reading from the source fails
*/
protected void readExternalClobFromArray(ArrayInputStream in, int charLen)
throws IOException {
resetForMaterialization();
if (rawData == null || rawData.length < charLen) {
rawData = new char[charLen];
}
arg_passer[0] = rawData;
rawLength = in.readDerbyUTF(arg_passer, 0);
rawData = arg_passer[0];
}
/**
* Resets state after materializing value from an array.
*/
private void resetForMaterialization() {
value = null;
stream = null;
cKey = null;
}
public void readExternal(ObjectInput in) throws IOException
{
// Read the stored length in the stream header.
int utflen = in.readUnsignedShort();
readExternal(in, utflen, 0);
}
/**
* Restores the data value from the source stream, materializing the value
* in memory.
*
* @param in the source stream
* @param utflen the byte length, or {@code 0} if unknown
* @param knownStrLen the char length, or {@code 0} if unknown
* @throws UTFDataFormatException if an encoding error is detected
* @throws IOException if reading the stream fails
*/
protected void readExternal(ObjectInput in, int utflen,
final int knownStrLen)
throws IOException {
int requiredLength;
// minimum amount that is reasonable to grow the array
// when we know the array needs to growby at least one
// byte but we dont want to grow by one byte as that
// is not performant
int minGrowBy = growBy();
if (utflen != 0)
{
// the object was not stored as a streaming column
// we know exactly how long it is
requiredLength = utflen;
}
else
{
// the object was stored as a streaming column
// and we have a clue how much we can read unblocked
// OR
// The original string was a 0 length string.
requiredLength = in.available();
if (requiredLength < minGrowBy)
requiredLength = minGrowBy;
}
char str[];
if ((rawData == null) || (requiredLength > rawData.length)) {
str = new char[requiredLength];
} else {
str = rawData;
}
int arrayLength = str.length;
// Set these to null to allow GC of the array if required.
rawData = null;
resetForMaterialization();
int count = 0;
int strlen = 0;
readingLoop:
while (((strlen < knownStrLen) || (knownStrLen == 0)) &&
((count < utflen) || (utflen == 0)))
{
int c;
try {
c = in.readUnsignedByte();
} catch (EOFException eof) {
if (utflen != 0)
throw new EOFException();
// This is the case for a 0 length string.
// OR the string was originally streamed in
// which puts a 0 for utflen but no trailing
// E0,0,0 markers.
break readingLoop;
}
//if (c == -1) // read EOF
//{
// if (utflen != 0)
// throw new EOFException();
// break;
//}
// change it to an unsigned byte
//c &= 0xFF;
if (strlen >= arrayLength) // the char array needs to be grown
{
int growby = in.available();
// We know that the array needs to be grown by at least one.
// However, even if the input stream wants to block on every
// byte, we don't want to grow by a byte at a time.
// Note, for large data (clob > 32k), it is performant
// to grow the array by atleast 4k rather than a small amount
// Even better maybe to grow by 32k but then may be
// a little excess(?) for small data.
// hopefully in.available() will give a fair
// estimate of how much data can be read to grow the
// array by larger and necessary chunks.
// This performance issue due to
// the slow growth of this array was noticed since inserts
// on clobs was taking a really long time as
// the array here grew previously by 64 bytes each time
// till stream was drained. (Derby-302)
// for char, growby 64 seems reasonable, but for varchar
// clob 4k or 32k is performant and hence
// growBy() is override correctly to ensure this
if (growby < minGrowBy)
growby = minGrowBy;
int newstrlength = arrayLength + growby;
char oldstr[] = str;
str = new char[newstrlength];
System.arraycopy(oldstr, 0, str, 0, arrayLength);
arrayLength = newstrlength;
}
/// top fours bits of the first unsigned byte that maps to a
// 1,2 or 3 byte character
//
// 0000xxxx - 0 - 1 byte char
// 0001xxxx - 1 - 1 byte char
// 0010xxxx - 2 - 1 byte char
// 0011xxxx - 3 - 1 byte char
// 0100xxxx - 4 - 1 byte char
// 0101xxxx - 5 - 1 byte char
// 0110xxxx - 6 - 1 byte char
// 0111xxxx - 7 - 1 byte char
// 1000xxxx - 8 - error
// 1001xxxx - 9 - error
// 1010xxxx - 10 - error
// 1011xxxx - 11 - error
// 1100xxxx - 12 - 2 byte char
// 1101xxxx - 13 - 2 byte char
// 1110xxxx - 14 - 3 byte char
// 1111xxxx - 15 - error
int char2, char3;
char actualChar;
if ((c & 0x80) == 0x00)
{
// one byte character
count++;
actualChar = (char) c;
}
else if ((c & 0x60) == 0x40) // we know the top bit is set here
{
// two byte character
count += 2;
if (utflen != 0 && count > utflen)
throw new UTFDataFormatException();
char2 = in.readUnsignedByte();
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException();
actualChar = (char)(((c & 0x1F) << 6) | (char2 & 0x3F));
}
else if ((c & 0x70) == 0x60) // we know the top bit is set here
{
// three byte character
count += 3;
if (utflen != 0 && count > utflen)
throw new UTFDataFormatException();
char2 = in.readUnsignedByte();
char3 = in.readUnsignedByte();
if ((c == 0xE0) && (char2 == 0) && (char3 == 0)
&& (utflen == 0))
{
// we reached the end of a long string,
// that was terminated with
// (11100000, 00000000, 00000000)
break readingLoop;
}
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException();
actualChar = (char)(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
}
else {
throw new UTFDataFormatException(
"Invalid code point: " + Integer.toHexString(c));
}
str[strlen++] = actualChar;
}
rawData = str;
rawLength = strlen;
}
/**
* returns the reasonable minimum amount by
* which the array can grow . See readExternal.
* when we know that the array needs to grow by at least
* one byte, it is not performant to grow by just one byte
* instead this amount is used to provide a resonable growby size.
* @return minimum reasonable growby size
*/
protected int growBy()
{
return GROWBY_FOR_CHAR; //seems reasonable for a char
}
/**
* @see Storable#restoreToNull
*
*/
public void restoreToNull()
{
value = null;
stream = null;
rawLength = -1;
cKey = null;
}
/**
@exception StandardException thrown on error
*/
public boolean compare(int op,
DataValueDescriptor other,
boolean orderedNulls,
boolean unknownRV)
throws StandardException
{
if (!orderedNulls) // nulls are unordered
{
if (this.isNull() || ((DataValueDescriptor) other).isNull())
return unknownRV;
}
/* When comparing String types to non-string types, we always
* convert the string type to the non-string type.
*/
if (! (other instanceof SQLChar))
{
return other.compare(flip(op), this, orderedNulls, unknownRV);
}
/* Do the comparison */
return super.compare(op, other, orderedNulls, unknownRV);
}
/**
@exception StandardException thrown on error
*/
public int compare(DataValueDescriptor other) throws StandardException
{
/* Use compare method from dominant type, negating result
* to reflect flipping of sides.
*/
if (typePrecedence() < other.typePrecedence())
{
return - (other.compare(this));
}
// stringCompare deals with null as comparable and smallest
return stringCompare(this, (SQLChar)other);
}
/*
* CloneableObject interface
*/
/** From CloneableObject
* Shallow clone a StreamStorable without objectifying. This is used to
* avoid unnecessary objectifying of a stream object. The only
* difference of this method from getClone is this method does not
* objectify a stream.
*/
public Object cloneObject()
{
if ((stream == null) && (_clobValue == null)) { return getClone(); }
SQLChar self = (SQLChar) getNewNull();
self.copyState(this);
return self;
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#getClone */
public DataValueDescriptor getClone()
{
try
{
return new SQLChar(getString());
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
SanityManager.THROWASSERT("Unexpected exception", se);
return null;
}
}
/**
* @see DataValueDescriptor#getNewNull
*
*/
public DataValueDescriptor getNewNull()
{
return new SQLChar();
}
/** @see StringDataValue#getValue(RuleBasedCollator) */
public StringDataValue getValue(RuleBasedCollator collatorForComparison)
{
if (collatorForComparison == null)
{//null collatorForComparison means use UCS_BASIC for collation
return this;
} else {
//non-null collatorForComparison means use collator sensitive
//implementation of SQLChar
CollatorSQLChar s = new CollatorSQLChar(collatorForComparison);
s.copyState(this);
return s;
}
}
/**
* @see DataValueDescriptor#setValueFromResultSet
*
* @exception SQLException Thrown on error
*/
public final void setValueFromResultSet(ResultSet resultSet, int colNumber,
boolean isNullable)
throws SQLException
{
setValue(resultSet.getString(colNumber));
}
/**
Set the value into a PreparedStatement.
*/
public final void setInto(
PreparedStatement ps,
int position)
throws SQLException, StandardException
{
ps.setString(position, getString());
}
public void setValue(Clob theValue)
{
stream = null;
rawLength = -1;
cKey = null;
value = null;
_clobValue = theValue;
}
public void setValue(String theValue)
{
stream = null;
rawLength = -1;
cKey = null;
_clobValue = null;
value = theValue;
}
public void setValue(boolean theValue) throws StandardException
{
// match JCC.
setValue(theValue ? "1" : "0");
}
public void setValue(int theValue) throws StandardException
{
setValue(Integer.toString(theValue));
}
public void setValue(double theValue) throws StandardException
{
setValue(Double.toString(theValue));
}
public void setValue(float theValue) throws StandardException
{
setValue(Float.toString(theValue));
}
public void setValue(short theValue) throws StandardException
{
setValue(Short.toString(theValue));
}
public void setValue(long theValue) throws StandardException
{
setValue(Long.toString(theValue));
}
public void setValue(byte theValue) throws StandardException
{
setValue(Byte.toString(theValue));
}
public void setValue(byte[] theValue) throws StandardException
{
if (theValue == null)
{
restoreToNull();
return;
}
/*
** We can't just do a new String(theValue)
** because that method assumes we are converting
** ASCII and it will take on char per byte.
** So we need to convert the byte array to a
** char array and go from there.
**
** If we have an odd number of bytes pad out.
*/
int mod = (theValue.length % 2);
int len = (theValue.length/2) + mod;
char[] carray = new char[len];
int cindex = 0;
int bindex = 0;
/*
** If we have a left over byte, then get
** that now.
*/
if (mod == 1)
{
carray[--len] = (char)(theValue[theValue.length - 1] << 8);
}
for (; cindex < len; bindex+=2, cindex++)
{
carray[cindex] = (char)((theValue[bindex] << 8) |
(theValue[bindex+1] & 0x00ff));
}
setValue(new String(carray));
}
/**
Only to be called when an application through JDBC is setting a
SQLChar to a java.math.BigDecimal.
*/
public void setBigDecimal(Number bigDecimal) throws StandardException
{
if (bigDecimal == null)
setToNull();
else
setValue(bigDecimal.toString());
}
/** @exception StandardException Thrown on error */
public void setValue(Date theValue, Calendar cal) throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCDate( cal, sb);
strValue= sb.toString();
}
}
setValue( strValue);
}
/** @exception StandardException Thrown on error */
public void setValue(Time theValue, Calendar cal) throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCTime( cal, sb);
strValue= sb.toString();
}
}
setValue( strValue);
}
/** @exception StandardException Thrown on error */
public void setValue(
Timestamp theValue,
Calendar cal)
throws StandardException
{
String strValue = null;
if( theValue != null)
{
if( cal == null)
strValue = theValue.toString();
else
{
cal.setTime( theValue);
StringBuffer sb = new StringBuffer();
formatJDBCDate( cal, sb);
sb.append( ' ');
formatJDBCTime( cal, sb);
int micros =
(theValue.getNanos() + SQLTimestamp.FRACTION_TO_NANO/2) /
SQLTimestamp.FRACTION_TO_NANO;
if( micros > 0)
{
sb.append( '.');
String microsStr = Integer.toString( micros);
if(microsStr.length() > SQLTimestamp.MAX_FRACTION_DIGITS)
{
sb.append(
microsStr.substring(
0, SQLTimestamp.MAX_FRACTION_DIGITS));
}
else
{
for(int i = microsStr.length();
i < SQLTimestamp.MAX_FRACTION_DIGITS ; i++)
{
sb.append( '0');
}
sb.append( microsStr);
}
}
strValue= sb.toString();
}
}
setValue( strValue);
}
private void formatJDBCDate( Calendar cal, StringBuffer sb)
{
SQLDate.dateToString( cal.get( Calendar.YEAR),
cal.get( Calendar.MONTH) - Calendar.JANUARY + 1,
cal.get( Calendar.DAY_OF_MONTH),
sb);
}
private void formatJDBCTime( Calendar cal, StringBuffer sb)
{
SQLTime.timeToString(
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND),
sb);
}
/**
* Set the value from the stream which is in the on-disk format.
* @param theStream On disk format of the stream
* @param valueLength length of the logical value in characters.
*/
public final void setValue(InputStream theStream, int valueLength)
{
setStream(theStream);
}
/**
* Allow any Java type to be cast to a character type using
* Object.toString.
* @see DataValueDescriptor#setObjectForCast
*
* @exception StandardException
* thrown on failure
*/
public void setObjectForCast(
Object theValue,
boolean instanceOfResultType,
String resultTypeClassName)
throws StandardException
{
if (theValue == null)
{
setToNull();
return;
}
if ("java.lang.String".equals(resultTypeClassName))
setValue(theValue.toString());
else
super.setObjectForCast(
theValue, instanceOfResultType, resultTypeClassName);
}
protected void setFrom(DataValueDescriptor theValue)
throws StandardException
{
if ( theValue instanceof SQLChar )
{
SQLChar that = (SQLChar) theValue;
if ( that._clobValue != null )
{
setValue( that._clobValue );
return;
}
}
setValue(theValue.getString());
}
/**
* Normalization method - this method may be called when putting
* a value into a SQLChar, for example, when inserting into a SQLChar
* column. See NormalizeResultSet in execution.
*
* @param desiredType The type to normalize the source column to
* @param source The value to normalize
*
*
* @exception StandardException Thrown for null into
* non-nullable column, and for
* truncation error
*/
public void normalize(
DataTypeDescriptor desiredType,
DataValueDescriptor source)
throws StandardException
{
normalize(desiredType, source.getString());
}
protected void normalize(DataTypeDescriptor desiredType, String sourceValue)
throws StandardException
{
int desiredWidth = desiredType.getMaximumWidth();
int sourceWidth = sourceValue.length();
/*
** If the input is already the right length, no normalization is
** necessary - just return the source.
*/
if (sourceWidth == desiredWidth) {
setValue(sourceValue);
return;
}
/*
** If the input is shorter than the desired type, construct a new
** SQLChar padded with blanks to the right length.
*/
if (sourceWidth < desiredWidth)
{
setToNull();
char[] ca;
if ((rawData == null) || (desiredWidth > rawData.length)) {
ca = rawData = new char[desiredWidth];
} else {
ca = rawData;
}
sourceValue.getChars(0, sourceWidth, ca, 0);
SQLChar.appendBlanks(ca, sourceWidth, desiredWidth - sourceWidth);
rawLength = desiredWidth;
return;
}
/*
** Check whether any non-blank characters will be truncated.
*/
hasNonBlankChars(sourceValue, desiredWidth, sourceWidth);
/*
** No non-blank characters will be truncated. Truncate the blanks
** to the desired width.
*/
String truncatedString = sourceValue.substring(0, desiredWidth);
setValue(truncatedString);
}
/*
** Method to check for truncation of non blank chars.
*/
protected final void hasNonBlankChars(String source, int start, int end)
throws StandardException
{
/*
** Check whether any non-blank characters will be truncated.
*/
for (int posn = start; posn < end; posn++)
{
if (source.charAt(posn) != ' ')
{
throw StandardException.newException(
SQLState.LANG_STRING_TRUNCATION,
getTypeName(),
StringUtil.formatForPrint(source),
String.valueOf(start));
}
}
}
///////////////////////////////////////////////////////////////
//
// VariableSizeDataValue INTERFACE
//
///////////////////////////////////////////////////////////////
/**
* Set the width of the to the desired value. Used
* when CASTing. Ideally we'd recycle normalize(), but
* the behavior is different (we issue a warning instead
* of an error, and we aren't interested in nullability).
*
* @param desiredWidth the desired length
* @param desiredScale the desired scale (ignored)
* @param errorOnTrunc throw an error on truncation
*
* @exception StandardException Thrown when errorOnTrunc
* is true and when a shrink will truncate non-white
* spaces.
*/
public void setWidth(int desiredWidth,
int desiredScale, // Ignored
boolean errorOnTrunc)
throws StandardException
{
int sourceWidth;
/*
** If the input is NULL, nothing to do.
*/
if ( (_clobValue == null ) && (getString() == null) )
{
return;
}
sourceWidth = getLength();
/*
** If the input is shorter than the desired type, construct a new
** SQLChar padded with blanks to the right length. Only
** do this if we have a SQLChar -- SQLVarchars don't
** pad.
*/
if (sourceWidth < desiredWidth)
{
if (!(this instanceof SQLVarchar))
{
StringBuffer strbuf;
strbuf = new StringBuffer(getString());
for ( ; sourceWidth < desiredWidth; sourceWidth++)
{
strbuf.append(' ');
}
setValue(new String(strbuf));
}
}
else if (sourceWidth > desiredWidth && desiredWidth > 0)
{
/*
** Check whether any non-blank characters will be truncated.
*/
if (errorOnTrunc)
hasNonBlankChars(getString(), desiredWidth, sourceWidth);
//RESOLVE: should issue a warning instead
/*
** Truncate to the desired width.
*/
setValue(getString().substring(0, desiredWidth));
}
return;
}
/*
** SQL Operators
*/
/**
* The = operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the =
* @param right The value on the right side of the =
*
* @return A SQL boolean value telling whether the two parameters are equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue equals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) == 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) == 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The <> operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <>
* @param right The value on the right side of the <>
*
* @return A SQL boolean value telling whether the two parameters
* are not equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue notEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) != 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) != 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The < operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <
* @param right The value on the right side of the <
*
* @return A SQL boolean value telling whether the first operand is
* less than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) < 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) < 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The > operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >
* @param right The value on the right side of the >
*
* @return A SQL boolean value telling whether the first operand is
* greater than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) > 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) > 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The <= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <=
* @param right The value on the right side of the <=
*
* @return A SQL boolean value telling whether the first operand is
* less than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) <= 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) <= 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/**
* The >= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >=
* @param right The value on the right side of the >=
*
* @return A SQL boolean value telling whether the first operand is
* greater than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
boolean comparison;
if ((left instanceof SQLChar) && (right instanceof SQLChar))
{
comparison = stringCompare((SQLChar) left, (SQLChar) right) >= 0;
}
else
{
comparison = stringCompare(left.getString(),
right.getString()) >= 0;
}
return SQLBoolean.truthValue(left,
right,
comparison);
}
/*
** Concatable interface
*/
/**
* This method implements the char_length function for char.
*
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLInteger containing the length of the char value
*
* @exception StandardException Thrown on error
*
* @see ConcatableDataValue#charLength(NumberDataValue)
*/
public NumberDataValue charLength(NumberDataValue result)
throws StandardException
{
if (result == null)
{
result = new SQLInteger();
}
if (this.isNull())
{
result.setToNull();
return result;
}
result.setValue(this.getLength());
return result;
}
/**
* @see StringDataValue#concatenate
*
* @exception StandardException Thrown on error
*/
public StringDataValue concatenate(
StringDataValue leftOperand,
StringDataValue rightOperand,
StringDataValue result)
throws StandardException
{
if (leftOperand.isNull() || leftOperand.getString() == null ||
rightOperand.isNull() || rightOperand.getString() == null)
{
result.setToNull();
return result;
}
result.setValue(
leftOperand.getString().concat(rightOperand.getString()));
return result;
}
/**
* This method implements the like function for char (with no escape value).
*
* @param pattern The pattern to use
*
* @return A SQL boolean value telling whether the first operand is
* like the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue like(DataValueDescriptor pattern)
throws StandardException
{
Boolean likeResult;
// note that we call getLength() because the length
// of the char array may be different than the
// length we should be using (i.e. getLength()).
// see getCharArray() for more info
char[] evalCharArray = getCharArray();
char[] patternCharArray = ((SQLChar)pattern).getCharArray();
likeResult = Like.like(evalCharArray,
getLength(),
patternCharArray,
pattern.getLength(),
null);
return SQLBoolean.truthValue(this,
pattern,
likeResult);
}
/**
* This method implements the like function for char with an escape value.
*
* @param pattern The pattern to use
*
* @return A SQL boolean value telling whether the first operand is
* like the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue like(
DataValueDescriptor pattern,
DataValueDescriptor escape)
throws StandardException
{
Boolean likeResult;
if (SanityManager.DEBUG)
SanityManager.ASSERT(
pattern instanceof StringDataValue &&
escape instanceof StringDataValue,
"All three operands must be instances of StringDataValue");
// ANSI states a null escape yields 'unknown' results
//
// This method is only called when we have an escape clause, so this
// test is valid
if (escape.isNull())
{
throw StandardException.newException(SQLState.LANG_ESCAPE_IS_NULL);
}
// note that we call getLength() because the length
// of the char array may be different than the
// length we should be using (i.e. getLength()).
// see getCharArray() for more info
char[] evalCharArray = getCharArray();
char[] patternCharArray = ((SQLChar)pattern).getCharArray();
char[] escapeCharArray = (((SQLChar) escape).getCharArray());
int escapeLength = escape.getLength();
if (escapeCharArray != null && escapeLength != 1 )
{
throw StandardException.newException(
SQLState.LANG_INVALID_ESCAPE_CHARACTER,
new String(escapeCharArray));
}
likeResult = Like.like(evalCharArray,
getLength(),
patternCharArray,
pattern.getLength(),
escapeCharArray,
escapeLength,
null);
return SQLBoolean.truthValue(this,
pattern,
likeResult);
}
/**
* This method implements the locate function for char.
* @param searchFrom - The string to search from
* @param start - The position to search from in string searchFrom
* @param result - The object to return
*
* Note: use getString() to get the string to search for.
*
* @return The position in searchFrom the fist occurrence of this.value.
* 0 is returned if searchFrom does not contain this.value.
* @exception StandardException Thrown on error
*/
public NumberDataValue locate( StringDataValue searchFrom,
NumberDataValue start,
NumberDataValue result)
throws StandardException
{
int startVal;
if( result == null )
{
result = new SQLInteger();
}
if( start.isNull() )
{
startVal = 1;
}
else
{
startVal = start.getInt();
}
if( isNull() || searchFrom.isNull() )
{
result.setToNull();
return result;
}
String mySearchFrom = searchFrom.getString();
String mySearchFor = this.getString();
/* the below 2 if conditions are to emulate DB2's behavior */
if( startVal < 1 )
{
throw StandardException.newException(
SQLState.LANG_INVALID_PARAMETER_FOR_SEARCH_POSITION,
new String(getString()), new String(mySearchFrom),
new Integer(startVal));
}
if( mySearchFor.length() == 0 )
{
result.setValue( startVal );
return result;
}
result.setValue( mySearchFrom.indexOf(mySearchFor, startVal - 1) + 1);
return result;
}
/**
* The SQL substr() function.
*
* @param start Start of substr
* @param length Length of substr
* @param result The result of a previous call to this method,
* null if not called yet.
* @param maxLen Maximum length of the result
*
* @return A ConcatableDataValue containing the result of the substr()
*
* @exception StandardException Thrown on error
*/
public ConcatableDataValue substring(
NumberDataValue start,
NumberDataValue length,
ConcatableDataValue result,
int maxLen)
throws StandardException
{
int startInt;
int lengthInt;
StringDataValue stringResult;
if (result == null)
{
result = getNewVarchar();
}
stringResult = (StringDataValue) result;
/* The result is null if the receiver (this) is null or if the length
* is negative.
* We will return null, which is the only sensible thing to do.
* (If user did not specify a length then length is not a user null.)
*/
if (this.isNull() || start.isNull() ||
(length != null && length.isNull()))
{
stringResult.setToNull();
return stringResult;
}
startInt = start.getInt();
// If length is not specified, make it till end of the string
if (length != null)
{
lengthInt = length.getInt();
}
else lengthInt = maxLen - startInt + 1;
/* DB2 Compatibility: Added these checks to match DB2. We currently
* enforce these limits in both modes. We could do these checks in DB2
* mode only, if needed, so leaving earlier code for out of range in
* for now, though will not be exercised
*/
if ((startInt <= 0 || lengthInt < 0 || startInt > maxLen ||
lengthInt > maxLen - startInt + 1))
{
throw StandardException.newException(
SQLState.LANG_SUBSTR_START_OR_LEN_OUT_OF_RANGE);
}
// Return null if length is non-positive
if (lengthInt < 0)
{
stringResult.setToNull();
return stringResult;
}
/* If startInt < 0 then we count from the right of the string */
if (startInt < 0)
{
// Return '' if window is to left of string.
if (startInt + getLength() < 0 &&
(startInt + getLength() + lengthInt <= 0))
{
stringResult.setValue("");
return stringResult;
}
// Convert startInt to positive to get substring from right
startInt += getLength();
while (startInt < 0)
{
startInt++;
lengthInt--;
}
}
else if (startInt > 0)
{
/* java substring() is 0 based */
startInt--;
}
/* Oracle docs don't say what happens if the window is to the
* left of the string. Return "" if the window
* is to the left or right.
*/
if (lengthInt == 0 ||
lengthInt <= 0 - startInt ||
startInt > getLength())
{
stringResult.setValue("");
return stringResult;
}
if (lengthInt >= getLength() - startInt)
{
stringResult.setValue(getString().substring(startInt));
}
else
{
stringResult.setValue(
getString().substring(startInt, startInt + lengthInt));
}
return stringResult;
}
/**
* This function public for testing purposes.
*
* @param trimType Type of trim (LEADING, TRAILING, or BOTH)
* @param trimChar Character to trim
* @param source String from which to trim trimChar
*
* @return A String containing the result of the trim.
*/
private String trimInternal(int trimType, char trimChar, String source)
{
if (source == null) {
return null;
}
int len = source.length();
int start = 0;
if (trimType == LEADING || trimType == BOTH)
{
for (; start < len; start++)
if (trimChar != source.charAt(start))
break;
}
if (start == len)
return "";
int end = len - 1;
if (trimType == TRAILING || trimType == BOTH)
{
for (; end >= 0; end--)
if (trimChar != source.charAt(end))
break;
}
if (end == -1)
return "";
return source.substring(start, end + 1);
}
/**
* @param trimType Type of trim (LEADING, TRAILING, or BOTH)
* @param trimChar Character to trim from this SQLChar (may be null)
* @param result The result of a previous call to this method,
* null if not called yet.
*
* @return A StringDataValue containing the result of the trim.
*/
public StringDataValue ansiTrim(
int trimType,
StringDataValue trimChar,
StringDataValue result)
throws StandardException
{
if (result == null)
{
result = getNewVarchar();
}
if (trimChar == null || trimChar.getString() == null)
{
result.setToNull();
return result;
}
if (trimChar.getString().length() != 1)
{
throw StandardException.newException(
SQLState.LANG_INVALID_TRIM_CHARACTER, trimChar.getString());
}
char trimCharacter = trimChar.getString().charAt(0);
result.setValue(trimInternal(trimType, trimCharacter, getString()));
return result;
}
/** @see StringDataValue#upper
*
* @exception StandardException Thrown on error
*/
public StringDataValue upper(StringDataValue result)
throws StandardException
{
if (result == null)
{
result = (StringDataValue) getNewNull();
}
if (this.isNull())
{
result.setToNull();
return result;
}
String upper = getString();
upper = upper.toUpperCase(getLocale());
result.setValue(upper);
return result;
}
/** @see StringDataValue#lower
*
* @exception StandardException Thrown on error
*/
public StringDataValue lower(StringDataValue result)
throws StandardException
{
if (result == null)
{
result = (StringDataValue) getNewNull();
}
if (this.isNull())
{
result.setToNull();
return result;
}
String lower = getString();
lower = lower.toLowerCase(getLocale());
result.setValue(lower);
return result;
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#typePrecedence */
public int typePrecedence()
{
return TypeId.CHAR_PRECEDENCE;
}
/**
* Compare two Strings using standard SQL semantics.
*
* @param op1 The first String
* @param op2 The second String
*
* @return -1 - op1 < op2
* 0 - op1 == op2
* 1 - op1 > op2
*/
protected static int stringCompare(String op1, String op2)
{
int posn;
char leftchar;
char rightchar;
int leftlen;
int rightlen;
int retvalIfLTSpace;
String remainingString;
int remainingLen;
/*
** By convention, nulls sort High, and null == null
*/
if (op1 == null || op2 == null)
{
if (op1 != null) // op2 == null
return -1;
if (op2 != null) // op1 == null
return 1;
return 0; // both null
}
/*
** Compare characters until we find one that isn't equal, or until
** one String or the other runs out of characters.
*/
leftlen = op1.length();
rightlen = op2.length();
int shorterLen = leftlen < rightlen ? leftlen : rightlen;
for (posn = 0; posn < shorterLen; posn++)
{
leftchar = op1.charAt(posn);
rightchar = op2.charAt(posn);
if (leftchar != rightchar)
{
if (leftchar < rightchar)
return -1;
else
return 1;
}
}
/*
** All the characters are equal up to the length of the shorter
** string. If the two strings are of equal length, the values are
** equal.
*/
if (leftlen == rightlen)
return 0;
/*
** One string is shorter than the other. Compare the remaining
** characters in the longer string to spaces (the SQL standard says
** that in this case the comparison is as if the shorter string is
** padded with blanks to the length of the longer string.
*/
if (leftlen > rightlen)
{
/*
** Remaining characters are on the left.
*/
/* If a remaining character is less than a space,
* return -1 (op1 < op2) */
retvalIfLTSpace = -1;
remainingString = op1;
posn = rightlen;
remainingLen = leftlen;
}
else
{
/*
** Remaining characters are on the right.
*/
/* If a remaining character is less than a space,
* return 1 (op1 > op2) */
retvalIfLTSpace = 1;
remainingString = op2;
posn = leftlen;
remainingLen = rightlen;
}
/* Look at the remaining characters in the longer string */
for ( ; posn < remainingLen; posn++)
{
char remainingChar;
/*
** Compare the characters to spaces, and return the appropriate
** value, depending on which is the longer string.
*/
remainingChar = remainingString.charAt(posn);
if (remainingChar < ' ')
return retvalIfLTSpace;
else if (remainingChar > ' ')
return -retvalIfLTSpace;
}
/* The remaining characters in the longer string were all spaces,
** so the strings are equal.
*/
return 0;
}
/**
* Compare two SQLChars.
*
* @exception StandardException Thrown on error
*/
protected int stringCompare(SQLChar char1, SQLChar char2)
throws StandardException
{
return stringCompare(char1.getCharArray(), char1.getLength(),
char2.getCharArray(), char2.getLength());
}
/**
* Compare two Strings using standard SQL semantics.
*
* @param op1 The first String
* @param op2 The second String
*
* @return -1 - op1 < op2
* 0 - op1 == op2
* 1 - op1 > op2
*/
protected static int stringCompare(
char[] op1,
int leftlen,
char[] op2,
int rightlen)
{
int posn;
char leftchar;
char rightchar;
int retvalIfLTSpace;
char[] remainingString;
int remainingLen;
/*
** By convention, nulls sort High, and null == null
*/
if (op1 == null || op2 == null)
{
if (op1 != null) // op2 == null
return -1;
if (op2 != null) // op1 == null
return 1;
return 0; // both null
}
/*
** Compare characters until we find one that isn't equal, or until
** one String or the other runs out of characters.
*/
int shorterLen = leftlen < rightlen ? leftlen : rightlen;
for (posn = 0; posn < shorterLen; posn++)
{
leftchar = op1[posn];
rightchar = op2[posn];
if (leftchar != rightchar)
{
if (leftchar < rightchar)
return -1;
else
return 1;
}
}
/*
** All the characters are equal up to the length of the shorter
** string. If the two strings are of equal length, the values are
** equal.
*/
if (leftlen == rightlen)
return 0;
/*
** One string is shorter than the other. Compare the remaining
** characters in the longer string to spaces (the SQL standard says
** that in this case the comparison is as if the shorter string is
** padded with blanks to the length of the longer string.
*/
if (leftlen > rightlen)
{
/*
** Remaining characters are on the left.
*/
/* If a remaining character is less than a space,
* return -1 (op1 < op2) */
retvalIfLTSpace = -1;
remainingString = op1;
posn = rightlen;
remainingLen = leftlen;
}
else
{
/*
** Remaining characters are on the right.
*/
/* If a remaining character is less than a space,
* return 1 (op1 > op2) */
retvalIfLTSpace = 1;
remainingString = op2;
posn = leftlen;
remainingLen = rightlen;
}
/* Look at the remaining characters in the longer string */
for ( ; posn < remainingLen; posn++)
{
char remainingChar;
/*
** Compare the characters to spaces, and return the appropriate
** value, depending on which is the longer string.
*/
remainingChar = remainingString[posn];
if (remainingChar < ' ')
return retvalIfLTSpace;
else if (remainingChar > ' ')
return -retvalIfLTSpace;
}
/* The remaining characters in the longer string were all spaces,
** so the strings are equal.
*/
return 0;
}
/**
* This method gets called for the collation sensitive char classes ie
* CollatorSQLChar, CollatorSQLVarchar, CollatorSQLLongvarchar,
* CollatorSQLClob. These collation sensitive chars need to have the
* collation key in order to do string comparison. And the collation key
* is obtained using the Collator object that these classes already have.
*
* @return CollationKey obtained using Collator on the string
* @throws StandardException
*/
protected CollationKey getCollationKey() throws StandardException
{
char tmpCharArray[];
if (cKey != null)
return cKey;
if (rawLength == -1)
{
/* materialize the string if input is a stream */
tmpCharArray = getCharArray();
if (tmpCharArray == null)
return null;
}
int lastNonspaceChar = rawLength;
while (lastNonspaceChar > 0 &&
rawData[lastNonspaceChar - 1] == '\u0020')
lastNonspaceChar--; // count off the trailing spaces.
RuleBasedCollator rbc = getCollatorForCollation();
cKey = rbc.getCollationKey(new String(rawData, 0, lastNonspaceChar));
return cKey;
}
/*
* String display of value
*/
public String toString()
{
if (isNull()) {
return "NULL";
}
if ((value == null) && (rawLength != -1)) {
return new String(rawData, 0, rawLength);
}
if (stream != null) {
try {
return getString();
} catch (Exception e) {
return e.toString();
}
}
return value;
}
/*
* Hash code
*/
public int hashCode()
{
if (SanityManager.DEBUG) {
SanityManager.ASSERT(!(this instanceof CollationElementsInterface),
"SQLChar.hashCode() does not work with collation");
}
try {
if (getString() == null)
{
return 0;
}
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
SanityManager.THROWASSERT("Unexpected exception", se);
return 0;
}
/* value.hashCode() doesn't work because of the SQL blank padding
* behavior.
* We want the hash code to be based on the value after the
* trailing blanks have been trimmed. Calling trim() is too expensive
* since it will create a new object, so here's what we do:
* o Walk from the right until we've found the 1st
* non-blank character.
* o Calculate the hash code based on the characters from the
* start up to the first non-blank character from the right.
*/
// value will have been set by the getString() above
String lvalue = value;
// Find 1st non-blank from the right
int lastNonPadChar = lvalue.length() - 1;
while (lastNonPadChar >= 0 && lvalue.charAt(lastNonPadChar) == PAD) {
lastNonPadChar--;
}
// Build the hash code. It should be identical to what we get from
// lvalue.substring(0, lastNonPadChar+1).hashCode(), but it should be
// cheaper this way since we don't allocate a new string.
int hashcode = 0;
for (int i = 0; i <= lastNonPadChar; i++) {
hashcode = hashcode * 31 + lvalue.charAt(i);
}
return hashcode;
}
/**
* Hash code implementation for collator sensitive subclasses.
*/
int hashCodeForCollation() {
CollationKey key = null;
try {
key = getCollationKey();
} catch (StandardException se) {
// ignore exceptions, like we do in hashCode()
if (SanityManager.DEBUG) {
SanityManager.THROWASSERT("Unexpected exception", se);
}
}
return key == null ? 0 : key.hashCode();
}
/**
* Get a SQLVarchar for a built-in string function.
*
* @return a SQLVarchar.
*
* @exception StandardException Thrown on error
*/
protected StringDataValue getNewVarchar() throws StandardException
{
return new SQLVarchar();
}
protected void setLocaleFinder(LocaleFinder localeFinder)
{
this.localeFinder = localeFinder;
}
/** @exception StandardException Thrown on error */
private Locale getLocale() throws StandardException
{
return getLocaleFinder().getCurrentLocale();
}
protected RuleBasedCollator getCollatorForCollation()
throws StandardException
{
return getLocaleFinder().getCollator();
}
protected LocaleFinder getLocaleFinder()
{
// This is not very satisfactory, as it creates a dependency on
// the DatabaseContext. It's the best I could do on short notice,
// though. - Jeff
if (localeFinder == null)
{
DatabaseContext dc = (DatabaseContext)
ContextService.getContext(DatabaseContext.CONTEXT_ID);
if( dc != null)
localeFinder = dc.getDatabase();
}
return localeFinder;
}
protected DateFormat getDateFormat() throws StandardException {
return getLocaleFinder().getDateFormat();
}
protected DateFormat getTimeFormat() throws StandardException {
return getLocaleFinder().getTimeFormat();
}
protected DateFormat getTimestampFormat() throws StandardException {
return getLocaleFinder().getTimestampFormat();
}
protected DateFormat getDateFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar( getLocaleFinder().getDateFormat(), cal);
}
protected DateFormat getTimeFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar( getLocaleFinder().getTimeFormat(), cal);
}
protected DateFormat getTimestampFormat( Calendar cal)
throws StandardException {
return setDateFormatCalendar(
getLocaleFinder().getTimestampFormat(), cal);
}
private DateFormat setDateFormatCalendar( DateFormat df, Calendar cal)
{
if( cal != null && df.getTimeZone() != cal.getTimeZone())
{
// The DateFormat returned by getDateFormat may be cached and used
// by other threads. Therefore we cannot change its calendar.
df = (DateFormat) df.clone();
df.setCalendar( cal);
}
return df;
}
public int estimateMemoryUsage()
{
int sz = BASE_MEMORY_USAGE + ClassSize.estimateMemoryUsage( value);
if( null != rawData)
sz += 2*rawData.length;
// Assume that cKey, stream, and localFinder are shared,
// so do not count their memory usage
return sz;
} // end of estimateMemoryUsage
protected void copyState(SQLChar other) {
this.value = other.value;
this.rawData = other.rawData;
this.rawLength = other.rawLength;
this.cKey = other.cKey;
this.stream = other.stream;
this._clobValue = other._clobValue;
this.localeFinder = localeFinder;
}
/**
* Gets a trace representation for debugging.
*
* @return a trace representation of this SQL Type.
*/
public String getTraceString() throws StandardException {
// Check if the value is SQL NULL.
if (isNull()) {
return "NULL";
}
return (toString());
}
/**
* Returns the default stream header generator for the string data types.
*
* @return A stream header generator.
*/
public StreamHeaderGenerator getStreamHeaderGenerator() {
return CHAR_HEADER_GENERATOR;
}
/**
* Sets the mode for the database being accessed.
*
* @param inSoftUpgradeMode {@code true} if the database is being accessed
* in soft upgrade mode, {@code false} if not, and {@code null} if
* unknown
*/
public void setSoftUpgradeMode(Boolean inSoftUpgradeMode) {
// Ignore this for CHAR, VARCHAR and LONG VARCHAR.
}
private int getClobLength() throws StandardException
{
try {
return rawGetClobLength();
}
catch (SQLException se) { throw StandardException.plainWrapException( se ); }
}
private int rawGetClobLength() throws SQLException
{
long maxLength = Integer.MAX_VALUE;
long length = _clobValue.length();
if ( length > Integer.MAX_VALUE )
{
StandardException se = StandardException.newException
( SQLState.BLOB_TOO_LARGE_FOR_CLIENT, Long.toString( length ), Long.toString( maxLength ) );
throw new SQLException( se.getMessage() );
}
return (int) length;
}
}
| DERBY-4465: Typo in error message from SQLChar
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@888754 13f79535-47bb-0310-9956-ffa450edef68
| java/engine/org/apache/derby/iapi/types/SQLChar.java | DERBY-4465: Typo in error message from SQLChar | <ide><path>ava/engine/org/apache/derby/iapi/types/SQLChar.java
<ide> throw StandardException.newException(
<ide> SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION,
<ide> ioe,
<del> "java.sql.String");
<add> String.class.getName());
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 6a7ac71a1edaae1e8c3e6b66ab7fcdc571980dd8 | 0 | susisu/Avocore | /*
* Avocore : avocore.js
* copyright (c) 2015 Susisu
*/
"use strict";
function end_module() {
module.exports = Object.freeze({
"actions": actions,
"twitter": twitter,
"Action": actions.Action,
"pure" : actions.pure,
"bind" : actions.bind,
"then" : actions.then,
"map" : actions.map,
"filter": actions.filter,
"reduce": actions.reduce,
"merge" : actions.merge,
"echo" : actions.echo,
"cron" : actions.cron
});
}
var actions = require("./actions.js"),
twitter = require("./twitter.js");
end_module();
| lib/avocore.js | /*
* Avocore : avocore.js
* copyright (c) 2015 Susisu
*/
"use strict";
function end_module() {
module.exports = Object.freeze({
"actions": require("./actions.js"),
"twitter": require("./twitter.js")
});
}
end_module();
| Update index
| lib/avocore.js | Update index | <ide><path>ib/avocore.js
<ide>
<ide> function end_module() {
<ide> module.exports = Object.freeze({
<del> "actions": require("./actions.js"),
<del> "twitter": require("./twitter.js")
<add> "actions": actions,
<add> "twitter": twitter,
<add>
<add> "Action": actions.Action,
<add> "pure" : actions.pure,
<add> "bind" : actions.bind,
<add> "then" : actions.then,
<add> "map" : actions.map,
<add> "filter": actions.filter,
<add> "reduce": actions.reduce,
<add> "merge" : actions.merge,
<add> "echo" : actions.echo,
<add> "cron" : actions.cron
<ide> });
<ide> }
<ide>
<add>var actions = require("./actions.js"),
<add> twitter = require("./twitter.js");
<add>
<ide> end_module(); |
|
Java | bsd-2-clause | 6f7820935d3985db93f0013bb0ba3ce8227d24b6 | 0 | f97one/ApcUpsCountdown | package net.formula97.android.apcupscountdown;
import java.util.Calendar;
/**
* Created by HAJIME on 14/02/08.
*/
public interface DateDialogFragmentListener {
public void dateDialogFragmentDateSet(Calendar date);
}
| android/src/main/java/net/formula97/android/apcupscountdown/DateDialogFragmentListener.java | package net.formula97.android.apcupscountdown;
/**
* Created by HAJIME on 14/02/08.
*/
public interface DateDialogFragmentListener {
}
| Interfaceに実装すべき内容を追加。
| android/src/main/java/net/formula97/android/apcupscountdown/DateDialogFragmentListener.java | Interfaceに実装すべき内容を追加。 | <ide><path>ndroid/src/main/java/net/formula97/android/apcupscountdown/DateDialogFragmentListener.java
<ide> package net.formula97.android.apcupscountdown;
<add>
<add>import java.util.Calendar;
<ide>
<ide> /**
<ide> * Created by HAJIME on 14/02/08.
<ide> */
<ide> public interface DateDialogFragmentListener {
<add> public void dateDialogFragmentDateSet(Calendar date);
<ide> } |
|
Java | mit | 64801e522704d8ba6188cdb497fc51946da47b55 | 0 | arnosthavelka/junit-poc,arnosthavelka/junit-poc | package com.github.aha.poc.junit.springboot.rest.assured;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.when;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import com.github.aha.poc.junit.springboot.City;
import com.github.aha.poc.junit.springboot.CityController;
import com.github.aha.poc.junit.springboot.CityService;
@SpringBootTest(webEnvironment = MOCK, classes = CityController.class)
public class CityControllerRestAssuredSingleTest {
private static final String ROOT_PATH = "/cities";
private static final long PRAGUE_ID = 1L;
@MockBean
CityService service;
@Autowired
CityController controller;
@Test
@DisplayName("should read one city")
void getCity() {
when(service.getItem(PRAGUE_ID)).thenReturn(new City(999L, "Tokyo"));
given()
.standaloneSetup(controller)
.when()
.get(ROOT_PATH + "/{id}", PRAGUE_ID)
.then()
.statusCode(200)
.assertThat().header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.assertThat().body("id", equalTo(999))
.assertThat().body("name", equalTo("Tokyo"));
}
}
| spring-boot/src/test/java/com/github/aha/poc/junit/springboot/rest/assured/CityControllerRestAssuredSingleTest.java | package com.github.aha.poc.junit.springboot.rest.assured;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.when;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import com.github.aha.poc.junit.springboot.City;
import com.github.aha.poc.junit.springboot.CityController;
import com.github.aha.poc.junit.springboot.CityService;
@SpringBootTest(webEnvironment = MOCK, classes = CityController.class)
public class CityControllerRestAssuredSingleTest {
private static final String ROOT_PATH = "/cities";
private static final long PRAGUE_ID = 1L;
@MockBean
CityService service;
@Autowired
CityController controller;
@Test
@DisplayName("should read one city")
void getCity() {
when(service.getItem(PRAGUE_ID)).thenReturn(new City(999L, "Tokyo"));
given()
.standaloneSetup(controller)
.when()
.get(ROOT_PATH + "/{id}", PRAGUE_ID)
.then()
.statusCode(200)
.assertThat().body("id", equalTo(999))
.assertThat().body("name", equalTo("Tokyo"));
}
}
| #11 validation of content type | spring-boot/src/test/java/com/github/aha/poc/junit/springboot/rest/assured/CityControllerRestAssuredSingleTest.java | #11 validation of content type | <ide><path>pring-boot/src/test/java/com/github/aha/poc/junit/springboot/rest/assured/CityControllerRestAssuredSingleTest.java
<ide> import static org.hamcrest.Matchers.equalTo;
<ide> import static org.mockito.Mockito.when;
<ide> import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
<add>import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
<add>import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
<ide>
<ide> import org.junit.jupiter.api.DisplayName;
<ide> import org.junit.jupiter.api.Test;
<ide> .get(ROOT_PATH + "/{id}", PRAGUE_ID)
<ide> .then()
<ide> .statusCode(200)
<add> .assertThat().header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
<ide> .assertThat().body("id", equalTo(999))
<ide> .assertThat().body("name", equalTo("Tokyo"));
<ide> } |
|
Java | apache-2.0 | 984ac2406180b908fe45801e43f0bb1f74f76cd9 | 0 | varshavaradarajan/gocd,tomzo/gocd,Skarlso/gocd,gocd/gocd,varshavaradarajan/gocd,ketan/gocd,tomzo/gocd,bdpiparva/gocd,varshavaradarajan/gocd,arvindsv/gocd,bdpiparva/gocd,ibnc/gocd,kierarad/gocd,ind9/gocd,arvindsv/gocd,varshavaradarajan/gocd,arvindsv/gocd,ketan/gocd,ind9/gocd,gocd/gocd,gocd/gocd,GaneshSPatil/gocd,marques-work/gocd,bdpiparva/gocd,tomzo/gocd,bdpiparva/gocd,ibnc/gocd,ketan/gocd,naveenbhaskar/gocd,GaneshSPatil/gocd,varshavaradarajan/gocd,naveenbhaskar/gocd,kierarad/gocd,naveenbhaskar/gocd,kierarad/gocd,GaneshSPatil/gocd,GaneshSPatil/gocd,naveenbhaskar/gocd,tomzo/gocd,ind9/gocd,marques-work/gocd,kierarad/gocd,marques-work/gocd,ibnc/gocd,ind9/gocd,marques-work/gocd,marques-work/gocd,ibnc/gocd,ibnc/gocd,GaneshSPatil/gocd,naveenbhaskar/gocd,marques-work/gocd,bdpiparva/gocd,ketan/gocd,bdpiparva/gocd,ibnc/gocd,Skarlso/gocd,ketan/gocd,varshavaradarajan/gocd,arvindsv/gocd,gocd/gocd,kierarad/gocd,kierarad/gocd,gocd/gocd,Skarlso/gocd,ind9/gocd,tomzo/gocd,Skarlso/gocd,Skarlso/gocd,arvindsv/gocd,ketan/gocd,GaneshSPatil/gocd,tomzo/gocd,arvindsv/gocd,Skarlso/gocd,gocd/gocd,naveenbhaskar/gocd | /*
* Copyright 2017 ThoughtWorks, 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 com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.domain.ServerSiteUrlConfig;
import com.thoughtworks.go.domain.User;
import com.thoughtworks.go.security.CryptoException;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.server.service.result.BulkUpdateUsersOperationResult;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import com.thoughtworks.go.util.GoConfigFileHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:WEB-INF/applicationContext-global.xml",
"classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
"classpath:testPropertyConfigurer.xml"
})
public class ServerConfigServiceIntegrationTest {
@Autowired
GoConfigService goConfigService;
@Autowired
ServerConfigService serverConfigService;
@Autowired
UserService userService;
@Autowired
GoConfigDao goConfigDao;
private GoConfigFileHelper configHelper = new GoConfigFileHelper();
@Before
public void setup() throws Exception {
configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
configHelper.onSetUp();
goConfigService.forceNotifyListeners();
goConfigService.security().securityAuthConfigs().add(new SecurityAuthConfig("file", "cd.go.authentication.passwordfile"));
}
@After
public void tearDown() throws Exception {
configHelper.onTearDown();
}
@Test
public void shouldUpdateServerConfigWithoutValidatingMailHostWhenMailhostisEmpty() {
MailHost mailHost = new MailHost(new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(result.isSuccessful(), is(true));
}
@Test
public void shouldUpdateServerConfig() throws CryptoException {
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", 10.0, 20.0, "42", true, "http://site_url", "https://secure_site_url", "gist-repo/folder",
result, goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(goConfigService.serverConfig().artifactsDir(), is("newArtifactsDir"));
assertThat(goConfigService.serverConfig().getSiteUrl().getUrl(), is("http://site_url"));
assertThat(goConfigService.serverConfig().getSecureSiteUrl().getUrl(), is("https://secure_site_url"));
assertThat(goConfigService.serverConfig().getJobTimeout(), is("42"));
assertThat(goConfigService.serverConfig().getPurgeStart(), is(10.0));
assertThat(goConfigService.serverConfig().getPurgeUpto(), is(20.0));
assertThat(goConfigService.serverConfig().getCommandRepositoryLocation(), is("gist-repo/folder"));
assertThat(result.isSuccessful(), is(true));
}
@Test
public void shouldAllowNullValuesForPurgeStartAndPurgeUpTo() throws CryptoException {
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", null, null, "42", true, "http://site_url", "https://secure_site_url", "default",
result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.serverConfig().getPurgeStart(), is(nullValue()));
assertThat(goConfigService.serverConfig().getPurgeUpto(), is(nullValue()));
}
@Test
public void shouldUpdateWithEmptySecureSiteUrlAndSiteUrl() throws CryptoException {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", null, null, "42", true, "", "", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.serverConfig().getSiteUrl(), is(new ServerSiteUrlConfig()));
assertThat(goConfigService.serverConfig().getSecureSiteUrl(), is(new ServerSiteUrlConfig()));
}
@Test
public void update_shouldKeepTheExistingSecurityAsIs() throws IOException {
Role role = new RoleConfig(new CaseInsensitiveString("awesome"), new RoleUser(new CaseInsensitiveString("first")));
configHelper.turnOnSecurity();
configHelper.addRole(role);
SecurityConfig securityConfig = createSecurity(role, null, false);
securityConfig.securityAuthConfigs().addAll(goConfigService.serverConfig().security().securityAuthConfigs());
MailHost mailHost = new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "[email protected]");
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(goConfigService.security(), is(securityConfig));
assertThat(result.isSuccessful(), is(true));
}
private SecurityConfig createSecurity(Role role, SecurityAuthConfig securityAuthConfig, boolean allowOnlyKnownUsersToLogin) {
SecurityConfig securityConfig = new SecurityConfig();
securityConfig.addRole(role);
if (securityAuthConfig != null) {
securityConfig.securityAuthConfigs().add(securityAuthConfig);
}
securityConfig.modifyAllowOnlyKnownUsers(allowOnlyKnownUsersToLogin);
return securityConfig;
}
@Test
public void shouldUpdateServerConfigShouldFailWhenConfigSaveFails() {
MailHost mailHost = new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "[email protected]");
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "-42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), containsString("Failed to save the server configuration. Reason: "));
assertThat(result.message(), containsString("Timeout cannot be a negative number as it represents number of minutes"));
}
@Test
public void updateServerConfig_ShouldFailWhenAllowAutoLoginIsTurnedOffWithNoAdminsRemaining() throws IOException {
configHelper.enableSecurity();
userService.deleteUsers(userService.allUsers().stream().map(User::getName).collect(Collectors.toList()), "admin", new BulkUpdateUsersOperationResult());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost(new GoCipher()), "artifacts", null, null, "42",
false,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), containsString("Cannot disable auto login with no admins enabled."));
}
@Test
public void shouldNotUpdateWhenHostnameIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo%bee", 1, "username", "password", true, true, "[email protected]", "[email protected]"),
"artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Invalid hostname. A valid hostname can only contain letters (A-z) digits (0-9) hyphens (-) dots (.) and underscores (_)."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenPortIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", -1, "username", "password", true, true, "[email protected]", "[email protected]"),
"artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Invalid port."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenEmailIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", 1, "username", "password", true, true, "from", "[email protected]"),
"artifacts", null, null, "42", true,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("From address is not a valid email address."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenAdminEmailIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "admin"),
"artifacts", null, null, "42", true,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Admin address is not a valid email address."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldSiteUrlForGivenUrl() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("http://foo.com"), new ServerSiteUrlConfig("https://bar.com"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("https://bar.com/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://foo.com/foo/bar"));
}
@Test
public void shouldReturnTheSameURLWhenNothingIsConfigured() throws URISyntaxException {
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("http://test.host/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://test.host/foo/bar"));
}
@Test
public void shouldUseTheSiteUrlWhenSecureSiteUrlIsNotPresentAndOnlyIfSiteUrlIsHttps() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("https://foo.com"), new ServerSiteUrlConfig());
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("https://foo.com/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("https://foo.com/foo/bar"));
}
@Test
public void shouldUseTheSecureSiteUrlInspiteOfCallerNotForcingSsl_whenAlreadyUsingHTTPS() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("http://foo.com:80"), new ServerSiteUrlConfig("https://bar.com:443"));
assertThat(serverConfigService.siteUrlFor("https://test.host:1000/foo/bar", false), is("https://bar.com:443/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://foo.com:80/foo/bar"));
}
}
| server/src/test-integration/java/com/thoughtworks/go/server/service/ServerConfigServiceIntegrationTest.java | /*
* Copyright 2017 ThoughtWorks, 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 com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.domain.ServerSiteUrlConfig;
import com.thoughtworks.go.domain.User;
import com.thoughtworks.go.security.CryptoException;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.server.service.result.BulkUpdateUsersOperationResult;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import com.thoughtworks.go.util.GoConfigFileHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:WEB-INF/applicationContext-global.xml",
"classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
"classpath:testPropertyConfigurer.xml"
})
public class ServerConfigServiceIntegrationTest {
@Autowired
GoConfigService goConfigService;
@Autowired
ServerConfigService serverConfigService;
@Autowired
UserService userService;
@Autowired
GoConfigDao goConfigDao;
private GoConfigFileHelper configHelper = new GoConfigFileHelper();
@Before
public void setup() throws Exception {
configHelper.usingCruiseConfigDao(goConfigDao).initializeConfigFile();
configHelper.onSetUp();
goConfigService.forceNotifyListeners();
goConfigService.security().securityAuthConfigs().add(new SecurityAuthConfig("file", "cd.go.authentication.passwordfile"));
}
@After
public void tearDown() throws Exception {
configHelper.onTearDown();
}
@Test
public void shouldUpdateServerConfigWithoutValidatingMailHostWhenMailhostisEmpty() {
MailHost mailHost = new MailHost(new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(result.isSuccessful(), is(true));
}
@Test
public void shouldUpdateServerConfig() throws CryptoException {
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", 10.0, 20.0, "42", true, "http://site_url", "https://secure_site_url", "gist-repo/folder",
result, goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(goConfigService.serverConfig().artifactsDir(), is("newArtifactsDir"));
assertThat(goConfigService.serverConfig().getSiteUrl().getUrl(), is("http://site_url"));
assertThat(goConfigService.serverConfig().getSecureSiteUrl().getUrl(), is("https://secure_site_url"));
assertThat(goConfigService.serverConfig().getJobTimeout(), is("42"));
assertThat(goConfigService.serverConfig().getPurgeStart(), is(10.0));
assertThat(goConfigService.serverConfig().getPurgeUpto(), is(20.0));
assertThat(goConfigService.serverConfig().getCommandRepositoryLocation(), is("gist-repo/folder"));
assertThat(result.isSuccessful(), is(true));
}
@Test
public void shouldAllowNullValuesForPurgeStartAndPurgeUpTo() throws CryptoException {
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", null, null, "42", true, "http://site_url", "https://secure_site_url", "default",
result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.serverConfig().getPurgeStart(), is(nullValue()));
assertThat(goConfigService.serverConfig().getPurgeUpto(), is(nullValue()));
}
@Test
public void shouldUpdateWithEmptySecureSiteUrlAndSiteUrl() throws CryptoException {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
MailHost mailHost = new MailHost("boo", 1, "username", "password", new GoCipher().encrypt("password"), true, true, "[email protected]", "[email protected]", new GoCipher());
serverConfigService.updateServerConfig(mailHost, "newArtifactsDir", null, null, "42", true, "", "", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.serverConfig().getSiteUrl(), is(new ServerSiteUrlConfig()));
assertThat(goConfigService.serverConfig().getSecureSiteUrl(), is(new ServerSiteUrlConfig()));
}
@Test
public void update_shouldKeepTheExistingSecurityAsIs() throws IOException {
Role role = new RoleConfig(new CaseInsensitiveString("awesome"), new RoleUser(new CaseInsensitiveString("first")));
configHelper.turnOnSecurity();
configHelper.addRole(role);
SecurityConfig securityConfig = createSecurity(role, null, false);
securityConfig.securityAuthConfigs().addAll(goConfigService.serverConfig().security().securityAuthConfigs());
MailHost mailHost = new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "[email protected]");
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(goConfigService.getMailHost(), is(mailHost));
assertThat(goConfigService.security(), is(securityConfig));
assertThat(result.isSuccessful(), is(true));
}
private SecurityConfig createSecurity(Role role, SecurityAuthConfig securityAuthConfig, boolean allowOnlyKnownUsersToLogin) {
SecurityConfig securityConfig = new SecurityConfig();
securityConfig.addRole(role);
if (securityAuthConfig != null) {
securityConfig.securityAuthConfigs().add(securityAuthConfig);
}
securityConfig.modifyAllowOnlyKnownUsers(allowOnlyKnownUsersToLogin);
return securityConfig;
}
@Test
public void shouldUpdateServerConfigShouldFailWhenConfigSaveFails() {
MailHost mailHost = new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "[email protected]");
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(mailHost, "artifacts", null, null, "-42", true, "http://site_url", "https://secure_site_url", "default", result,
goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), containsString("Failed to save the server configuration. Reason: "));
assertThat(result.message(), containsString("Timeout cannot be a negative number as it represents number of minutes"));
}
@Test
public void updateServerConfig_ShouldFailWhenAllowAutoLoginIsTurnedOffWithNoAdminsRemaining() throws IOException {
configHelper.enableSecurity();
userService.deleteUsers(userService.allUsers().stream().map(User::getName).collect(Collectors.toList()), new BulkUpdateUsersOperationResult());
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost(new GoCipher()), "artifacts", null, null, "42",
false,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), containsString("Cannot disable auto login with no admins enabled."));
}
@Test
public void shouldNotUpdateWhenHostnameIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo%bee", 1, "username", "password", true, true, "[email protected]", "[email protected]"),
"artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Invalid hostname. A valid hostname can only contain letters (A-z) digits (0-9) hyphens (-) dots (.) and underscores (_)."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenPortIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", -1, "username", "password", true, true, "[email protected]", "[email protected]"),
"artifacts", null, null, "42", true, "http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Invalid port."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenEmailIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", 1, "username", "password", true, true, "from", "[email protected]"),
"artifacts", null, null, "42", true,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("From address is not a valid email address."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldNotUpdateWhenAdminEmailIsInvalid() {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
serverConfigService.updateServerConfig(new MailHost("boo", 1, "username", "password", true, true, "[email protected]", "admin"),
"artifacts", null, null, "42", true,
"http://site_url", "https://secure_site_url", "default", result, goConfigDao.md5OfConfigFile());
assertThat(result.isSuccessful(), is(false));
assertThat(result.message(), is("Admin address is not a valid email address."));
assertThat(goConfigService.getMailHost(), is(new MailHost(new GoCipher())));
}
@Test
public void shouldSiteUrlForGivenUrl() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("http://foo.com"), new ServerSiteUrlConfig("https://bar.com"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("https://bar.com/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://foo.com/foo/bar"));
}
@Test
public void shouldReturnTheSameURLWhenNothingIsConfigured() throws URISyntaxException {
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("http://test.host/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://test.host/foo/bar"));
}
@Test
public void shouldUseTheSiteUrlWhenSecureSiteUrlIsNotPresentAndOnlyIfSiteUrlIsHttps() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("https://foo.com"), new ServerSiteUrlConfig());
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", true), is("https://foo.com/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("https://foo.com/foo/bar"));
}
@Test
public void shouldUseTheSecureSiteUrlInspiteOfCallerNotForcingSsl_whenAlreadyUsingHTTPS() throws URISyntaxException {
configHelper.setBaseUrls(new ServerSiteUrlConfig("http://foo.com:80"), new ServerSiteUrlConfig("https://bar.com:443"));
assertThat(serverConfigService.siteUrlFor("https://test.host:1000/foo/bar", false), is("https://bar.com:443/foo/bar"));
assertThat(serverConfigService.siteUrlFor("http://test.host/foo/bar", false), is("http://foo.com:80/foo/bar"));
}
}
| Fix compiler error
| server/src/test-integration/java/com/thoughtworks/go/server/service/ServerConfigServiceIntegrationTest.java | Fix compiler error | <ide><path>erver/src/test-integration/java/com/thoughtworks/go/server/service/ServerConfigServiceIntegrationTest.java
<ide> @Test
<ide> public void updateServerConfig_ShouldFailWhenAllowAutoLoginIsTurnedOffWithNoAdminsRemaining() throws IOException {
<ide> configHelper.enableSecurity();
<del> userService.deleteUsers(userService.allUsers().stream().map(User::getName).collect(Collectors.toList()), new BulkUpdateUsersOperationResult());
<add> userService.deleteUsers(userService.allUsers().stream().map(User::getName).collect(Collectors.toList()), "admin", new BulkUpdateUsersOperationResult());
<ide> HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
<ide>
<ide> serverConfigService.updateServerConfig(new MailHost(new GoCipher()), "artifacts", null, null, "42", |
|
Java | mit | c4fe0aa7ffb3139d9abcfb387b9f83e3ebe52c66 | 0 | zalando/nakadi,zalando/nakadi | package de.zalando.aruha.nakadi.validation;
import de.zalando.aruha.nakadi.domain.EventType;
import de.zalando.aruha.nakadi.domain.ValidationStrategyConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class EventValidation {
public static EventTypeValidator forType(final EventType eventType) {
final EventTypeValidator etv = new EventTypeValidator(eventType);
final ValidationStrategyConfiguration vsc = new ValidationStrategyConfiguration();
vsc.setStrategyName(EventBodyMustRespectSchema.NAME);
return etv.withConfiguration(vsc);
}
public static JSONObject effectiveSchema(final EventType eventType) throws JSONException {
final JSONObject schema = new JSONObject(eventType.getSchema().getSchema());
switch (eventType.getCategory()) {
case BUSINESS: return addMetadata(schema, eventType);
case DATA: return wrapSchemaInData(schema, eventType);
default: return schema;
}
}
private static JSONObject wrapSchemaInData(final JSONObject schema, EventType eventType) {
final JSONObject wrapper = new JSONObject();
normalizeSchema(wrapper);
addMetadata(wrapper, eventType);
wrapper.getJSONObject("properties").put("data_type", new JSONObject("{\"type\": \"string\"}"));
wrapper.getJSONObject("properties").put("data_op", new JSONObject("{\"type\": \"string\", \"enum\": [\"C\", \"U\", \"D\", \"S\"]}"));
wrapper.getJSONObject("properties").put("data", schema);
wrapper.put("additionalProperties", false);
addToRequired(wrapper, new String[]{ "data_type", "data_op", "data" });
return wrapper;
}
private static JSONObject addMetadata(final JSONObject schema, EventType eventType) {
normalizeSchema(schema);
final JSONObject metadata = new JSONObject();
final JSONObject metadataProperties = new JSONObject();
final JSONObject uuid = new JSONObject("{\"type\": \"string\", \"pattern\": \"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$\"}");
final JSONObject arrayOfUUIDs = new JSONObject();
arrayOfUUIDs.put("type", "array");
arrayOfUUIDs.put("items", uuid);
final JSONObject eventTypeString = new JSONObject("{\"type\": \"string\", \"enum\": [\"" + eventType.getName() + "\"]}");
final JSONObject string = new JSONObject("{\"type\": \"string\"}");
final String dateTimePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}(T| )[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$";
final JSONObject dateTime = new JSONObject("{\"type\": \"string\", \"pattern\": \"" + dateTimePattern + "\"}");
metadataProperties.put("eid", uuid);
metadataProperties.put("event_type", eventTypeString);
metadataProperties.put("occurred_at", dateTime);
metadataProperties.put("parent_eids", uuid);
metadataProperties.put("flow_id", string);
metadata.put("type", "object");
metadata.put("properties", metadataProperties);
metadata.put("required", Arrays.asList(new String[]{"eid", "occurred_at"}));
metadata.put("additionalProperties", false);
schema.getJSONObject("properties").put("metadata", metadata);
addToRequired(schema, new String[]{ "metadata" });
return schema;
}
private static void addToRequired(final JSONObject schema, final String[] toBeRequired) {
final Set<String> required = new HashSet<>(Arrays.asList(toBeRequired));
JSONArray currentRequired = schema.getJSONArray("required");
for(int i = 0; i < currentRequired.length(); i++) {
required.add(currentRequired.getString(i));
}
schema.put("required", required);
}
private static void normalizeSchema(final JSONObject schema) {
schema.put("type", "object");
if (!schema.has("properties")) {
schema.put("properties", new JSONObject());
}
if (!schema.has("required")) {
schema.put("required", new JSONArray());
}
}
}
| src/main/java/de/zalando/aruha/nakadi/validation/EventValidation.java | package de.zalando.aruha.nakadi.validation;
import de.zalando.aruha.nakadi.domain.EventType;
import de.zalando.aruha.nakadi.domain.ValidationStrategyConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class EventValidation {
public static EventTypeValidator forType(final EventType eventType) {
final EventTypeValidator etv = new EventTypeValidator(eventType);
final ValidationStrategyConfiguration vsc = new ValidationStrategyConfiguration();
vsc.setStrategyName(EventBodyMustRespectSchema.NAME);
return etv.withConfiguration(vsc);
}
public static JSONObject effectiveSchema(final EventType eventType) throws JSONException {
final JSONObject schema = new JSONObject(eventType.getSchema().getSchema());
switch (eventType.getCategory()) {
case BUSINESS: return addMetadata(schema, eventType);
case DATA: return wrapSchemaInData(schema, eventType);
default: return schema;
}
}
private static JSONObject wrapSchemaInData(final JSONObject schema, EventType eventType) {
final JSONObject wrapper = new JSONObject();
normalizeSchema(wrapper);
addMetadata(wrapper, eventType);
wrapper.getJSONObject("properties").put("data_type", new JSONObject("{\"type\": \"string\"}"));
wrapper.getJSONObject("properties").put("data_op", new JSONObject("{\"type\": \"string\", \"enum\": [\"C\", \"U\", \"D\", \"S\"]}"));
wrapper.getJSONObject("properties").put("data", schema);
wrapper.put("additionalProperties", false);
addToRequired(wrapper, new String[]{ "data_type", "data_op", "data" });
return wrapper;
}
private static JSONObject addMetadata(final JSONObject schema, EventType eventType) {
normalizeSchema(schema);
final JSONObject metadata = new JSONObject();
final JSONObject metadataProperties = new JSONObject();
final JSONObject uuid = new JSONObject("{\"type\": \"string\", \"pattern\": \"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$\"}");
final JSONObject arrayOfUUIDs = new JSONObject();
arrayOfUUIDs.put("type", "array");
arrayOfUUIDs.put("items", uuid);
final JSONObject eventTypeString = new JSONObject("{\"type\": \"string\", \"enum\": [\"" + eventType.getName() + "\"]}");
final JSONObject string = new JSONObject("{\"type\": \"string\"}");
final String dateTimePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}(T| )[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$";
final JSONObject dateTime = new JSONObject("{\"type\": \"string\", \"pattern\": \"" + dateTimePattern + "\"}");
metadataProperties.put("eid", uuid);
metadataProperties.put("event_type", eventTypeString);
metadataProperties.put("occurred_at", dateTime);
metadataProperties.put("parent_eids", uuid);
metadataProperties.put("root_eid", uuid);
metadataProperties.put("flow_id", string);
metadata.put("type", "object");
metadata.put("properties", metadataProperties);
metadata.put("required", Arrays.asList(new String[]{"eid", "occurred_at"}));
metadata.put("additionalProperties", false);
schema.getJSONObject("properties").put("metadata", metadata);
addToRequired(schema, new String[]{ "metadata" });
return schema;
}
private static void addToRequired(final JSONObject schema, final String[] toBeRequired) {
final Set<String> required = new HashSet<>(Arrays.asList(toBeRequired));
JSONArray currentRequired = schema.getJSONArray("required");
for(int i = 0; i < currentRequired.length(); i++) {
required.add(currentRequired.getString(i));
}
schema.put("required", required);
}
private static void normalizeSchema(final JSONObject schema) {
schema.put("type", "object");
if (!schema.has("properties")) {
schema.put("properties", new JSONObject());
}
if (!schema.has("required")) {
schema.put("required", new JSONArray());
}
}
}
| aruha-114 remove root_eid since it was removed from the api
| src/main/java/de/zalando/aruha/nakadi/validation/EventValidation.java | aruha-114 remove root_eid since it was removed from the api | <ide><path>rc/main/java/de/zalando/aruha/nakadi/validation/EventValidation.java
<ide> metadataProperties.put("event_type", eventTypeString);
<ide> metadataProperties.put("occurred_at", dateTime);
<ide> metadataProperties.put("parent_eids", uuid);
<del> metadataProperties.put("root_eid", uuid);
<ide> metadataProperties.put("flow_id", string);
<ide>
<ide> metadata.put("type", "object"); |
|
Java | unlicense | cebfbecc70033e096df02aee60801a94f9becef4 | 0 | daipenger/minema,ata4/minema | /*
** 2014 July 29
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package info.ata4.minecraft.minema.client.modules.exporters;
import java.io.File;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import info.ata4.minecraft.minema.client.capture.Capturer;
import info.ata4.minecraft.minema.client.config.MinemaConfig;
import info.ata4.minecraft.minema.client.event.FrameCaptureEvent;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class PipeFrameExporter extends FrameExporter {
private static final Logger L = LogManager.getLogger();
private Process proc;
private WritableByteChannel pipe;
public PipeFrameExporter(MinemaConfig cfg) {
super(cfg);
}
@Override
protected void doEnable() throws Exception {
super.doEnable();
String params = cfg.videoEncoderParams.get();
params = params.replace("%WIDTH%", String.valueOf(cfg.getFrameWidth()));
params = params.replace("%HEIGHT%", String.valueOf(cfg.getFrameHeight()));
params = params.replace("%FPS%", String.valueOf(cfg.frameRate.get()));
List<String> cmds = new ArrayList<>();
cmds.add(cfg.videoEncoderPath.get());
cmds.addAll(Arrays.asList(StringUtils.split(params, ' ')));
// build encoder process and redirect output
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.directory(cfg.getMovieDir());
pb.redirectErrorStream(true);
pb.redirectOutput(new File(cfg.getMovieDir(), "encoder.log"));
proc = pb.start();
// create channel from output stream
pipe = Channels.newChannel(proc.getOutputStream());
}
@Override
protected void doDisable() throws Exception {
super.doDisable();
IOUtils.closeQuietly(pipe);
if (proc != null) {
try {
proc.waitFor(1, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
L.warn("Pipe program termination interrupted", ex);
}
proc.destroy();
}
}
@Override
public void configureCapturer(Capturer fbc) {
}
@Override
protected void doExportFrame(FrameCaptureEvent evt) throws Exception {
if (pipe.isOpen()) {
pipe.write(evt.frameBuffer);
}
}
}
| src/main/java/info/ata4/minecraft/minema/client/modules/exporters/PipeFrameExporter.java | /*
** 2014 July 29
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package info.ata4.minecraft.minema.client.modules.exporters;
import java.io.File;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import info.ata4.minecraft.minema.client.capture.Capturer;
import info.ata4.minecraft.minema.client.config.MinemaConfig;
import info.ata4.minecraft.minema.client.event.FrameCaptureEvent;
import java.util.Arrays;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class PipeFrameExporter extends FrameExporter {
private static final Logger L = LogManager.getLogger();
private Process proc;
private WritableByteChannel pipe;
public PipeFrameExporter(MinemaConfig cfg) {
super(cfg);
}
@Override
protected void doEnable() throws Exception {
super.doEnable();
String params = cfg.videoEncoderParams.get();
params = params.replace("%WIDTH%", String.valueOf(cfg.getFrameWidth()));
params = params.replace("%HEIGHT%", String.valueOf(cfg.getFrameHeight()));
params = params.replace("%FPS%", String.valueOf(cfg.frameRate.get()));
List<String> cmds = new ArrayList<>();
cmds.add(cfg.videoEncoderPath.get());
cmds.addAll(Arrays.asList(StringUtils.split(params, ' ')));
// build encoder process and redirect output
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.directory(cfg.getMovieDir());
pb.redirectErrorStream(true);
pb.redirectOutput(new File(cfg.getMovieDir(), "encoder.log"));
proc = pb.start();
// create channel from output stream
pipe = Channels.newChannel(proc.getOutputStream());
}
@Override
protected void doDisable() throws Exception {
super.doDisable();
IOUtils.closeQuietly(pipe);
if (proc != null) {
try {
proc.waitFor();
} catch (InterruptedException ex) {
L.warn("Pipe program termination interrupted", ex);
}
proc.destroy();
}
}
@Override
public void configureCapturer(Capturer fbc) {
}
@Override
protected void doExportFrame(FrameCaptureEvent evt) throws Exception {
if (pipe.isOpen()) {
pipe.write(evt.frameBuffer);
}
}
}
| Wait one minute for the process instead of infinitely | src/main/java/info/ata4/minecraft/minema/client/modules/exporters/PipeFrameExporter.java | Wait one minute for the process instead of infinitely | <ide><path>rc/main/java/info/ata4/minecraft/minema/client/modules/exporters/PipeFrameExporter.java
<ide> import info.ata4.minecraft.minema.client.config.MinemaConfig;
<ide> import info.ata4.minecraft.minema.client.event.FrameCaptureEvent;
<ide> import java.util.Arrays;
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> /**
<ide> *
<ide>
<ide> if (proc != null) {
<ide> try {
<del> proc.waitFor();
<add> proc.waitFor(1, TimeUnit.MINUTES);
<ide> } catch (InterruptedException ex) {
<ide> L.warn("Pipe program termination interrupted", ex);
<ide> } |
|
Java | mit | 1c85d2e6075c16e9498700a9c0349e74fafbce08 | 0 | Squadity/bb-utils | package net.bolbat.utils.lang;
import java.util.Calendar;
/**
* Time utils.
*
* @author Vasyl Zarva
*/
public final class TimeUtils {
/**
* Default constructor with preventing instantiations of this class.
*/
private TimeUtils() {
throw new IllegalAccessError("Can't be instantiated.");
}
/**
* Get timestamp for X years ago from now.
*
* @param years
* years, can't be <code>null</code>
* @param mode
* rounding mode
* @return timestamp
*/
public static long getYearsFromNow(final int years, final Rounding mode) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, years);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundYearTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given months.
*
* @param months
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getMonthFromNow(final int months, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, months);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundMonthTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given days.
*
* @param days
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getDaysFromNow(final int days, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, days);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundDayTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given hours.
*
* @param hours
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getHoursFromNow(final int hours, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, hours);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundHourTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Rounding incoming time to seconds, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToSecondTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundSecondTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in second, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundSecondTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding incoming time to minutes, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToMinuteTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundMinuteTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in minute, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundMinuteTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding incoming time to hour, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToHourTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundHourTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in hour, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundHourTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding incoming time to day, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToDayTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundDayTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in day, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundDayTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null)
return;
switch (mode) {
case MAX:
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
return;
case MIN:
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
return;
case NONE:
default:
break;
}
}
/**
* Rounding incoming time to Month, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToMonthTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundMonthTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in month, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundMonthTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding incoming time to Year, up/down rounding defined by {@link Rounding}.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundTimeToYearTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundYearTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in year, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundYearTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding mode.
*
* @author Alexandr Bolbat
*/
public enum Rounding {
/**
* No rounding.
*/
NONE,
/**
* Round to min time.
*/
MAX,
/**
* Round to max time.
*/
MIN;
/**
* Default {@link Rounding}.
*/
public static final Rounding DEFAULT = NONE;
}
}
| src/net/bolbat/utils/lang/TimeUtils.java | package net.bolbat.utils.lang;
import java.util.Calendar;
/**
* Time utils.
*
* @author Vasyl Zarva
*/
public final class TimeUtils {
/**
* Default constructor with preventing instantiations of this class.
*/
private TimeUtils() {
throw new IllegalAccessError("Can't be instantiated.");
}
/**
* Get timestamp for X years ago from now.
*
* @param years
* years, can't be <code>null</code>
* @param mode
* rounding mode
* @return timestamp
*/
public static long getYearsFromNow(final int years, final Rounding mode) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, years);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundYearTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given months.
*
* @param months
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getMonthFromNow(final int months, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, months);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundMonthTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given days.
*
* @param days
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getDaysFromNow(final int days, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, days);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundDayTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Get timestamp from now for given hours.
*
* @param hours
* days count
* @param mode
* rounding mode
* @return timestamp
*/
public static long getHoursFromNow(final int hours, final Rounding mode) {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, hours);
if (mode == null || Rounding.NONE == mode)
return cal.getTimeInMillis();
roundHourTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in second, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundSecondTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Round date to maximum or minimum in minute, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundMinuteTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Round date to maximum or minimum in hour, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundHourTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Round time in millis to maximum or minimum in day, depending of rounding mode.
*
* @param time
* time in millis
* @param mode
* rounding mode
* @return rounded time in millis
*/
public static long roundDayTime(final long time, final Rounding mode) {
if (mode == null || Rounding.NONE == mode)
return time;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
roundDayTime(cal, mode);
return cal.getTimeInMillis();
}
/**
* Round date to maximum or minimum in day, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundDayTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null)
return;
switch (mode) {
case MAX:
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
return;
case MIN:
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
return;
case NONE:
default:
break;
}
}
/**
* Round date to maximum or minimum in month, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundMonthTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Round date to maximum or minimum in year, depending of rounding mode.
*
* @param cal
* {@link Calendar} with configured date
* @param mode
* rounding mode
*/
public static void roundYearTime(final Calendar cal, final Rounding mode) {
if (cal == null)
throw new IllegalArgumentException("cal argument is null.");
if (mode == null || Rounding.NONE == mode)
return;
switch (mode) {
case MAX:
cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
break;
case MIN:
cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
break;
case NONE:
default:
break;
}
}
/**
* Rounding mode.
*
* @author Alexandr Bolbat
*/
public enum Rounding {
/**
* No rounding.
*/
NONE,
/**
* Round to min time.
*/
MAX,
/**
* Round to max time.
*/
MIN;
/**
* Default {@link Rounding}.
*/
public static final Rounding DEFAULT = NONE;
}
}
| additional methods added
| src/net/bolbat/utils/lang/TimeUtils.java | additional methods added | <ide><path>rc/net/bolbat/utils/lang/TimeUtils.java
<ide> public static long getYearsFromNow(final int years, final Rounding mode) {
<ide> Calendar cal = Calendar.getInstance();
<ide> cal.add(Calendar.YEAR, years);
<del>
<ide> if (mode == null || Rounding.NONE == mode)
<ide> return cal.getTimeInMillis();
<del>
<ide> roundYearTime(cal, mode);
<ide> return cal.getTimeInMillis();
<ide> }
<ide> public static long getMonthFromNow(final int months, final Rounding mode) {
<ide> final Calendar cal = Calendar.getInstance();
<ide> cal.add(Calendar.MONTH, months);
<del>
<ide> if (mode == null || Rounding.NONE == mode)
<ide> return cal.getTimeInMillis();
<del>
<ide> roundMonthTime(cal, mode);
<ide> return cal.getTimeInMillis();
<ide> }
<ide> public static long getDaysFromNow(final int days, final Rounding mode) {
<ide> final Calendar cal = Calendar.getInstance();
<ide> cal.add(Calendar.DAY_OF_MONTH, days);
<del>
<ide> if (mode == null || Rounding.NONE == mode)
<ide> return cal.getTimeInMillis();
<del>
<ide> roundDayTime(cal, mode);
<ide> return cal.getTimeInMillis();
<ide> }
<ide> public static long getHoursFromNow(final int hours, final Rounding mode) {
<ide> final Calendar cal = Calendar.getInstance();
<ide> cal.add(Calendar.HOUR_OF_DAY, hours);
<del>
<ide> if (mode == null || Rounding.NONE == mode)
<ide> return cal.getTimeInMillis();
<del>
<ide> roundHourTime(cal, mode);
<ide> return cal.getTimeInMillis();
<ide> }
<ide>
<ide> /**
<add> * Rounding incoming time to seconds, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToSecondTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<add> final Calendar cal = Calendar.getInstance();
<add> cal.setTimeInMillis(time);
<add> roundSecondTime(cal, mode);
<add> return cal.getTimeInMillis();
<add> }
<add>
<add> /**
<ide> * Round date to maximum or minimum in second, depending of rounding mode.
<ide> *
<ide> * @param cal
<ide> }
<ide>
<ide> /**
<add> * Rounding incoming time to minutes, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToMinuteTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<add> final Calendar cal = Calendar.getInstance();
<add> cal.setTimeInMillis(time);
<add> roundMinuteTime(cal, mode);
<add> return cal.getTimeInMillis();
<add> }
<add>
<add> /**
<ide> * Round date to maximum or minimum in minute, depending of rounding mode.
<ide> *
<ide> * @param cal
<ide> throw new IllegalArgumentException("cal argument is null.");
<ide> if (mode == null || Rounding.NONE == mode)
<ide> return;
<del>
<ide> switch (mode) {
<ide> case MAX:
<ide> cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
<ide> default:
<ide> break;
<ide> }
<add> }
<add>
<add> /**
<add> * Rounding incoming time to hour, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToHourTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<add> final Calendar cal = Calendar.getInstance();
<add> cal.setTimeInMillis(time);
<add> roundHourTime(cal, mode);
<add> return cal.getTimeInMillis();
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<del> * Round time in millis to maximum or minimum in day, depending of rounding mode.
<del> *
<del> * @param time
<del> * time in millis
<del> * @param mode
<del> * rounding mode
<del> * @return rounded time in millis
<del> */
<del> public static long roundDayTime(final long time, final Rounding mode) {
<del> if (mode == null || Rounding.NONE == mode)
<del> return time;
<del>
<add> * Rounding incoming time to day, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToDayTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<ide> final Calendar cal = Calendar.getInstance();
<ide> cal.setTimeInMillis(time);
<ide> roundDayTime(cal, mode);
<ide> default:
<ide> break;
<ide> }
<add> }
<add>
<add>
<add> /**
<add> * Rounding incoming time to Month, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToMonthTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<add> final Calendar cal = Calendar.getInstance();
<add> cal.setTimeInMillis(time);
<add> roundMonthTime(cal, mode);
<add> return cal.getTimeInMillis();
<ide> }
<ide>
<ide> /**
<ide> default:
<ide> break;
<ide> }
<add> }
<add>
<add> /**
<add> * Rounding incoming time to Year, up/down rounding defined by {@link Rounding}.
<add> *
<add> * @param time
<add> * time in millis
<add> * @param mode
<add> * rounding mode
<add> * @return rounded time in millis
<add> */
<add> public static long roundTimeToYearTime(final long time, final Rounding mode) {
<add> if (mode == null || Rounding.NONE == mode)
<add> return time;
<add> final Calendar cal = Calendar.getInstance();
<add> cal.setTimeInMillis(time);
<add> roundYearTime(cal, mode);
<add> return cal.getTimeInMillis();
<ide> }
<ide>
<ide> /** |
|
Java | mit | bdbad6adca3e42465d2c6ed8423e411db9cdb8cf | 0 | gcnew/muppet,gcnew/muppet | package bg.marinov.muppet;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
final boolean showHelp = Arrays.asList(args).stream().anyMatch(x -> "--help".equals(x));
if ((args.length != 1) || showHelp) {
System.err.println("Syntax: muppet <file>");
System.exit(-1);
}
final String fileName = args[0];
final File file = new File(fileName);
if (!file.exists()) {
System.err.println("File not found: " + fileName);
System.exit(-1);
}
try (final FileInputStream fs = new FileInputStream(file)) {
final String contents = readStream(fs);
final String result = TemplateContainer.eval(contents);
System.out.print(result);
} catch (Exception e) {
System.err.println("Building template failed!");
e.printStackTrace(System.err);
System.exit(-1);
}
}
@SuppressWarnings("resource")
private static String readStream(final InputStream aStream) {
final Scanner s = new Scanner(aStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
| src/bg/marinov/muppet/Main.java | package bg.marinov.muppet;
public class Main {
public static void main(String[] args) {
try {
final String s = TemplateContainer.eval("<? echo('Hello')");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| - implemented cli
| src/bg/marinov/muppet/Main.java | - implemented cli | <ide><path>rc/bg/marinov/muppet/Main.java
<ide> package bg.marinov.muppet;
<ide>
<add>import java.io.File;
<add>import java.io.FileInputStream;
<add>import java.io.InputStream;
<add>import java.util.Arrays;
<add>import java.util.Scanner;
<add>
<ide> public class Main {
<del> public static void main(String[] args) {
<del> try {
<del> final String s = TemplateContainer.eval("<? echo('Hello')");
<add> public static void main(final String[] args) {
<add> final boolean showHelp = Arrays.asList(args).stream().anyMatch(x -> "--help".equals(x));
<ide>
<del> System.out.println(s);
<add> if ((args.length != 1) || showHelp) {
<add> System.err.println("Syntax: muppet <file>");
<add> System.exit(-1);
<add> }
<add>
<add> final String fileName = args[0];
<add> final File file = new File(fileName);
<add>
<add> if (!file.exists()) {
<add> System.err.println("File not found: " + fileName);
<add> System.exit(-1);
<add> }
<add>
<add> try (final FileInputStream fs = new FileInputStream(file)) {
<add> final String contents = readStream(fs);
<add> final String result = TemplateContainer.eval(contents);
<add>
<add> System.out.print(result);
<ide> } catch (Exception e) {
<del> e.printStackTrace();
<add> System.err.println("Building template failed!");
<add> e.printStackTrace(System.err);
<add>
<add> System.exit(-1);
<ide> }
<ide> }
<add>
<add> @SuppressWarnings("resource")
<add> private static String readStream(final InputStream aStream) {
<add> final Scanner s = new Scanner(aStream).useDelimiter("\\A");
<add> return s.hasNext() ? s.next() : "";
<add> }
<ide> } |
|
Java | mpl-2.0 | 9d68994a3d8175d01dc8500b76f5676911313723 | 0 | Ch3ck/openmrs-core,macorrales/openmrs-core,dlahn/openmrs-core,AbhijitParate/openmrs-core,jcantu1988/openmrs-core,pselle/openmrs-core,MuhammadSafwan/Stop-Button-Ability,naraink/openmrs-core,macorrales/openmrs-core,sadhanvejella/openmrs,koskedk/openmrs-core,lilo2k/openmrs-core,maany/openmrs-core,preethi29/openmrs-core,WANeves/openmrs-core,MuhammadSafwan/Stop-Button-Ability,asifur77/openmrs,pselle/openmrs-core,lilo2k/openmrs-core,maany/openmrs-core,andyvand/OpenMRS,spereverziev/openmrs-core,WANeves/openmrs-core,MuhammadSafwan/Stop-Button-Ability,nilusi/Legacy-UI,milankarunarathne/openmrs-core,preethi29/openmrs-core,geoff-wasilwa/openmrs-core,kigsmtua/openmrs-core,lilo2k/openmrs-core,jamesfeshner/openmrs-module,naraink/openmrs-core,nilusi/Legacy-UI,maany/openmrs-core,rbtracker/openmrs-core,alexei-grigoriev/openmrs-core,MuhammadSafwan/Stop-Button-Ability,WANeves/openmrs-core,kristopherschmidt/openmrs-core,kigsmtua/openmrs-core,ssmusoke/openmrs-core,trsorsimoII/openmrs-core,kristopherschmidt/openmrs-core,foolchan2556/openmrs-core,dlahn/openmrs-core,MitchellBot/openmrs-core,kristopherschmidt/openmrs-core,hoquangtruong/TestMylyn,asifur77/openmrs,jembi/openmrs-core,jcantu1988/openmrs-core,spereverziev/openmrs-core,prisamuel/openmrs-core,dlahn/openmrs-core,MuhammadSafwan/Stop-Button-Ability,ern2/openmrs-core,pselle/openmrs-core,vinayvenu/openmrs-core,preethi29/openmrs-core,AbhijitParate/openmrs-core,hoquangtruong/TestMylyn,vinayvenu/openmrs-core,alexei-grigoriev/openmrs-core,iLoop2/openmrs-core,jembi/openmrs-core,koskedk/openmrs-core,donaldgavis/openmrs-core,aboutdata/openmrs-core,asifur77/openmrs,andyvand/OpenMRS,spereverziev/openmrs-core,aj-jaswanth/openmrs-core,sintjuri/openmrs-core,milankarunarathne/openmrs-core,alexei-grigoriev/openmrs-core,michaelhofer/openmrs-core,Negatu/openmrs-core,sintjuri/openmrs-core,lbl52001/openmrs-core,dcmul/openmrs-core,joansmith/openmrs-core,milankarunarathne/openmrs-core,kabariyamilind/openMRSDEV,siddharthkhabia/openmrs-core,ssmusoke/openmrs-core,milankarunarathne/openmrs-core,iLoop2/openmrs-core,jvena1/openmrs-core,preethi29/openmrs-core,ldf92/openmrs-core,trsorsimoII/openmrs-core,chethandeshpande/openmrs-core,nilusi/Legacy-UI,koskedk/openmrs-core,lbl52001/openmrs-core,kristopherschmidt/openmrs-core,kigsmtua/openmrs-core,shiangree/openmrs-core,andyvand/OpenMRS,chethandeshpande/openmrs-core,Ch3ck/openmrs-core,Negatu/openmrs-core,sintjuri/openmrs-core,MuhammadSafwan/Stop-Button-Ability,milankarunarathne/openmrs-core,dcmul/openmrs-core,WANeves/openmrs-core,prisamuel/openmrs-core,kckc/openmrs-core,siddharthkhabia/openmrs-core,chethandeshpande/openmrs-core,jembi/openmrs-core,aboutdata/openmrs-core,lbl52001/openmrs-core,Openmrs-joel/openmrs-core,vinayvenu/openmrs-core,jvena1/openmrs-core,iLoop2/openmrs-core,sravanthi17/openmrs-core,maekstr/openmrs-core,rbtracker/openmrs-core,aboutdata/openmrs-core,sravanthi17/openmrs-core,kabariyamilind/openMRSDEV,hoquangtruong/TestMylyn,lilo2k/openmrs-core,MitchellBot/openmrs-core,prisamuel/openmrs-core,maekstr/openmrs-core,kckc/openmrs-core,siddharthkhabia/openmrs-core,lbl52001/openmrs-core,kckc/openmrs-core,Openmrs-joel/openmrs-core,kigsmtua/openmrs-core,ssmusoke/openmrs-core,rbtracker/openmrs-core,AbhijitParate/openmrs-core,ldf92/openmrs-core,asifur77/openmrs,ldf92/openmrs-core,jembi/openmrs-core,jcantu1988/openmrs-core,trsorsimoII/openmrs-core,Ch3ck/openmrs-core,dcmul/openmrs-core,shiangree/openmrs-core,rbtracker/openmrs-core,michaelhofer/openmrs-core,Ch3ck/openmrs-core,jembi/openmrs-core,koskedk/openmrs-core,aj-jaswanth/openmrs-core,hoquangtruong/TestMylyn,donaldgavis/openmrs-core,prisamuel/openmrs-core,ern2/openmrs-core,aboutdata/openmrs-core,MitchellBot/openmrs-core,joansmith/openmrs-core,MitchellBot/openmrs-core,shiangree/openmrs-core,hoquangtruong/TestMylyn,Negatu/openmrs-core,jvena1/openmrs-core,jcantu1988/openmrs-core,ern2/openmrs-core,siddharthkhabia/openmrs-core,geoff-wasilwa/openmrs-core,aboutdata/openmrs-core,pselle/openmrs-core,foolchan2556/openmrs-core,kckc/openmrs-core,preethi29/openmrs-core,jcantu1988/openmrs-core,ssmusoke/openmrs-core,foolchan2556/openmrs-core,Ch3ck/openmrs-core,joansmith/openmrs-core,WANeves/openmrs-core,naraink/openmrs-core,dcmul/openmrs-core,andyvand/OpenMRS,michaelhofer/openmrs-core,sintjuri/openmrs-core,sadhanvejella/openmrs,asifur77/openmrs,maekstr/openmrs-core,sintjuri/openmrs-core,foolchan2556/openmrs-core,sravanthi17/openmrs-core,aj-jaswanth/openmrs-core,sadhanvejella/openmrs,jamesfeshner/openmrs-module,sadhanvejella/openmrs,WANeves/openmrs-core,macorrales/openmrs-core,shiangree/openmrs-core,dlahn/openmrs-core,aboutdata/openmrs-core,alexei-grigoriev/openmrs-core,shiangree/openmrs-core,macorrales/openmrs-core,MitchellBot/openmrs-core,trsorsimoII/openmrs-core,spereverziev/openmrs-core,sadhanvejella/openmrs,kabariyamilind/openMRSDEV,Negatu/openmrs-core,trsorsimoII/openmrs-core,iLoop2/openmrs-core,chethandeshpande/openmrs-core,andyvand/OpenMRS,shiangree/openmrs-core,prisamuel/openmrs-core,sravanthi17/openmrs-core,macorrales/openmrs-core,dcmul/openmrs-core,jvena1/openmrs-core,jamesfeshner/openmrs-module,ern2/openmrs-core,maekstr/openmrs-core,foolchan2556/openmrs-core,vinayvenu/openmrs-core,hoquangtruong/TestMylyn,alexei-grigoriev/openmrs-core,kckc/openmrs-core,alexwind26/openmrs-core,kabariyamilind/openMRSDEV,koskedk/openmrs-core,nilusi/Legacy-UI,joansmith/openmrs-core,geoff-wasilwa/openmrs-core,ern2/openmrs-core,sadhanvejella/openmrs,siddharthkhabia/openmrs-core,vinayvenu/openmrs-core,ssmusoke/openmrs-core,pselle/openmrs-core,ldf92/openmrs-core,Openmrs-joel/openmrs-core,Openmrs-joel/openmrs-core,lbl52001/openmrs-core,dcmul/openmrs-core,nilusi/Legacy-UI,maekstr/openmrs-core,koskedk/openmrs-core,jvena1/openmrs-core,lilo2k/openmrs-core,iLoop2/openmrs-core,ldf92/openmrs-core,dlahn/openmrs-core,jamesfeshner/openmrs-module,maany/openmrs-core,alexwind26/openmrs-core,iLoop2/openmrs-core,kristopherschmidt/openmrs-core,jembi/openmrs-core,jamesfeshner/openmrs-module,AbhijitParate/openmrs-core,spereverziev/openmrs-core,kckc/openmrs-core,alexwind26/openmrs-core,prisamuel/openmrs-core,kigsmtua/openmrs-core,Openmrs-joel/openmrs-core,milankarunarathne/openmrs-core,spereverziev/openmrs-core,chethandeshpande/openmrs-core,Negatu/openmrs-core,siddharthkhabia/openmrs-core,geoff-wasilwa/openmrs-core,alexwind26/openmrs-core,maekstr/openmrs-core,alexei-grigoriev/openmrs-core,lilo2k/openmrs-core,Negatu/openmrs-core,maany/openmrs-core,nilusi/Legacy-UI,rbtracker/openmrs-core,geoff-wasilwa/openmrs-core,sintjuri/openmrs-core,foolchan2556/openmrs-core,michaelhofer/openmrs-core,lbl52001/openmrs-core,sravanthi17/openmrs-core,kigsmtua/openmrs-core,aj-jaswanth/openmrs-core,AbhijitParate/openmrs-core,joansmith/openmrs-core,donaldgavis/openmrs-core,aj-jaswanth/openmrs-core,kabariyamilind/openMRSDEV,alexwind26/openmrs-core,donaldgavis/openmrs-core,naraink/openmrs-core,naraink/openmrs-core,andyvand/OpenMRS,michaelhofer/openmrs-core,donaldgavis/openmrs-core,pselle/openmrs-core,naraink/openmrs-core,AbhijitParate/openmrs-core | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
/**
* This class represents a list of patientIds. If it is generated from a CohortDefinition via
* {@link ReportService#evaluate(org.openmrs.report.ReportSchema, Cohort, EvaluationContext)} then
* it will contain a link back to the CohortDefinition it came from and the EvalutionContext that
* definition was evaluated in.
*
* @see org.openmrs.cohort.CohortDefinition
*/
@Root(strict = false)
public class Cohort extends BaseOpenmrsData implements Serializable {
public static final long serialVersionUID = 0L;
private static final Log log = LogFactory.getLog(Cohort.class);
private Integer cohortId;
private String name;
private String description;
private Set<Integer> memberIds;
public Cohort() {
memberIds = new TreeSet<Integer>();
}
/**
* Convenience constructor to create a Cohort object that has an primarykey/internal identifier
* of <code>cohortId</code>
*
* @param cohortId the internal identifier for this cohort
*/
public Cohort(Integer cohortId) {
this();
this.cohortId = cohortId;
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param ids option array of Integer ids
*/
public Cohort(String name, String description, Integer[] ids) {
this();
this.name = name;
this.description = description;
if (ids != null) {
memberIds.addAll(Arrays.asList(ids));
}
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param patients optional array of patients
*/
public Cohort(String name, String description, Patient[] patients) {
this(name, description, (Integer[]) null);
if (patients != null) {
for (Patient p : patients) {
memberIds.add(p.getPatientId());
}
}
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param patientsOrIds optional collection which may contain Patients, or patientIds which may
* be Integers, Strings, or anything whose toString() can be parsed to an Integer.
*/
@SuppressWarnings("unchecked")
public Cohort(Collection patientsOrIds) {
this(null, null, patientsOrIds);
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param patientsOrIds optional collection which may contain Patients, or patientIds which may
* be Integers, Strings, or anything whose toString() can be parsed to an Integer.
*/
@SuppressWarnings("unchecked")
public Cohort(String name, String description, Collection patientsOrIds) {
this(name, description, (Integer[]) null);
if (patientsOrIds != null) {
for (Object o : patientsOrIds) {
if (o instanceof Patient) {
memberIds.add(((Patient) o).getPatientId());
} else if (o instanceof Integer) {
memberIds.add((Integer) o);
} else {
memberIds.add(Integer.valueOf(o.toString()));
}
}
}
}
/**
* Convenience contructor taking in a string that is a list of comma separated patient ids This
* constructor does not check whether the database contains patients with the given ids, but
*
* @see CohortService.saveCohort(Cohort) will.
* @param commaSeparatedIds
*/
public Cohort(String commaSeparatedIds) {
this();
for (StringTokenizer st = new StringTokenizer(commaSeparatedIds, ","); st.hasMoreTokens();) {
String id = st.nextToken();
memberIds.add(Integer.valueOf(id.trim()));
}
}
/**
* @return Returns a comma-separated list of patient ids in the cohort.
*/
public String getCommaSeparatedPatientIds() {
StringBuilder sb = new StringBuilder();
for (Iterator<Integer> i = getMemberIds().iterator(); i.hasNext();) {
sb.append(i.next());
if (i.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
public boolean contains(Patient patient) {
return getMemberIds() != null && getMemberIds().contains(patient.getPatientId());
}
public boolean contains(Integer patientId) {
return getMemberIds() != null && getMemberIds().contains(patientId);
}
public String toString() {
StringBuilder sb = new StringBuilder("Cohort id=" + getCohortId());
if (getName() != null) {
sb.append(" name=" + getName());
}
if (getMemberIds() != null) {
sb.append(" size=" + getMemberIds().size());
}
return sb.toString();
}
public void addMember(Integer memberId) {
getMemberIds().add(memberId);
}
public void removeMember(Integer memberId) {
getMemberIds().remove(memberId);
}
public int size() {
return getMemberIds() == null ? 0 : getMemberIds().size();
}
public int getSize() {
return size();
}
public boolean isEmpty() {
return size() == 0;
}
// static utility methods
/**
* Returns the union of two cohorts
*
* @param a The first Cohort
* @param b The second Cohort
* @return Cohort
*/
public static Cohort union(Cohort a, Cohort b) {
Cohort ret = new Cohort();
if (a != null) {
ret.getMemberIds().addAll(a.getMemberIds());
}
if (b != null) {
ret.getMemberIds().addAll(b.getMemberIds());
}
if (a != null && b != null) {
ret.setName("(" + a.getName() + " + " + b.getName() + ")");
}
return ret;
}
/**
* Returns the intersection of two cohorts, treating null as an empty cohort
*
* @param a The first Cohort
* @param b The second Cohort
* @return Cohort
*/
public static Cohort intersect(Cohort a, Cohort b) {
Cohort ret = new Cohort();
ret.setName("(" + (a == null ? "NULL" : a.getName()) + " * " + (b == null ? "NULL" : b.getName()) + ")");
if (a != null && b != null) {
ret.getMemberIds().addAll(a.getMemberIds());
ret.getMemberIds().retainAll(b.getMemberIds());
}
return ret;
}
/**
* Subtracts a cohort from a cohort
*
* @param a the original Cohort
* @param b the Cohort to subtract
* @return Cohort
*/
public static Cohort subtract(Cohort a, Cohort b) {
Cohort ret = new Cohort();
if (a != null) {
ret.getMemberIds().addAll(a.getMemberIds());
if (b != null) {
ret.getMemberIds().removeAll(b.getMemberIds());
ret.setName("(" + a.getName() + " - " + b.getName() + ")");
}
}
return ret;
}
// getters and setters
@Attribute(required = false)
public Integer getCohortId() {
return cohortId;
}
@Attribute(required = false)
public void setCohortId(Integer cohortId) {
this.cohortId = cohortId;
}
@Element(required = false)
public String getDescription() {
return description;
}
@Element(required = false)
public void setDescription(String description) {
this.description = description;
}
@Element(required = false)
public String getName() {
return name;
}
@Element(required = false)
public void setName(String name) {
this.name = name;
}
@ElementList(required = true)
public Set<Integer> getMemberIds() {
return memberIds;
}
/**
* This method is only here for some backwards compatibility with the PatientSet object that
* this Cohort object replaced. Do not use this method.
*
* @deprecated use #getMemberIds()
* @return the memberIds
*/
@Deprecated
public Set<Integer> getPatientIds() {
return getMemberIds();
}
@ElementList(required = true)
public void setMemberIds(Set<Integer> memberIds) {
this.memberIds = memberIds;
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#getId()
*/
public Integer getId() {
return getCohortId();
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
*/
public void setId(Integer id) {
setCohortId(id);
}
}
| api/src/main/java/org/openmrs/Cohort.java | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
/**
* This class represents a list of patientIds. If it is generated from a CohortDefinition via
* {@link ReportService#evaluate(org.openmrs.report.ReportSchema, Cohort, EvaluationContext)} then
* it will contain a link back to the CohortDefinition it came from and the EvalutionContext that
* definition was evaluated in.
*
* @see org.openmrs.cohort.CohortDefinition
*/
@Root(strict = false)
public class Cohort extends BaseOpenmrsData implements Serializable {
public static final long serialVersionUID = 0L;
private static final Log logger = LogFactory.getLog(Cohort.class);
private Integer cohortId;
private String name;
private String description;
private Set<Integer> memberIds;
public Cohort() {
memberIds = new TreeSet<Integer>();
}
/**
* Convenience constructor to create a Cohort object that has an primarykey/internal identifier
* of <code>cohortId</code>
*
* @param cohortId the internal identifier for this cohort
*/
public Cohort(Integer cohortId) {
this();
this.cohortId = cohortId;
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param ids option array of Integer ids
*/
public Cohort(String name, String description, Integer[] ids) {
this();
this.name = name;
this.description = description;
if (ids != null) {
memberIds.addAll(Arrays.asList(ids));
}
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param patients optional array of patients
*/
public Cohort(String name, String description, Patient[] patients) {
this(name, description, (Integer[]) null);
if (patients != null) {
for (Patient p : patients) {
memberIds.add(p.getPatientId());
}
}
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param patientsOrIds optional collection which may contain Patients, or patientIds which may
* be Integers, Strings, or anything whose toString() can be parsed to an Integer.
*/
@SuppressWarnings("unchecked")
public Cohort(Collection patientsOrIds) {
this(null, null, patientsOrIds);
}
/**
* This constructor does not check whether the database contains patients with the given ids,
* but
*
* @see CohortService.saveCohort(Cohort) will.
* @param name
* @param description optional description
* @param patientsOrIds optional collection which may contain Patients, or patientIds which may
* be Integers, Strings, or anything whose toString() can be parsed to an Integer.
*/
@SuppressWarnings("unchecked")
public Cohort(String name, String description, Collection patientsOrIds) {
this(name, description, (Integer[]) null);
if (patientsOrIds != null) {
for (Object o : patientsOrIds) {
if (o instanceof Patient) {
memberIds.add(((Patient) o).getPatientId());
} else if (o instanceof Integer) {
memberIds.add((Integer) o);
} else {
memberIds.add(Integer.valueOf(o.toString()));
}
}
}
}
/**
* Convenience contructor taking in a string that is a list of comma separated patient ids This
* constructor does not check whether the database contains patients with the given ids, but
*
* @see CohortService.saveCohort(Cohort) will.
* @param commaSeparatedIds
*/
public Cohort(String commaSeparatedIds) {
this();
for (StringTokenizer st = new StringTokenizer(commaSeparatedIds, ","); st.hasMoreTokens();) {
String id = st.nextToken();
memberIds.add(Integer.valueOf(id.trim()));
}
}
/**
* @return Returns a comma-separated list of patient ids in the cohort.
*/
public String getCommaSeparatedPatientIds() {
StringBuilder sb = new StringBuilder();
for (Iterator<Integer> i = getMemberIds().iterator(); i.hasNext();) {
sb.append(i.next());
if (i.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
public boolean contains(Patient patient) {
return getMemberIds() != null && getMemberIds().contains(patient.getPatientId());
}
public boolean contains(Integer patientId) {
return getMemberIds() != null && getMemberIds().contains(patientId);
}
public String toString() {
StringBuilder sb = new StringBuilder("Cohort id=" + getCohortId());
if (getName() != null) {
sb.append(" name=" + getName());
}
if (getMemberIds() != null) {
sb.append(" size=" + getMemberIds().size());
}
return sb.toString();
}
public void addMember(Integer memberId) {
getMemberIds().add(memberId);
}
public void removeMember(Integer memberId) {
getMemberIds().remove(memberId);
}
public int size() {
return getMemberIds() == null ? 0 : getMemberIds().size();
}
public int getSize() {
return size();
}
public boolean isEmpty() {
return size() == 0;
}
// static utility methods
/**
* Returns the union of two cohorts
*
* @param a The first Cohort
* @param b The second Cohort
* @return Cohort
*/
public static Cohort union(Cohort a, Cohort b) {
Cohort ret = new Cohort();
if (a != null) {
ret.getMemberIds().addAll(a.getMemberIds());
}
if (b != null) {
ret.getMemberIds().addAll(b.getMemberIds());
}
if (a != null && b != null) {
ret.setName("(" + a.getName() + " + " + b.getName() + ")");
}
return ret;
}
/**
* Returns the intersection of two cohorts, treating null as an empty cohort
*
* @param a The first Cohort
* @param b The second Cohort
* @return Cohort
*/
public static Cohort intersect(Cohort a, Cohort b) {
Cohort ret = new Cohort();
ret.setName("(" + (a == null ? "NULL" : a.getName()) + " * " + (b == null ? "NULL" : b.getName()) + ")");
if (a != null && b != null) {
ret.getMemberIds().addAll(a.getMemberIds());
ret.getMemberIds().retainAll(b.getMemberIds());
}
return ret;
}
/**
* Subtracts a cohort from a cohort
*
* @param a the original Cohort
* @param b the Cohort to subtract
* @return Cohort
*/
public static Cohort subtract(Cohort a, Cohort b) {
Cohort ret = new Cohort();
if (a != null) {
ret.getMemberIds().addAll(a.getMemberIds());
if (b != null) {
ret.getMemberIds().removeAll(b.getMemberIds());
ret.setName("(" + a.getName() + " - " + b.getName() + ")");
}
}
return ret;
}
// getters and setters
@Attribute(required = false)
public Integer getCohortId() {
return cohortId;
}
@Attribute(required = false)
public void setCohortId(Integer cohortId) {
this.cohortId = cohortId;
}
@Element(required = false)
public String getDescription() {
return description;
}
@Element(required = false)
public void setDescription(String description) {
this.description = description;
}
@Element(required = false)
public String getName() {
return name;
}
@Element(required = false)
public void setName(String name) {
this.name = name;
}
@ElementList(required = true)
public Set<Integer> getMemberIds() {
return memberIds;
}
/**
* This method is only here for some backwards compatibility with the PatientSet object that
* this Cohort object replaced. Do not use this method.
*
* @deprecated use #getMemberIds()
* @return the memberIds
*/
@Deprecated
public Set<Integer> getPatientIds() {
return getMemberIds();
}
@ElementList(required = true)
public void setMemberIds(Set<Integer> memberIds) {
this.memberIds = memberIds;
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#getId()
*/
public Integer getId() {
return getCohortId();
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
*/
public void setId(Integer id) {
setCohortId(id);
}
}
| re-renamed logger to log in Cohort.java
| api/src/main/java/org/openmrs/Cohort.java | re-renamed logger to log in Cohort.java | <ide><path>pi/src/main/java/org/openmrs/Cohort.java
<ide>
<ide> public static final long serialVersionUID = 0L;
<ide>
<del> private static final Log logger = LogFactory.getLog(Cohort.class);
<add> private static final Log log = LogFactory.getLog(Cohort.class);
<ide>
<ide> private Integer cohortId;
<ide> |
|
Java | apache-2.0 | cfb47362be5408550414d3b4ffba59d6b2fa41dc | 0 | apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox | /*
* 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.io;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Unittest for org.apache.pdfbox.io.SequenceRandomAccessRead
*
*/
class SequenceRandomAccessReadTest
{
@Test
void TestCreateAndRead() throws IOException
{
String input1 = "This is a test string number 1";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "This is a test string number 2";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
{
assertThrows(IOException.class, () -> sequenceRandomAccessRead.createView(0, 10));
int overallLength = input1.length() + input2.length();
assertEquals(overallLength, sequenceRandomAccessRead.length());
byte[] bytesRead = new byte[overallLength];
assertEquals(overallLength, sequenceRandomAccessRead.read(bytesRead));
assertEquals(input1 + input2, new String(bytesRead));
}
// test missing parameter
assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(null));
// test empty list
assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(Collections.emptyList()));
// test problematic list
assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(inputList));
}
@Test
void TestSeekPeekAndRewind() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
// test seek, rewind and peek in the first part of the sequence
try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
{
// test seek, rewind and peek in the first part of the sequence
sequenceRandomAccessRead.seek(4);
assertEquals(4, sequenceRandomAccessRead.getPosition());
assertEquals('4', sequenceRandomAccessRead.read());
assertEquals(5, sequenceRandomAccessRead.getPosition());
sequenceRandomAccessRead.rewind(1);
assertEquals(4, sequenceRandomAccessRead.getPosition());
assertEquals('4', sequenceRandomAccessRead.read());
assertEquals('5', sequenceRandomAccessRead.peek());
assertEquals(5, sequenceRandomAccessRead.getPosition());
assertEquals('5', sequenceRandomAccessRead.read());
assertEquals(6, sequenceRandomAccessRead.getPosition());
// test seek, rewind and peek in the second part of the sequence
sequenceRandomAccessRead.seek(24);
assertEquals(24, sequenceRandomAccessRead.getPosition());
assertEquals('e', sequenceRandomAccessRead.read());
sequenceRandomAccessRead.rewind(1);
assertEquals('e', sequenceRandomAccessRead.read());
assertEquals('f', sequenceRandomAccessRead.peek());
assertEquals('f', sequenceRandomAccessRead.read());
assertThrows(IOException.class, () -> sequenceRandomAccessRead.seek(-1));
}
}
@Test
void TestBorderCases() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
// jump to the last byte of the first part of the sequence
try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
{
// jump to the last byte of the first part of the sequence
sequenceRandomAccessRead.seek(19);
assertEquals('9', sequenceRandomAccessRead.read());
sequenceRandomAccessRead.rewind(1);
assertEquals('9', sequenceRandomAccessRead.read());
assertEquals('a', sequenceRandomAccessRead.peek());
assertEquals('a', sequenceRandomAccessRead.read());
// jump back to the first sequence
sequenceRandomAccessRead.seek(17);
byte[] bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("789abc", new String(bytesRead));
assertEquals(23, sequenceRandomAccessRead.getPosition());
// rewind back to the first sequence
sequenceRandomAccessRead.rewind(6);
assertEquals(17, sequenceRandomAccessRead.getPosition());
bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("789abc", new String(bytesRead));
// jump to the start of the sequence
sequenceRandomAccessRead.seek(0);
bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("012345", new String(bytesRead));
}
}
@Test
void TestEOF() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
int overallLength = input1.length() + input2.length();
sequenceRandomAccessRead.seek(overallLength - 1);
assertFalse(sequenceRandomAccessRead.isEOF());
assertEquals('t', sequenceRandomAccessRead.peek());
assertFalse(sequenceRandomAccessRead.isEOF());
assertEquals('t', sequenceRandomAccessRead.read());
assertTrue(sequenceRandomAccessRead.isEOF());
assertEquals(-1, sequenceRandomAccessRead.read());
assertEquals(-1, sequenceRandomAccessRead.read(new byte[1], 0, 1));
// rewind
sequenceRandomAccessRead.rewind(5);
assertFalse(sequenceRandomAccessRead.isEOF());
byte[] bytesRead = new byte[5];
assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
assertEquals("pqrst", new String(bytesRead));
assertTrue(sequenceRandomAccessRead.isEOF());
// seek to a position beyond the end of the input
sequenceRandomAccessRead.seek(overallLength + 10);
assertTrue(sequenceRandomAccessRead.isEOF());
assertEquals(overallLength, sequenceRandomAccessRead.getPosition());
assertFalse(sequenceRandomAccessRead.isClosed());
sequenceRandomAccessRead.close();
assertTrue(sequenceRandomAccessRead.isClosed());
// closing a SequenceRandomAccessRead twice shouldn't be a problem
sequenceRandomAccessRead.close();
assertThrows(IOException.class, () -> sequenceRandomAccessRead.read(),
"checkClosed should have thrown an IOException");
}
@Test
void TestEmptyStream() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
RandomAccessReadBuffer emptyBuffer = new RandomAccessReadBuffer("".getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1, emptyBuffer,
randomAccessReadBuffer2);
try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
{
// check length
assertEquals(sequenceRandomAccessRead.length(), input1.length() + input2.length());
// read from both parts of the sequence
byte[] bytesRead = new byte[10];
sequenceRandomAccessRead.seek(15);
assertEquals(10, sequenceRandomAccessRead.read(bytesRead));
assertEquals("56789abcde", new String(bytesRead));
// rewind and read again
sequenceRandomAccessRead.rewind(15);
bytesRead = new byte[5];
assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
assertEquals("01234", new String(bytesRead));
// check EOF when reading
bytesRead = new byte[5];
sequenceRandomAccessRead.seek(38);
assertEquals(2, sequenceRandomAccessRead.read(bytesRead));
assertEquals("st", new String(bytesRead, 0, 2));
// check EOF after seek
sequenceRandomAccessRead.seek(40);
assertTrue(sequenceRandomAccessRead.isEOF());
}
}
}
| pdfbox/src/test/java/org/apache/pdfbox/io/SequenceRandomAccessReadTest.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.io;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Unittest for org.apache.pdfbox.io.SequenceRandomAccessRead
*
*/
class SequenceRandomAccessReadTest
{
@Test
void TestCreateAndRead() throws IOException
{
String input1 = "This is a test string number 1";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "This is a test string number 2";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
try
{
sequenceRandomAccessRead.createView(0, 10);
fail("createView should have thrown an IOException");
}
catch(IOException e)
{
}
int overallLength = input1.length() + input2.length();
assertEquals(overallLength, sequenceRandomAccessRead.length());
byte[] bytesRead = new byte[overallLength];
assertEquals(overallLength, sequenceRandomAccessRead.read(bytesRead));
assertEquals(input1 + input2, new String(bytesRead));
sequenceRandomAccessRead.close();
// test missing parameter
try (RandomAccessRead read = new SequenceRandomAccessRead(null))
{
fail("Constructor should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
// test empty list
try (RandomAccessRead read = new SequenceRandomAccessRead(Collections.emptyList()))
{
fail("Constructor should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
// test problematic list
try (RandomAccessRead read = new SequenceRandomAccessRead(inputList))
{
fail("Constructor should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
}
}
@Test
void TestSeekPeekAndRewind() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
// test seek, rewind and peek in the first part of the sequence
sequenceRandomAccessRead.seek(4);
assertEquals(4, sequenceRandomAccessRead.getPosition());
assertEquals('4', sequenceRandomAccessRead.read());
assertEquals(5, sequenceRandomAccessRead.getPosition());
sequenceRandomAccessRead.rewind(1);
assertEquals(4, sequenceRandomAccessRead.getPosition());
assertEquals('4', sequenceRandomAccessRead.read());
assertEquals('5', sequenceRandomAccessRead.peek());
assertEquals(5, sequenceRandomAccessRead.getPosition());
assertEquals('5', sequenceRandomAccessRead.read());
assertEquals(6, sequenceRandomAccessRead.getPosition());
// test seek, rewind and peek in the second part of the sequence
sequenceRandomAccessRead.seek(24);
assertEquals(24, sequenceRandomAccessRead.getPosition());
assertEquals('e', sequenceRandomAccessRead.read());
sequenceRandomAccessRead.rewind(1);
assertEquals('e', sequenceRandomAccessRead.read());
assertEquals('f', sequenceRandomAccessRead.peek());
assertEquals('f', sequenceRandomAccessRead.read());
try
{
sequenceRandomAccessRead.seek(-1);
fail("seek should have thrown an IOException");
}
catch (IOException e)
{
}
sequenceRandomAccessRead.close();
}
@Test
void TestBorderCases() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
// jump to the last byte of the first part of the sequence
sequenceRandomAccessRead.seek(19);
assertEquals('9', sequenceRandomAccessRead.read());
sequenceRandomAccessRead.rewind(1);
assertEquals('9', sequenceRandomAccessRead.read());
assertEquals('a', sequenceRandomAccessRead.peek());
assertEquals('a', sequenceRandomAccessRead.read());
// jump back to the first sequence
sequenceRandomAccessRead.seek(17);
byte[] bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("789abc", new String(bytesRead));
assertEquals(23, sequenceRandomAccessRead.getPosition());
// rewind back to the first sequence
sequenceRandomAccessRead.rewind(6);
assertEquals(17, sequenceRandomAccessRead.getPosition());
bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("789abc", new String(bytesRead));
// jump to the start of the sequence
sequenceRandomAccessRead.seek(0);
bytesRead = new byte[6];
assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
assertEquals("012345", new String(bytesRead));
sequenceRandomAccessRead.close();
}
@Test
void TestEOF() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
int overallLength = input1.length() + input2.length();
sequenceRandomAccessRead.seek(overallLength - 1);
assertFalse(sequenceRandomAccessRead.isEOF());
assertEquals('t', sequenceRandomAccessRead.peek());
assertFalse(sequenceRandomAccessRead.isEOF());
assertEquals('t', sequenceRandomAccessRead.read());
assertTrue(sequenceRandomAccessRead.isEOF());
assertEquals(-1, sequenceRandomAccessRead.read());
assertEquals(-1, sequenceRandomAccessRead.read(new byte[1], 0, 1));
// rewind
sequenceRandomAccessRead.rewind(5);
assertFalse(sequenceRandomAccessRead.isEOF());
byte[] bytesRead = new byte[5];
assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
assertEquals("pqrst", new String(bytesRead));
assertTrue(sequenceRandomAccessRead.isEOF());
// seek to a position beyond the end of the input
sequenceRandomAccessRead.seek(overallLength + 10);
assertTrue(sequenceRandomAccessRead.isEOF());
assertEquals(overallLength, sequenceRandomAccessRead.getPosition());
assertFalse(sequenceRandomAccessRead.isClosed());
sequenceRandomAccessRead.close();
assertTrue(sequenceRandomAccessRead.isClosed());
// closing a SequenceRandomAccessRead twice shouldn't be a problem
sequenceRandomAccessRead.close();
try
{
sequenceRandomAccessRead.read();
fail("checkClosed should have thrown an IOException");
}
catch (IOException e)
{
}
}
@Test
void TestEmptyStream() throws IOException
{
String input1 = "01234567890123456789";
RandomAccessReadBuffer randomAccessReadBuffer1 = new RandomAccessReadBuffer(
input1.getBytes());
String input2 = "abcdefghijklmnopqrst";
RandomAccessReadBuffer randomAccessReadBuffer2 = new RandomAccessReadBuffer(
input2.getBytes());
RandomAccessReadBuffer emptyBuffer = new RandomAccessReadBuffer("".getBytes());
List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1, emptyBuffer,
randomAccessReadBuffer2);
SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
// check length
assertEquals(sequenceRandomAccessRead.length(), input1.length() + input2.length());
// read from both parts of the sequence
byte[] bytesRead = new byte[10];
sequenceRandomAccessRead.seek(15);
assertEquals(10, sequenceRandomAccessRead.read(bytesRead));
assertEquals("56789abcde", new String(bytesRead));
// rewind and read again
sequenceRandomAccessRead.rewind(15);
bytesRead = new byte[5];
assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
assertEquals("01234", new String(bytesRead));
// check EOF when reading
bytesRead = new byte[5];
sequenceRandomAccessRead.seek(38);
assertEquals(2, sequenceRandomAccessRead.read(bytesRead));
assertEquals("st", new String(bytesRead, 0, 2));
// check EOF after seek
sequenceRandomAccessRead.seek(40);
assertTrue(sequenceRandomAccessRead.isEOF());
sequenceRandomAccessRead.close();
}
}
| PDFBOX-4892: use try-with-resources; use assertThrows
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1885003 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/test/java/org/apache/pdfbox/io/SequenceRandomAccessReadTest.java | PDFBOX-4892: use try-with-resources; use assertThrows | <ide><path>dfbox/src/test/java/org/apache/pdfbox/io/SequenceRandomAccessReadTest.java
<ide>
<ide> package org.apache.pdfbox.io;
<ide>
<del>import static org.junit.jupiter.api.Assertions.assertEquals;
<del>import static org.junit.jupiter.api.Assertions.assertFalse;
<del>import static org.junit.jupiter.api.Assertions.assertTrue;
<del>import static org.junit.jupiter.api.Assertions.fail;
<del>
<ide> import java.io.IOException;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<add>import static org.junit.jupiter.api.Assertions.assertEquals;
<add>import static org.junit.jupiter.api.Assertions.assertFalse;
<add>import static org.junit.jupiter.api.Assertions.assertThrows;
<add>import static org.junit.jupiter.api.Assertions.assertTrue;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> /**
<ide> input2.getBytes());
<ide> List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
<ide> randomAccessReadBuffer2);
<del> SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
<del>
<del> try
<del> {
<del> sequenceRandomAccessRead.createView(0, 10);
<del> fail("createView should have thrown an IOException");
<del> }
<del> catch(IOException e)
<del> {
<del> }
<del>
<del> int overallLength = input1.length() + input2.length();
<del> assertEquals(overallLength, sequenceRandomAccessRead.length());
<del>
<del> byte[] bytesRead = new byte[overallLength];
<del>
<del> assertEquals(overallLength, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals(input1 + input2, new String(bytesRead));
<del>
<del> sequenceRandomAccessRead.close();
<add> try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
<add> {
<add> assertThrows(IOException.class, () -> sequenceRandomAccessRead.createView(0, 10));
<add>
<add> int overallLength = input1.length() + input2.length();
<add> assertEquals(overallLength, sequenceRandomAccessRead.length());
<add>
<add> byte[] bytesRead = new byte[overallLength];
<add>
<add> assertEquals(overallLength, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals(input1 + input2, new String(bytesRead));
<add> }
<ide>
<ide> // test missing parameter
<del> try (RandomAccessRead read = new SequenceRandomAccessRead(null))
<del> {
<del> fail("Constructor should have thrown an IllegalArgumentException");
<del> }
<del> catch (IllegalArgumentException e)
<del> {
<del> }
<add> assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(null));
<ide>
<ide> // test empty list
<del> try (RandomAccessRead read = new SequenceRandomAccessRead(Collections.emptyList()))
<del> {
<del> fail("Constructor should have thrown an IllegalArgumentException");
<del> }
<del> catch (IllegalArgumentException e)
<del> {
<del> }
<add> assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(Collections.emptyList()));
<add>
<ide> // test problematic list
<del> try (RandomAccessRead read = new SequenceRandomAccessRead(inputList))
<del> {
<del> fail("Constructor should have thrown an IllegalArgumentException");
<del> }
<del> catch (IllegalArgumentException e)
<del> {
<del> }
<add> assertThrows(IllegalArgumentException.class, () -> new SequenceRandomAccessRead(inputList));
<ide> }
<ide>
<ide> @Test
<ide> input2.getBytes());
<ide> List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
<ide> randomAccessReadBuffer2);
<del> SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
<del>
<ide> // test seek, rewind and peek in the first part of the sequence
<del> sequenceRandomAccessRead.seek(4);
<del> assertEquals(4, sequenceRandomAccessRead.getPosition());
<del> assertEquals('4', sequenceRandomAccessRead.read());
<del> assertEquals(5, sequenceRandomAccessRead.getPosition());
<del> sequenceRandomAccessRead.rewind(1);
<del> assertEquals(4, sequenceRandomAccessRead.getPosition());
<del> assertEquals('4', sequenceRandomAccessRead.read());
<del> assertEquals('5', sequenceRandomAccessRead.peek());
<del> assertEquals(5, sequenceRandomAccessRead.getPosition());
<del> assertEquals('5', sequenceRandomAccessRead.read());
<del> assertEquals(6, sequenceRandomAccessRead.getPosition());
<del>
<del> // test seek, rewind and peek in the second part of the sequence
<del> sequenceRandomAccessRead.seek(24);
<del> assertEquals(24, sequenceRandomAccessRead.getPosition());
<del> assertEquals('e', sequenceRandomAccessRead.read());
<del> sequenceRandomAccessRead.rewind(1);
<del> assertEquals('e', sequenceRandomAccessRead.read());
<del> assertEquals('f', sequenceRandomAccessRead.peek());
<del> assertEquals('f', sequenceRandomAccessRead.read());
<del>
<del> try
<del> {
<del> sequenceRandomAccessRead.seek(-1);
<del> fail("seek should have thrown an IOException");
<del> }
<del> catch (IOException e)
<del> {
<del> }
<del>
<del> sequenceRandomAccessRead.close();
<add> try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
<add> {
<add> // test seek, rewind and peek in the first part of the sequence
<add> sequenceRandomAccessRead.seek(4);
<add> assertEquals(4, sequenceRandomAccessRead.getPosition());
<add> assertEquals('4', sequenceRandomAccessRead.read());
<add> assertEquals(5, sequenceRandomAccessRead.getPosition());
<add> sequenceRandomAccessRead.rewind(1);
<add> assertEquals(4, sequenceRandomAccessRead.getPosition());
<add> assertEquals('4', sequenceRandomAccessRead.read());
<add> assertEquals('5', sequenceRandomAccessRead.peek());
<add> assertEquals(5, sequenceRandomAccessRead.getPosition());
<add> assertEquals('5', sequenceRandomAccessRead.read());
<add> assertEquals(6, sequenceRandomAccessRead.getPosition());
<add> // test seek, rewind and peek in the second part of the sequence
<add> sequenceRandomAccessRead.seek(24);
<add> assertEquals(24, sequenceRandomAccessRead.getPosition());
<add> assertEquals('e', sequenceRandomAccessRead.read());
<add> sequenceRandomAccessRead.rewind(1);
<add> assertEquals('e', sequenceRandomAccessRead.read());
<add> assertEquals('f', sequenceRandomAccessRead.peek());
<add> assertEquals('f', sequenceRandomAccessRead.read());
<add> assertThrows(IOException.class, () -> sequenceRandomAccessRead.seek(-1));
<add> }
<ide> }
<ide>
<ide> @Test
<ide> input2.getBytes());
<ide> List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1,
<ide> randomAccessReadBuffer2);
<del> SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
<del>
<ide> // jump to the last byte of the first part of the sequence
<del> sequenceRandomAccessRead.seek(19);
<del> assertEquals('9', sequenceRandomAccessRead.read());
<del> sequenceRandomAccessRead.rewind(1);
<del> assertEquals('9', sequenceRandomAccessRead.read());
<del> assertEquals('a', sequenceRandomAccessRead.peek());
<del> assertEquals('a', sequenceRandomAccessRead.read());
<del>
<del> // jump back to the first sequence
<del> sequenceRandomAccessRead.seek(17);
<del> byte[] bytesRead = new byte[6];
<del> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("789abc", new String(bytesRead));
<del> assertEquals(23, sequenceRandomAccessRead.getPosition());
<del>
<del> // rewind back to the first sequence
<del> sequenceRandomAccessRead.rewind(6);
<del> assertEquals(17, sequenceRandomAccessRead.getPosition());
<del> bytesRead = new byte[6];
<del> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("789abc", new String(bytesRead));
<del>
<del> // jump to the start of the sequence
<del> sequenceRandomAccessRead.seek(0);
<del> bytesRead = new byte[6];
<del> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("012345", new String(bytesRead));
<del>
<del> sequenceRandomAccessRead.close();
<add> try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
<add> {
<add> // jump to the last byte of the first part of the sequence
<add> sequenceRandomAccessRead.seek(19);
<add> assertEquals('9', sequenceRandomAccessRead.read());
<add> sequenceRandomAccessRead.rewind(1);
<add> assertEquals('9', sequenceRandomAccessRead.read());
<add> assertEquals('a', sequenceRandomAccessRead.peek());
<add> assertEquals('a', sequenceRandomAccessRead.read());
<add>
<add> // jump back to the first sequence
<add> sequenceRandomAccessRead.seek(17);
<add> byte[] bytesRead = new byte[6];
<add> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("789abc", new String(bytesRead));
<add> assertEquals(23, sequenceRandomAccessRead.getPosition());
<add>
<add> // rewind back to the first sequence
<add> sequenceRandomAccessRead.rewind(6);
<add> assertEquals(17, sequenceRandomAccessRead.getPosition());
<add> bytesRead = new byte[6];
<add> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("789abc", new String(bytesRead));
<add>
<add> // jump to the start of the sequence
<add> sequenceRandomAccessRead.seek(0);
<add> bytesRead = new byte[6];
<add> assertEquals(6, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("012345", new String(bytesRead));
<add> }
<ide> }
<ide>
<ide> @Test
<ide> // closing a SequenceRandomAccessRead twice shouldn't be a problem
<ide> sequenceRandomAccessRead.close();
<ide>
<del> try
<del> {
<del> sequenceRandomAccessRead.read();
<del> fail("checkClosed should have thrown an IOException");
<del> }
<del> catch (IOException e)
<del> {
<del> }
<add> assertThrows(IOException.class, () -> sequenceRandomAccessRead.read(),
<add> "checkClosed should have thrown an IOException");
<ide> }
<ide>
<ide> @Test
<ide>
<ide> List<RandomAccessRead> inputList = Arrays.asList(randomAccessReadBuffer1, emptyBuffer,
<ide> randomAccessReadBuffer2);
<del> SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList);
<del>
<del> // check length
<del> assertEquals(sequenceRandomAccessRead.length(), input1.length() + input2.length());
<del>
<del> // read from both parts of the sequence
<del> byte[] bytesRead = new byte[10];
<del> sequenceRandomAccessRead.seek(15);
<del> assertEquals(10, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("56789abcde", new String(bytesRead));
<del>
<del> // rewind and read again
<del> sequenceRandomAccessRead.rewind(15);
<del> bytesRead = new byte[5];
<del> assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("01234", new String(bytesRead));
<del>
<del> // check EOF when reading
<del> bytesRead = new byte[5];
<del> sequenceRandomAccessRead.seek(38);
<del> assertEquals(2, sequenceRandomAccessRead.read(bytesRead));
<del> assertEquals("st", new String(bytesRead, 0, 2));
<del>
<del> // check EOF after seek
<del> sequenceRandomAccessRead.seek(40);
<del> assertTrue(sequenceRandomAccessRead.isEOF());
<del>
<del> sequenceRandomAccessRead.close();
<add>
<add> try (SequenceRandomAccessRead sequenceRandomAccessRead = new SequenceRandomAccessRead(inputList))
<add> {
<add> // check length
<add> assertEquals(sequenceRandomAccessRead.length(), input1.length() + input2.length());
<add>
<add> // read from both parts of the sequence
<add> byte[] bytesRead = new byte[10];
<add> sequenceRandomAccessRead.seek(15);
<add> assertEquals(10, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("56789abcde", new String(bytesRead));
<add>
<add> // rewind and read again
<add> sequenceRandomAccessRead.rewind(15);
<add> bytesRead = new byte[5];
<add> assertEquals(5, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("01234", new String(bytesRead));
<add>
<add> // check EOF when reading
<add> bytesRead = new byte[5];
<add> sequenceRandomAccessRead.seek(38);
<add> assertEquals(2, sequenceRandomAccessRead.read(bytesRead));
<add> assertEquals("st", new String(bytesRead, 0, 2));
<add>
<add> // check EOF after seek
<add> sequenceRandomAccessRead.seek(40);
<add> assertTrue(sequenceRandomAccessRead.isEOF());
<add> }
<ide> }
<ide> } |
|
Java | bsd-3-clause | 4db312bd279f1ef5ab97d09e865737ef9689ceb8 | 0 | wakatime/jetbrains-wakatime,VISTALL/consulo-wakatime | /* ==========================================================
File: Dependencies.java
Description: Manages plugin dependencies.
Maintainer: WakaTime <[email protected]>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
===========================================================*/
package com.wakatime.intellij.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Dependencies {
private static final String cliVersion = "3.0.5";
private static String pythonLocation = null;
private static String resourcesLocation = null;
private static String cliLocation = null;
public static boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
String separator = "[\\\\/]";
Dependencies.resourcesLocation = WakaTime.class.getResource("WakaTime.class").getPath()
.replaceFirst("file:", "")
.replaceAll("%20", " ")
.replaceFirst("com" + separator + "wakatime" + separator + "intellij" + separator + "plugin" + separator + "WakaTime.class", "")
.replaceFirst("WakaTime.jar!" + separator, "") + "WakaTime-resources";
if (System.getProperty("os.name").startsWith("Windows") && Dependencies.resourcesLocation.startsWith("/")) {
Dependencies.resourcesLocation = Dependencies.resourcesLocation.substring(1);
}
}
return Dependencies.resourcesLocation;
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
String []paths = new String[] {
"pythonw",
"python",
"/usr/local/bin/python",
"/usr/bin/python",
"\\python37\\pythonw",
"\\Python37\\pythonw",
"\\python36\\pythonw",
"\\Python36\\pythonw",
"\\python35\\pythonw",
"\\Python35\\pythonw",
"\\python34\\pythonw",
"\\Python34\\pythonw",
"\\python33\\pythonw",
"\\Python33\\pythonw",
"\\python32\\pythonw",
"\\Python32\\pythonw",
"\\python31\\pythonw",
"\\Python31\\pythonw",
"\\python30\\pythonw",
"\\Python30\\pythonw",
"\\python27\\pythonw",
"\\Python27\\pythonw",
"\\python26\\pythonw",
"\\Python26\\pythonw",
"\\python37\\python",
"\\Python37\\python",
"\\python36\\python",
"\\Python36\\python",
"\\python35\\python",
"\\Python35\\python",
"\\python34\\python",
"\\Python34\\python",
"\\python33\\python",
"\\Python33\\python",
"\\python32\\python",
"\\Python32\\python",
"\\python31\\python",
"\\Python31\\python",
"\\python30\\python",
"\\Python30\\python",
"\\python27\\python",
"\\Python27\\python",
"\\python26\\python",
"\\Python26\\python",
};
for (int i=0; i<paths.length; i++) {
try {
Runtime.getRuntime().exec(paths[i]);
Dependencies.pythonLocation = paths[i];
break;
} catch (Exception e) { }
}
return Dependencies.pythonLocation;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return (cli.exists() && !cli.isDirectory());
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getPythonLocation());
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
if (cliVersion.equals(stdError.readLine())) {
return false;
}
} catch (Exception e) { }
return true;
}
public static String getCLILocation() {
return Dependencies.getResourcesLocation()+File.separator+"wakatime-master"+File.separator+"wakatime-cli.py";
}
public static void installCLI() {
File cli = new File(Dependencies.getCLILocation());
if (!cli.getParentFile().getParentFile().exists())
cli.getParentFile().getParentFile().mkdirs();
URL url = null;
try {
url = new URL("https://codeload.github.com/wakatime/wakatime/zip/master");
} catch (MalformedURLException e) { }
String zipFile = cli.getParentFile().getParentFile().getAbsolutePath()+File.separator+"wakatime-cli.zip";
File outputDir = cli.getParentFile().getParentFile();
// download wakatime-master.zip file
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(url.openStream());
fos = new FileOutputStream(zipFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
Dependencies.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
} catch (IOException e) {
WakaTime.log.error(e);
}
}
public static void upgradeCLI() {
File cliDir = new File(new File(Dependencies.getCLILocation()).getParent());
cliDir.delete();
Dependencies.installCLI();
}
public static void installPython() {
if (System.getProperty("os.name").contains("Windows")) {
String url = "https://www.python.org/ftp/python/3.4.2/python-3.4.2.msi";
if (System.getenv("ProgramFiles(x86)") != null) {
url = "https://www.python.org/ftp/python/3.4.2/python-3.4.2.amd64.msi";
}
File cli = new File(Dependencies.getCLILocation());
String outFile = cli.getParentFile().getParentFile().getAbsolutePath()+File.separator+"python.msi";
if (downloadFile(url, outFile)) {
// execute python msi installer
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("msiexec");
cmds.add("/i");
cmds.add(outFile);
cmds.add("/norestart");
cmds.add("/qb!");
try {
Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
return true;
} catch (IOException e) {
WakaTime.log.error(e);
}
return false;
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
}
| src/com/wakatime/intellij/plugin/Dependencies.java | /* ==========================================================
File: Dependencies.java
Description: Manages plugin dependencies.
Maintainer: WakaTime <[email protected]>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
===========================================================*/
package com.wakatime.intellij.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Dependencies {
private static final String cliVersion = "3.0.5";
private static String pythonLocation = null;
private static String resourcesLocation = null;
private static String cliLocation = null;
public static boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
String separator = "[\\\\/]";
Dependencies.resourcesLocation = WakaTime.class.getResource("WakaTime.class").getPath()
.replaceFirst("file:", "")
.replaceAll("%20", " ")
.replaceFirst("com" + separator + "wakatime" + separator + "intellij" + separator + "plugin" + separator + "WakaTime.class", "")
.replaceFirst("WakaTime.jar!" + separator, "") + "WakaTime-resources";
if (System.getProperty("os.name").startsWith("Windows") && Dependencies.resourcesLocation.startsWith("/")) {
Dependencies.resourcesLocation = Dependencies.resourcesLocation.substring(1);
}
}
return Dependencies.resourcesLocation;
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
String []paths = new String[] {
"pythonw",
"python",
"usr/bin/python",
"\\python37\\pythonw",
"\\python36\\pythonw",
"\\python35\\pythonw",
"\\python34\\pythonw",
"\\python33\\pythonw",
"\\python32\\pythonw",
"\\python31\\pythonw",
"\\python30\\pythonw",
"\\python27\\pythonw",
"\\python26\\pythonw",
"\\python37\\python",
"\\python36\\python",
"\\python35\\python",
"\\python34\\python",
"\\python33\\python",
"\\python32\\python",
"\\python31\\python",
"\\python30\\python",
"\\python27\\python",
"\\python26\\python",
};
for (int i=0; i<paths.length; i++) {
try {
Runtime.getRuntime().exec(paths[i]);
Dependencies.pythonLocation = paths[i];
break;
} catch (Exception e) { }
}
return Dependencies.pythonLocation;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return (cli.exists() && !cli.isDirectory());
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getPythonLocation());
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
if (cliVersion.equals(stdError.readLine())) {
return false;
}
} catch (Exception e) { }
return true;
}
public static String getCLILocation() {
return Dependencies.getResourcesLocation()+File.separator+"wakatime-master"+File.separator+"wakatime-cli.py";
}
public static void installCLI() {
File cli = new File(Dependencies.getCLILocation());
if (!cli.getParentFile().getParentFile().exists())
cli.getParentFile().getParentFile().mkdirs();
URL url = null;
try {
url = new URL("https://codeload.github.com/wakatime/wakatime/zip/master");
} catch (MalformedURLException e) { }
String zipFile = cli.getParentFile().getParentFile().getAbsolutePath()+File.separator+"wakatime-cli.zip";
File outputDir = cli.getParentFile().getParentFile();
// download wakatime-master.zip file
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(url.openStream());
fos = new FileOutputStream(zipFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
Dependencies.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
} catch (IOException e) {
WakaTime.log.error(e);
}
}
public static void upgradeCLI() {
File cliDir = new File(new File(Dependencies.getCLILocation()).getParent());
cliDir.delete();
Dependencies.installCLI();
}
public static void installPython() {
if (System.getProperty("os.name").contains("Windows")) {
String url = "https://www.python.org/ftp/python/3.4.2/python-3.4.2.msi";
if (System.getenv("ProgramFiles(x86)") != null) {
url = "https://www.python.org/ftp/python/3.4.2/python-3.4.2.amd64.msi";
}
File cli = new File(Dependencies.getCLILocation());
String outFile = cli.getParentFile().getParentFile().getAbsolutePath()+File.separator+"python.msi";
if (downloadFile(url, outFile)) {
// execute python msi installer
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("msiexec");
cmds.add("/i");
cmds.add(outFile);
cmds.add("/norestart");
cmds.add("/qb!");
try {
Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
return true;
} catch (IOException e) {
WakaTime.log.error(e);
}
return false;
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
}
| look in all default install locations for python exe
| src/com/wakatime/intellij/plugin/Dependencies.java | look in all default install locations for python exe | <ide><path>rc/com/wakatime/intellij/plugin/Dependencies.java
<ide> String []paths = new String[] {
<ide> "pythonw",
<ide> "python",
<del> "usr/bin/python",
<add> "/usr/local/bin/python",
<add> "/usr/bin/python",
<ide> "\\python37\\pythonw",
<add> "\\Python37\\pythonw",
<ide> "\\python36\\pythonw",
<add> "\\Python36\\pythonw",
<ide> "\\python35\\pythonw",
<add> "\\Python35\\pythonw",
<ide> "\\python34\\pythonw",
<add> "\\Python34\\pythonw",
<ide> "\\python33\\pythonw",
<add> "\\Python33\\pythonw",
<ide> "\\python32\\pythonw",
<add> "\\Python32\\pythonw",
<ide> "\\python31\\pythonw",
<add> "\\Python31\\pythonw",
<ide> "\\python30\\pythonw",
<add> "\\Python30\\pythonw",
<ide> "\\python27\\pythonw",
<add> "\\Python27\\pythonw",
<ide> "\\python26\\pythonw",
<add> "\\Python26\\pythonw",
<ide> "\\python37\\python",
<add> "\\Python37\\python",
<ide> "\\python36\\python",
<add> "\\Python36\\python",
<ide> "\\python35\\python",
<add> "\\Python35\\python",
<ide> "\\python34\\python",
<add> "\\Python34\\python",
<ide> "\\python33\\python",
<add> "\\Python33\\python",
<ide> "\\python32\\python",
<add> "\\Python32\\python",
<ide> "\\python31\\python",
<add> "\\Python31\\python",
<ide> "\\python30\\python",
<add> "\\Python30\\python",
<ide> "\\python27\\python",
<add> "\\Python27\\python",
<ide> "\\python26\\python",
<add> "\\Python26\\python",
<ide> };
<ide> for (int i=0; i<paths.length; i++) {
<ide> try { |
|
Java | apache-2.0 | e8450c28b239fc851f7aca4a1d3888525ed35160 | 0 | hellojavaer/ddal,hellojavaer/ddr | /*
* Copyright 2016-2017 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.hellojavaer.ddal.spring.context.scan;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.hellojavaer.ddal.ddr.shard.ShardRouteContext;
import org.hellojavaer.ddal.ddr.shard.annotation.ShardRoute;
import org.hellojavaer.ddal.ddr.shard.enums.ContextPropagation;
import org.hellojavaer.ddal.ddr.utils.DDRStringUtils;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 01/01/2017.
*/
@Aspect
@Component
public class EnableShardRouteAnnotation {
private ParameterNameDiscoverer parameterNameDiscoverer = null;
private static boolean notSupportParameterNameDiscoverer = false;
private Map<Method, InnerBean> expressionCache = new HashMap<Method, InnerBean>();
@Around("@annotation(shardRoute)")
public Object around(ProceedingJoinPoint joinPoint, ShardRoute shardRoute) throws Throwable {
try {
//
if (shardRoute.value() == ContextPropagation.SUB_CONTEXT) {
ShardRouteContext.pushSubContext();
} else {
ShardRouteContext.clear();
}
if (shardRoute.scName() != null && shardRoute.scName().length() > 0 //
&& shardRoute.sdValue() != null && shardRoute.sdValue().length() > 0) {// 禁止对系统变量路由
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
InnerBean innerBean = expressionCache.get(method);
Object[] args = joinPoint.getArgs();
Object val = null;
if (innerBean == null) {
synchronized (this) {
innerBean = expressionCache.get(method);
if (innerBean == null) {
ExpressionParser parser = new SpelExpressionParser();
Expression expression0 = null;
String sdValue = shardRoute.sdValue();
sdValue = DDRStringUtils.trimToNull(sdValue);
if (sdValue != null) {
expression0 = parser.parseExpression(sdValue, PARSER_CONTEXT);
}
String[] paramNames = getParameterNames(method);
val = calculate(expression0, paramNames, args);
InnerBean innerBean1 = new InnerBean(paramNames, expression0);
innerBean1.getExpression();//
expressionCache.put(method, innerBean1);
} else {
val = calculate(innerBean.getExpression(), innerBean.getParameterNames(), args);
}
}
} else {
val = calculate(innerBean.getExpression(), innerBean.getParameterNames(), args);
}
ShardRouteContext.setDefaultRouteInfo(shardRoute.scName(), val);
} else {
if ((shardRoute.scName() == null || shardRoute.scName().length() == 0)
&& (shardRoute.sdValue() == null || shardRoute.sdValue().length() == 0)) {
// ok
} else {
throw new IllegalArgumentException(
"scName and sdValue should either both have a non-empty value or both have a empty value");
}
}
return joinPoint.proceed(joinPoint.getArgs());
} finally {
if (shardRoute.value() == ContextPropagation.SUB_CONTEXT) {
ShardRouteContext.popSubContext();
} else {
ShardRouteContext.clear();
}
}
}
/**
* DefaultParameterNameDiscoverer is supported spring 4.0
* @return
*/
private String[] getParameterNames(Method method) {
if (notSupportParameterNameDiscoverer) {
return null;
} else {
try {
parameterNameDiscoverer = new DefaultParameterNameDiscoverer();// only support from spring4
return parameterNameDiscoverer.getParameterNames(method);
} catch (NoClassDefFoundError e) {
notSupportParameterNameDiscoverer = true;
return null;
}
}
}
private Object calculate(Expression expression, String[] parameterNames, Object[] args) {
if (expression == null) {
return null;
}
EvaluationContext context = new StandardEvaluationContext();
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (parameterNames != null && parameterNames.length > i) {
context.setVariable(parameterNames[i], args[i]);
}
context.setVariable("$" + i, args[i]);
}
}
return expression.getValue(context);
}
private class InnerBean {
public InnerBean(String[] parameterNames, Expression expression) {
this.parameterNames = parameterNames;
this.expression = expression;
}
private String[] parameterNames;
private Expression expression;
public String[] getParameterNames() {
return parameterNames;
}
public void setParameterNames(String[] parameterNames) {
this.parameterNames = parameterNames;
}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
}
private static ParserContext PARSER_CONTEXT = new ParserContext() {
public boolean isTemplate() {
return false;
}
public String getExpressionPrefix() {
return null;
}
public String getExpressionSuffix() {
return null;
}
};
}
| ddal-spring-context/src/main/java/org/hellojavaer/ddal/spring/context/scan/EnableShardRouteAnnotation.java | /*
* Copyright 2016-2017 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.hellojavaer.ddal.spring.context.scan;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.hellojavaer.ddal.ddr.shard.ShardRouteContext;
import org.hellojavaer.ddal.ddr.shard.annotation.ShardRoute;
import org.hellojavaer.ddal.ddr.shard.enums.ContextPropagation;
import org.hellojavaer.ddal.ddr.utils.DDRStringUtils;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 01/01/2017.
*/
@Aspect
@Component
public class EnableShardRouteAnnotation {
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
private static boolean notSupportParameterNameDiscoverer = false;
private Map<Method, InnerBean> expressionCache = new HashMap<Method, InnerBean>();
@Around("@annotation(shardRoute)")
public Object around(ProceedingJoinPoint joinPoint, ShardRoute shardRoute) throws Throwable {
try {
//
if (shardRoute.value() == ContextPropagation.SUB_CONTEXT) {
ShardRouteContext.pushSubContext();
} else {
ShardRouteContext.clear();
}
if (shardRoute.scName() != null && shardRoute.scName().length() > 0 //
&& shardRoute.sdValue() != null && shardRoute.sdValue().length() > 0) {// 禁止对系统变量路由
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
InnerBean innerBean = expressionCache.get(method);
Object[] args = joinPoint.getArgs();
Object val = null;
if (innerBean == null) {
synchronized (this) {
innerBean = expressionCache.get(method);
if (innerBean == null) {
ExpressionParser parser = new SpelExpressionParser();
Expression expression0 = null;
String sdValue = shardRoute.sdValue();
sdValue = DDRStringUtils.trim(sdValue);
if (sdValue != null) {
expression0 = parser.parseExpression(sdValue, PARSER_CONTEXT);
}
String[] paramNames = getParameterNames(method);
val = calculate(expression0, paramNames, args);
InnerBean innerBean1 = new InnerBean(paramNames, expression0);
innerBean1.getExpression();//
expressionCache.put(method, innerBean1);
} else {
val = calculate(innerBean.getExpression(), innerBean.getParameterNames(), args);
}
}
} else {
val = calculate(innerBean.getExpression(), innerBean.getParameterNames(), args);
}
ShardRouteContext.setDefaultRouteInfo(shardRoute.scName(), val);
} else {
if ((shardRoute.scName() == null || shardRoute.scName().length() == 0)
&& (shardRoute.sdValue() == null || shardRoute.sdValue().length() == 0)) {
// ok
} else {
throw new IllegalArgumentException(
"scName and sdValue should either both have a non-empty value or both have a empty value");
}
}
return joinPoint.proceed(joinPoint.getArgs());
} finally {
if (shardRoute.value() == ContextPropagation.SUB_CONTEXT) {
ShardRouteContext.popSubContext();
} else {
ShardRouteContext.clear();
}
}
}
/**
* DefaultParameterNameDiscoverer is supported spring 4.0
* @return
*/
private String[] getParameterNames(Method method) {
if (notSupportParameterNameDiscoverer) {
return null;
} else {
try {
return parameterNameDiscoverer.getParameterNames(method);
} catch (NoClassDefFoundError e) {
notSupportParameterNameDiscoverer = true;
return null;
}
}
}
private Object calculate(Expression expression, String[] parameterNames, Object[] args) {
if (expression == null) {
return null;
}
EvaluationContext context = new StandardEvaluationContext();
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (parameterNames != null && parameterNames.length > i) {
context.setVariable(parameterNames[i], args[i]);
}
context.setVariable("$" + i, args[i]);
}
}
return expression.getValue(context);
}
private class InnerBean {
public InnerBean(String[] parameterNames, Expression expression) {
this.parameterNames = parameterNames;
this.expression = expression;
}
private String[] parameterNames;
private Expression expression;
public String[] getParameterNames() {
return parameterNames;
}
public void setParameterNames(String[] parameterNames) {
this.parameterNames = parameterNames;
}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
}
private static ParserContext PARSER_CONTEXT = new ParserContext() {
public boolean isTemplate() {
return false;
}
public String getExpressionPrefix() {
return null;
}
public String getExpressionSuffix() {
return null;
}
};
}
| update
| ddal-spring-context/src/main/java/org/hellojavaer/ddal/spring/context/scan/EnableShardRouteAnnotation.java | update | <ide><path>dal-spring-context/src/main/java/org/hellojavaer/ddal/spring/context/scan/EnableShardRouteAnnotation.java
<ide> @Component
<ide> public class EnableShardRouteAnnotation {
<ide>
<del> private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
<add> private ParameterNameDiscoverer parameterNameDiscoverer = null;
<ide> private static boolean notSupportParameterNameDiscoverer = false;
<ide>
<ide> private Map<Method, InnerBean> expressionCache = new HashMap<Method, InnerBean>();
<ide> ExpressionParser parser = new SpelExpressionParser();
<ide> Expression expression0 = null;
<ide> String sdValue = shardRoute.sdValue();
<del> sdValue = DDRStringUtils.trim(sdValue);
<add> sdValue = DDRStringUtils.trimToNull(sdValue);
<ide> if (sdValue != null) {
<ide> expression0 = parser.parseExpression(sdValue, PARSER_CONTEXT);
<ide> }
<ide> return null;
<ide> } else {
<ide> try {
<add> parameterNameDiscoverer = new DefaultParameterNameDiscoverer();// only support from spring4
<ide> return parameterNameDiscoverer.getParameterNames(method);
<ide> } catch (NoClassDefFoundError e) {
<ide> notSupportParameterNameDiscoverer = true; |
|
JavaScript | apache-2.0 | 69e0778af5f9929dd21ed84b4f9a556adff11fab | 0 | CenterForOpenScience/osf.io,emetsger/osf.io,GageGaskins/osf.io,lyndsysimon/osf.io,hmoco/osf.io,barbour-em/osf.io,barbour-em/osf.io,samanehsan/osf.io,jolene-esposito/osf.io,petermalcolm/osf.io,barbour-em/osf.io,brianjgeiger/osf.io,dplorimer/osf,Nesiehr/osf.io,dplorimer/osf,brianjgeiger/osf.io,KAsante95/osf.io,doublebits/osf.io,doublebits/osf.io,samanehsan/osf.io,arpitar/osf.io,alexschiller/osf.io,MerlinZhang/osf.io,haoyuchen1992/osf.io,hmoco/osf.io,mluo613/osf.io,reinaH/osf.io,kushG/osf.io,MerlinZhang/osf.io,doublebits/osf.io,jnayak1/osf.io,sbt9uc/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,sloria/osf.io,ticklemepierce/osf.io,wearpants/osf.io,jeffreyliu3230/osf.io,caseyrygt/osf.io,kushG/osf.io,RomanZWang/osf.io,danielneis/osf.io,sbt9uc/osf.io,HalcyonChimera/osf.io,revanthkolli/osf.io,billyhunt/osf.io,KAsante95/osf.io,ticklemepierce/osf.io,mluo613/osf.io,abought/osf.io,laurenrevere/osf.io,mattclark/osf.io,jmcarp/osf.io,billyhunt/osf.io,zamattiac/osf.io,lamdnhan/osf.io,bdyetton/prettychart,leb2dg/osf.io,mfraezz/osf.io,jnayak1/osf.io,mluo613/osf.io,chrisseto/osf.io,bdyetton/prettychart,kch8qx/osf.io,zachjanicki/osf.io,mattclark/osf.io,laurenrevere/osf.io,jmcarp/osf.io,brandonPurvis/osf.io,brandonPurvis/osf.io,wearpants/osf.io,cslzchen/osf.io,mfraezz/osf.io,haoyuchen1992/osf.io,lamdnhan/osf.io,felliott/osf.io,binoculars/osf.io,cosenal/osf.io,amyshi188/osf.io,chennan47/osf.io,felliott/osf.io,kushG/osf.io,acshi/osf.io,GaryKriebel/osf.io,RomanZWang/osf.io,danielneis/osf.io,KAsante95/osf.io,zkraime/osf.io,felliott/osf.io,alexschiller/osf.io,samanehsan/osf.io,jinluyuan/osf.io,cwisecarver/osf.io,zkraime/osf.io,RomanZWang/osf.io,reinaH/osf.io,adlius/osf.io,abought/osf.io,acshi/osf.io,GaryKriebel/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,leb2dg/osf.io,aaxelb/osf.io,SSJohns/osf.io,haoyuchen1992/osf.io,petermalcolm/osf.io,himanshuo/osf.io,jinluyuan/osf.io,alexschiller/osf.io,crcresearch/osf.io,felliott/osf.io,danielneis/osf.io,leb2dg/osf.io,KAsante95/osf.io,alexschiller/osf.io,GageGaskins/osf.io,ticklemepierce/osf.io,petermalcolm/osf.io,wearpants/osf.io,jeffreyliu3230/osf.io,HarryRybacki/osf.io,rdhyee/osf.io,reinaH/osf.io,Johnetordoff/osf.io,caseyrygt/osf.io,doublebits/osf.io,caneruguz/osf.io,saradbowman/osf.io,billyhunt/osf.io,SSJohns/osf.io,HarryRybacki/osf.io,ckc6cz/osf.io,ckc6cz/osf.io,mluke93/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,GageGaskins/osf.io,billyhunt/osf.io,icereval/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,amyshi188/osf.io,binoculars/osf.io,Nesiehr/osf.io,lyndsysimon/osf.io,Johnetordoff/osf.io,Ghalko/osf.io,kwierman/osf.io,njantrania/osf.io,laurenrevere/osf.io,KAsante95/osf.io,lamdnhan/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,acshi/osf.io,GaryKriebel/osf.io,kch8qx/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,cosenal/osf.io,binoculars/osf.io,zkraime/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,revanthkolli/osf.io,cldershem/osf.io,kch8qx/osf.io,kch8qx/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,jolene-esposito/osf.io,abought/osf.io,MerlinZhang/osf.io,dplorimer/osf,billyhunt/osf.io,caseyrygt/osf.io,asanfilippo7/osf.io,revanthkolli/osf.io,bdyetton/prettychart,samchrisinger/osf.io,zachjanicki/osf.io,rdhyee/osf.io,aaxelb/osf.io,aaxelb/osf.io,baylee-d/osf.io,TomBaxter/osf.io,asanfilippo7/osf.io,mluo613/osf.io,acshi/osf.io,rdhyee/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,petermalcolm/osf.io,lyndsysimon/osf.io,fabianvf/osf.io,njantrania/osf.io,icereval/osf.io,SSJohns/osf.io,cldershem/osf.io,cldershem/osf.io,danielneis/osf.io,adlius/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,cosenal/osf.io,pattisdr/osf.io,jinluyuan/osf.io,chrisseto/osf.io,revanthkolli/osf.io,ZobairAlijan/osf.io,jinluyuan/osf.io,himanshuo/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,TomHeatwole/osf.io,saradbowman/osf.io,asanfilippo7/osf.io,ZobairAlijan/osf.io,emetsger/osf.io,emetsger/osf.io,jnayak1/osf.io,mluo613/osf.io,cslzchen/osf.io,erinspace/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,jnayak1/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,abought/osf.io,sloria/osf.io,mluke93/osf.io,sloria/osf.io,emetsger/osf.io,adlius/osf.io,monikagrabowska/osf.io,ckc6cz/osf.io,zachjanicki/osf.io,cwisecarver/osf.io,jolene-esposito/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,Nesiehr/osf.io,MerlinZhang/osf.io,jolene-esposito/osf.io,arpitar/osf.io,zamattiac/osf.io,zamattiac/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,arpitar/osf.io,adlius/osf.io,TomHeatwole/osf.io,reinaH/osf.io,mfraezz/osf.io,kwierman/osf.io,Johnetordoff/osf.io,himanshuo/osf.io,fabianvf/osf.io,caseyrygt/osf.io,caseyrollins/osf.io,icereval/osf.io,mluke93/osf.io,hmoco/osf.io,fabianvf/osf.io,njantrania/osf.io,mattclark/osf.io,kch8qx/osf.io,zachjanicki/osf.io,acshi/osf.io,erinspace/osf.io,himanshuo/osf.io,cslzchen/osf.io,amyshi188/osf.io,njantrania/osf.io,hmoco/osf.io,ckc6cz/osf.io,haoyuchen1992/osf.io,mfraezz/osf.io,lyndsysimon/osf.io,doublebits/osf.io,wearpants/osf.io,baylee-d/osf.io,aaxelb/osf.io,HarryRybacki/osf.io,jeffreyliu3230/osf.io,RomanZWang/osf.io,ZobairAlijan/osf.io,brandonPurvis/osf.io,kwierman/osf.io,jmcarp/osf.io,lamdnhan/osf.io,kwierman/osf.io,Ghalko/osf.io,caneruguz/osf.io,RomanZWang/osf.io,cslzchen/osf.io,GageGaskins/osf.io,chennan47/osf.io,bdyetton/prettychart,brandonPurvis/osf.io,chrisseto/osf.io,pattisdr/osf.io,pattisdr/osf.io,caseyrollins/osf.io,leb2dg/osf.io,arpitar/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,sbt9uc/osf.io,Ghalko/osf.io,baylee-d/osf.io,HarryRybacki/osf.io,Ghalko/osf.io,dplorimer/osf,rdhyee/osf.io,ZobairAlijan/osf.io,barbour-em/osf.io,erinspace/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,asanfilippo7/osf.io,jeffreyliu3230/osf.io,cldershem/osf.io,cosenal/osf.io,kushG/osf.io,mluke93/osf.io,zkraime/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,chennan47/osf.io | 'use strict';
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('osfHelpers');
var mathrender = require('mathrender');
var md = require('markdown').full;
var mdQuick = require('markdown').quick;
var diffTool = require('wikiDiff');
var THROTTLE = 500;
//<div id="preview" data-bind="mathjaxify">
ko.bindingHandlers.mathjaxify = {
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var vm = context.$data;
if(vm.allowMathjaxification() && vm.allowFullRender()) {
mathrender.mathjaxify('#' + element.id);
}
}
};
function ViewWidget(visible, version, viewText, rendered, contentURL, allowMathjaxification, allowFullRender, editor) {
var self = this;
self.version = version;
self.viewText = viewText; // comes from EditWidget.viewText
self.rendered = rendered;
self.visible = visible;
self.allowMathjaxification = allowMathjaxification;
self.editor = editor;
self.allowFullRender = allowFullRender;
self.renderTimeout = null;
self.displaySource = ko.observable('');
self.renderMarkdown = function(rawContent){
if(self.allowFullRender()) {
return md.render(rawContent);
} else {
return mdQuick.render(rawContent);
}
};
if (typeof self.editor !== 'undefined') {
self.editor.on('change', function () {
// Quick render
self.allowFullRender(false);
// Full render
clearTimeout(self.renderTimeout);
self.renderTimeout = setTimeout(function () {
self.allowFullRender(true);
}, THROTTLE);
});
} else {
self.allowFullRender(true);
}
self.displayText = ko.computed(function() {
var requestURL;
if (typeof self.version() !== 'undefined') {
if (self.version() === 'preview') {
self.rendered(self.renderMarkdown(self.viewText()));
self.displaySource(self.viewText());
} else {
if (self.version() === 'current') {
requestURL = contentURL;
} else {
requestURL= contentURL + self.version();
}
var request = $.ajax({
url: requestURL
});
request.done(function (resp) {
var rawContent = resp.wiki_content || '*No wiki content*';
if (resp.wiki_rendered) {
// Use pre-rendered python, if provided. Don't mathjaxify
self.allowMathjaxification(false);
if(self.visible()) {
self.rendered(resp.wiki_rendered);
}
} else {
// Render raw markdown
if(self.visible()) {
self.allowMathjaxification(true);
self.rendered(self.renderMarkdown(rawContent));
}
}
self.displaySource(rawContent);
});
}
} else {
self.displaySource('');
}
});
}
// currentText comes from ViewWidget.displayText
function CompareWidget(visible, compareVersion, currentText, rendered, contentURL) {
var self = this;
self.compareVersion = compareVersion;
self.currentText = currentText;
self.rendered = rendered;
self.visible = visible;
self.contentURL = contentURL;
self.compareSource = ko.observable('');
self.compareText = ko.computed(function() {
var requestURL;
if (self.compareVersion() === 'current') {
requestURL = self.contentURL;
} else {
requestURL= self.contentURL + self.compareVersion();
}
var request = $.ajax({
url: requestURL
});
request.done(function (resp) {
var rawText = resp.wiki_content;
self.compareSource(rawText);
});
});
self.compareOutput = ko.computed(function() {
var output = diffTool.diff(self.compareSource(), self.currentText());
self.rendered(output);
return output;
}).extend({ notify: 'always' });
}
var defaultOptions = {
editVisible: false,
viewVisible: true,
compareVisible: false,
canEdit: true,
viewVersion: 'current',
compareVersion: 'current',
urls: {
content: '',
draft: '',
page: ''
},
metadata: {}
};
function ViewModel(options){
var self = this;
// enabled?
self.editVis = ko.observable(options.editVisible);
self.viewVis = ko.observable(options.viewVisible);
self.compareVis = ko.observable(options.compareVisible);
self.compareVersion = ko.observable(options.compareVersion);
self.viewVersion = ko.observable(options.viewVersion);
self.draftURL = options.urls.draft;
self.contentURL = options.urls.content;
self.pageURL = options.urls.page;
self.editorMetadata = options.metadata;
self.canEdit = options.canEdit;
self.viewText = ko.observable('');
self.renderedView = ko.observable('');
self.renderedCompare = ko.observable('');
self.allowMathjaxification = ko.observable(true);
self.allowFullRender = ko.observable(true);
self.currentURL = ko.computed(function() {
var url = self.pageURL;
if (self.editVis()) {
url += 'edit/';
}
if (self.viewVis() && ((self.editVis() && self.compareVis()) || (self.viewVersion() !== 'current' && self.viewVersion() !== 'preview'))) {
url += 'view/';
if(self.viewVersion() !== 'current' && self.viewVersion() !== 'preview'){
url += self.viewVersion() + '/';
}
}
if (self.compareVis()) {
url += 'compare/';
if(self.compareVersion() !== 'current'){
url += self.compareVersion() + '/';
}
}
history.replaceState({}, '', url);
});
if(self.canEdit) {
self.editor = ace.edit('editor');
var ShareJSDoc = require('addons/wiki/static/ShareJSDoc.js');
self.editVM = new ShareJSDoc(self.draftURL, self.editorMetadata, self.viewText, self.editor);
}
self.viewVM = new ViewWidget(self.viewVis, self.viewVersion, self.viewText, self.renderedView, self.contentURL, self.allowMathjaxification, self.allowFullRender, self.editor);
self.compareVM = new CompareWidget(self.compareVis, self.compareVersion, self.viewVM.displaySource, self.renderedCompare, self.contentURL);
$('body').on('togglePanel', function (event, panel, display) {
// Update self.editVis, self.viewVis, or self.compareVis in viewmodel
self[panel + 'Vis'](display);
//URL needs to be a computed observable, and this should just update the panel states, which will feed URL
// Switch view to correct version
if (panel === 'edit') {
if (display) {
self.viewVersion('preview');
} else if (self.viewVersion() === 'preview') {
self.viewVersion('current');
}
}
});
}
var WikiPage = function(selector, options) {
var self = this;
self.options = $.extend({}, defaultOptions, options);
this.viewModel = new ViewModel(self.options);
$osf.applyBindings(self.viewModel, selector);
};
module.exports = WikiPage;
//self.ButtonController = {
// view.onClick = function () {
// // logic...
// $(this).trigger('editEnabled')
// };
| website/addons/wiki/static/wikiPage.js | 'use strict';
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('osfHelpers');
var mathrender = require('mathrender');
var md = require('markdown').full;
var mdQuick = require('markdown').quick;
var diffTool = require('wikiDiff');
var THROTTLE = 500;
//<div id="preview" data-bind="mathjaxify">
ko.bindingHandlers.mathjaxify = {
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var vm = context.$data;
if(vm.allowMathjaxification() && vm.allowFullRender()) {
mathrender.mathjaxify('#' + element.id);
}
}
};
function ViewWidget(visible, version, viewText, rendered, contentURL, allowMathjaxification, allowFullRender, editor) {
var self = this;
self.version = version;
self.viewText = viewText; // comes from EditWidget.viewText
self.rendered = rendered;
self.visible = visible;
self.allowMathjaxification = allowMathjaxification;
self.editor = editor;
self.allowFullRender = allowFullRender;
self.renderTimeout = null;
self.displaySource = ko.observable('');
self.renderMarkdown = function(rawContent){
if(self.allowFullRender()) {
return md.render(rawContent);
} else {
return mdQuick.render(rawContent);
}
};
if (typeof self.editor !== 'undefined') {
self.editor.on('change', function () {
// Quick render
self.allowFullRender(false);
// Full render
clearTimeout(self.renderTimeout);
self.renderTimeout = setTimeout(function () {
self.allowFullRender(true);
}, THROTTLE);
});
} else {
self.allowFullRender(true);
}
self.displayText = ko.computed(function() {
var requestURL;
if (typeof self.version() !== 'undefined') {
if (self.version() === 'preview') {
self.rendered(self.renderMarkdown(self.viewText()));
self.displaySource(self.viewText());
} else {
if (self.version() === 'current') {
requestURL = contentURL;
} else {
requestURL= contentURL + self.version();
}
var request = $.ajax({
url: requestURL
});
request.done(function (resp) {
var rawContent = resp.wiki_content || '*No wiki content*';
if (resp.wiki_rendered) {
// Use pre-rendered python, if provided. Don't mathjaxify
self.allowMathjaxification(false);
if(self.visible()) {
self.rendered(resp.wiki_rendered);
}
} else {
// Render raw markdown
if(self.visible()) {
self.allowMathjaxification(true);
self.rendered(self.renderMarkdown(rawContent));
}
}
self.displaySource(rawContent);
});
}
} else {
self.displaySource('');
}
});
}
// currentText comes from ViewWidget.displayText
function CompareWidget(visible, compareVersion, currentText, rendered, contentURL) {
var self = this;
self.compareVersion = compareVersion;
self.currentText = currentText;
self.rendered = rendered;
self.visible = visible;
self.contentURL = contentURL;
self.compareSource = ko.observable('');
self.compareText = ko.computed(function() {
var requestURL;
if (self.compareVersion() === 'current') {
requestURL = self.contentURL;
} else {
requestURL= self.contentURL + self.compareVersion();
}
var request = $.ajax({
url: requestURL
});
request.done(function (resp) {
var rawText = resp.wiki_content;
self.compareSource(rawText);
});
});
self.compareOutput = ko.computed(function() {
var output = diffTool.diff(self.compareSource(), self.currentText());
self.rendered(output);
return output;
}).extend({ notify: 'always' });
}
var defaultOptions = {
editVisible: false,
viewVisible: true,
compareVisible: false,
canEdit: true,
viewVersion: 'current',
compareVersion: 'current',
urls: {
content: '',
draft: '',
page: ''
},
metadata: {}
};
function ViewModel(options){
var self = this;
// enabled?
self.editVis = ko.observable(options.editVisible);
self.viewVis = ko.observable(options.viewVisible);
self.compareVis = ko.observable(options.compareVisible);
self.compareVersion = ko.observable(options.compareVersion);
self.viewVersion = ko.observable(options.viewVersion);
self.draftURL = options.urls.draft;
self.contentURL = options.urls.content;
self.pageURL = options.urls.page;
self.editorMetadata = options.metadata;
self.canEdit = options.canEdit;
self.viewText = ko.observable('');
self.renderedView = ko.observable('');
self.renderedCompare = ko.observable('');
self.allowMathjaxification = ko.observable(true);
self.allowFullRender = ko.observable(true);
self.currentURL = ko.computed(function() {
console.log("ping");
var url = self.pageURL;
if (self.editVis()) {
url += 'edit/';
}
if (self.viewVis() && ((self.editVis() && self.compareVis()) || (self.viewVersion() !== 'current' && self.viewVersion() !== 'preview'))) {
url += 'view/';
if(self.viewVersion() !== 'current' && self.viewVersion() !== 'preview'){
url += self.viewVersion() + '/';
}
}
if (self.compareVis()) {
url += 'compare/';
if(self.compareVersion() !== 'current'){
url += self.compareVesion() + '/';
}
}
console.log(url);
history.replaceState({}, '', url);
});
if(self.canEdit) {
self.editor = ace.edit('editor');
var ShareJSDoc = require('addons/wiki/static/ShareJSDoc.js');
self.editVM = new ShareJSDoc(self.draftURL, self.editorMetadata, self.viewText, self.editor);
}
self.viewVM = new ViewWidget(self.viewVis, self.viewVersion, self.viewText, self.renderedView, self.contentURL, self.allowMathjaxification, self.allowFullRender, self.editor);
self.compareVM = new CompareWidget(self.compareVis, self.compareVersion, self.viewVM.displaySource, self.renderedCompare, self.contentURL);
$('body').on('togglePanel', function (event, panel, display) {
// Update self.editVis, self.viewVis, or self.compareVis in viewmodel
self[panel + 'Vis'](display);
//URL needs to be a computed observable, and this should just update the panel states, which will feed URL
// Switch view to correct version
if (panel === 'edit') {
if (display) {
self.viewVersion('preview');
} else if (self.viewVersion() === 'preview') {
self.viewVersion('current');
}
}
});
}
var WikiPage = function(selector, options) {
var self = this;
self.options = $.extend({}, defaultOptions, options);
this.viewModel = new ViewModel(self.options);
$osf.applyBindings(self.viewModel, selector);
};
module.exports = WikiPage;
//self.ButtonController = {
// view.onClick = function () {
// // logic...
// $(this).trigger('editEnabled')
// };
| Fix misnamed variable to make URL computed work
| website/addons/wiki/static/wikiPage.js | Fix misnamed variable to make URL computed work | <ide><path>ebsite/addons/wiki/static/wikiPage.js
<ide> self.allowFullRender = ko.observable(true);
<ide>
<ide> self.currentURL = ko.computed(function() {
<del> console.log("ping");
<ide> var url = self.pageURL;
<ide>
<ide> if (self.editVis()) {
<ide> if (self.compareVis()) {
<ide> url += 'compare/';
<ide> if(self.compareVersion() !== 'current'){
<del> url += self.compareVesion() + '/';
<del> }
<del> }
<del> console.log(url);
<add> url += self.compareVersion() + '/';
<add> }
<add> }
<ide>
<ide> history.replaceState({}, '', url);
<ide> }); |
|
Java | mpl-2.0 | 4217a52c502f190b5b0b95e1825706f9d0e8016b | 0 | etomica/etomica,etomica/etomica,etomica/etomica | package etomica.freeenergy.npath;
import etomica.action.IAction;
import etomica.atom.*;
import etomica.box.Box;
import etomica.data.DataSourceIndependentSimple;
import etomica.data.DataTag;
import etomica.data.IData;
import etomica.data.IDataSink;
import etomica.data.meter.MeterStructureFactor;
import etomica.data.types.DataDoubleArray;
import etomica.data.types.DataFunction;
import etomica.graphics.*;
import etomica.math.numerical.ArrayReader1D;
import etomica.modifier.Modifier;
import etomica.modifier.ModifierBoolean;
import etomica.molecule.IMolecule;
import etomica.simulation.Simulation;
import etomica.space.*;
import etomica.space3d.Space3D;
import etomica.species.Species;
import etomica.species.SpeciesSpheresRotating;
import etomica.units.*;
import etomica.units.Dimension;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* This reads ATOM files from LAMMPS and creates a display of one of the
* configurations.
* <p>
* Created by andrew on 4/25/17.
*/
public class ConfigFromFileLAMMPS {
public static void main(String[] args) throws IOException {
ConfigFromFileLAMMPSParam params = new ConfigFromFileLAMMPSParam();
if (args.length == 0) {
throw new RuntimeException("Usage: ConfigFromFileLAMMPS -filename sim.atom -configNum n -crystal CRYSTAL");
}
ParseArgs.doParseArgs(params, args);
String filename = params.filename;
boolean doSfac = params.doSfac;
double cutoffS = params.cutS;
double thresholdS = params.thresholdS;
boolean GUI = params.GUI;
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
String read = "";
int numAtoms = -1;
int item = -1;
Space space = Space3D.getInstance();
Vector[] edges = space.makeVectorArray(3);
double[][] boundaryStuff = new double[3][3];
Simulation sim = new Simulation(space);
Species species = new SpeciesSpheresRotating(sim, space);
sim.addSpecies(species);
Box box = new Box(space);
sim.addBox(box);
int config = 0;
List<Vector[]> allCoords = new ArrayList<>();
Vector[] iCoords = null;
List<Vector[]> allEdges = new ArrayList<>();
List<DataFunction> sfacData = new ArrayList<>();
List<DataFunction.DataInfoFunction> sfacDataInfo = new ArrayList<>();
DataTag sfacTag = new DataTag();
ModifierConfiguration modifierConfig = new ModifierConfiguration(box, allCoords, allEdges, sfacData, sfacDataInfo, sfacTag);
while ((line = reader.readLine()) != null) {
if (line.matches("ITEM:.*")) {
read = "";
if (line.equals("ITEM: NUMBER OF ATOMS")) {
read = "numAtoms";
}
else if (line.matches("ITEM: BOX BOUNDS.*")) {
read = "boundary";
}
else if (line.matches("ITEM: ATOMS.*")) {
read = "atoms";
allEdges.add(edges);
if (config == 0) {
Boundary boundary = new BoundaryDeformablePeriodic(space, edges);
box.setBoundary(boundary);
}
iCoords = new Vector[numAtoms];
}
item = 0;
continue;
}
if (read.equals("numAtoms")) {
numAtoms = Integer.parseInt(line);
System.out.println("numAtoms: " + numAtoms);
box.setNMolecules(species, numAtoms);
} else if (read.equals("boundary")) {
String[] bits = line.split("[ \t]+");
if (bits.length == 2) {
double xlo = Double.parseDouble(bits[0]);
double xhi = Double.parseDouble(bits[1]);
edges[item].setX(item, xhi - xlo);
}
else {
for (int i = 0; i < 3; i++) {
boundaryStuff[item][i] = Double.parseDouble(bits[i]);
}
if (item == 2) {
double xy = boundaryStuff[0][2];
double xz = boundaryStuff[1][2];
double yz = boundaryStuff[2][2];
double zlo = boundaryStuff[2][0];
double zhi = boundaryStuff[2][1];
double yhi = boundaryStuff[1][1] - Math.max(0, yz);
double ylo = boundaryStuff[1][0] - Math.min(0, yz);
double offset = Math.max(Math.max(Math.max(0, xy), xz), xy + xz);
double xhi = boundaryStuff[0][1] - offset;
offset = Math.min(Math.min(Math.min(0, xy), xz), xy + xz);
double xlo = boundaryStuff[0][0] - offset;
edges[0].E(new double[]{xhi - xlo, 0, 0});
edges[1].E(new double[]{xy, yhi - ylo, 0});
edges[2].E(new double[]{xz, yz, zhi - zlo});
}
}
item++;
} else if (read.equals("atoms")) {
item++;
String[] bits = line.split("[ \t]+");
Vector p = space.makeVector();
p.E(0);
for (int i = 0; i < 3; i++) {
p.PEa1Tv1(Double.parseDouble(bits[i + 2]) - 0.5, edges[i]);
}
iCoords[item - 1] = p;
if (item == numAtoms) {
allCoords.add(iCoords);
if (doSfac) {
File sfile = new File(config + ".sfac");
if (!sfile.exists()) {
modifierConfig.setValue(config);
MeterStructureFactor meter = new MeterStructureFactor(space, box, cutoffS);
writeFile(meter, thresholdS, config);
}
}
config++;
edges = space.makeVectorArray(3);
}
}
}
if (!GUI) return;
SimulationGraphic graphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, space, sim.getController());
final DisplayBox display = new DisplayBox(sim, box, space, sim.getController());
final DisplayBoxCanvasG3DSys.OrientedSite site = new DisplayBoxCanvasG3DSys.OrientedSite(0.5, Color.WHITE, 0.5);
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[]{site});
graphic.add(display);
ColorSchemeDeviation colorScheme = new ColorSchemeDeviation(box, space);
graphic.getDisplayBox(box).setColorScheme(colorScheme);
final AtomFilterDeviation atomFilter = new AtomFilterDeviation(colorScheme);
display.setAtomFilter(atomFilter);
modifierConfig.setColorScheme(colorScheme);
DeviceSlider filterSlider = new DeviceSlider(sim.getController(), new Modifier() {
@Override
public double getValue() {
return atomFilter.getThreshold();
}
@Override
public void setValue(double newValue) {
atomFilter.setThreshold(newValue);
}
@Override
public Dimension getDimension() {
return Null.DIMENSION;
}
@Override
public String getLabel() {
return "Displacement Threshold";
}
});
filterSlider.setMinimum(0);
filterSlider.setMaximum(2);
filterSlider.setPrecision(2);
filterSlider.setNMajor(4);
filterSlider.setPostAction(new IAction() {
@Override
public void actionPerformed() {
graphic.getDisplayBox(box).repaint();
}
});
graphic.add(filterSlider);
DeviceSlider configSlider = new DeviceSlider(sim.getController(), modifierConfig);
configSlider.setMaximum(config - 1);
configSlider.setNMajor(config);
configSlider.setMinimum(0);
configSlider.setPrecision(0);
modifierConfig.setPostAction(new IAction() {
@Override
public void actionPerformed() {
graphic.getDisplayBox(box).repaint();
}
});
graphic.add(configSlider);
configSlider.setValue(0);
DisplayPlot sfacPlot = null;
IDataSink sfacPlotSink = null;
for (int i = 0; i <= config; i++) {
int xMin = (int) cutoffS + 1;
File sfile = new File(i + ".sfac");
if (sfile.exists()) {
double[][] xy = ArrayReader1D.getFromFile(i + ".sfac");
double[] x = new double[xy.length];
double[] y = new double[xy.length];
for (int j = 0; j < x.length; j++) {
x[j] = xy[j][0];
if (xMin > x[j]) xMin = (int) x[j];
y[j] = xy[j][1];
}
DataFunction data = new DataFunction(new int[]{y.length}, y);
DataDoubleArray.DataInfoDoubleArray xDataInfo = new DataDoubleArray.DataInfoDoubleArray("wave vector", new CompoundDimension(new Dimension[]{Length.DIMENSION}, new double[]{-1}), new int[]{x.length});
DataSourceIndependentSimple xDataSource = new DataSourceIndependentSimple(x, xDataInfo);
DataFunction.DataInfoFunction dataInfo = new DataFunction.DataInfoFunction("structure factor", Null.DIMENSION, xDataSource);
dataInfo.addTag(sfacTag);
if (sfacPlot == null) {
sfacPlot = new DisplayPlot();
sfacPlot.getPlot().setYLog(true);
sfacPlot.getPlot().setXRange(xMin, cutoffS);
sfacPlot.getPlot().setYRange(Math.log10(thresholdS), Math.log10(2));
sfacPlot.setLabel("structure factor");
sfacPlot.setDoLegend(false);
sfacPlotSink = sfacPlot.getDataSet().makeDataSink();
sfacPlotSink.putDataInfo(dataInfo);
sfacPlot.setDoDrawLines(new DataTag[]{sfacTag}, false);
graphic.add(sfacPlot);
modifierConfig.setSfacPlotSink(sfacPlotSink);
}
sfacData.add(data);
sfacDataInfo.add(dataInfo);
}
}
modifierConfig.setValue(0);
DeviceToggleRadioButtons deviceDoPrevious = new DeviceToggleRadioButtons(new ModifierBoolean() {
@Override
public void setBoolean(boolean b) {
modifierConfig.setDoPrevious(b);
}
@Override
public boolean getBoolean() {
return modifierConfig.getDoPrevious();
}
},"Deviation from","previous","original");
graphic.add(deviceDoPrevious);
DeviceCheckBox deviceShowDirection = new DeviceCheckBox("Show direction", new ModifierBoolean() {
boolean sitesShown = true;
@Override
public boolean getBoolean() {
return sitesShown;
}
@Override
public void setBoolean(boolean b) {
if (b == sitesShown) return;
if (b) {
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[]{site});
} else {
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[0]);
}
sitesShown = b;
display.repaint();
}
});
graphic.add(deviceShowDirection);
graphic.makeAndDisplayFrame();
}
public static void writeFile(MeterStructureFactor meter, double threshold, int config) throws IOException {
IData data = meter.getData();
IData xData = ((DataFunction.DataInfoFunction) meter.getDataInfo()).getXDataSource().getIndependentData(0);
FileWriter fw = new FileWriter(config + ".sfac");
for (int i = 0; i < data.getLength(); i++) {
double sfac = data.getValue(i);
if (sfac > threshold) fw.write(xData.getValue(i) + " " + sfac + "\n");
}
fw.close();
}
public static class ConfigFromFileLAMMPSParam extends ParameterBase {
public String filename;
public boolean doSfac = false;
public double cutS = 8;
public double thresholdS = 0.001;
public boolean GUI = true;
}
public static class ColorSchemeDeviation extends ColorScheme implements ColorSchemeCollective {
protected final Vector[] scaledCoords0, rescaledCoords0;
protected final Box box;
protected final Vector dr;
protected final Color[] colors;
protected final Vector[] edges;
protected final Tensor t;
protected final Vector r0;
protected double rNbr;
public ColorSchemeDeviation(Box box, Space space) {
this.box = box;
dr = space.makeVector();
colors = new Color[511];
for (int i = 0; i < 256; i++) {
colors[i] = new Color(0, i, 255 - i);
}
for (int i = 1; i < 256; i++) {
colors[255 + i] = new Color(i, 255 - i, 0);
}
edges = space.makeVectorArray(3);
for (int i = 0; i < 3; i++) {
edges[i] = box.getBoundary().getEdgeVector(i);
}
int numAtoms = box.getLeafList().getAtomCount();
t = space.makeTensor();
scaledCoords0 = space.makeVectorArray(numAtoms);
rescaledCoords0 = space.makeVectorArray(numAtoms);
r0 = space.makeVector();
}
public void setLattice(Vector[] latticeEdges, Vector[] latticeCoords) {
t.E(latticeEdges);
t.invert();
for (int i = 0; i < scaledCoords0.length; i++) {
scaledCoords0[i].E(latticeCoords[i]);
t.transform(scaledCoords0[i]);
}
}
@Override
public void colorAllAtoms() {
IAtomList atoms = box.getLeafList();
double vol = box.getBoundary().volume() / atoms.getAtomCount();
double a = Math.cbrt(vol);
rNbr = a * Math.sqrt(3) / 2;
BoundaryDeformablePeriodic boundary = (BoundaryDeformablePeriodic) box.getBoundary();
for (int i = 0; i < 3; i++) {
edges[i] = boundary.getEdgeVector(i);
}
t.E(edges);
for (int i = 0; i < atoms.getAtomCount(); i++) {
r0.E(scaledCoords0[i]);
t.transform(r0);
rescaledCoords0[i].E(r0);
dr.Ev1Mv2(atoms.getAtom(i).getPosition(), r0);
boundary.nearestImage(dr);
double r2 = dr.squared();
}
}
public Vector getDisplacement(IAtom a) {
dr.Ev1Mv2(a.getPosition(), rescaledCoords0[a.getLeafIndex()]);
box.getBoundary().nearestImage(dr);
return dr;
}
public double getRelativeDisplacement(IAtom a) {
return Math.sqrt(getDisplacement(a).squared()) / rNbr;
}
@Override
public Color getAtomColor(IAtom a) {
double s = getRelativeDisplacement(a);
if (s >= 2) return colors[510];
int i = (int) (510.9999 * s / 2);
return colors[i];
}
}
public static class ModifierConfiguration implements Modifier {
protected final List<Vector[]> allCoords;
protected final List<Vector[]> allEdges;
protected final List<DataFunction> sfacData;
protected final List<DataFunction.DataInfoFunction> sfacDataInfo;
protected final DataFunction.DataInfoFunction emptySfacDataInfo;
protected final DataFunction emptySfacData;
protected int configIndex = -1;
protected Box box;
protected IDataSink sfacPlotSink;
protected ColorSchemeDeviation colorScheme;
protected boolean doPrevious;
protected IAction postAction;
public ModifierConfiguration(Box box, List<Vector[]> allCoords, List<Vector[]> allEdges, List<DataFunction> sfacData, List<DataFunction.DataInfoFunction> sfacDataInfo, DataTag sfacTag) {
this.box = box;
this.allCoords = allCoords;
this.allEdges = allEdges;
this.sfacData = sfacData;
this.sfacDataInfo = sfacDataInfo;
this.emptySfacData = new DataFunction(new int[]{0}, new double[0]);
DataDoubleArray.DataInfoDoubleArray xDataInfo = new DataDoubleArray.DataInfoDoubleArray("wave vector", new CompoundDimension(new Dimension[]{Length.DIMENSION}, new double[]{-1}), new int[]{0});
double[] x = new double[0];
DataSourceIndependentSimple xDataSource = new DataSourceIndependentSimple(x, xDataInfo);
emptySfacDataInfo = new DataFunction.DataInfoFunction("structure factor", Null.DIMENSION, xDataSource);
emptySfacDataInfo.addTag(sfacTag);
}
public void setPostAction(IAction postAction) {
this.postAction = postAction;
}
public boolean getDoPrevious() {
return doPrevious;
}
public void setDoPrevious(boolean doPrevious) {
if (this.doPrevious == doPrevious) return;
this.doPrevious = doPrevious;
int foo = configIndex;
configIndex = -1;
setValue(foo);
}
public void setColorScheme(ColorSchemeDeviation colorScheme) {
this.colorScheme = colorScheme;
}
public void setSfacPlotSink(IDataSink sfacPlotSink) {
this.sfacPlotSink = sfacPlotSink;
}
@Override
public double getValue() {
return configIndex;
}
@Override
public void setValue(double newValue) {
int nv = (int) Math.round(newValue);
if (nv == configIndex) return;
configIndex = nv;
for (int i = 0; i < 3; i++) {
((BoundaryDeformablePeriodic) box.getBoundary()).setEdgeVector(i, allEdges.get(configIndex)[i]);
}
IAtomList atoms = box.getLeafList();
Vector[] myCoords = allCoords.get(configIndex);
for (int i = 0; i < atoms.getAtomCount(); i++) {
IAtom a = atoms.getAtom(i);
a.getPosition().E(myCoords[i]);
if (colorScheme != null) {
Vector orientation = colorScheme.getDisplacement(a);
orientation.normalize();
((IAtomOriented) a).getOrientation().setDirection(orientation);
}
}
if (colorScheme != null) {
if (doPrevious && configIndex > 0) {
colorScheme.setLattice(allEdges.get(configIndex - 1), allCoords.get(configIndex - 1));
} else {
colorScheme.setLattice(allEdges.get(0), allCoords.get(0));
}
}
if (sfacPlotSink != null) {
if (configIndex < sfacData.size()) {
sfacPlotSink.putDataInfo(sfacDataInfo.get(configIndex));
sfacPlotSink.putData(sfacData.get(configIndex));
} else {
sfacPlotSink.putDataInfo(emptySfacDataInfo);
sfacPlotSink.putData(emptySfacData);
}
}
if (postAction!= null) {
postAction.actionPerformed();
}
}
@Override
public Dimension getDimension() {
return Quantity.DIMENSION;
}
@Override
public String getLabel() {
return "Configuration";
}
}
public static class AtomFilterDeviation implements AtomFilter {
protected final ColorSchemeDeviation colorScheme;
protected double threshold = 0;
public AtomFilterDeviation(ColorSchemeDeviation colorScheme) {
this.colorScheme = colorScheme;
}
public double getThreshold() {
return threshold;
}
public void setThreshold(double threshold) {
this.threshold = threshold;
}
@Override
public boolean accept(IAtom a) {
double x = colorScheme.getRelativeDisplacement(a);
return x >= threshold;
}
@Override
public boolean accept(IMolecule mole) {
return false;
}
}
}
| etomica-apps/src/main/java/etomica/freeenergy/npath/ConfigFromFileLAMMPS.java | package etomica.freeenergy.npath;
import etomica.action.IAction;
import etomica.atom.*;
import etomica.box.Box;
import etomica.data.DataSourceIndependentSimple;
import etomica.data.DataTag;
import etomica.data.IData;
import etomica.data.IDataSink;
import etomica.data.meter.MeterStructureFactor;
import etomica.data.types.DataDoubleArray;
import etomica.data.types.DataFunction;
import etomica.graphics.*;
import etomica.math.numerical.ArrayReader1D;
import etomica.modifier.Modifier;
import etomica.modifier.ModifierBoolean;
import etomica.molecule.IMolecule;
import etomica.simulation.Simulation;
import etomica.space.*;
import etomica.space3d.Space3D;
import etomica.species.Species;
import etomica.species.SpeciesSpheresRotating;
import etomica.units.*;
import etomica.units.Dimension;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* This reads ATOM files from LAMMPS and creates a display of one of the
* configurations.
* <p>
* Created by andrew on 4/25/17.
*/
public class ConfigFromFileLAMMPS {
public static void main(String[] args) throws IOException {
ConfigFromFileLAMMPSParam params = new ConfigFromFileLAMMPSParam();
if (args.length == 0) {
throw new RuntimeException("Usage: ConfigFromFileLAMMPS -filename sim.atom -configNum n -crystal CRYSTAL");
}
ParseArgs.doParseArgs(params, args);
String filename = params.filename;
boolean doSfac = params.doSfac;
double cutoffS = params.cutS;
double thresholdS = params.thresholdS;
boolean GUI = params.GUI;
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
String read = "";
int numAtoms = -1;
int item = -1;
Space space = Space3D.getInstance();
Vector[] edges = space.makeVectorArray(3);
double[][] boundaryStuff = new double[3][3];
Simulation sim = new Simulation(space);
Species species = new SpeciesSpheresRotating(sim, space);
sim.addSpecies(species);
Box box = new Box(space);
sim.addBox(box);
int config = 0;
List<Vector[]> allCoords = new ArrayList<>();
Vector[] iCoords = null;
List<Vector[]> allEdges = new ArrayList<>();
List<DataFunction> sfacData = new ArrayList<>();
List<DataFunction.DataInfoFunction> sfacDataInfo = new ArrayList<>();
DataTag sfacTag = new DataTag();
ModifierConfiguration modifierConfig = new ModifierConfiguration(box, allCoords, allEdges, sfacData, sfacDataInfo, sfacTag);
while ((line = reader.readLine()) != null) {
if (line.matches("ITEM:.*")) {
read = "";
if (line.equals("ITEM: NUMBER OF ATOMS")) {
read = "numAtoms";
}
else if (line.matches("ITEM: BOX BOUNDS.*")) {
read = "boundary";
}
else if (line.matches("ITEM: ATOMS.*")) {
read = "atoms";
allEdges.add(edges);
if (config == 0) {
Boundary boundary = new BoundaryDeformablePeriodic(space, edges);
box.setBoundary(boundary);
}
iCoords = new Vector[numAtoms];
}
item = 0;
continue;
}
if (read.equals("numAtoms")) {
numAtoms = Integer.parseInt(line);
System.out.println("numAtoms: " + numAtoms);
box.setNMolecules(species, numAtoms);
} else if (read.equals("boundary")) {
String[] bits = line.split("[ \t]+");
if (bits.length == 2) {
double xlo = Double.parseDouble(bits[0]);
double xhi = Double.parseDouble(bits[1]);
edges[item].setX(item, xhi - xlo);
}
else {
for (int i = 0; i < 3; i++) {
boundaryStuff[item][i] = Double.parseDouble(bits[i]);
}
if (item == 2) {
double xy = boundaryStuff[0][2];
double xz = boundaryStuff[1][2];
double yz = boundaryStuff[2][2];
double zlo = boundaryStuff[2][0];
double zhi = boundaryStuff[2][1];
double yhi = boundaryStuff[1][1] - Math.max(0, yz);
double ylo = boundaryStuff[1][0] - Math.min(0, yz);
double offset = Math.max(Math.max(Math.max(0, xy), xz), xy + xz);
double xhi = boundaryStuff[0][1] - offset;
offset = Math.min(Math.min(Math.min(0, xy), xz), xy + xz);
double xlo = boundaryStuff[0][0] - offset;
edges[0].E(new double[]{xhi - xlo, 0, 0});
edges[1].E(new double[]{xy, yhi - ylo, 0});
edges[2].E(new double[]{xz, yz, zhi - zlo});
}
}
item++;
} else if (read.equals("atoms")) {
item++;
String[] bits = line.split("[ \t]+");
Vector p = space.makeVector();
p.E(0);
for (int i = 0; i < 3; i++) {
p.PEa1Tv1(Double.parseDouble(bits[i + 2]) - 0.5, edges[i]);
}
iCoords[item - 1] = p;
if (item == numAtoms) {
allCoords.add(iCoords);
if (doSfac) {
File sfile = new File(config + ".sfac");
if (!sfile.exists()) {
modifierConfig.setValue(config);
MeterStructureFactor meter = new MeterStructureFactor(space, box, cutoffS);
writeFile(meter, thresholdS, config);
}
}
config++;
edges = space.makeVectorArray(3);
}
}
}
if (!GUI) return;
SimulationGraphic graphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, space, sim.getController());
final DisplayBox display = new DisplayBox(sim, box, space, sim.getController());
final DisplayBoxCanvasG3DSys.OrientedSite site = new DisplayBoxCanvasG3DSys.OrientedSite(0.5, Color.WHITE, 0.5);
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[]{site});
graphic.add(display);
ColorSchemeDeviation colorScheme = new ColorSchemeDeviation(box, space);
graphic.getDisplayBox(box).setColorScheme(colorScheme);
final AtomFilterDeviation atomFilter = new AtomFilterDeviation(colorScheme);
display.setAtomFilter(atomFilter);
modifierConfig.setColorScheme(colorScheme);
DeviceSlider filterSlider = new DeviceSlider(sim.getController(), new Modifier() {
@Override
public double getValue() {
return atomFilter.getThreshold();
}
@Override
public void setValue(double newValue) {
atomFilter.setThreshold(newValue);
}
@Override
public Dimension getDimension() {
return Null.DIMENSION;
}
@Override
public String getLabel() {
return "Displacement Threshold";
}
});
filterSlider.setMinimum(0);
filterSlider.setMaximum(2);
filterSlider.setPrecision(2);
filterSlider.setNMajor(4);
filterSlider.setPostAction(new IAction() {
@Override
public void actionPerformed() {
graphic.getDisplayBox(box).repaint();
}
});
graphic.add(filterSlider);
DeviceSlider configSlider = new DeviceSlider(sim.getController(), modifierConfig);
configSlider.setMaximum(config - 1);
configSlider.setNMajor(config);
configSlider.setMinimum(0);
configSlider.setPrecision(0);
modifierConfig.setPostAction(new IAction() {
@Override
public void actionPerformed() {
graphic.getDisplayBox(box).repaint();
}
});
graphic.add(configSlider);
configSlider.setValue(0);
DisplayPlot sfacPlot = null;
IDataSink sfacPlotSink = null;
for (int i = 0; i <= config; i++) {
int xMin = (int) cutoffS + 1;
File sfile = new File(i + ".sfac");
if (sfile.exists()) {
double[][] xy = ArrayReader1D.getFromFile(i + ".sfac");
double[] x = new double[xy.length];
double[] y = new double[xy.length];
for (int j = 0; j < x.length; j++) {
x[j] = xy[j][0];
if (xMin > x[j]) xMin = (int) x[j];
y[j] = xy[j][1];
}
DataFunction data = new DataFunction(new int[]{y.length}, y);
DataDoubleArray.DataInfoDoubleArray xDataInfo = new DataDoubleArray.DataInfoDoubleArray("wave vector", new CompoundDimension(new Dimension[]{Length.DIMENSION}, new double[]{-1}), new int[]{x.length});
DataSourceIndependentSimple xDataSource = new DataSourceIndependentSimple(x, xDataInfo);
DataFunction.DataInfoFunction dataInfo = new DataFunction.DataInfoFunction("structure factor", Null.DIMENSION, xDataSource);
dataInfo.addTag(sfacTag);
if (sfacPlot == null) {
sfacPlot = new DisplayPlot();
sfacPlot.getPlot().setYLog(true);
sfacPlot.getPlot().setXRange(xMin, cutoffS);
sfacPlot.getPlot().setYRange(Math.log10(thresholdS), Math.log10(2));
sfacPlot.setLabel("structure factor");
sfacPlot.setDoLegend(false);
sfacPlotSink = sfacPlot.getDataSet().makeDataSink();
sfacPlotSink.putDataInfo(dataInfo);
sfacPlot.setDoDrawLines(new DataTag[]{sfacTag}, false);
graphic.add(sfacPlot);
modifierConfig.setSfacPlotSink(sfacPlotSink);
}
sfacData.add(data);
sfacDataInfo.add(dataInfo);
}
}
modifierConfig.setValue(0);
DeviceToggleRadioButtons deviceDoPrevious = new DeviceToggleRadioButtons(new ModifierBoolean() {
@Override
public void setBoolean(boolean b) {
modifierConfig.setDoPrevious(b);
}
@Override
public boolean getBoolean() {
return modifierConfig.getDoPrevious();
}
},"Deviation from","previous","original");
graphic.add(deviceDoPrevious);
DeviceCheckBox deviceShowDirection = new DeviceCheckBox("Show direction", new ModifierBoolean() {
boolean sitesShown = true;
@Override
public boolean getBoolean() {
return sitesShown;
}
@Override
public void setBoolean(boolean b) {
if (b == sitesShown) return;
if (b) {
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[]{site});
} else {
((DisplayBoxCanvasG3DSys) display.canvas).setOrientationSites((AtomTypeOriented) species.getAtomType(0), new DisplayBoxCanvasG3DSys.OrientedSite[0]);
}
sitesShown = b;
display.repaint();
}
});
graphic.add(deviceShowDirection);
graphic.makeAndDisplayFrame();
}
public static void writeFile(MeterStructureFactor meter, double threshold, int config) throws IOException {
IData data = meter.getData();
IData xData = ((DataFunction.DataInfoFunction) meter.getDataInfo()).getXDataSource().getIndependentData(0);
FileWriter fw = new FileWriter(config + ".sfac");
for (int i = 0; i < data.getLength(); i++) {
double sfac = data.getValue(i);
if (sfac > threshold) fw.write(xData.getValue(i) + " " + sfac + "\n");
}
fw.close();
}
public static class ConfigFromFileLAMMPSParam extends ParameterBase {
public String filename;
public boolean doSfac = false;
public double cutS = 8;
public double thresholdS = 0.001;
public boolean GUI = true;
}
public static class ColorSchemeDeviation extends ColorScheme implements ColorSchemeCollective {
protected final Vector[] scaledCoords0, rescaledCoords0;
protected final Box box;
protected final Vector dr;
protected final Color[] colors;
protected final Vector[] edges;
protected final Tensor t;
protected final Vector r0;
protected double rNbr;
public ColorSchemeDeviation(Box box, Space space) {
this.box = box;
dr = space.makeVector();
colors = new Color[511];
for (int i = 0; i < 256; i++) {
colors[i] = new Color(0, i, 255 - i);
}
for (int i = 1; i < 256; i++) {
colors[255 + i] = new Color(i, 255 - i, 0);
}
edges = space.makeVectorArray(3);
for (int i = 0; i < 3; i++) {
edges[i] = box.getBoundary().getEdgeVector(i);
}
int numAtoms = box.getLeafList().getAtomCount();
t = space.makeTensor();
scaledCoords0 = space.makeVectorArray(numAtoms);
rescaledCoords0 = space.makeVectorArray(numAtoms);
r0 = space.makeVector();
}
public void setLattice(Vector[] latticeEdges, Vector[] latticeCoords) {
t.E(latticeEdges);
t.invert();
for (int i = 0; i < scaledCoords0.length; i++) {
scaledCoords0[i].E(latticeCoords[i]);
t.transform(scaledCoords0[i]);
}
}
@Override
public void colorAllAtoms() {
IAtomList atoms = box.getLeafList();
double vol = box.getBoundary().volume() / atoms.getAtomCount();
double a = Math.cbrt(vol);
rNbr = a * Math.sqrt(3) / 2;
BoundaryDeformablePeriodic boundary = (BoundaryDeformablePeriodic) box.getBoundary();
for (int i = 0; i < 3; i++) {
edges[i] = boundary.getEdgeVector(i);
}
t.E(edges);
for (int i = 0; i < atoms.getAtomCount(); i++) {
r0.E(scaledCoords0[i]);
t.transform(r0);
rescaledCoords0[i].E(r0);
dr.Ev1Mv2(atoms.getAtom(i).getPosition(), r0);
boundary.nearestImage(dr);
double r2 = dr.squared();
}
}
public Vector getDisplacement(IAtom a) {
dr.Ev1Mv2(a.getPosition(), rescaledCoords0[a.getLeafIndex()]);
box.getBoundary().nearestImage(dr);
return dr;
}
public double getRelativeDisplacement(IAtom a) {
return Math.sqrt(getDisplacement(a).squared()) / rNbr;
}
@Override
public Color getAtomColor(IAtom a) {
double s = getRelativeDisplacement(a);
if (s >= 2) return colors[510];
int i = (int) (510.9999 * s / 2);
return colors[i];
}
}
public static class ModifierConfiguration implements Modifier {
protected final List<Vector[]> allCoords;
protected final List<Vector[]> allEdges;
protected final List<DataFunction> sfacData;
protected final List<DataFunction.DataInfoFunction> sfacDataInfo;
protected final DataFunction.DataInfoFunction emptySfacDataInfo;
protected final DataFunction emptySfacData;
protected int configIndex = -1;
protected Box box;
protected IDataSink sfacPlotSink;
protected ColorSchemeDeviation colorScheme;
protected boolean doPrevious;
protected IAction postAction;
public ModifierConfiguration(Box box, List<Vector[]> allCoords, List<Vector[]> allEdges, List<DataFunction> sfacData, List<DataFunction.DataInfoFunction> sfacDataInfo, DataTag sfacTag) {
this.box = box;
this.allCoords = allCoords;
this.allEdges = allEdges;
this.sfacData = sfacData;
this.sfacDataInfo = sfacDataInfo;
this.emptySfacData = new DataFunction(new int[]{0}, new double[0]);
DataDoubleArray.DataInfoDoubleArray xDataInfo = new DataDoubleArray.DataInfoDoubleArray("wave vector", new CompoundDimension(new Dimension[]{Length.DIMENSION}, new double[]{-1}), new int[]{0});
double[] x = new double[0];
DataSourceIndependentSimple xDataSource = new DataSourceIndependentSimple(x, xDataInfo);
emptySfacDataInfo = new DataFunction.DataInfoFunction("structure factor", Null.DIMENSION, xDataSource);
emptySfacDataInfo.addTag(sfacTag);
}
public void setPostAction(IAction postAction) {
this.postAction = postAction;
}
public boolean getDoPrevious() {
return doPrevious;
}
public void setDoPrevious(boolean doPrevious) {
if (this.doPrevious == doPrevious) return;
this.doPrevious = doPrevious;
int foo = configIndex;
configIndex = -1;
setValue(foo);
}
public void setColorScheme(ColorSchemeDeviation colorScheme) {
this.colorScheme = colorScheme;
}
public void setSfacPlotSink(IDataSink sfacPlotSink) {
this.sfacPlotSink = sfacPlotSink;
}
@Override
public double getValue() {
return configIndex;
}
@Override
public void setValue(double newValue) {
int nv = (int) Math.round(newValue);
if (nv == configIndex) return;
configIndex = nv;
for (int i = 0; i < 3; i++) {
((BoundaryDeformablePeriodic) box.getBoundary()).setEdgeVector(i, allEdges.get(configIndex)[i]);
}
IAtomList atoms = box.getLeafList();
Vector[] myCoords = allCoords.get(configIndex);
for (int i = 0; i < atoms.getAtomCount(); i++) {
IAtom a = atoms.getAtom(i);
a.getPosition().E(myCoords[i]);
Vector orientation = colorScheme.getDisplacement(a);
orientation.normalize();
((IAtomOriented) a).getOrientation().setDirection(orientation);
}
if (doPrevious && configIndex>0) {
colorScheme.setLattice(allEdges.get(configIndex-1), allCoords.get(configIndex-1));
}
else {
colorScheme.setLattice(allEdges.get(0), allCoords.get(0));
}
if (sfacPlotSink != null) {
if (configIndex < sfacData.size()) {
sfacPlotSink.putDataInfo(sfacDataInfo.get(configIndex));
sfacPlotSink.putData(sfacData.get(configIndex));
} else {
sfacPlotSink.putDataInfo(emptySfacDataInfo);
sfacPlotSink.putData(emptySfacData);
}
}
if (postAction!= null) {
postAction.actionPerformed();
}
}
@Override
public Dimension getDimension() {
return Quantity.DIMENSION;
}
@Override
public String getLabel() {
return "Configuration";
}
}
public static class AtomFilterDeviation implements AtomFilter {
protected final ColorSchemeDeviation colorScheme;
protected double threshold = 0;
public AtomFilterDeviation(ColorSchemeDeviation colorScheme) {
this.colorScheme = colorScheme;
}
public double getThreshold() {
return threshold;
}
public void setThreshold(double threshold) {
this.threshold = threshold;
}
@Override
public boolean accept(IAtom a) {
double x = colorScheme.getRelativeDisplacement(a);
return x >= threshold;
}
@Override
public boolean accept(IMolecule mole) {
return false;
}
}
}
| config modifier gets used even without a GUI, so handle null colorScheme
| etomica-apps/src/main/java/etomica/freeenergy/npath/ConfigFromFileLAMMPS.java | config modifier gets used even without a GUI, so handle null colorScheme | <ide><path>tomica-apps/src/main/java/etomica/freeenergy/npath/ConfigFromFileLAMMPS.java
<ide> for (int i = 0; i < atoms.getAtomCount(); i++) {
<ide> IAtom a = atoms.getAtom(i);
<ide> a.getPosition().E(myCoords[i]);
<del> Vector orientation = colorScheme.getDisplacement(a);
<del> orientation.normalize();
<del> ((IAtomOriented) a).getOrientation().setDirection(orientation);
<del> }
<del> if (doPrevious && configIndex>0) {
<del> colorScheme.setLattice(allEdges.get(configIndex-1), allCoords.get(configIndex-1));
<del> }
<del> else {
<del> colorScheme.setLattice(allEdges.get(0), allCoords.get(0));
<add> if (colorScheme != null) {
<add> Vector orientation = colorScheme.getDisplacement(a);
<add> orientation.normalize();
<add> ((IAtomOriented) a).getOrientation().setDirection(orientation);
<add> }
<add> }
<add> if (colorScheme != null) {
<add> if (doPrevious && configIndex > 0) {
<add> colorScheme.setLattice(allEdges.get(configIndex - 1), allCoords.get(configIndex - 1));
<add> } else {
<add> colorScheme.setLattice(allEdges.get(0), allCoords.get(0));
<add> }
<ide> }
<ide>
<ide> if (sfacPlotSink != null) { |
|
Java | mit | 0392d1c5358ef2a96a7373e0e873d5e00a7abdff | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.application.readonly.populator;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings;
import org.innovateuk.ifs.application.readonly.viewmodel.GenericQuestionReadOnlyViewModel;
import org.innovateuk.ifs.application.resource.FormInputResponseResource;
import org.innovateuk.ifs.assessment.resource.AssessorFormInputResponseResource;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.resource.MultipleChoiceOptionResource;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.question.resource.QuestionSetupType;
import org.innovateuk.ifs.user.resource.Role;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
import static org.innovateuk.ifs.form.resource.FormInputType.*;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.*;
@Component
public class GenericQuestionReadOnlyViewModelPopulator implements QuestionReadOnlyViewModelPopulator<GenericQuestionReadOnlyViewModel> {
@Override
public GenericQuestionReadOnlyViewModel populate(QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) {
Collection<FormInputResource> formInputs = data.getQuestionIdToApplicationFormInputs().get(question.getId());
Optional<FormInputResource> textInput = formInputs.stream().filter(formInput -> formInput.getType().equals(TEXTAREA)
|| formInput.getType().equals(MULTIPLE_CHOICE))
.findAny();
Optional<FormInputResource> appendix = formInputs.stream().filter(formInput -> formInput.getType().equals(FILEUPLOAD))
.findAny();
Optional<FormInputResource> templateDocument = formInputs.stream().filter(formInput -> formInput.getType().equals(TEMPLATE_DOCUMENT))
.findAny();
Optional<FormInputResponseResource> textResponse = textInput
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
String answer = null;
if (textInput.isPresent()) {
FormInputResource input = textInput.get();
if (input.getType().equals(TEXTAREA)) {
answer = textResponse.map(FormInputResponseResource::getValue).orElse(null);
} else {
answer = textResponse.map(response -> input.getMultipleChoiceOptions().stream()
.filter(multipleChoice -> multipleChoice.getId().equals(Long.getLong(response.getValue())))
.findAny()
.map(MultipleChoiceOptionResource::getText).orElse(null))
.orElse(null);
}
}
Optional<FormInputResponseResource> appendixResponse = appendix
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
Optional<FormInputResponseResource> templateDocumentResponse = templateDocument
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
Optional<AssessorFormInputResponseResource> feedback = Optional.empty();
Optional<AssessorFormInputResponseResource> score = Optional.empty();
if (settings.isIncludeAssessment()) {
Optional<Collection<AssessorFormInputResponseResource>> responses = Optional.ofNullable(data.getQuestionToAssessorResponse().get(question.getId()));
feedback = responses.flatMap(resps ->
resps.stream()
.filter(resp -> data.getFormInputIdToAssessorFormInput().get(resp.getFormInput()).getType().equals(TEXTAREA))
.findAny());
score = responses.flatMap(resps ->
resps.stream()
.filter(resp -> data.getFormInputIdToAssessorFormInput().get(resp.getFormInput()).getType().equals(ASSESSOR_SCORE))
.findAny());
}
return new GenericQuestionReadOnlyViewModel(data, question, questionName(question),
question.getName(),
answer,
appendixResponse.map(FormInputResponseResource::getFilename).orElse(null),
appendixResponse.map(response -> urlForFormInputDownload(response.getFormInput(), question, data, settings)).orElse(null),
appendixResponse.map(FormInputResponseResource::getFormInput).orElse(null),
templateDocumentResponse.map(FormInputResponseResource::getFilename).orElse(null),
templateDocumentResponse.map(response -> urlForFormInputDownload(response.getFormInput(), question, data, settings)).orElse(null),
templateDocument.map(FormInputResource::getDescription).orElse(null),
templateDocumentResponse.map(FormInputResponseResource::getFormInput).orElse(null),
feedback.map(AssessorFormInputResponseResource::getValue).orElse(null),
score.map(AssessorFormInputResponseResource::getValue).orElse(null)
);
}
private String urlForFormInputDownload(long formInputId, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) {
if (data.getApplicantProcessRole().isPresent()) {
return String.format("/application/%d/form/question/%d/forminput/%d/download", data.getApplication().getId(), question.getId(), formInputId);
} else if (data.getUser().hasRole(Role.ASSESSOR) && settings.isIncludeAssessment()) {
return String.format("/assessment/%d/application/%d/formInput/%d/download", settings.getAssessmentId(), data.getApplication().getId(), formInputId);
} else {
return String.format("/management/competition/%d/application/%d/forminput/%d/download", data.getCompetition().getId(), data.getApplication().getId(), formInputId);
}
}
private String questionName(QuestionResource question) {
return question.getQuestionSetupType() == ASSESSED_QUESTION ?
String.format("%s. %s", question.getQuestionNumber(), question.getShortName()) :
question.getShortName();
}
@Override
public Set<QuestionSetupType> questionTypes() {
return asSet(ASSESSED_QUESTION, SCOPE, PUBLIC_DESCRIPTION, PROJECT_SUMMARY);
}
}
| ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/populator/GenericQuestionReadOnlyViewModelPopulator.java | package org.innovateuk.ifs.application.readonly.populator;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings;
import org.innovateuk.ifs.application.readonly.viewmodel.GenericQuestionReadOnlyViewModel;
import org.innovateuk.ifs.application.resource.FormInputResponseResource;
import org.innovateuk.ifs.assessment.resource.AssessorFormInputResponseResource;
import org.innovateuk.ifs.commons.security.UserAuthenticationService;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.question.resource.QuestionSetupType;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.util.HttpServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
import static org.innovateuk.ifs.form.resource.FormInputType.*;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.*;
@Component
public class GenericQuestionReadOnlyViewModelPopulator implements QuestionReadOnlyViewModelPopulator<GenericQuestionReadOnlyViewModel> {
@Override
public GenericQuestionReadOnlyViewModel populate(QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) {
Collection<FormInputResource> formInputs = data.getQuestionIdToApplicationFormInputs().get(question.getId());
Optional<FormInputResource> textInput = formInputs.stream().filter(formInput -> formInput.getType().equals(TEXTAREA))
.findAny();
Optional<FormInputResource> appendix = formInputs.stream().filter(formInput -> formInput.getType().equals(FILEUPLOAD))
.findAny();
Optional<FormInputResource> templateDocument = formInputs.stream().filter(formInput -> formInput.getType().equals(TEMPLATE_DOCUMENT))
.findAny();
Optional<FormInputResponseResource> textResponse = textInput
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
Optional<FormInputResponseResource> appendixResponse = appendix
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
Optional<FormInputResponseResource> templateDocumentResponse = templateDocument
.map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
Optional<AssessorFormInputResponseResource> feedback = Optional.empty();
Optional<AssessorFormInputResponseResource> score = Optional.empty();
if (settings.isIncludeAssessment()) {
Optional<Collection<AssessorFormInputResponseResource>> responses = Optional.ofNullable(data.getQuestionToAssessorResponse().get(question.getId()));
feedback = responses.flatMap(resps ->
resps.stream()
.filter(resp -> data.getFormInputIdToAssessorFormInput().get(resp.getFormInput()).getType().equals(TEXTAREA))
.findAny());
score = responses.flatMap(resps ->
resps.stream()
.filter(resp -> data.getFormInputIdToAssessorFormInput().get(resp.getFormInput()).getType().equals(ASSESSOR_SCORE))
.findAny());
}
return new GenericQuestionReadOnlyViewModel(data, question, questionName(question),
question.getName(),
textResponse.map(FormInputResponseResource::getValue).orElse(null),
appendixResponse.map(FormInputResponseResource::getFilename).orElse(null),
appendixResponse.map(response -> urlForFormInputDownload(response.getFormInput(), question, data, settings)).orElse(null),
appendixResponse.map(FormInputResponseResource::getFormInput).orElse(null),
templateDocumentResponse.map(FormInputResponseResource::getFilename).orElse(null),
templateDocumentResponse.map(response -> urlForFormInputDownload(response.getFormInput(), question, data, settings)).orElse(null),
templateDocument.map(FormInputResource::getDescription).orElse(null),
templateDocumentResponse.map(FormInputResponseResource::getFormInput).orElse(null),
feedback.map(AssessorFormInputResponseResource::getValue).orElse(null),
score.map(AssessorFormInputResponseResource::getValue).orElse(null)
);
}
private String urlForFormInputDownload(long formInputId, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) {
if (data.getApplicantProcessRole().isPresent()) {
return String.format("/application/%d/form/question/%d/forminput/%d/download", data.getApplication().getId(), question.getId(), formInputId);
} else if (data.getUser().hasRole(Role.ASSESSOR) && settings.isIncludeAssessment()) {
return String.format("/assessment/%d/application/%d/formInput/%d/download", settings.getAssessmentId(), data.getApplication().getId(), formInputId);
} else {
return String.format("/management/competition/%d/application/%d/forminput/%d/download", data.getCompetition().getId(), data.getApplication().getId(), formInputId);
}
}
private String questionName(QuestionResource question) {
return question.getQuestionSetupType() == ASSESSED_QUESTION ?
String.format("%s. %s", question.getQuestionNumber(), question.getShortName()) :
question.getShortName();
}
@Override
public Set<QuestionSetupType> questionTypes() {
return asSet(ASSESSED_QUESTION, SCOPE, PUBLIC_DESCRIPTION, PROJECT_SUMMARY);
}
}
| fixed the read only view for generic questions
| ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/populator/GenericQuestionReadOnlyViewModelPopulator.java | fixed the read only view for generic questions | <ide><path>fs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/populator/GenericQuestionReadOnlyViewModelPopulator.java
<ide> import org.innovateuk.ifs.application.readonly.viewmodel.GenericQuestionReadOnlyViewModel;
<ide> import org.innovateuk.ifs.application.resource.FormInputResponseResource;
<ide> import org.innovateuk.ifs.assessment.resource.AssessorFormInputResponseResource;
<del>import org.innovateuk.ifs.commons.security.UserAuthenticationService;
<ide> import org.innovateuk.ifs.form.resource.FormInputResource;
<add>import org.innovateuk.ifs.form.resource.MultipleChoiceOptionResource;
<ide> import org.innovateuk.ifs.form.resource.QuestionResource;
<ide> import org.innovateuk.ifs.question.resource.QuestionSetupType;
<ide> import org.innovateuk.ifs.user.resource.Role;
<del>import org.innovateuk.ifs.util.HttpServletUtil;
<del>import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> import java.util.Collection;
<ide> @Override
<ide> public GenericQuestionReadOnlyViewModel populate(QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) {
<ide> Collection<FormInputResource> formInputs = data.getQuestionIdToApplicationFormInputs().get(question.getId());
<del> Optional<FormInputResource> textInput = formInputs.stream().filter(formInput -> formInput.getType().equals(TEXTAREA))
<add> Optional<FormInputResource> textInput = formInputs.stream().filter(formInput -> formInput.getType().equals(TEXTAREA)
<add> || formInput.getType().equals(MULTIPLE_CHOICE))
<ide> .findAny();
<ide>
<ide> Optional<FormInputResource> appendix = formInputs.stream().filter(formInput -> formInput.getType().equals(FILEUPLOAD))
<ide>
<ide> Optional<FormInputResponseResource> textResponse = textInput
<ide> .map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
<add>
<add> String answer = null;
<add> if (textInput.isPresent()) {
<add> FormInputResource input = textInput.get();
<add> if (input.getType().equals(TEXTAREA)) {
<add> answer = textResponse.map(FormInputResponseResource::getValue).orElse(null);
<add> } else {
<add> answer = textResponse.map(response -> input.getMultipleChoiceOptions().stream()
<add> .filter(multipleChoice -> multipleChoice.getId().equals(Long.getLong(response.getValue())))
<add> .findAny()
<add> .map(MultipleChoiceOptionResource::getText).orElse(null))
<add> .orElse(null);
<add> }
<add> }
<ide>
<ide> Optional<FormInputResponseResource> appendixResponse = appendix
<ide> .map(input -> data.getFormInputIdToFormInputResponses().get(input.getId()));
<ide>
<ide> return new GenericQuestionReadOnlyViewModel(data, question, questionName(question),
<ide> question.getName(),
<del> textResponse.map(FormInputResponseResource::getValue).orElse(null),
<add> answer,
<ide> appendixResponse.map(FormInputResponseResource::getFilename).orElse(null),
<ide> appendixResponse.map(response -> urlForFormInputDownload(response.getFormInput(), question, data, settings)).orElse(null),
<ide> appendixResponse.map(FormInputResponseResource::getFormInput).orElse(null), |
|
Java | agpl-3.0 | 0525f95257104125802b5a2e1e674f0a3913f1c0 | 0 | acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library 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; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionaltests;
import java.io.File;
import java.net.URL;
import junit.framework.Assert;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.task.Log4JTaskLogs;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingService;
import org.ow2.tests.FunctionalTest;
import functionaltests.executables.Logging;
/**
* @author cdelbe
*
*/
public class TestLoggers extends FunctionalTest {
private static URL jobDescriptor = TestLoggers.class
.getResource("/functionaltests/descriptors/Job_Test_Loggers.xml");
private final static int TEST_TIMEOUT = 10000;
/**
* Tests start here.
*
* @throws Throwable any exception that can be thrown during the test.
*/
@org.junit.Test
public void run() throws Throwable {
// socket loggers
LogForwardingService lfsPA = new LogForwardingService(
"org.ow2.proactive.scheduler.common.util.logforwarder.providers.ProActiveBasedForwardingProvider");
lfsPA.initialize();
LogForwardingService lfsSocket = new LogForwardingService(
"org.ow2.proactive.scheduler.common.util.logforwarder.providers.SocketBasedForwardingProvider");
lfsSocket.initialize();
JobId id1 = SchedulerTHelper.submitJob(new File(jobDescriptor.toURI()).getAbsolutePath());
JobId id2 = SchedulerTHelper.submitJob(new File(jobDescriptor.toURI()).getAbsolutePath());
//JobId id3 = SchedulerTHelper.submitJob(jobDescriptor);
Logger l1 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id1);
Logger l2 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id2);
//Logger l3 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id3);
l1.setAdditivity(false);
l1.removeAllAppenders();
l2.setAdditivity(false);
l2.removeAllAppenders();
//l3.setAdditivity(false);
//l3.removeAllAppenders();
AppenderTester test1 = new AppenderTester();
AppenderTester test2 = new AppenderTester();
//AppenderTester test3 = new AppenderTester();
l1.addAppender(test1);
l2.addAppender(test2);
//l3.addAppender(test3);
SchedulerTHelper.getSchedulerInterface().listenJobLogs(id1, lfsPA.getAppenderProvider());
SchedulerTHelper.getSchedulerInterface().listenJobLogs(id2, lfsSocket.getAppenderProvider());
//SchedulerTHelper.getUserInterface().listenLog(id3, lfsPA.getAppenderProvider());
SchedulerTHelper.waitForEventJobFinished(id1);
SchedulerTHelper.waitForEventJobFinished(id2);
//SchedulerTHelper.waitForEventJobFinished(id3);
// waiting for the end of the job is not enough ... :(
// listenLog is asynchronous, i.e. "eventually" semantic
Thread.sleep(TEST_TIMEOUT);
Assert.assertTrue(test1.receivedOnlyAwaitedEvents());
Assert.assertEquals(2, test1.getNumberOfAppendedLogs());
Assert.assertTrue(test2.receivedOnlyAwaitedEvents());
Assert.assertEquals(2, test2.getNumberOfAppendedLogs());
//Assert.assertTrue(test3.receivedOnlyAwaitedEvents());
//Assert.assertEquals(2, test3.getNumberOfAppendedLogs());
lfsPA.terminate();
lfsSocket.terminate();
SchedulerTHelper.killScheduler();
}
public class AppenderTester extends AppenderSkeleton {
private boolean allLogsAwaited = true;
private int numberOfAppendedLogs = 0;
@Override
protected void append(LoggingEvent loggingevent) {
//System.out.println(">> AppenderTester.append() : " + loggingevent.getMessage());
if (loggingevent.getLevel().equals(Log4JTaskLogs.STDERR_LEVEL)) {
return;
} else if (!Logging.MSG.equals(loggingevent.getMessage())) {
this.allLogsAwaited = false;
}
numberOfAppendedLogs++;
}
public int getNumberOfAppendedLogs() {
return this.numberOfAppendedLogs;
}
public boolean receivedOnlyAwaitedEvents() {
return this.allLogsAwaited;
}
@Override
public void close() {
super.closed = true;
}
@Override
public boolean requiresLayout() {
return false;
}
}
}
| src/scheduler/tests/functionaltests/TestLoggers.java | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library 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; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionaltests;
import java.io.File;
import java.net.URL;
import junit.framework.Assert;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.task.Log4JTaskLogs;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingService;
import org.ow2.tests.FunctionalTest;
import functionaltests.executables.Logging;
/**
* @author cdelbe
*
*/
public class TestLoggers extends FunctionalTest {
private static URL jobDescriptor = TestLoggers.class
.getResource("/functionaltests/descriptors/Job_Test_Loggers.xml");
private final static int TEST_TIMEOUT = 10000;
/**
* Tests start here.
*
* @throws Throwable any exception that can be thrown during the test.
*/
@org.junit.Test
public void run() throws Throwable {
// socket loggers
LogForwardingService lfsPA = new LogForwardingService(
"org.ow2.proactive.scheduler.common.util.logforwarder.providers.ProActiveBasedForwardingProvider");
lfsPA.initialize();
LogForwardingService lfsSocket = new LogForwardingService(
"org.ow2.proactive.scheduler.common.util.logforwarder.providers.SocketBasedForwardingProvider");
lfsSocket.initialize();
JobId id1 = SchedulerTHelper.submitJob(new File(jobDescriptor.toURI()).getAbsolutePath());
JobId id2 = SchedulerTHelper.submitJob(new File(jobDescriptor.toURI()).getAbsolutePath());
//JobId id3 = SchedulerTHelper.submitJob(jobDescriptor);
Logger l1 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id1);
Logger l2 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id2);
//Logger l3 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + id3);
l1.setAdditivity(false);
l1.removeAllAppenders();
l2.setAdditivity(false);
l2.removeAllAppenders();
//l3.setAdditivity(false);
//l3.removeAllAppenders();
AppenderTester test1 = new AppenderTester();
AppenderTester test2 = new AppenderTester();
//AppenderTester test3 = new AppenderTester();
l1.addAppender(test1);
l2.addAppender(test2);
//l3.addAppender(test3);
SchedulerTHelper.getSchedulerInterface().listenJobLogs(id1, lfsPA.getAppenderProvider());
SchedulerTHelper.getSchedulerInterface().listenJobLogs(id2, lfsSocket.getAppenderProvider());
//SchedulerTHelper.getUserInterface().listenLog(id3, lfsPA.getAppenderProvider());
SchedulerTHelper.waitForEventJobFinished(id1);
SchedulerTHelper.waitForEventJobFinished(id2);
//SchedulerTHelper.waitForEventJobFinished(id3);
// waiting for the end of the job is not enough ... :(
// listenLog is asynchronous, i.e. "eventually" semantic
Thread.sleep(TEST_TIMEOUT);
Assert.assertTrue(test1.receivedOnlyAwaitedEvents());
Assert.assertEquals(2, test1.getNumberOfAppendedLogs());
Assert.assertTrue(test2.receivedOnlyAwaitedEvents());
Assert.assertEquals(2, test2.getNumberOfAppendedLogs());
//Assert.assertTrue(test3.receivedOnlyAwaitedEvents());
//Assert.assertEquals(2, test3.getNumberOfAppendedLogs());
lfsPA.terminate();
lfsSocket.terminate();
SchedulerTHelper.killScheduler();
}
public class AppenderTester extends AppenderSkeleton {
private boolean allLogsAwaited = true;
private int numberOfAppendedLogs = 0;
@Override
protected void append(LoggingEvent loggingevent) {
//System.out.println(">> AppenderTester.append() : " + loggingevent.getMessage());
if (!Logging.MSG.equals(loggingevent.getMessage())) {
this.allLogsAwaited = false;
}
numberOfAppendedLogs++;
}
public int getNumberOfAppendedLogs() {
return this.numberOfAppendedLogs;
}
public boolean receivedOnlyAwaitedEvents() {
return this.allLogsAwaited;
}
@Override
public void close() {
super.closed = true;
}
@Override
public boolean requiresLayout() {
return false;
}
}
}
| SCHEDULING-1414 : Fix TestLoggers
git-svn-id: 27916816d6cfa57849e9a885196bf7392b80e1ac@21247 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/scheduler/tests/functionaltests/TestLoggers.java | SCHEDULING-1414 : Fix TestLoggers | <ide><path>rc/scheduler/tests/functionaltests/TestLoggers.java
<ide> @Override
<ide> protected void append(LoggingEvent loggingevent) {
<ide> //System.out.println(">> AppenderTester.append() : " + loggingevent.getMessage());
<del> if (!Logging.MSG.equals(loggingevent.getMessage())) {
<add> if (loggingevent.getLevel().equals(Log4JTaskLogs.STDERR_LEVEL)) {
<add> return;
<add> } else if (!Logging.MSG.equals(loggingevent.getMessage())) {
<ide> this.allLogsAwaited = false;
<ide> }
<ide> numberOfAppendedLogs++; |
|
Java | mit | 846d2c6e6d87ecdc29d5f981ce8c72485a5fc1d6 | 0 | broadinstitute/picard,alecw/picard,annkupi/picard,nh13/picard,annkupi/picard,alecw/picard,annkupi/picard,annkupi/picard,nh13/picard,nh13/picard,broadinstitute/picard,broadinstitute/picard,alecw/picard,nh13/picard,alecw/picard,broadinstitute/picard,broadinstitute/picard | /*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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.
*/
package net.sf.picard.analysis;
import java.io.File;
import java.util.HashMap;
import java.util.Map.Entry;
import net.sf.picard.PicardException;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.io.IoUtil;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.sam.SamPairUtil;
import net.sf.picard.util.Histogram;
import net.sf.picard.util.Log;
import net.sf.picard.util.RExecutor;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.util.CloseableIterator;
import net.sf.picard.sam.SamPairUtil.PairOrientation;
/**
* Command line program to read non-duplicate insert sizes, create a histogram
* and report distribution statistics.
*
* @author Doug Voet (dvoet at broadinstitute dot org)
*/
public class CollectInsertSizeMetrics extends CommandLineProgram {
private static final Log log = Log.getInstance(CollectInsertSizeMetrics.class);
private static final String HISTOGRAM_R_SCRIPT = "net/sf/picard/analysis/insertSizeHistogram.R";
// Usage and parameters
@Usage
public String USAGE = "Reads a SAM or BAM file and writes a file containing metrics about " +
"the statistical distribution of insert size (excluding duplicates) " +
"and generates a histogram plot.\n";
@Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="SAM or BAM file") public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="File to write insert size metrics to") public File OUTPUT;
@Option(shortName="H", doc="File to write insert size histogram chart to") public File HISTOGRAM_FILE;
@Option(shortName="T", doc="When calculating mean and stdev stop when the bins in the tail of the distribution " +
"contain fewer than mode/TAIL_LIMIT items. This also limits how much data goes into each data category of the histogram.")
public int TAIL_LIMIT = 10000;
@Option(shortName="W", doc="Explicitly sets the histogram width, overriding the TAIL_LIMIT option. Also, when calculating " +
"mean and stdev, only bins <= HISTOGRAM_WIDTH will be included.", optional=true)
public Integer HISTOGRAM_WIDTH = null;
@Option(shortName="M", doc="When generating the histogram, discard any data categories (out of FR, TANDEM, RF) that have fewer than this " +
"percentage of overall reads. (Range: 0 to 1)")
public float MINIMUM_PCT = 0.01f;
@Option(doc="Stop after processing N reads, mainly for debugging.") public int STOP_AFTER = 0;
/** Required main method implementation. */
public static void main(final String[] argv) {
System.exit(new CollectInsertSizeMetrics().instanceMain(argv));
}
/**
* Put any custom command-line validation in an override of this method.
* clp is initialized at this point and can be used to print usage and access argv.
* Any options set by command-line parser can be validated.
*
* @return null if command line is valid. If command line is invalid, returns an array of error message
* to be written to the appropriate place.
*/
@Override
protected String[] customCommandLineValidation() {
if (MINIMUM_PCT < 0 || MINIMUM_PCT > 0.5) {
return new String[]{"MINIMUM_PCT was set to " + MINIMUM_PCT + ". It must be between 0 and 0.5 so all data categories don't get discarded."};
}
return super.customCommandLineValidation();
}
@Override
protected int doWork() {
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(HISTOGRAM_FILE);
final SAMFileReader in = new SAMFileReader(INPUT);
in.setValidationStringency(ValidationStringency.SILENT);
final MetricsFile<InsertSizeMetrics, Integer> file = collectMetrics(in.iterator());
in.close();
file.write(OUTPUT);
if (file.getMetrics().get(0).READ_PAIRS == 0) {
log.warn("Input file did not contain any records with insert size information.");
} else {
final int rResult;
if(HISTOGRAM_WIDTH == null) {
rResult = RExecutor.executeFromClasspath(
HISTOGRAM_R_SCRIPT,
OUTPUT.getAbsolutePath(),
HISTOGRAM_FILE.getAbsolutePath(),
INPUT.getName());
} else {
rResult = RExecutor.executeFromClasspath(
HISTOGRAM_R_SCRIPT,
OUTPUT.getAbsolutePath(),
HISTOGRAM_FILE.getAbsolutePath(),
INPUT.getName(),
String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last
//bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user.
}
if (rResult != 0) {
throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult);
}
}
return 0;
}
/**
* Does all the work of iterating through the sam file and collecting insert size metrics.
*/
MetricsFile<InsertSizeMetrics, Integer> collectMetrics(final CloseableIterator<SAMRecord> samIterator) {
HashMap<PairOrientation, Histogram<Integer>> histograms = new HashMap<PairOrientation, Histogram<Integer>>();
histograms.put(PairOrientation.FR, new Histogram<Integer>("insert_size", "fr_count"));
histograms.put(PairOrientation.TANDEM, new Histogram<Integer>("insert_size", "tandem_count"));
histograms.put(PairOrientation.RF, new Histogram<Integer>("insert_size", "rf_count"));
int validRecordCounter = 0;
while (samIterator.hasNext()) {
final SAMRecord record = samIterator.next();
if (skipRecord(record)) {
continue;
}
//add record to 1 of the 3 data categories
final int insertSize = Math.abs(record.getInferredInsertSize());
final PairOrientation orientation = SamPairUtil.getPairOrientation(record);
histograms.get(orientation).increment(insertSize);
validRecordCounter++;
if (STOP_AFTER > 0 && validRecordCounter >= STOP_AFTER) break;
}
final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile();
for(Entry<PairOrientation, Histogram<Integer>> entry : histograms.entrySet())
{
PairOrientation pairOrientation = entry.getKey();
Histogram<Integer> histogram = entry.getValue();
final double total = histogram.getCount();
final InsertSizeMetrics metrics = new InsertSizeMetrics();
if( total > validRecordCounter * MINIMUM_PCT ) {
metrics.PAIR_ORIENTATION = pairOrientation;
metrics.READ_PAIRS = (long) total;
metrics.MAX_INSERT_SIZE = (int) histogram.getMax();
metrics.MIN_INSERT_SIZE = (int) histogram.getMin();
metrics.MEDIAN_INSERT_SIZE = histogram.getMedian();
final double median = histogram.getMedian();
double covered = 0;
double low = median;
double high = median;
while (low >= histogram.getMin() || high <= histogram.getMax()) {
final Histogram<Integer>.Bin lowBin = histogram.get((int) low);
if (lowBin != null) covered += lowBin.getValue();
if (low != high) {
final Histogram<Integer>.Bin highBin = histogram.get((int) high);
if (highBin != null) covered += highBin.getValue();
}
final double percentCovered = covered / total;
final int distance = (int) (high - low) + 1;
if (percentCovered >= 0.1 && metrics.WIDTH_OF_10_PERCENT == 0) metrics.WIDTH_OF_10_PERCENT = distance;
if (percentCovered >= 0.2 && metrics.WIDTH_OF_20_PERCENT == 0) metrics.WIDTH_OF_20_PERCENT = distance;
if (percentCovered >= 0.3 && metrics.WIDTH_OF_30_PERCENT == 0) metrics.WIDTH_OF_30_PERCENT = distance;
if (percentCovered >= 0.4 && metrics.WIDTH_OF_40_PERCENT == 0) metrics.WIDTH_OF_40_PERCENT = distance;
if (percentCovered >= 0.5 && metrics.WIDTH_OF_50_PERCENT == 0) metrics.WIDTH_OF_50_PERCENT = distance;
if (percentCovered >= 0.6 && metrics.WIDTH_OF_60_PERCENT == 0) metrics.WIDTH_OF_60_PERCENT = distance;
if (percentCovered >= 0.7 && metrics.WIDTH_OF_70_PERCENT == 0) metrics.WIDTH_OF_70_PERCENT = distance;
if (percentCovered >= 0.8 && metrics.WIDTH_OF_80_PERCENT == 0) metrics.WIDTH_OF_80_PERCENT = distance;
if (percentCovered >= 0.9 && metrics.WIDTH_OF_90_PERCENT == 0) metrics.WIDTH_OF_90_PERCENT = distance;
if (percentCovered >= 0.99 && metrics.WIDTH_OF_99_PERCENT == 0) metrics.WIDTH_OF_99_PERCENT = distance;
--low;
++high;
}
// Trim the histogram down to get rid of outliers that would make the chart useless.
final Histogram<Integer> trimmedHisto = histogram; //alias it
if(HISTOGRAM_WIDTH != null) {
trimmedHisto.trimByWidth(HISTOGRAM_WIDTH);
} else {
trimmedHisto.trimByTailLimit(TAIL_LIMIT);
}
metrics.MEAN_INSERT_SIZE = trimmedHisto.getMean();
metrics.STANDARD_DEVIATION = trimmedHisto.getStandardDeviation();
file.addHistogram(trimmedHisto);
file.addMetric(metrics);
}
}
if(file.getNumHistograms() == 0) {
//can happen if user sets MINIMUM_PCT = 0.95, etc.
throw new PicardException("All data categories were discarded becaused they had an insufficient"+
" percentage of the data. Try lowering MINIMUM_PCT (currently set to: " + MINIMUM_PCT + ").");
}
return file;
}
/**
* Figures out whether or not the record should be included in the counting of insert sizes
*/
private boolean skipRecord(final SAMRecord record) {
return !record.getReadPairedFlag() ||
record.getReadUnmappedFlag() ||
record.getMateUnmappedFlag() ||
record.getFirstOfPairFlag() ||
record.getNotPrimaryAlignmentFlag() ||
record.getDuplicateReadFlag() ||
record.getInferredInsertSize() == 0;
}
}
| src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java | /*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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.
*/
package net.sf.picard.analysis;
import java.io.File;
import java.util.HashMap;
import java.util.Map.Entry;
import net.sf.picard.PicardException;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.io.IoUtil;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.sam.SamPairUtil;
import net.sf.picard.util.Histogram;
import net.sf.picard.util.Log;
import net.sf.picard.util.RExecutor;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.util.CloseableIterator;
import net.sf.picard.sam.SamPairUtil.PairOrientation;
/**
* Command line program to read non-duplicate insert sizes, create a histogram
* and report distribution statistics.
*
* @author Doug Voet (dvoet at broadinstitute dot org)
*/
public class CollectInsertSizeMetrics extends CommandLineProgram {
private static final Log log = Log.getInstance(CollectInsertSizeMetrics.class);
private static final String HISTOGRAM_R_SCRIPT = "net/sf/picard/analysis/insertSizeHistogram.R";
// Usage and parameters
@Usage
public String USAGE = "Reads a SAM or BAM file and writes a file containing metrics about " +
"the statistical distribution of insert size (excluding duplicates) " +
"and generates a histogram plot.\n";
@Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="SAM or BAM file") public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="File to write insert size metrics to") public File OUTPUT;
@Option(shortName="H", doc="File to write insert size histogram chart to") public File HISTOGRAM_FILE;
@Option(shortName="T", doc="When calculating mean and stdev stop when the bins in the tail of the distribution " +
"contain fewer than mode/TAIL_LIMIT items. This also limits how much data goes into each data category of the histogram.")
public int TAIL_LIMIT = 10000;
@Option(shortName="W", doc="Explicitly sets the histogram width, overriding the TAIL_LIMIT option. Also, when calculating " +
"mean and stdev, only bins <= HISTOGRAM_WIDTH will be included.", optional=true)
public Integer HISTOGRAM_WIDTH = null;
@Option(shortName="M", doc="When generating the histogram, discard any data categories (out of FR, TANDEM, RF) that have fewer than this " +
"percentage of overall reads. (Range: 0 to 1)")
public float MINIMUM_PCT = 0.01f;
@Option(doc="Stop after processing N reads, mainly for debugging.") public int STOP_AFTER = 0;
/** Required main method implementation. */
public static void main(final String[] argv) {
System.exit(new CollectInsertSizeMetrics().instanceMain(argv));
}
/**
* Put any custom command-line validation in an override of this method.
* clp is initialized at this point and can be used to print usage and access argv.
* Any options set by command-line parser can be validated.
*
* @return null if command line is valid. If command line is invalid, returns an array of error message
* to be written to the appropriate place.
*/
@Override
protected String[] customCommandLineValidation() {
if (MINIMUM_PCT < 0 || MINIMUM_PCT > 0.5) {
return new String[]{"MINIMUM_PCT was set to " + MINIMUM_PCT + ". It must be between 0 and 0.5 so all data categories don't get discarded."};
}
return super.customCommandLineValidation();
}
@Override
protected int doWork() {
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(HISTOGRAM_FILE);
final SAMFileReader in = new SAMFileReader(INPUT);
in.setValidationStringency(ValidationStringency.SILENT);
final MetricsFile<InsertSizeMetrics, Integer> file = collectMetrics(in.iterator());
in.close();
file.write(OUTPUT);
if (file.getMetrics().get(0).READ_PAIRS == 0) {
log.warn("Input file did not contain any records with insert size information.");
} else {
final int rResult;
if(HISTOGRAM_WIDTH == null) {
rResult = RExecutor.executeFromClasspath(
HISTOGRAM_R_SCRIPT,
OUTPUT.getAbsolutePath(),
HISTOGRAM_FILE.getAbsolutePath(),
INPUT.getName());
} else {
rResult = RExecutor.executeFromClasspath(
HISTOGRAM_R_SCRIPT,
OUTPUT.getAbsolutePath(),
HISTOGRAM_FILE.getAbsolutePath(),
INPUT.getName(),
String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last
//bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user.
}
if (rResult != 0) {
throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult);
}
}
return 0;
}
/**
* Does all the work of iterating through the sam file and collecting insert size metrics.
*/
MetricsFile<InsertSizeMetrics, Integer> collectMetrics(final CloseableIterator<SAMRecord> samIterator) {
HashMap<PairOrientation, Histogram<Integer>> histograms = new HashMap<PairOrientation, Histogram<Integer>>();
histograms.put(PairOrientation.FR, new Histogram<Integer>("insert_size", "fr_count"));
histograms.put(PairOrientation.TANDEM, new Histogram<Integer>("insert_size", "tandem_count"));
histograms.put(PairOrientation.RF, new Histogram<Integer>("insert_size", "rf_count"));
int validRecordCounter = 0;
while (samIterator.hasNext()) {
final SAMRecord record = samIterator.next();
if (skipRecord(record)) {
continue;
}
//add record to 1 of the 3 data categories
final int insertSize = Math.abs(record.getInferredInsertSize());
final PairOrientation orientation = SamPairUtil.getPairOrientation(record);
histograms.get(orientation).increment(insertSize);
validRecordCounter++;
if (STOP_AFTER > 0 && validRecordCounter >= STOP_AFTER) break;
}
final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile();
for(Entry<PairOrientation, Histogram<Integer>> entry : histograms.entrySet())
{
PairOrientation pairOrientation = entry.getKey();
Histogram<Integer> histogram = entry.getValue();
final double total = histogram.getCount();
final InsertSizeMetrics metrics = new InsertSizeMetrics();
if( total > validRecordCounter * MINIMUM_PCT ) {
metrics.PAIR_ORIENTATION = pairOrientation;
metrics.READ_PAIRS = (long) total;
metrics.MAX_INSERT_SIZE = (int) histogram.getMax();
metrics.MIN_INSERT_SIZE = (int) histogram.getMin();
metrics.MEDIAN_INSERT_SIZE = histogram.getMedian();
final double median = histogram.getMedian();
double covered = 0;
double low = median;
double high = median;
while (low >= histogram.getMin() || high <= histogram.getMax()) {
final Histogram<Integer>.Bin lowBin = histogram.get((int) low);
if (lowBin != null) covered += lowBin.getValue();
if (low != high) {
final Histogram<Integer>.Bin highBin = histogram.get((int) high);
if (highBin != null) covered += highBin.getValue();
}
final double percentCovered = covered / total;
final int distance = (int) (high - low) + 1;
if (percentCovered >= 0.1 && metrics.WIDTH_OF_10_PERCENT == 0) metrics.WIDTH_OF_10_PERCENT = distance;
if (percentCovered >= 0.2 && metrics.WIDTH_OF_20_PERCENT == 0) metrics.WIDTH_OF_20_PERCENT = distance;
if (percentCovered >= 0.3 && metrics.WIDTH_OF_30_PERCENT == 0) metrics.WIDTH_OF_30_PERCENT = distance;
if (percentCovered >= 0.4 && metrics.WIDTH_OF_40_PERCENT == 0) metrics.WIDTH_OF_40_PERCENT = distance;
if (percentCovered >= 0.5 && metrics.WIDTH_OF_50_PERCENT == 0) metrics.WIDTH_OF_50_PERCENT = distance;
if (percentCovered >= 0.6 && metrics.WIDTH_OF_60_PERCENT == 0) metrics.WIDTH_OF_60_PERCENT = distance;
if (percentCovered >= 0.7 && metrics.WIDTH_OF_70_PERCENT == 0) metrics.WIDTH_OF_70_PERCENT = distance;
if (percentCovered >= 0.8 && metrics.WIDTH_OF_80_PERCENT == 0) metrics.WIDTH_OF_80_PERCENT = distance;
if (percentCovered >= 0.9 && metrics.WIDTH_OF_90_PERCENT == 0) metrics.WIDTH_OF_90_PERCENT = distance;
if (percentCovered >= 0.99 && metrics.WIDTH_OF_99_PERCENT == 0) metrics.WIDTH_OF_99_PERCENT = distance;
--low;
++high;
}
// Trim the histogram down to get rid of outliers that would make the chart useless.
final Histogram<Integer> trimmedHisto = histogram; //alias it
if(HISTOGRAM_WIDTH != null) {
trimmedHisto.trimByWidth(HISTOGRAM_WIDTH);
} else {
trimmedHisto.trimByTailLimit(TAIL_LIMIT);
}
metrics.MEAN_INSERT_SIZE = trimmedHisto.getMean();
metrics.STANDARD_DEVIATION = trimmedHisto.getStandardDeviation();
file.addHistogram(trimmedHisto);
file.addMetric(metrics);
}
}
if(file.getNumHistograms() == 0) {
//can happen if user sets MINIMUM_PCT = 0.95, etc.
throw new PicardException("All data categories were discarded becaused they had an insufficient"+
" percentage of the data. Try lowering MINIMUM_PCT (currently set to: " + MINIMUM_PCT + ").");
}
return file;
}
/**
* Figures out whether or not the record should be included in the counting of insert sizes
*/
private boolean skipRecord(final SAMRecord record) {
return !record.getReadPairedFlag() ||
record.getMateUnmappedFlag() ||
record.getFirstOfPairFlag() ||
record.getNotPrimaryAlignmentFlag() ||
record.getDuplicateReadFlag() ||
record.getInferredInsertSize() == 0;
}
}
| Added a check that the read being examine must be mapped.
| src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java | Added a check that the read being examine must be mapped. | <ide><path>rc/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java
<ide> */
<ide> private boolean skipRecord(final SAMRecord record) {
<ide> return !record.getReadPairedFlag() ||
<add> record.getReadUnmappedFlag() ||
<ide> record.getMateUnmappedFlag() ||
<ide> record.getFirstOfPairFlag() ||
<ide> record.getNotPrimaryAlignmentFlag() ||
<ide> record.getDuplicateReadFlag() ||
<ide> record.getInferredInsertSize() == 0;
<ide> }
<del>
<del>
<del>
<ide> } |
|
Java | apache-2.0 | 59f77035393e33b17e8528c71836841ebacec8a1 | 0 | yusuke/twitter4j,yusuke/twitter4j,takke/twitter4j,takke/twitter4j | /*
* Copyright 2007 Yusuke Yamamoto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package twitter4j;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Twitter4J 2.2.4
*/
public class UsersResourcesTest extends TwitterTestBase {
private long twit4jblockID = 39771963L;
public UsersResourcesTest(String name) {
super(name);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testShowUser() throws Exception {
User user = twitter1.showUser("yusuke");
assertEquals("yusuke", user.getScreenName());
assertNotNull(user.getLocation());
assertNotNull(user.getDescription());
assertNotNull(user.getProfileImageURL());
assertNotNull(user.getBiggerProfileImageURL());
assertNotNull(user.getMiniProfileImageURL());
assertNotNull(user.getOriginalProfileImageURL());
assertNotNull(user.getProfileImageURLHttps());
assertNotNull(user.getBiggerProfileImageURLHttps());
assertNotNull(user.getMiniProfileImageURLHttps());
assertNotNull(user.getOriginalProfileImageURLHttps());
assertNotNull(user.getProfileBannerURL());
HttpClient http = HttpClientFactory.getInstance(conf1.getHttpClientConfiguration());
http.head(user.getProfileBannerURL());
http.head(user.getProfileBannerRetinaURL());
http.head(user.getProfileBannerIPadURL());
http.head(user.getProfileBannerIPadRetinaURL());
http.head(user.getProfileBannerMobileURL());
http.head(user.getProfileBannerMobileRetinaURL());
assertNotNull(user.getURL());
assertFalse(user.isProtected());
assertTrue(0 <= user.getFavouritesCount());
assertTrue(0 <= user.getFollowersCount());
assertTrue(0 <= user.getFriendsCount());
assertNotNull(user.getCreatedAt());
// timezone can be
// assertNotNull(user.getTimeZone());
assertNotNull(user.getProfileBackgroundImageURL());
assertTrue(0 <= user.getStatusesCount());
assertNotNull(user.getProfileBackgroundColor());
assertNotNull(user.getProfileTextColor());
assertNotNull(user.getProfileLinkColor());
assertNotNull(user.getProfileSidebarBorderColor());
assertNotNull(user.getProfileSidebarFillColor());
assertNotNull(user.getProfileTextColor());
assertTrue(1 < user.getFollowersCount());
if (user.getStatus() != null) {
assertNotNull(user.getStatus().getCreatedAt());
assertNotNull(user.getStatus().getText());
assertNotNull(user.getStatus().getSource());
}
assertTrue(1 <= user.getListedCount());
assertFalse(user.isFollowRequestSent());
assertEquals(user, twitter1.showUser("@yusuke"));
//test case for TFJ-91 null pointer exception getting user detail on users with no statuses
//http://yusuke.homeip.net/jira/browse/TFJ-91
user = twitter1.showUser("twit4jnoupdate");
assertNull(user.getProfileBannerURL());
user = twitter1.showUser("tigertest");
User previousUser = user;
assertNotNull(TwitterObjectFactory.getRawJSON(user));
user = twitter1.showUser(numberId);
assertEquals(numberIdId, user.getId());
assertNull(TwitterObjectFactory.getRawJSON(previousUser));
assertNotNull(TwitterObjectFactory.getRawJSON(user));
assertEquals(user, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user)));
previousUser = user;
user = twitter1.showUser(numberIdId);
assertEquals(numberIdId, user.getId());
assertNotNull(TwitterObjectFactory.getRawJSON(user));
assertEquals(user, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user)));
}
public void testLookupUsers() throws TwitterException {
ResponseList<User> users = twitter1.lookupUsers(id1.screenName, id2.screenName);
assertEquals(2, users.size());
assertContains(users, id1);
assertContains(users, id2);
users = twitter1.lookupUsers(id1.id, id2.id);
assertEquals(2, users.size());
assertContains(users, id1);
assertContains(users, id2);
assertNotNull(TwitterObjectFactory.getRawJSON(users.get(0)));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertNotNull(TwitterObjectFactory.getRawJSON(users));
}
private void assertContains(ResponseList<User> users, TestUserInfo user) {
boolean found = false;
for (User aUser : users) {
if (aUser.getId() == user.id && aUser.getScreenName().equals(user.screenName)) {
found = true;
break;
}
}
if (!found) {
fail(user.screenName + " not found in the result.");
}
}
public void testSearchUser() throws TwitterException {
ResponseList<User> users = twitter1.searchUsers("Doug Williams", 1);
assertTrue(4 < users.size());
assertNotNull(TwitterObjectFactory.getRawJSON(users.get(0)));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertNotNull(TwitterObjectFactory.getRawJSON(users));
}
public void testBanner() throws Exception {
twitter1.updateProfileBanner(getRandomlyChosenFile(banners));
User user = twitter1.verifyCredentials();
if (user.getProfileBannerURL() != null) {
twitter1.removeProfileBanner();
}
}
public void testAccountMethods() throws Exception {
User original = twitter1.verifyCredentials();
assertNotNull(TwitterObjectFactory.getRawJSON(original));
assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
String newName = "name" + System.currentTimeMillis();
String newURL = "https://yusuke.blog/" + System.currentTimeMillis();
String newLocation = "city:" + System.currentTimeMillis();
String newDescription = "description:" + System.currentTimeMillis();
User altered = twitter1.updateProfile(
newName, newURL, newLocation, newDescription);
assertNotNull(TwitterObjectFactory.getRawJSON(altered));
assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
assertEquals(altered, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(altered)));
twitter1.updateProfile(original.getName(), original.getURL(), original.getLocation(), original.getDescription());
assertEquals(newName, altered.getName());
assertTrue(altered.getURL().startsWith("https://t.co/"));
assertEquals(newLocation, altered.getLocation());
assertEquals(newDescription, altered.getDescription());
AccountSettings settings = twitter1.getAccountSettings();
assertTrue(settings.isSleepTimeEnabled());
assertTrue(settings.isGeoEnabled());
assertEquals("en", settings.getLanguage());
assertEquals("Rome", settings.getTimeZone().getName());
assertTrue(settings.isAlwaysUseHttps());
assertFalse(settings.isDiscoverableByEmail());
Location[] locations = settings.getTrendLocations();
assertTrue(0 < locations.length);
AccountSettings intermSettings = twitter1.updateAccountSettings(1 /* GLOBAL */, true,
"23", "08", "Helsinki", "it");
assertTrue(intermSettings.isSleepTimeEnabled());
assertEquals(intermSettings.getSleepStartTime(), "23");
assertEquals(intermSettings.getSleepEndTime(), "8");
assertTrue(intermSettings.isGeoEnabled());
assertEquals("it", intermSettings.getLanguage());
assertTrue(intermSettings.isAlwaysUseHttps());
assertFalse(intermSettings.isDiscoverableByEmail());
assertEquals("Helsinki", intermSettings.getTimeZone().getName());
Location[] intermLocations = intermSettings.getTrendLocations();
assertTrue(0 < intermLocations.length);
AccountSettings lastSettings = twitter1.updateAccountSettings(settings.getTrendLocations()[0].getWoeid(), settings.isSleepTimeEnabled(),
settings.getSleepStartTime(), settings.getSleepStartTime(), settings.getTimeZone().getName(), settings.getLanguage());
assertEquals(settings.getLanguage(), lastSettings.getLanguage());
assertEquals(settings.isSleepTimeEnabled(), lastSettings.isSleepTimeEnabled());
assertEquals(settings.getTimeZone().getName(), lastSettings.getTimeZone().getName());
assertEquals(settings.getSleepEndTime(), lastSettings.getSleepEndTime());
}
public void testAccountProfileImageUpdates() throws Exception {
User user = twitter1.updateProfileImage(new FileInputStream(getRandomlyChosenFile()));
assertNotNull(TwitterObjectFactory.getRawJSON(user));
// tile randomly
User user2 = twitter1.updateProfileBackgroundImage(getRandomlyChosenFile(),
(5 < System.currentTimeMillis() % 5));
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
}
private static final String[] profileImages = {"src/test/resources/t4j-reverse.jpeg",
"src/test/resources/t4j-reverse.png",
"src/test/resources/t4j-reverse.gif",
"src/test/resources/t4j.jpeg",
"src/test/resources/t4j.png",
"src/test/resources/t4j.gif",
};
private static final String[] banners = {
// gif format fails with {"errors":[{"message":"Image error: is not an accepted format","code":211}]}
// "src/test/resources/t4j-banner.gif",
"src/test/resources/t4j-banner.jpeg",
"src/test/resources/t4j-banner.png",
};
private static File getRandomlyChosenFile() {
return getRandomlyChosenFile(profileImages);
}
private static File getRandomlyChosenFile(String[] files) {
int rand = (int) (System.currentTimeMillis() % files.length);
File file = new File(files[rand]);
if (!file.exists()) {
file = new File("twitter4j-core/" + files[rand]);
}
return file;
}
public void testBlockMethods() throws Exception {
User user1 = twitter2.createBlock(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
User user2 = twitter2.destroyBlock(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
user1 = twitter2.createBlock("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
user2 = twitter2.destroyBlock("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
PagableResponseList<User> users = twitter1.getBlocksList();
assertNotNull(TwitterObjectFactory.getRawJSON(users));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertEquals(1, users.size());
assertEquals(twit4jblockID, users.get(0).getId());
IDs ids = twitter1.getBlocksIDs();
assertNull(TwitterObjectFactory.getRawJSON(users));
assertNotNull(TwitterObjectFactory.getRawJSON(ids));
assertEquals(1, ids.getIDs().length);
assertEquals(twit4jblockID, ids.getIDs()[0]);
ids = twitter1.getBlocksIDs(-1);
assertTrue(ids.getIDs().length > 0);
}
public void testMuteMethods() throws Exception {
User user1 = twitter2.createMute(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
User user2 = twitter2.destroyMute(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
user1 = twitter2.createMute("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
try {
user2 = twitter2.destroyMute("@"+id1.screenName);
// assertNotNull(TwitterObjectFactory.getRawJSON(user2));
// assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
} catch (TwitterException e) {
// The request with '@'+screen_name could not make mute user.
assertEquals(e.getStatusCode(), 403);
assertEquals(e.getErrorCode(), 272);
}
twitter1.createMute(twit4jblockID);
PagableResponseList<User> users = twitter1.getMutesList(-1L);
assertNotNull(TwitterObjectFactory.getRawJSON(users));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertEquals(1, users.size());
assertEquals(twit4jblockID, users.get(0).getId());
IDs ids = twitter1.getMutesIDs(-1L);
assertNull(TwitterObjectFactory.getRawJSON(users));
assertNotNull(TwitterObjectFactory.getRawJSON(ids));
assertEquals(1, ids.getIDs().length);
assertEquals(twit4jblockID, ids.getIDs()[0]);
}
}
| twitter4j-core/src/test/java/twitter4j/UsersResourcesTest.java | /*
* Copyright 2007 Yusuke Yamamoto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package twitter4j;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Twitter4J 2.2.4
*/
public class UsersResourcesTest extends TwitterTestBase {
private long twit4jblockID = 39771963L;
public UsersResourcesTest(String name) {
super(name);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testShowUser() throws Exception {
User user = twitter1.showUser("yusuke");
assertEquals("yusuke", user.getScreenName());
assertNotNull(user.getLocation());
assertNotNull(user.getDescription());
assertNotNull(user.getProfileImageURL());
assertNotNull(user.getBiggerProfileImageURL());
assertNotNull(user.getMiniProfileImageURL());
assertNotNull(user.getOriginalProfileImageURL());
assertNotNull(user.getProfileImageURLHttps());
assertNotNull(user.getBiggerProfileImageURLHttps());
assertNotNull(user.getMiniProfileImageURLHttps());
assertNotNull(user.getOriginalProfileImageURLHttps());
assertNotNull(user.getProfileBannerURL());
HttpClient http = HttpClientFactory.getInstance(conf1.getHttpClientConfiguration());
http.head(user.getProfileBannerURL());
http.head(user.getProfileBannerRetinaURL());
http.head(user.getProfileBannerIPadURL());
http.head(user.getProfileBannerIPadRetinaURL());
http.head(user.getProfileBannerMobileURL());
http.head(user.getProfileBannerMobileRetinaURL());
assertNotNull(user.getURL());
assertFalse(user.isProtected());
assertTrue(0 <= user.getFavouritesCount());
assertTrue(0 <= user.getFollowersCount());
assertTrue(0 <= user.getFriendsCount());
assertNotNull(user.getCreatedAt());
// timezone can be
// assertNotNull(user.getTimeZone());
assertNotNull(user.getProfileBackgroundImageURL());
assertTrue(0 <= user.getStatusesCount());
assertNotNull(user.getProfileBackgroundColor());
assertNotNull(user.getProfileTextColor());
assertNotNull(user.getProfileLinkColor());
assertNotNull(user.getProfileSidebarBorderColor());
assertNotNull(user.getProfileSidebarFillColor());
assertNotNull(user.getProfileTextColor());
assertTrue(1 < user.getFollowersCount());
if (user.getStatus() != null) {
assertNotNull(user.getStatus().getCreatedAt());
assertNotNull(user.getStatus().getText());
assertNotNull(user.getStatus().getSource());
}
assertTrue(1 <= user.getListedCount());
assertFalse(user.isFollowRequestSent());
assertEquals(user, twitter1.showUser("@yusuke"));
//test case for TFJ-91 null pointer exception getting user detail on users with no statuses
//http://yusuke.homeip.net/jira/browse/TFJ-91
user = twitter1.showUser("twit4jnoupdate");
assertNull(user.getProfileBannerURL());
user = twitter1.showUser("tigertest");
User previousUser = user;
assertNotNull(TwitterObjectFactory.getRawJSON(user));
user = twitter1.showUser(numberId);
assertEquals(numberIdId, user.getId());
assertNull(TwitterObjectFactory.getRawJSON(previousUser));
assertNotNull(TwitterObjectFactory.getRawJSON(user));
assertEquals(user, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user)));
previousUser = user;
user = twitter1.showUser(numberIdId);
assertEquals(numberIdId, user.getId());
assertNotNull(TwitterObjectFactory.getRawJSON(user));
assertEquals(user, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user)));
}
public void testLookupUsers() throws TwitterException {
ResponseList<User> users = twitter1.lookupUsers(id1.screenName, id2.screenName);
assertEquals(2, users.size());
assertContains(users, id1);
assertContains(users, id2);
users = twitter1.lookupUsers(id1.id, id2.id);
assertEquals(2, users.size());
assertContains(users, id1);
assertContains(users, id2);
assertNotNull(TwitterObjectFactory.getRawJSON(users.get(0)));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertNotNull(TwitterObjectFactory.getRawJSON(users));
}
private void assertContains(ResponseList<User> users, TestUserInfo user) {
boolean found = false;
for (User aUser : users) {
if (aUser.getId() == user.id && aUser.getScreenName().equals(user.screenName)) {
found = true;
break;
}
}
if (!found) {
fail(user.screenName + " not found in the result.");
}
}
public void testSearchUser() throws TwitterException {
ResponseList<User> users = twitter1.searchUsers("Doug Williams", 1);
assertTrue(4 < users.size());
assertNotNull(TwitterObjectFactory.getRawJSON(users.get(0)));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertNotNull(TwitterObjectFactory.getRawJSON(users));
}
public void testBanner() throws Exception {
twitter1.updateProfileBanner(getRandomlyChosenFile(banners));
User user = twitter1.verifyCredentials();
if (user.getProfileBannerURL() != null) {
twitter1.removeProfileBanner();
}
}
public void testAccountMethods() throws Exception {
User original = twitter1.verifyCredentials();
assertNotNull(TwitterObjectFactory.getRawJSON(original));
assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
if (original.getScreenName().endsWith("new") ||
original.getName().endsWith("new")) {
original = twitter1.updateProfile(
"twit4j", "http://yusuke.homeip.net/twitter4j/"
, "location:", "Hi there, I do test a lot!new");
}
String newName, newURL, newLocation, newDescription;
String neu = "new";
newName = original.getName() + neu;
newURL = original.getURL() + neu;
newLocation = new Date().toString();
newDescription = original.getDescription() + neu;
User altered = twitter1.updateProfile(
newName, newURL, newLocation, newDescription);
assertNotNull(TwitterObjectFactory.getRawJSON(altered));
assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
assertEquals(altered, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(altered)));
twitter1.updateProfile(original.getName(), original.getURL().toString(), original.getLocation(), original.getDescription());
assertEquals(newName, altered.getName());
assertEquals(newURL, altered.getURL().toString());
assertEquals(newLocation, altered.getLocation());
assertEquals(newDescription, altered.getDescription());
AccountSettings settings = twitter1.getAccountSettings();
assertTrue(settings.isSleepTimeEnabled());
assertTrue(settings.isGeoEnabled());
assertEquals("en", settings.getLanguage());
assertEquals("Rome", settings.getTimeZone().getName());
assertTrue(settings.isAlwaysUseHttps());
assertFalse(settings.isDiscoverableByEmail());
Location[] locations = settings.getTrendLocations();
assertTrue(0 < locations.length);
AccountSettings intermSettings = twitter1.updateAccountSettings(1 /* GLOBAL */, true,
"23", "08", "Helsinki", "it");
assertTrue(intermSettings.isSleepTimeEnabled());
assertEquals(intermSettings.getSleepStartTime(), "23");
assertEquals(intermSettings.getSleepEndTime(), "8");
assertTrue(intermSettings.isGeoEnabled());
assertEquals("it", intermSettings.getLanguage());
assertTrue(intermSettings.isAlwaysUseHttps());
assertFalse(intermSettings.isDiscoverableByEmail());
assertEquals("Helsinki", intermSettings.getTimeZone().getName());
Location[] intermLocations = intermSettings.getTrendLocations();
assertTrue(0 < intermLocations.length);
AccountSettings lastSettings = twitter1.updateAccountSettings(settings.getTrendLocations()[0].getWoeid(), settings.isSleepTimeEnabled(),
settings.getSleepStartTime(), settings.getSleepStartTime(), settings.getTimeZone().getName(), settings.getLanguage());
assertEquals(settings.getLanguage(), lastSettings.getLanguage());
assertEquals(settings.isSleepTimeEnabled(), lastSettings.isSleepTimeEnabled());
assertEquals(settings.getTimeZone().getName(), lastSettings.getTimeZone().getName());
assertEquals(settings.getSleepEndTime(), lastSettings.getSleepEndTime());
}
public void testAccountProfileImageUpdates() throws Exception {
User user = twitter1.updateProfileImage(new FileInputStream(getRandomlyChosenFile()));
assertNotNull(TwitterObjectFactory.getRawJSON(user));
// tile randomly
User user2 = twitter1.updateProfileBackgroundImage(getRandomlyChosenFile(),
(5 < System.currentTimeMillis() % 5));
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
}
private static final String[] profileImages = {"src/test/resources/t4j-reverse.jpeg",
"src/test/resources/t4j-reverse.png",
"src/test/resources/t4j-reverse.gif",
"src/test/resources/t4j.jpeg",
"src/test/resources/t4j.png",
"src/test/resources/t4j.gif",
};
private static final String[] banners = {
// gif format fails with {"errors":[{"message":"Image error: is not an accepted format","code":211}]}
// "src/test/resources/t4j-banner.gif",
"src/test/resources/t4j-banner.jpeg",
"src/test/resources/t4j-banner.png",
};
private static File getRandomlyChosenFile() {
return getRandomlyChosenFile(profileImages);
}
private static File getRandomlyChosenFile(String[] files) {
int rand = (int) (System.currentTimeMillis() % files.length);
File file = new File(files[rand]);
if (!file.exists()) {
file = new File("twitter4j-core/" + files[rand]);
}
return file;
}
public void testBlockMethods() throws Exception {
User user1 = twitter2.createBlock(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
User user2 = twitter2.destroyBlock(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
user1 = twitter2.createBlock("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
user2 = twitter2.destroyBlock("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
PagableResponseList<User> users = twitter1.getBlocksList();
assertNotNull(TwitterObjectFactory.getRawJSON(users));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertEquals(1, users.size());
assertEquals(twit4jblockID, users.get(0).getId());
IDs ids = twitter1.getBlocksIDs();
assertNull(TwitterObjectFactory.getRawJSON(users));
assertNotNull(TwitterObjectFactory.getRawJSON(ids));
assertEquals(1, ids.getIDs().length);
assertEquals(twit4jblockID, ids.getIDs()[0]);
ids = twitter1.getBlocksIDs(-1);
assertTrue(ids.getIDs().length > 0);
}
public void testMuteMethods() throws Exception {
User user1 = twitter2.createMute(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
User user2 = twitter2.destroyMute(id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user2));
assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
user1 = twitter2.createMute("@"+id1.screenName);
assertNotNull(TwitterObjectFactory.getRawJSON(user1));
assertEquals(user1, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user1)));
try {
user2 = twitter2.destroyMute("@"+id1.screenName);
// assertNotNull(TwitterObjectFactory.getRawJSON(user2));
// assertEquals(user2, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(user2)));
} catch (TwitterException e) {
// The request with '@'+screen_name could not make mute user.
assertEquals(e.getStatusCode(), 403);
assertEquals(e.getErrorCode(), 272);
}
twitter1.createMute(twit4jblockID);
PagableResponseList<User> users = twitter1.getMutesList(-1L);
assertNotNull(TwitterObjectFactory.getRawJSON(users));
assertEquals(users.get(0), TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(users.get(0))));
assertEquals(1, users.size());
assertEquals(twit4jblockID, users.get(0).getId());
IDs ids = twitter1.getMutesIDs(-1L);
assertNull(TwitterObjectFactory.getRawJSON(users));
assertNotNull(TwitterObjectFactory.getRawJSON(ids));
assertEquals(1, ids.getIDs().length);
assertEquals(twit4jblockID, ids.getIDs()[0]);
}
}
| fix testAccountMethods
| twitter4j-core/src/test/java/twitter4j/UsersResourcesTest.java | fix testAccountMethods | <ide><path>witter4j-core/src/test/java/twitter4j/UsersResourcesTest.java
<ide> User original = twitter1.verifyCredentials();
<ide> assertNotNull(TwitterObjectFactory.getRawJSON(original));
<ide> assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
<del> if (original.getScreenName().endsWith("new") ||
<del> original.getName().endsWith("new")) {
<del> original = twitter1.updateProfile(
<del> "twit4j", "http://yusuke.homeip.net/twitter4j/"
<del> , "location:", "Hi there, I do test a lot!new");
<del>
<del> }
<del> String newName, newURL, newLocation, newDescription;
<del> String neu = "new";
<del> newName = original.getName() + neu;
<del> newURL = original.getURL() + neu;
<del> newLocation = new Date().toString();
<del> newDescription = original.getDescription() + neu;
<add>
<add> String newName = "name" + System.currentTimeMillis();
<add> String newURL = "https://yusuke.blog/" + System.currentTimeMillis();
<add> String newLocation = "city:" + System.currentTimeMillis();
<add> String newDescription = "description:" + System.currentTimeMillis();
<ide>
<ide> User altered = twitter1.updateProfile(
<ide> newName, newURL, newLocation, newDescription);
<ide> assertNotNull(TwitterObjectFactory.getRawJSON(altered));
<ide> assertEquals(original, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(original)));
<ide> assertEquals(altered, TwitterObjectFactory.createUser(TwitterObjectFactory.getRawJSON(altered)));
<del> twitter1.updateProfile(original.getName(), original.getURL().toString(), original.getLocation(), original.getDescription());
<add> twitter1.updateProfile(original.getName(), original.getURL(), original.getLocation(), original.getDescription());
<ide> assertEquals(newName, altered.getName());
<del> assertEquals(newURL, altered.getURL().toString());
<add> assertTrue(altered.getURL().startsWith("https://t.co/"));
<ide> assertEquals(newLocation, altered.getLocation());
<ide> assertEquals(newDescription, altered.getDescription());
<ide> |
|
Java | apache-2.0 | a418695b69e890e7e257aeaf2b25fb6c6c864673 | 0 | seanox/devwex-test,seanox/devwex-test,seanox/devwex-test | /**
* LIZENZBEDINGUNGEN - Seanox Software Solutions ist ein Open-Source-Projekt, im
* Folgenden Seanox Software Solutions oder kurz Seanox genannt.
* Diese Software unterliegt der Version 2 der Apache License.
*
* Devwex, Advanced Server Development
* Copyright (C) 2022 Seanox Software Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package module;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.Socket;
import java.util.Map;
class AbstractWorkerModule extends AbstractModule {
public void filter(final Object facade, final String options)
throws Exception {
final Worker worker = Worker.create(facade);
try {this.filter(worker, options);
} finally {
worker.synchronize();
}
}
public void filter(final Worker worker, final String options)
throws Exception {
return;
}
public void service(final Object facade, final String options)
throws Exception {
final Worker worker = Worker.create(facade);
try {this.service(worker, options);
} finally {
worker.synchronize();
}
}
public void service(final Worker worker, final String options)
throws Exception {
return;
}
static class Worker {
/** referenced worker */
private Object facade;
/** socket of worker */
protected Socket accept;
/** worker output stream */
protected OutputStream output;
/** worker environment */
private Object environment;
/** internal map of worker environment */
protected Map<String, String> environmentMap;
/** worker connection control */
protected boolean control;
/** worker response status */
protected int status;
/**
* Synchronizes the fields of two objects.
* In the target object is searched for the fields from the source object
* and synchronized when if they exist.
* @param source
* @param target
*/
private static void synchronizeFields(final Object source, final Object target)
throws Exception {
for (final Field inport : source.getClass().getDeclaredFields()) {
final Field export;
try {export = target.getClass().getDeclaredField(inport.getName());
} catch (NoSuchFieldException exception) {
continue;
}
export.setAccessible(true);
inport.setAccessible(true);
if (inport.getType().equals(Boolean.TYPE))
export.setBoolean(target, inport.getBoolean(source));
else if (inport.getType().equals(Integer.TYPE))
export.setInt(target, inport.getInt(source));
else if (inport.getType().equals(Long.TYPE))
export.setLong(target, inport.getLong(source));
else if (!inport.getType().isPrimitive())
export.set(target, inport.get(source));
}
}
private static Object getField(final Object source, final String field)
throws Exception {
final Field export = source.getClass().getDeclaredField(field);
export.setAccessible(true);
return export.get(source);
}
static Worker create(final Object facade)
throws Exception {
final Worker worker = new Worker();
worker.facade = facade;
Worker.synchronizeFields(facade, worker);
if (worker.environment != null)
worker.environmentMap = (Map<String, String>)Worker.getField(worker.environment, "entries");
if (worker.output == null)
worker.output = worker.accept.getOutputStream();
return worker;
}
void synchronize()
throws Exception {
Worker.synchronizeFields(this, this.facade);
}
}
} | resources/libraries/module/AbstractWorkerModule.java | /**
* LIZENZBEDINGUNGEN - Seanox Software Solutions ist ein Open-Source-Projekt, im
* Folgenden Seanox Software Solutions oder kurz Seanox genannt.
* Diese Software unterliegt der Version 2 der Apache License.
*
* Devwex, Advanced Server Development
* Copyright (C) 2022 Seanox Software Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package module;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.Socket;
import java.util.Map;
class AbstractWorkerModule extends AbstractModule {
public void filter(final Object facade, final String options)
throws Exception {
final Worker worker = Worker.create(facade);
try {this.filter(worker, options);
} finally {
worker.synchronize();
}
}
public void filter(final Worker worker, final String options)
throws Exception {
return;
}
public void service(final Object facade, final String options)
throws Exception {
final Worker worker = Worker.create(facade);
try {this.service(worker, options);
} finally {
worker.synchronize();
}
}
public void service(final Worker worker, final String options)
throws Exception {
return;
}
static class Worker {
/** referenced worker */
private Object facade;
/** socket of worker */
protected Socket socket;
/** worker output stream */
protected OutputStream output;
/** worker environment */
private Object environment;
/** internal map of worker environment */
protected Map<String, String> environmentMap;
/** worker connection control */
protected boolean control;
/** worker response status */
protected int status;
/**
* Synchronizes the fields of two objects.
* In the target object is searched for the fields from the source object
* and synchronized when if they exist.
* @param source
* @param target
*/
private static void synchronizeFields(final Object source, final Object target)
throws Exception {
for (final Field inport : source.getClass().getDeclaredFields()) {
final Field export;
try {export = target.getClass().getDeclaredField(inport.getName());
} catch (NoSuchFieldException exception) {
continue;
}
export.setAccessible(true);
inport.setAccessible(true);
if (inport.getType().equals(Boolean.TYPE))
export.setBoolean(target, inport.getBoolean(source));
else if (inport.getType().equals(Integer.TYPE))
export.setInt(target, inport.getInt(source));
else if (inport.getType().equals(Long.TYPE))
export.setLong(target, inport.getLong(source));
else if (!inport.getType().isPrimitive())
export.set(target, inport.get(source));
}
}
private static Object getField(final Object source, final String field)
throws Exception {
final Field export = source.getClass().getDeclaredField(field);
export.setAccessible(true);
return export.get(source);
}
static Worker create(final Object facade)
throws Exception {
final Worker worker = new Worker();
worker.facade = facade;
Worker.synchronizeFields(facade, worker);
if (worker.environment != null)
worker.environmentMap = (Map<String, String>)Worker.getField(worker.environment, "entries");
if (worker.output == null)
worker.output = worker.socket.getOutputStream();
return worker;
}
void synchronize()
throws Exception {
Worker.synchronizeFields(this, this.facade);
}
}
} | #0000 Test: Optimization of environment
| resources/libraries/module/AbstractWorkerModule.java | #0000 Test: Optimization of environment | <ide><path>esources/libraries/module/AbstractWorkerModule.java
<ide> private Object facade;
<ide>
<ide> /** socket of worker */
<del> protected Socket socket;
<add> protected Socket accept;
<ide>
<ide> /** worker output stream */
<ide> protected OutputStream output;
<ide> if (worker.environment != null)
<ide> worker.environmentMap = (Map<String, String>)Worker.getField(worker.environment, "entries");
<ide> if (worker.output == null)
<del> worker.output = worker.socket.getOutputStream();
<add> worker.output = worker.accept.getOutputStream();
<ide>
<ide> return worker;
<ide> } |
|
JavaScript | mit | f82340bf8322bd45b4d0d0d0fb0311c02d20d713 | 0 | linagora/overture,fastmail/overture,Hokua/overture,linagora/overture,adityab/overture | // -------------------------------------------------------------------------- \\
// File: UndoManager.js \\
// Module: DataStore \\
// Requires: Core, Foundation \\
// Author: Neil Jenkins \\
// License: © 2010-2014 FastMail Pty Ltd. All rights reserved. \\
// -------------------------------------------------------------------------- \\
"use strict";
( function ( NS ) {
/**
Class: O.UndoManager
*/
var UndoManager = NS.Class({
Extends: NS.Object,
init: function ( mixin ) {
this._undoStack = [];
this._redoStack = [];
this._isInUndoState = false;
this.canUndo = false;
this.canRedo = false;
this.maxUndoCount = 1;
UndoManager.parent.init.call( this, mixin );
},
_pushState: function ( stack, data ) {
stack.push( data );
while ( stack.length > this.maxUndoCount ) {
stack.shift();
}
this._isInUndoState = true;
},
dataDidChange: function () {
this._isInUndoState = false;
this._redoStack.length = 0;
this.set( 'canRedo', false )
.set( 'canUndo', true );
return this;
},
saveUndoCheckpoint: function () {
if ( !this._isInUndoState ) {
var data = this.getUndoData();
if ( data !== null ) {
this._pushState( this._undoStack, data );
} else {
this._isInUndoState = true;
this.set( 'canUndo', !!this._undoStack.length );
}
}
return this;
},
undo: function () {
if ( this.get( 'canUndo' ) ) {
if ( !this._isInUndoState ) {
this.saveUndoCheckpoint();
return this.undo();
} else {
this._pushState( this._redoStack,
this.applyChange( this._undoStack.pop(), false )
);
this.set( 'canUndo', !!this._undoStack.length )
.set( 'canRedo', true );
}
}
return this;
},
redo: function () {
if ( this.get( 'canRedo' ) ) {
this._pushState( this._undoStack,
this.applyChange( this._redoStack.pop(), true )
);
this.set( 'canUndo', true )
.set( 'canRedo', !!this._redoStack.length );
}
return this;
},
getUndoData: function () {},
applyChange: function (/* data, isRedo */) {}
});
var StoreUndoManager = NS.Class({
Extends: UndoManager,
init: function ( mixin ) {
var store = mixin.store;
store.on( 'willCommit', this, 'saveUndoCheckpoint' )
.on( 'record:user:create', this, 'dataDidChange' )
.on( 'record:user:update', this, 'dataDidChange' )
.on( 'record:user:destroy', this, 'dataDidChange' );
StoreUndoManager.parent.init.call( this, mixin );
},
destroy: function () {
this.store.off( 'willCommit', this, 'saveUndoCheckpoint' )
.off( 'record:user:create', this, 'dataDidChange' )
.off( 'record:user:update', this, 'dataDidChange' )
.off( 'record:user:destroy', this, 'dataDidChange' );
StoreUndoManager.parent.destroy.call( this );
},
getUndoData: function () {
var store = this.store;
return store.hasChanges() ? store.getInverseChanges() : null;
},
_updateStoreKeys: function ( stack, created ) {
var l = stack.length,
item, create, update, destroy, i, ll, storeKey;
while ( l-- ) {
item = stack[l];
create = item.create;
update = item.update;
destroy = item.destroy;
for ( i = 0, ll = create.length; i < ll; i += 1 ) {
storeKey = created[ create[i][0] ];
if ( storeKey ) {
create[i][0] = storeKey;
}
}
for ( i = 0, ll = update.length; i < ll; i += 1 ) {
storeKey = created[ update[i][0] ];
if ( storeKey ) {
update[i][0] = storeKey;
}
}
for ( i = 0, ll = destroy.length; i < ll; i += 1 ) {
storeKey = created[ destroy[i] ];
if ( storeKey ) {
destroy[i] = storeKey;
}
}
}
},
applyChange: function ( data ) {
var store = this.store,
created = store.applyChanges( data ),
inverse;
this._updateStoreKeys( this._undoStack, created );
this._updateStoreKeys( this._redoStack, created );
inverse = store.getInverseChanges();
store.commitChanges();
return inverse;
}
});
NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;
}( O ) );
| source/Overture/datastore/store/UndoManager.js | // -------------------------------------------------------------------------- \\
// File: UndoManager.js \\
// Module: DataStore \\
// Requires: Core, Foundation \\
// Author: Neil Jenkins \\
// License: © 2010-2014 FastMail Pty Ltd. All rights reserved. \\
// -------------------------------------------------------------------------- \\
"use strict";
( function ( NS ) {
/**
Class: O.UndoManager
*/
var UndoManager = NS.Class({
Extends: NS.Object,
init: function ( mixin ) {
this._undoStack = [];
this._redoStack = [];
this._isInUndoState = false;
this.canUndo = false;
this.canRedo = false;
this.maxUndoCount = 1;
UndoManager.parent.init.call( this, mixin );
},
_pushState: function ( stack, data ) {
stack.push( data );
while ( stack > this.maxUndoCount ) {
stack.shift();
}
this._isInUndoState = true;
},
dataDidChange: function () {
this._isInUndoState = false;
this._redoStack.length = 0;
this.set( 'canRedo', false )
.set( 'canUndo', true );
return this;
},
saveUndoCheckpoint: function () {
if ( !this._isInUndoState ) {
var data = this.getUndoData();
if ( data !== null ) {
this._pushState( this._undoStack, data );
} else {
this._isInUndoState = true;
this.set( 'canUndo', !!this._undoStack.length );
}
}
return this;
},
undo: function () {
if ( this.get( 'canUndo' ) ) {
if ( !this._isInUndoState ) {
this.saveUndoCheckpoint();
return this.undo();
} else {
this._pushState( this._redoStack,
this.applyChange( this._undoStack.pop(), false )
);
this.set( 'canUndo', !!this._undoStack.length )
.set( 'canRedo', true );
}
}
return this;
},
redo: function () {
if ( this.get( 'canRedo' ) ) {
this._pushState( this._undoStack,
this.applyChange( this._redoStack.pop(), true )
);
this.set( 'canUndo', true )
.set( 'canRedo', !!this._redoStack.length );
}
return this;
},
getUndoData: function () {},
applyChange: function (/* data, isRedo */) {}
});
var StoreUndoManager = NS.Class({
Extends: UndoManager,
init: function ( mixin ) {
var store = mixin.store;
store.on( 'willCommit', this, 'saveUndoCheckpoint' )
.on( 'record:user:create', this, 'dataDidChange' )
.on( 'record:user:update', this, 'dataDidChange' )
.on( 'record:user:destroy', this, 'dataDidChange' );
StoreUndoManager.parent.init.call( this, mixin );
},
destroy: function () {
this.store.off( 'willCommit', this, 'saveUndoCheckpoint' )
.off( 'record:user:create', this, 'dataDidChange' )
.off( 'record:user:update', this, 'dataDidChange' )
.off( 'record:user:destroy', this, 'dataDidChange' );
StoreUndoManager.parent.destroy.call( this );
},
getUndoData: function () {
var store = this.store;
return store.hasChanges() ? store.getInverseChanges() : null;
},
_updateStoreKeys: function ( stack, created ) {
var l = stack.length,
item, create, update, destroy, i, ll, storeKey;
while ( l-- ) {
item = stack[l];
create = item.create;
update = item.update;
destroy = item.destroy;
for ( i = 0, ll = create.length; i < ll; i += 1 ) {
storeKey = created[ create[i][0] ];
if ( storeKey ) {
create[i][0] = storeKey;
}
}
for ( i = 0, ll = update.length; i < ll; i += 1 ) {
storeKey = created[ update[i][0] ];
if ( storeKey ) {
update[i][0] = storeKey;
}
}
for ( i = 0, ll = destroy.length; i < ll; i += 1 ) {
storeKey = created[ destroy[i] ];
if ( storeKey ) {
destroy[i] = storeKey;
}
}
}
},
applyChange: function ( data ) {
var store = this.store,
created = store.applyChanges( data ),
inverse;
this._updateStoreKeys( this._undoStack, created );
this._updateStoreKeys( this._redoStack, created );
inverse = store.getInverseChanges();
store.commitChanges();
return inverse;
}
});
NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;
}( O ) );
| Fix UndoManager max undo count limit.
| source/Overture/datastore/store/UndoManager.js | Fix UndoManager max undo count limit. | <ide><path>ource/Overture/datastore/store/UndoManager.js
<ide>
<ide> _pushState: function ( stack, data ) {
<ide> stack.push( data );
<del> while ( stack > this.maxUndoCount ) {
<add> while ( stack.length > this.maxUndoCount ) {
<ide> stack.shift();
<ide> }
<ide> this._isInUndoState = true; |
|
Java | apache-2.0 | 7c1a904bf32ca5b2bc160163f3a97bf2d27be348 | 0 | cristiani/encuestame,cristiani/encuestame,cristiani/encuestame,cristiani/encuestame,cristiani/encuestame | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
************************************************************************************
*/
package org.encuestame.business.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.encuestame.core.service.AbstractBaseService;
import org.encuestame.core.service.imp.IFrontEndService;
import org.encuestame.core.service.imp.SecurityOperations;
import org.encuestame.core.util.ConvertDomainBean;
import org.encuestame.core.util.EnMeUtils;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.HashTagRanking;
import org.encuestame.persistence.domain.Hit;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSavedPublishedStatus;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.persistence.exception.EnMePollNotFoundException;
import org.encuestame.persistence.exception.EnMeSearchException;
import org.encuestame.utils.DateUtil;
import org.encuestame.utils.RelativeTimeEnum;
import org.encuestame.utils.enums.SearchPeriods;
import org.encuestame.utils.enums.TypeSearchResult;
import org.encuestame.utils.json.HomeBean;
import org.encuestame.utils.json.LinksSocialBean;
import org.encuestame.utils.json.TweetPollBean;
import org.encuestame.utils.web.HashTagBean;
import org.encuestame.utils.web.PollBean;
import org.encuestame.utils.web.ProfileRatedTopBean;
import org.encuestame.utils.web.SurveyBean;
import org.encuestame.utils.web.stats.GenericStatsBean;
import org.encuestame.utils.web.stats.HashTagDetailStats;
import org.encuestame.utils.web.stats.HashTagRankingBean;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Front End Service.
* @author Picado, Juan juanATencuestame.org
* @since Oct 17, 2010 11:29:38 AM
* @version $Id:$
*/
@Service
public class FrontEndService extends AbstractBaseService implements IFrontEndService {
/** Front End Service Log. **/
private Logger log = Logger.getLogger(this.getClass());
/** Max Results. **/
private final Integer MAX_RESULTS = 15;
/** **/
@Autowired
private TweetPollService tweetPollService;
/** {@link PollService} **/
@Autowired
private PollService pollService;
/** {@link SurveyService} **/
@Autowired
private SurveyService surveyService;
/** {@link SecurityOperations} **/
@Autowired
private SecurityOperations securityService;
/**
* Search Items By tweetPoll.
* @param maxResults limit of results to return.
* @return result of the search.
* @throws EnMeSearchException search exception.
*/
public List<TweetPollBean> searchItemsByTweetPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request)
throws EnMeSearchException{
final List<TweetPollBean> results = new ArrayList<TweetPollBean>();
if(maxResults == null){
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results: "+maxResults);
log.debug("Period Results: "+period);
final List<TweetPoll> items = new ArrayList<TweetPoll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndAllTime(start, maxResults));
}
results.addAll(ConvertDomainBean.convertListToTweetPollBean(items));
for (TweetPollBean tweetPoll : results) {
//log.debug("Iterate Home TweetPoll id: "+tweetPoll.getId());
//log.debug("Iterate Home Tweetpoll Hashtag Size: "+tweetPoll.getHashTags().size());
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
tweetPoll.setTotalComments(this.getTotalCommentsbyType(tweetPoll.getId(), TypeSearchResult.TWEETPOLL));
}
}
log.debug("Search Items by TweetPoll: "+results.size());
return results;
}
/**
*
*/
public List<SurveyBean> searchItemsBySurvey(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
final List<SurveyBean> results = new ArrayList<SurveyBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results " + maxResults);
final List<Survey> items = new ArrayList<Survey>();
if (period == null) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods
.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast7Days(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast30Days(
start, maxResults));
} else if (periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getSurveyFrontEndAllTime(start,
maxResults));
}
log.debug("TweetPoll " + items.size());
results.addAll(ConvertDomainBean.convertListSurveyToBean(items));
for (SurveyBean surveyBean : results) {
surveyBean.setTotalComments(this.getTotalCommentsbyType(surveyBean.getSid(), TypeSearchResult.SURVEY));
}
}
return results;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getFrontEndItems(java.lang.String, java.lang.Integer, java.lang.Integer, javax.servlet.http.HttpServletRequest)
*/
public List<HomeBean> getFrontEndItems(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
// Sorted list based comparable interface
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this.searchItemsByTweetPoll(
period, start, maxResults, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
final List<PollBean> pollItems = this.searchItemsByPoll(period, start,
maxResults);
log.debug("FrontEnd Poll items size :" + pollItems.size());
allItems.addAll(ConvertDomainBean.convertPollListToHomeBean(pollItems));
final List<SurveyBean> surveyItems = this.searchItemsBySurvey(period,
start, maxResults, request);
log.debug("FrontEnd Survey items size :" + surveyItems.size());
allItems.addAll(ConvertDomainBean
.convertSurveyListToHomeBean(surveyItems));
log.debug("Home bean list size :" + allItems.size());
Collections.sort(allItems);
return allItems;
}
/**
* Search items by poll.
* @param period
* @param maxResults
* @return
* @throws EnMeSearchException
*/
public List<PollBean> searchItemsByPoll(
final String period,
final Integer start,
Integer maxResults)
throws EnMeSearchException{
final List<PollBean> results = new ArrayList<PollBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<Poll> items = new ArrayList<Poll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)){
items.addAll(getFrontEndDao().getPollFrontEndAllTime(start, maxResults));
}
log.debug("Poll "+items.size());
results.addAll(ConvertDomainBean.convertListToPollBean((items)));
for (PollBean pollbean : results) {
pollbean.setTotalComments(this.getTotalCommentsbyType(pollbean.getId(), TypeSearchResult.POLL));
}
}
return results;
}
public void search(){
}
/**
* Get hashTags
* @param maxResults the max results to display
* @param start to pagination propose.
* @return List of {@link HashTagBean}
*/
public List<HashTagBean> getHashTags(
Integer maxResults,
final Integer start,
final String tagCriteria) {
final List<HashTagBean> hashBean = new ArrayList<HashTagBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<HashTag> tags = getHashTagDao().getHashTags(maxResults, start, tagCriteria);
hashBean.addAll(ConvertDomainBean.convertListHashTagsToBean(tags));
return hashBean;
}
/**
* Get hashTag item.
* @param tagName
* @return
* @throws EnMeNoResultsFoundException
*/
public HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException {
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag == null){
throw new EnMeNoResultsFoundException("hashtag not found");
}
return tag;
}
/**
* Get TweetPolls by hashTag id.
* @param hashTagId
* @param limit
* @return
*/
public List<TweetPollBean> getTweetPollsbyHashTagName(
final String tagName,
final Integer initResults,
final Integer limit,
final String filter,
final HttpServletRequest request){
final List<TweetPoll> tweetPolls = getTweetPollDao().getTweetpollByHashTagName(tagName, initResults, limit, TypeSearchResult.getTypeSearchResult(filter));
log.debug("TweetPoll by HashTagId total size ---> "+tweetPolls.size());
final List<TweetPollBean> tweetPollBean = ConvertDomainBean.convertListToTweetPollBean(tweetPolls);
for (TweetPollBean tweetPoll : tweetPollBean) {
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
}
return tweetPollBean;
}
public List<HomeBean> searchLastPublicationsbyHashTag(
final HashTag hashTag, final String keyword,
final Integer initResults, final Integer limit,
final String filter, final HttpServletRequest request) {
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this
.getTweetPollsbyHashTagName(hashTag.getHashTag(), initResults,
limit, filter, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
Collections.sort(allItems);
return allItems;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#checkPreviousHit(java.lang.String, java.lang.Long, java.lang.String)
*/
public Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby){
boolean hit = false;
final List<Hit> hitList = getFrontEndDao().getHitsByIpAndType(ipAddress, id, searchHitby);
try {
if(hitList.size() == 1){
if(hitList.get(0).getIpAddress().equals(ipAddress)){
hit = true;
}
}
else if(hitList.size() > 1){
log.error("List cant'be greater than one");
}
} catch (Exception e) {
log.error(e);
}
return hit;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#registerHit(org.encuestame.persistence.domain.tweetpoll.TweetPoll, org.encuestame.persistence.domain.survey.Poll, org.encuestame.persistence.domain.survey.Survey, org.encuestame.persistence.domain.HashTag, java.lang.String)
*/
public Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ip) throws EnMeNoResultsFoundException{
final Hit hit ;
Long hitCount = 1L;
Boolean register = false;
// HashTag
if (ip != null){
if (tag != null){
hit = this.newHashTagHit(tag, ip);
hitCount = tag.getHits() == null ? 0L : tag.getHits() + hitCount;
tag.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tag);
register = true;
}
else if(tweetPoll != null){
hit = this.newTweetPollHit(tweetPoll, ip);
hitCount = tweetPoll.getHits() + hitCount;
tweetPoll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tweetPoll);
register = true;
}
else if(poll != null){
hit = this.newPollHit(poll, ip);
hitCount = poll.getHits() + hitCount;
poll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(poll);
register = true;
}
else if(survey != null ){
hit = this.newSurveyHit(survey, ip);
hitCount = survey.getHits() + hitCount;
survey.setHits(hitCount);
getFrontEndDao().saveOrUpdate(survey);
register = true;
}
}
return register;
}
/**
* New hit item.
* @param tweetPoll
* @param poll
* @param survey
* @param tag
* @param ipAddress
* @return
*/
@Transactional(readOnly = false)
private Hit newHitItem(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ipAddress) {
final Hit hitItem = new Hit();
hitItem.setHitDate(Calendar.getInstance().getTime());
hitItem.setHashTag(tag);
hitItem.setIpAddress(ipAddress);
hitItem.setTweetPoll(tweetPoll);
hitItem.setPoll(poll);
hitItem.setSurvey(survey);
getFrontEndDao().saveOrUpdate(hitItem);
return hitItem;
}
/**
* New tweet poll hit item.
* @param tweetPoll
* @param ipAddress
* @return
*/
private Hit newTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
return this.newHitItem(tweetPoll, null, null, null, ipAddress);
}
/**
* New poll hit item.
* @param poll
* @param ipAddress
* @return
*/
private Hit newPollHit(final Poll poll, final String ipAddress){
return this.newHitItem(null, poll, null, null, ipAddress);
}
/**
* New hash tag hit item.
* @param tag
* @param ipAddress
* @return
*/
private Hit newHashTagHit(final HashTag tag, final String ipAddress){
return this.newHitItem(null, null, null, tag, ipAddress);
}
/**
* New survey hit item.
* @param survey
* @param ipAddress
* @return
*/
private Hit newSurveyHit(final Survey survey, final String ipAddress){
return this.newHitItem(null, null, survey, null, ipAddress);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#registerAccessRate(org.encuestame.persistence.domain.TypeSearchResult, java.lang.Long, java.lang.String, java.lang.Boolean)
*/
public AccessRate registerAccessRate(final TypeSearchResult type,
final Long itemId, final String ipAddress, final Boolean rate)
throws EnMeExpcetion {
AccessRate recordAccessRate = new AccessRate();
if (ipAddress != null) {
if (type.equals(TypeSearchResult.TWEETPOLL)) {
// Find tweetPoll by itemId.
final TweetPoll tweetPoll = this.getTweetPoll(itemId);
Assert.assertNotNull(tweetPoll);
// Check if exist a previous tweetpoll access record.
recordAccessRate = this.checkExistTweetPollPreviousRecord(tweetPoll, ipAddress,
rate);
}
// Poll Acces rate item.
if (type.equals(TypeSearchResult.POLL)) {
// Find poll by itemId.
final Poll poll = this.getPoll(itemId);
Assert.assertNotNull(poll);
// Check if exist a previous poll access record.
recordAccessRate = this.checkExistPollPreviousRecord(poll, ipAddress,
rate);
}
// Survey Access rate item.
if (type.equals(TypeSearchResult.SURVEY)) {
// Find survey by itemId.
final Survey survey = this.getSurvey(itemId);
Assert.assertNotNull(survey);
// Check if exist a previous survey access record.
recordAccessRate = this.checkExistSurveyPreviousRecord(survey, ipAddress,
rate);
}
}
return recordAccessRate;
}
/**
* Check exist tweetPoll previous record.
* @param tpoll
* @param ipAddress
* @param option
* @throws EnMeExpcetion
*/
private AccessRate checkExistTweetPollPreviousRecord(final TweetPoll tpoll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by tweetPpll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
tpoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setTweetPollSocialOption(option,
tpoll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newTweetPollAccessRate(tpoll, ipAddress, option);
// update tweetPoll record.
this.setTweetPollSocialOption(option,
tpoll);
}
return accessRate;
}
/**
* Check exist Poll previous record.
* @param poll
* @param ipAddress
* @param option
* @return
* @throws EnMeExpcetion
*/
private AccessRate checkExistPollPreviousRecord(final Poll poll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by poll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
poll.getPollId(), TypeSearchResult.POLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setPollSocialOption(option,
poll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newPollAccessRate(poll, ipAddress, option);
// update poll record.
this.setPollSocialOption(option,
poll);
}
return accessRate;
}
/**
* Check exist Survey previous record.
* @param survey
* @param ipAddress
* @param option
* @return
* @throws EnMeExpcetion
*/
private AccessRate checkExistSurveyPreviousRecord(final Survey survey,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by survey in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
survey.getSid(), TypeSearchResult.SURVEY);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of survey
this.setSurveySocialOption(option, survey);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newSurveyAccessRate(survey, ipAddress, option);
// update poll record.
this.setSurveySocialOption(option,
survey);
}
return accessRate;
}
/**
* Set tweetpoll social options.
* @param socialOption
* @param tpoll
* @return
*/
private TweetPoll setTweetPollSocialOption(final Boolean socialOption,
final TweetPoll tpoll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = tpoll.getLikeVote() + valueSocialVote;
tpoll.setLikeVote(valueSocialVote);
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setDislikeVote(tpoll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(tpoll);
} else {
valueSocialVote = tpoll.getDislikeVote() + valueSocialVote;
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setLikeVote(tpoll.getLikeVote() == 0 ? 0 : optionValue);
tpoll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(tpoll);
}
return tpoll;
}
/**
* Set Poll social option.
* @param socialOption
* @param poll
* @return
*/
private Poll setPollSocialOption(final Boolean socialOption, final Poll poll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = poll.getLikeVote() + valueSocialVote;
poll.setLikeVote(valueSocialVote);
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setDislikeVote(poll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(poll);
} else {
valueSocialVote = poll.getDislikeVote() + valueSocialVote;
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setLikeVote(poll.getLikeVote() == 0 ? 0 : optionValue);
poll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(poll);
}
return poll;
}
/**
* Set Survey social option.
* @param socialOption
* @param survey
* @return
*/
private Survey setSurveySocialOption(final Boolean socialOption,
final Survey survey) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = survey.getLikeVote() + valueSocialVote;
survey.setLikeVote(valueSocialVote);
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setDislikeVote(survey.getDislikeVote() == 0 ? 0
: optionValue);
getTweetPollDao().saveOrUpdate(survey);
} else {
valueSocialVote = survey.getDislikeVote() + valueSocialVote;
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setLikeVote(survey.getLikeVote() == 0 ? 0 : optionValue);
survey.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(survey);
}
return survey;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getAccessRateItem(java.lang.String, java.lang.Long, org.encuestame.persistence.domain.TypeSearchResult)
*/
private List<AccessRate> getAccessRateItem(final String ipAddress,
final Long itemId, final TypeSearchResult searchby)
throws EnMeExpcetion {
final List<AccessRate> itemAccessList = getFrontEndDao()
.getAccessRatebyItem(ipAddress, itemId, searchby);
return itemAccessList;
}
/**
* New access rate item.
*
* @param tweetPoll
* @param poll
* @param survey
* @param ipAddress
* @param rate
* @return
*/
@Transactional(readOnly = false)
private AccessRate newAccessRateItem(final TweetPoll tweetPoll,
final Poll poll, final Survey survey, final String ipAddress,
final Boolean rate) {
final AccessRate itemRate = new AccessRate();
itemRate.setTweetPoll(tweetPoll);
itemRate.setPoll(poll);
itemRate.setSurvey(survey);
itemRate.setRate(rate);
itemRate.setUser(null);
itemRate.setIpAddress(ipAddress);
getTweetPollDao().saveOrUpdate(itemRate);
return itemRate;
}
/**
* New TweetPoll access rate.
*
* @param tweetPoll
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newTweetPollAccessRate(final TweetPoll tweetPoll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(tweetPoll, null, null, ipAddress, rate);
}
/**
* New Poll access rate.
*
* @param poll
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newPollAccessRate(final Poll poll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, poll, null, ipAddress, rate);
}
/**
* New Survey access rate.
* @param survey
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newSurveyAccessRate(final Survey survey,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, null, survey, ipAddress, rate);
}
/**
*
* @param id
* @return
* @throws EnMeNoResultsFoundException
*/
private TweetPoll getTweetPoll(final Long id) throws EnMeNoResultsFoundException{
return getTweetPollService().getTweetPollById(id);
}
private Integer getSocialAccountsLinksByItem(final TweetPoll tpoll, final Survey survey, final Poll poll, final TypeSearchResult itemType){
final List<TweetPollSavedPublishedStatus> totalAccounts = getTweetPollDao().getLinksByTweetPoll(tpoll, survey, poll, itemType);
return totalAccounts.size();
}
/**
* Get Relevance value by item.
* @param likeVote
* @param dislikeVote
* @param hits
* @param totalComments
* @param totalSocialAccounts
* @param totalNumberVotes
* @param totalHashTagHits
* @return
*/
private long getRelevanceValue(final long likeVote, final long dislikeVote,
final long hits, final long totalComments,
final long totalSocialAccounts, final long totalNumberVotes,
final long totalHashTagHits) {
final long relevanceValue = EnMeUtils.calculateRelevance(likeVote,
dislikeVote, hits, totalComments, totalSocialAccounts,
totalNumberVotes, totalHashTagHits);
log.info("*******************************");
log.info("******* Resume of Process *****");
log.info("-------------------------------");
log.info("| Total like votes : " + likeVote + " |");
log.info("| Total dislike votes : " + dislikeVote + " |");
log.info("| Total hits : " + hits + " |");
log.info("| Total Comments : " + totalComments + " |");
log.info("| Total Social Network : " + totalSocialAccounts + " |");
log.info("| Total Votes : " + totalNumberVotes + " |");
log.info("| Total HashTag hits : " + totalHashTagHits + " |");
log.info("-------------------------------");
log.info("*******************************");
log.info("************ Finished Start Relevance calculate job **************");
return relevanceValue;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#processItemstoCalculateRelevance(java.util.List, java.util.List, java.util.List, java.util.Calendar, java.util.Calendar)
*/
public void processItemstoCalculateRelevance(
final List<TweetPoll> tweetPollList,
final List<Poll> pollList,
final List<Survey> surveyList,
final Calendar datebefore,
final Calendar todayDate) {
long likeVote;
long dislikeVote;
long hits;
long relevance;
long comments;
long socialAccounts;
long numberVotes;
long hashTagHits;
for (TweetPoll tweetPoll : tweetPollList) {
likeVote = tweetPoll.getLikeVote() == null ? 0 : tweetPoll
.getLikeVote();
dislikeVote = tweetPoll.getDislikeVote() == null ? 0
: tweetPoll.getDislikeVote();
hits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
// final Long userId = tweetPoll.getEditorOwner().getUid();
socialAccounts = this.getSocialAccountsLinksByItem(tweetPoll, null, null, TypeSearchResult.TWEETPOLL);
numberVotes = tweetPoll.getNumbervotes();
comments = getTotalCommentsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
log.debug("Total comments by TweetPoll ---->" + comments);
hashTagHits = this.getHashTagHits(tweetPoll.getTweetPollId(), TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits, comments, socialAccounts, numberVotes, hashTagHits);
tweetPoll.setRelevance(relevance);
getTweetPollDao().saveOrUpdate(tweetPoll);
}
for (Poll poll : pollList) {
likeVote = poll.getLikeVote() == null ? 0 : poll.getLikeVote();
dislikeVote = poll.getDislikeVote() == null ? 0 : poll
.getDislikeVote();
hits = poll.getHits() == null ? 0 : poll.getHits();
socialAccounts = this.getSocialAccountsLinksByItem(null, null,
poll, TypeSearchResult.POLL);
numberVotes = poll.getNumbervotes();
comments = getTotalCommentsbyType(poll.getPollId(), TypeSearchResult.POLL);
log.debug("Total Comments by Poll ---->" + comments);
hashTagHits = this.getHashTagHits(poll.getPollId(),
TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits,
comments, socialAccounts, numberVotes, hashTagHits);
poll.setRelevance(relevance);
getPollDao().saveOrUpdate(poll);
}
}
/**
* Get total hash tag hits.
* @param id
* @param filterby
* @return
*/
private Long getHashTagHits(final Long id, final TypeSearchResult filterby){
final Long totalHashTagHits = getFrontEndDao().getTotalHitsbyType(id,
TypeSearchResult.HASHTAG);
return totalHashTagHits;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagHitsbyName(java.lang.String, org.encuestame.utils.enums.TypeSearchResult)
*/
public Long getHashTagHitsbyName(final String tagName, final TypeSearchResult filterBy){
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
final Long hits = this.getHashTagHits(tag.getHashTagId(), TypeSearchResult.HASHTAG);
return hits;
}
/**
* Get total comments by item type {@link TweetPoll}, {@link Poll} or {@link Survey}.
* @param itemId
* @param itemType
* @return
*/
private Long getTotalCommentsbyType(final Long itemId, final TypeSearchResult itemType){
final Long totalComments = getCommentsOperations().getTotalCommentsbyItem(itemId, itemType);
return totalComments;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTotalUsageByHashTag(java.lang.Long, java.lang.Integer, java.lang.Integer, java.lang.String)
*/
public Long getTotalUsageByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
// Validate if tag belongs to hashtag and filter isn't empty.
Long totalUsagebyHashTag = 0L;
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag != null) {
final List<TweetPoll> tweetsbyTag = this.getTweetPollsByHashTag(tagName, initResults, maxResults, filter);
final int totatTweetPolls = tweetsbyTag.size();
final List<Poll> pollsbyTag = this.getPollsByHashTag(tagName, initResults, maxResults, filter);
final int totalPolls = pollsbyTag.size();
final List<Survey> surveysbyTag = this.getSurveysByHashTag(tagName, initResults, maxResults, filter);
final int totalSurveys = surveysbyTag.size();
totalUsagebyHashTag = (long) (totatTweetPolls + totalPolls + totalSurveys);
}
return totalUsagebyHashTag;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getSocialNetworkUseByHashTag(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String)
*/
public Long getSocialNetworkUseByHashTag(final String tagName,
final Integer initResults, final Integer maxResults) {
// 1- Get tweetPoll, Polls o Survey
Long linksbyTweetPoll = 0L;
Long linksbyPoll = 0L;
Long totalSocialLinks = 0L;
linksbyTweetPoll = this.getTweetPollSocialNetworkLinksbyTag(tagName,
initResults, maxResults, TypeSearchResult.TWEETPOLL);
linksbyPoll = this.getPollsSocialNetworkLinksByTag(tagName,
initResults, maxResults, TypeSearchResult.POLL);
totalSocialLinks = linksbyTweetPoll + linksbyPoll;
return totalSocialLinks;
}
/**
* Get polls social network links by tag.
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private Long getPollsSocialNetworkLinksByTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByPoll = 0L;
final List<Poll> polls = this.getPollsByHashTag(tagName, initResults,
maxResults, filter);
for (Poll poll : polls) {
linksbyItem = getTweetPollDao().getSocialLinksByType(null, null,
poll, TypeSearchResult.POLL);
totalLinksByPoll = totalLinksByPoll + linksbyItem;
}
return totalLinksByPoll;
}
/**
* Get tweetPolls social network links by tag
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private Long getTweetPollSocialNetworkLinksbyTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByTweetPoll = 0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName,
initResults, maxResults, filter);
for (TweetPoll tweetPoll : tp) {
// Get total value by links
linksbyItem = getTweetPollDao().getSocialLinksByType(tweetPoll,
null, null, TypeSearchResult.TWEETPOLL);
totalLinksByTweetPoll = totalLinksByTweetPoll + linksbyItem;
}
return totalLinksByTweetPoll;
}
/**
* Get surveys by HashTag.
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<Survey> getSurveysByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Survey> surveysByTag = getSurveyDaoImp()
.getSurveysByHashTagName(tagName, initResults, maxResults,
filter);
return surveysByTag;
}
/**
* Get Polls by HashTag
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<Poll> getPollsByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Poll> pollsByTag = getPollDao().getPollByHashTagName(
tagName, initResults, maxResults, filter);
return pollsByTag;
}
/**
* Get TweetPolls by hashTag.
* @param tagId
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<TweetPoll> getTweetPollsByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
final List<TweetPoll> tweetsbyTag = getTweetPollDao()
.getTweetpollByHashTagName(tagName, initResults, maxResults, filter);
return tweetsbyTag;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagUsedOnItemsVoted(java.lang.String)
*/
public Long getHashTagUsedOnItemsVoted(final String tagName, final Integer initResults, final Integer maxResults){
Long totalVotesbyTweetPoll= 0L;
Long total=0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName, 0, 100, TypeSearchResult.HASHTAG);
for (TweetPoll tweetPoll : tp) {
totalVotesbyTweetPoll = getTweetPollDao().getTotalVotesByTweetPollId(tweetPoll.getTweetPollId());
total = total + totalVotesbyTweetPoll;
}
log.debug("Total HashTag used by Tweetpoll voted: " + total);
return total;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagRanking(java.lang.String)
*/
public List<HashTagRankingBean> getHashTagRanking(final String tagName) {
List<HashTagRanking> hashTagRankingList = getHashTagDao()
.getHashTagRankStats();
final Integer value = 1;
Integer position = 0;
final List<HashTagRankingBean> tagRankingBeanList = new ArrayList<HashTagRankingBean>();
final HashTagRankingBean tagRank = new HashTagRankingBean();
final HashTagRankingBean tagRankBef = new HashTagRankingBean();
final HashTagRankingBean tagRankAfter = new HashTagRankingBean();
final Integer hashTagRankListSize = hashTagRankingList.size() - value;
Integer positionBefore;
Integer positionAfter;
log.debug("Hashtag ranking list --->" + hashTagRankListSize);
for (int i = 0; i < hashTagRankingList.size(); i++) {
if (hashTagRankingList.get(i).getHashTag().getHashTag()
.equals(tagName)) {
// Retrieve hashtag main.
position = i;
tagRank.setAverage(hashTagRankingList.get(i).getAverage());
tagRank.setPosition(i);
tagRank.setTagName(tagName);
tagRank.setRankId(hashTagRankingList.get(i).getRankId());
tagRankingBeanList.add(tagRank);
log.debug("HashTag ranking main ---> "
+ hashTagRankingList.get(i).getHashTag().getHashTag());
log.debug("HashTag ranking main position---> " + position);
positionBefore = position - value;
positionAfter = position + value;
if ((position > 0) && (position < hashTagRankListSize)) {
log.debug(" --- HashTag ranking first option ---");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
} else if ((position > 0) && (position == hashTagRankListSize)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
} else if ((position == 0)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
}
}
}
Collections.sort(tagRankingBeanList);
return tagRankingBeanList;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#retrieveGenericStats(java.lang.String, org.encuestame.utils.enums.TypeSearchResult)
*/
public GenericStatsBean retrieveGenericStats(final String itemId, final TypeSearchResult itemType) throws EnMeNoResultsFoundException{
Long totalHits = 0L;
String createdBy = " ";
Date createdAt = null;
double average= 0;
Long likeDislikeRate = 0L;
Long likeVotes;
Long dislikeVotes;
Long id;
HashMap<Integer, RelativeTimeEnum> relative;
if (itemType.equals(TypeSearchResult.TWEETPOLL)) {
id = new Long(Long.parseLong(itemId));
final TweetPoll tweetPoll = this.getTweetPoll(id);
totalHits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
createdBy = tweetPoll.getEditorOwner().getUsername() == null ? "" : tweetPoll.getEditorOwner().getUsername();
createdAt = tweetPoll.getCreateDate();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = tweetPoll.getLikeVote() == null ? 0L : tweetPoll.getLikeVote();
dislikeVotes = tweetPoll.getDislikeVote() == null ? 0L : tweetPoll.getDislikeVote();
// Like/Dislike Rate = Total Like votes minus total dislike votes.
likeDislikeRate = (likeVotes - dislikeVotes);
} else if (itemType.equals(TypeSearchResult.POLL)) {
id = new Long(Long.parseLong(itemId));
final Poll poll = this.getPoll(id);
totalHits = poll.getHits() == null ? 0 : poll.getHits();
createdBy = poll.getEditorOwner().getUsername() ;
createdAt = poll.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = poll.getLikeVote() == null ? 0L : poll.getLikeVote();
dislikeVotes = poll.getDislikeVote() == null ? 0L : poll.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.SURVEY)) {
id = new Long(Long.parseLong(itemId));
final Survey survey = this.getSurvey(id);
totalHits = survey.getHits();
createdBy = survey.getEditorOwner().getUsername() == null ? " " : survey.getEditorOwner().getUsername();
createdAt = survey.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = survey.getLikeVote();
dislikeVotes = survey.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.HASHTAG)) {
final HashTag tag = getHashTagItem(itemId);
totalHits = tag.getHits();
createdAt = tag.getUpdatedDate();
relative = DateUtil.getRelativeTime(createdAt);
}
final GenericStatsBean genericBean = new GenericStatsBean();
genericBean.setLikeDislikeRate(likeDislikeRate);;
genericBean.setHits(totalHits);
genericBean.setCreatedBy(createdBy);
genericBean.setAverage(average);
genericBean.setCreatedAt(createdAt);
return genericBean;
}
public void retrieveHashTagGraphData(){
}
/**
* Get survey by id.
* @param id
* @return
* @throws EnMeNoResultsFoundException
*/
private Survey getSurvey(final Long id) throws EnMeNoResultsFoundException{
return getSurveyService().getSurveyById(id);
}
/**
* Get Poll by id.
* @param id
* @return
* @throws EnMePollNotFoundException
*/
private Poll getPoll(final Long id) throws EnMePollNotFoundException{
return getPollService().getPollById(id);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTopRatedProfile(java.lang.Boolean)
*/
public List<ProfileRatedTopBean> getTopRatedProfile(final Boolean status)
throws EnMeNoResultsFoundException {
Long topValue = 0L;
Long totalTweetPollPublished;
Long totalPollPublished;
Long total;
final List<UserAccount> users = getSecurityService()
.getUserAccountsAvailable(status);
final List<ProfileRatedTopBean> profiles = ConvertDomainBean
.convertUserAccountListToProfileRated(users);
for (ProfileRatedTopBean profileRatedTopBean : profiles) {
totalTweetPollPublished = getTweetPollDao().getTotalTweetPoll(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
totalPollPublished = getPollDao().getTotalPollsbyUser(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
total = totalTweetPollPublished + totalPollPublished;
topValue = topValue + total;
log.debug("total value asigned to -->" + totalTweetPollPublished);
profileRatedTopBean.setTopValue(topValue);
}
Collections.sort(profiles);
return profiles;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagLinks(org.encuestame.persistence.domain.HashTag)
*/
public List<LinksSocialBean> getHashTagLinks(final HashTag hash) {
final List<TweetPollSavedPublishedStatus> links = getFrontEndDao()
.getLinksByHomeItem(hash, null, null, null, null,
TypeSearchResult.HASHTAG);
log.debug("getTweetPollLinks "+links.size());
return ConvertDomainBean.convertTweetPollSavedPublishedStatus(links);
}
// Total Usage by item.
public void getTotalUsagebyHashTagAndDateRange(){
}
/**
* Create hashTag details stats.
* @param label
* @param value
* @return
*/
private HashTagDetailStats createTagDetailsStats(final String label, final Long value){
final HashTagDetailStats tagDetails = new HashTagDetailStats();
tagDetails.setLabel(label);
tagDetails.setValue(value);
return tagDetails;
}
/**
* Counter items by HashTag.
* @param month
* @param counter
* @return
*/
private Long counterItemsbyHashTag(final int month, Long counter){
switch(month) {
case 1:
counter ++;
break;
case 2:
counter ++;
break;
case 3:
counter ++;
break;
case 4:
counter ++;
break;
case 5:
counter ++;
break;
case 6:
counter ++;
break;
case 7:
counter ++;
break;
case 8:
counter ++;
break;
case 9:
counter ++;
break;
case 10:
counter ++;
break;
case 11:
counter ++;
break;
case 12:
counter ++;
break;
default:
log.debug("Month not found");
}
return counter;
}
/**
*
* @param tpolls
* @param polls
* @param surveys
* @param counter
* @return
*/
private DateTime getAfterOrCurrentlyItemCreationDate(
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counter) {
DateTime monthValue;
if (tpolls != null) {
monthValue = new DateTime(tpolls.get(counter).getCreateDate());
} else if (polls != null) {
monthValue = new DateTime(polls.get(counter).getCreatedAt());
} else {
monthValue = new DateTime(surveys.get(counter).getCreatedAt());
}
return monthValue;
}
/**
*
* @param tpolls
* @param polls
* @param surveys
* @return
*/
private List<HashTagDetailStats> getTagDetail(final List<TweetPoll> tpolls,
final List<Poll> polls, final List<Survey> surveys) {
// Tamano del array segun venga.
int totalList = 0;
List<HashTagDetailStats> statDetail = new ArrayList<HashTagDetailStats>();
if (tpolls != null) {
totalList = tpolls.size();
System.out.println(" Tweetpolls List size --->" + tpolls.size());
} else if (polls != null) {
totalList = polls.size();
} else {
totalList = surveys.size();
}
int counterI = 0;
if (totalList > 0) {
log.debug(" Total items by hashTag ---> " + totalList);
for (int i = 0; i < totalList; i++) {
statDetail = this.addHashTagStatsDetail(totalList, tpolls, polls, surveys, i);
}
} else
log.error("Items by HashTag not found");
return statDetail;
}
private List<HashTagDetailStats> addHashTagStatsDetail(final int totalList,
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counterIValue) {
int month = 0;
Long counterTweetPoll = 0L;
int afterMonth = 0;
int counterAfterMonthValue = 0;
HashTagDetailStats tagDetail = new HashTagDetailStats();
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
DateTime currentlyMonth = this.getAfterOrCurrentlyItemCreationDate(
tpolls, polls, surveys, counterIValue);
month = currentlyMonth.getMonthOfYear();
if (counterIValue < totalList - 1) {
counterAfterMonthValue = counterAfterMonthValue + 1;
DateTime dt2 = this.getAfterOrCurrentlyItemCreationDate(tpolls,
polls, surveys, counterAfterMonthValue);
afterMonth = dt2.getMonthOfYear();
System.out.println(" Currently month --> " + month + " After month --> " + afterMonth);
} else {
counterAfterMonthValue = counterIValue;
afterMonth = 0;
}
counterTweetPoll = this.counterItemsbyHashTag(month, counterTweetPoll);
if (month != afterMonth) {
System.out.println(" \n Added month --> " + month);
tagDetail = this.createTagDetailsStats(String.valueOf(month),
counterTweetPoll);
tagStatsDetail.add(tagDetail);
counterTweetPoll = 0L;
}
return tagStatsDetail;
}
private List<HashTagDetailStats> getTotalTweetPollUsageByHashTagAndDateRange(
final String tagName, final Integer period,
final Integer startResults, final Integer maxResults) {
List<TweetPoll> tweetPollsByHashTag = new ArrayList<TweetPoll>();
List<HashTagDetailStats> tagStatsDetailbyTweetPoll = new ArrayList<HashTagDetailStats>();
tweetPollsByHashTag = getTweetPollDao()
.getTweetPollsbyHashTagNameAndDateRange(tagName, period,
startResults, maxResults);
System.out.println(" Tweetpolls List por HashTag --->" + tweetPollsByHashTag.size());
// Obtiene el detalle de hashtags por tweetpoll.
tagStatsDetailbyTweetPoll = this.getTagDetail(tweetPollsByHashTag,
null, null);
System.out.println(" tagStatsDetailbyTweetPoll --->" + tweetPollsByHashTag.size());
return tagStatsDetailbyTweetPoll;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTotalUsagebyHashTagAndDateRange(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Integer)
*/
public List<HashTagDetailStats> getTotalUsagebyHashTagAndDateRange(
final String hashTagName, final Integer period,
final Integer startResults, final Integer maxResults)
throws EnMeNoResultsFoundException {
final HashTag tag = this.getHashTag(hashTagName, Boolean.TRUE);
// Get tweetPoll List
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
System.out.println("Tag Stats Detail Total --->" + tagStatsDetail);
if (tag != null) {
tagStatsDetail = this.getTotalTweetPollUsageByHashTagAndDateRange(hashTagName, period, startResults, maxResults);
//int month = 0;
//Long counterTweetPoll = 0L;
//int afterMonth = 0;
//int totalList = tweetPollsByHashTag.size();
//int counterI = 0;
}
return tagStatsDetail;
}
/**
* @return the tweetPollService
*/
public TweetPollService getTweetPollService() {
return tweetPollService;
}
/**
* @param tweetPollService the tweetPollService to set
*/
public void setTweetPollService(TweetPollService tweetPollService) {
this.tweetPollService = tweetPollService;
}
/**
* @return the pollService
*/
public PollService getPollService() {
return pollService;
}
/**
* @param pollService the pollService to set
*/
public void setPollService(final PollService pollService) {
this.pollService = pollService;
}
/**
* @return the surveyService
*/
public SurveyService getSurveyService() {
return surveyService;
}
/**
* @param surveyService the surveyService to set
*/
public void setSurveyService(final SurveyService surveyService) {
this.surveyService = surveyService;
}
/**
* @return the securityService
*/
public SecurityOperations getSecurityService() {
return securityService;
}
/**
* @param securityService the securityService to set
*/
public void setSecurityService(SecurityOperations securityService) {
this.securityService = securityService;
}
}
| encuestame-business/src/main/java/org/encuestame/business/service/FrontEndService.java | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
************************************************************************************
*/
package org.encuestame.business.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.encuestame.core.service.AbstractBaseService;
import org.encuestame.core.service.imp.IFrontEndService;
import org.encuestame.core.service.imp.SecurityOperations;
import org.encuestame.core.util.ConvertDomainBean;
import org.encuestame.core.util.EnMeUtils;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.HashTagRanking;
import org.encuestame.persistence.domain.Hit;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSavedPublishedStatus;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.persistence.exception.EnMePollNotFoundException;
import org.encuestame.persistence.exception.EnMeSearchException;
import org.encuestame.utils.DateUtil;
import org.encuestame.utils.RelativeTimeEnum;
import org.encuestame.utils.enums.SearchPeriods;
import org.encuestame.utils.enums.TypeSearchResult;
import org.encuestame.utils.json.HomeBean;
import org.encuestame.utils.json.LinksSocialBean;
import org.encuestame.utils.json.TweetPollBean;
import org.encuestame.utils.web.HashTagBean;
import org.encuestame.utils.web.PollBean;
import org.encuestame.utils.web.ProfileRatedTopBean;
import org.encuestame.utils.web.SurveyBean;
import org.encuestame.utils.web.stats.GenericStatsBean;
import org.encuestame.utils.web.stats.HashTagDetailStats;
import org.encuestame.utils.web.stats.HashTagRankingBean;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Front End Service.
* @author Picado, Juan juanATencuestame.org
* @since Oct 17, 2010 11:29:38 AM
* @version $Id:$
*/
@Service
public class FrontEndService extends AbstractBaseService implements IFrontEndService {
/** Front End Service Log. **/
private Logger log = Logger.getLogger(this.getClass());
/** Max Results. **/
private final Integer MAX_RESULTS = 15;
/** **/
@Autowired
private TweetPollService tweetPollService;
/** {@link PollService} **/
@Autowired
private PollService pollService;
/** {@link SurveyService} **/
@Autowired
private SurveyService surveyService;
/** {@link SecurityOperations} **/
@Autowired
private SecurityOperations securityService;
/**
* Search Items By tweetPoll.
* @param maxResults limit of results to return.
* @return result of the search.
* @throws EnMeSearchException search exception.
*/
public List<TweetPollBean> searchItemsByTweetPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request)
throws EnMeSearchException{
final List<TweetPollBean> results = new ArrayList<TweetPollBean>();
if(maxResults == null){
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results: "+maxResults);
log.debug("Period Results: "+period);
final List<TweetPoll> items = new ArrayList<TweetPoll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndAllTime(start, maxResults));
}
results.addAll(ConvertDomainBean.convertListToTweetPollBean(items));
for (TweetPollBean tweetPoll : results) {
//log.debug("Iterate Home TweetPoll id: "+tweetPoll.getId());
//log.debug("Iterate Home Tweetpoll Hashtag Size: "+tweetPoll.getHashTags().size());
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
tweetPoll.setTotalComments(this.getTotalCommentsbyType(tweetPoll.getId(), TypeSearchResult.TWEETPOLL));
}
}
log.debug("Search Items by TweetPoll: "+results.size());
return results;
}
/**
*
*/
public List<SurveyBean> searchItemsBySurvey(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
final List<SurveyBean> results = new ArrayList<SurveyBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results " + maxResults);
final List<Survey> items = new ArrayList<Survey>();
if (period == null) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods
.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast7Days(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast30Days(
start, maxResults));
} else if (periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getSurveyFrontEndAllTime(start,
maxResults));
}
log.debug("TweetPoll " + items.size());
results.addAll(ConvertDomainBean.convertListSurveyToBean(items));
for (SurveyBean surveyBean : results) {
surveyBean.setTotalComments(this.getTotalCommentsbyType(surveyBean.getSid(), TypeSearchResult.SURVEY));
}
}
return results;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getFrontEndItems(java.lang.String, java.lang.Integer, java.lang.Integer, javax.servlet.http.HttpServletRequest)
*/
public List<HomeBean> getFrontEndItems(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
// Sorted list based comparable interface
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this.searchItemsByTweetPoll(
period, start, maxResults, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
final List<PollBean> pollItems = this.searchItemsByPoll(period, start,
maxResults);
log.debug("FrontEnd Poll items size :" + pollItems.size());
allItems.addAll(ConvertDomainBean.convertPollListToHomeBean(pollItems));
final List<SurveyBean> surveyItems = this.searchItemsBySurvey(period,
start, maxResults, request);
log.debug("FrontEnd Survey items size :" + surveyItems.size());
allItems.addAll(ConvertDomainBean
.convertSurveyListToHomeBean(surveyItems));
log.debug("Home bean list size :" + allItems.size());
Collections.sort(allItems);
return allItems;
}
/**
* Search items by poll.
* @param period
* @param maxResults
* @return
* @throws EnMeSearchException
*/
public List<PollBean> searchItemsByPoll(
final String period,
final Integer start,
Integer maxResults)
throws EnMeSearchException{
final List<PollBean> results = new ArrayList<PollBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<Poll> items = new ArrayList<Poll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)){
items.addAll(getFrontEndDao().getPollFrontEndAllTime(start, maxResults));
}
log.debug("Poll "+items.size());
results.addAll(ConvertDomainBean.convertListToPollBean((items)));
for (PollBean pollbean : results) {
pollbean.setTotalComments(this.getTotalCommentsbyType(pollbean.getId(), TypeSearchResult.POLL));
}
}
return results;
}
public void search(){
}
/**
* Get hashTags
* @param maxResults the max results to display
* @param start to pagination propose.
* @return List of {@link HashTagBean}
*/
public List<HashTagBean> getHashTags(
Integer maxResults,
final Integer start,
final String tagCriteria) {
final List<HashTagBean> hashBean = new ArrayList<HashTagBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<HashTag> tags = getHashTagDao().getHashTags(maxResults, start, tagCriteria);
hashBean.addAll(ConvertDomainBean.convertListHashTagsToBean(tags));
return hashBean;
}
/**
* Get hashTag item.
* @param tagName
* @return
* @throws EnMeNoResultsFoundException
*/
public HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException {
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag == null){
throw new EnMeNoResultsFoundException("hashtag not found");
}
return tag;
}
/**
* Get TweetPolls by hashTag id.
* @param hashTagId
* @param limit
* @return
*/
public List<TweetPollBean> getTweetPollsbyHashTagName(
final String tagName,
final Integer initResults,
final Integer limit,
final String filter,
final HttpServletRequest request){
final List<TweetPoll> tweetPolls = getTweetPollDao().getTweetpollByHashTagName(tagName, initResults, limit, TypeSearchResult.getTypeSearchResult(filter));
log.debug("TweetPoll by HashTagId total size ---> "+tweetPolls.size());
final List<TweetPollBean> tweetPollBean = ConvertDomainBean.convertListToTweetPollBean(tweetPolls);
for (TweetPollBean tweetPoll : tweetPollBean) {
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
}
return tweetPollBean;
}
public List<HomeBean> searchLastPublicationsbyHashTag(
final HashTag hashTag, final String keyword,
final Integer initResults, final Integer limit,
final String filter, final HttpServletRequest request) {
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this
.getTweetPollsbyHashTagName(hashTag.getHashTag(), initResults,
limit, filter, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
Collections.sort(allItems);
return allItems;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#checkPreviousHit(java.lang.String, java.lang.Long, java.lang.String)
*/
public Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby){
boolean hit = false;
final List<Hit> hitList = getFrontEndDao().getHitsByIpAndType(ipAddress, id, searchHitby);
try {
if(hitList.size() == 1){
if(hitList.get(0).getIpAddress().equals(ipAddress)){
hit = true;
}
}
else if(hitList.size() > 1){
log.error("List cant'be greater than one");
}
} catch (Exception e) {
log.error(e);
}
return hit;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#registerHit(org.encuestame.persistence.domain.tweetpoll.TweetPoll, org.encuestame.persistence.domain.survey.Poll, org.encuestame.persistence.domain.survey.Survey, org.encuestame.persistence.domain.HashTag, java.lang.String)
*/
public Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ip) throws EnMeNoResultsFoundException{
final Hit hit ;
Long hitCount = 1L;
Boolean register = false;
// HashTag
if (ip != null){
if (tag != null){
hit = this.newHashTagHit(tag, ip);
hitCount = tag.getHits() == null ? 0L : tag.getHits() + hitCount;
tag.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tag);
register = true;
}
else if(tweetPoll != null){
hit = this.newTweetPollHit(tweetPoll, ip);
hitCount = tweetPoll.getHits() + hitCount;
tweetPoll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tweetPoll);
register = true;
}
else if(poll != null){
hit = this.newPollHit(poll, ip);
hitCount = poll.getHits() + hitCount;
poll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(poll);
register = true;
}
else if(survey != null ){
hit = this.newSurveyHit(survey, ip);
hitCount = survey.getHits() + hitCount;
survey.setHits(hitCount);
getFrontEndDao().saveOrUpdate(survey);
register = true;
}
}
return register;
}
/**
* New hit item.
* @param tweetPoll
* @param poll
* @param survey
* @param tag
* @param ipAddress
* @return
*/
@Transactional(readOnly = false)
private Hit newHitItem(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ipAddress) {
final Hit hitItem = new Hit();
hitItem.setHitDate(Calendar.getInstance().getTime());
hitItem.setHashTag(tag);
hitItem.setIpAddress(ipAddress);
hitItem.setTweetPoll(tweetPoll);
hitItem.setPoll(poll);
hitItem.setSurvey(survey);
getFrontEndDao().saveOrUpdate(hitItem);
return hitItem;
}
/**
* New tweet poll hit item.
* @param tweetPoll
* @param ipAddress
* @return
*/
private Hit newTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
return this.newHitItem(tweetPoll, null, null, null, ipAddress);
}
/**
* New poll hit item.
* @param poll
* @param ipAddress
* @return
*/
private Hit newPollHit(final Poll poll, final String ipAddress){
return this.newHitItem(null, poll, null, null, ipAddress);
}
/**
* New hash tag hit item.
* @param tag
* @param ipAddress
* @return
*/
private Hit newHashTagHit(final HashTag tag, final String ipAddress){
return this.newHitItem(null, null, null, tag, ipAddress);
}
/**
* New survey hit item.
* @param survey
* @param ipAddress
* @return
*/
private Hit newSurveyHit(final Survey survey, final String ipAddress){
return this.newHitItem(null, null, survey, null, ipAddress);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#registerAccessRate(org.encuestame.persistence.domain.TypeSearchResult, java.lang.Long, java.lang.String, java.lang.Boolean)
*/
public AccessRate registerAccessRate(final TypeSearchResult type,
final Long itemId, final String ipAddress, final Boolean rate)
throws EnMeExpcetion {
AccessRate recordAccessRate = new AccessRate();
if (ipAddress != null) {
if (type.equals(TypeSearchResult.TWEETPOLL)) {
// Find tweetPoll by itemId.
final TweetPoll tweetPoll = this.getTweetPoll(itemId);
Assert.assertNotNull(tweetPoll);
// Check if exist a previous tweetpoll access record.
recordAccessRate = this.checkExistTweetPollPreviousRecord(tweetPoll, ipAddress,
rate);
}
// Poll Acces rate item.
if (type.equals(TypeSearchResult.POLL)) {
// Find poll by itemId.
final Poll poll = this.getPoll(itemId);
Assert.assertNotNull(poll);
// Check if exist a previous poll access record.
recordAccessRate = this.checkExistPollPreviousRecord(poll, ipAddress,
rate);
}
// Survey Access rate item.
if (type.equals(TypeSearchResult.SURVEY)) {
// Find survey by itemId.
final Survey survey = this.getSurvey(itemId);
Assert.assertNotNull(survey);
// Check if exist a previous survey access record.
recordAccessRate = this.checkExistSurveyPreviousRecord(survey, ipAddress,
rate);
}
}
return recordAccessRate;
}
/**
* Check exist tweetPoll previous record.
* @param tpoll
* @param ipAddress
* @param option
* @throws EnMeExpcetion
*/
private AccessRate checkExistTweetPollPreviousRecord(final TweetPoll tpoll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by tweetPpll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
tpoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setTweetPollSocialOption(option,
tpoll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newTweetPollAccessRate(tpoll, ipAddress, option);
// update tweetPoll record.
this.setTweetPollSocialOption(option,
tpoll);
}
return accessRate;
}
/**
* Check exist Poll previous record.
* @param poll
* @param ipAddress
* @param option
* @return
* @throws EnMeExpcetion
*/
private AccessRate checkExistPollPreviousRecord(final Poll poll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by poll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
poll.getPollId(), TypeSearchResult.POLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setPollSocialOption(option,
poll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newPollAccessRate(poll, ipAddress, option);
// update poll record.
this.setPollSocialOption(option,
poll);
}
return accessRate;
}
/**
* Check exist Survey previous record.
* @param survey
* @param ipAddress
* @param option
* @return
* @throws EnMeExpcetion
*/
private AccessRate checkExistSurveyPreviousRecord(final Survey survey,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by survey in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
survey.getSid(), TypeSearchResult.SURVEY);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of survey
this.setSurveySocialOption(option, survey);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newSurveyAccessRate(survey, ipAddress, option);
// update poll record.
this.setSurveySocialOption(option,
survey);
}
return accessRate;
}
/**
* Set tweetpoll social options.
* @param socialOption
* @param tpoll
* @return
*/
private TweetPoll setTweetPollSocialOption(final Boolean socialOption,
final TweetPoll tpoll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = tpoll.getLikeVote() + valueSocialVote;
tpoll.setLikeVote(valueSocialVote);
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setDislikeVote(tpoll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(tpoll);
} else {
valueSocialVote = tpoll.getDislikeVote() + valueSocialVote;
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setLikeVote(tpoll.getLikeVote() == 0 ? 0 : optionValue);
tpoll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(tpoll);
}
return tpoll;
}
/**
* Set Poll social option.
* @param socialOption
* @param poll
* @return
*/
private Poll setPollSocialOption(final Boolean socialOption, final Poll poll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = poll.getLikeVote() + valueSocialVote;
poll.setLikeVote(valueSocialVote);
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setDislikeVote(poll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(poll);
} else {
valueSocialVote = poll.getDislikeVote() + valueSocialVote;
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setLikeVote(poll.getLikeVote() == 0 ? 0 : optionValue);
poll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(poll);
}
return poll;
}
/**
* Set Survey social option.
* @param socialOption
* @param survey
* @return
*/
private Survey setSurveySocialOption(final Boolean socialOption,
final Survey survey) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = survey.getLikeVote() + valueSocialVote;
survey.setLikeVote(valueSocialVote);
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setDislikeVote(survey.getDislikeVote() == 0 ? 0
: optionValue);
getTweetPollDao().saveOrUpdate(survey);
} else {
valueSocialVote = survey.getDislikeVote() + valueSocialVote;
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setLikeVote(survey.getLikeVote() == 0 ? 0 : optionValue);
survey.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(survey);
}
return survey;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getAccessRateItem(java.lang.String, java.lang.Long, org.encuestame.persistence.domain.TypeSearchResult)
*/
private List<AccessRate> getAccessRateItem(final String ipAddress,
final Long itemId, final TypeSearchResult searchby)
throws EnMeExpcetion {
final List<AccessRate> itemAccessList = getFrontEndDao()
.getAccessRatebyItem(ipAddress, itemId, searchby);
return itemAccessList;
}
/**
* New access rate item.
*
* @param tweetPoll
* @param poll
* @param survey
* @param ipAddress
* @param rate
* @return
*/
@Transactional(readOnly = false)
private AccessRate newAccessRateItem(final TweetPoll tweetPoll,
final Poll poll, final Survey survey, final String ipAddress,
final Boolean rate) {
final AccessRate itemRate = new AccessRate();
itemRate.setTweetPoll(tweetPoll);
itemRate.setPoll(poll);
itemRate.setSurvey(survey);
itemRate.setRate(rate);
itemRate.setUser(null);
itemRate.setIpAddress(ipAddress);
getTweetPollDao().saveOrUpdate(itemRate);
return itemRate;
}
/**
* New TweetPoll access rate.
*
* @param tweetPoll
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newTweetPollAccessRate(final TweetPoll tweetPoll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(tweetPoll, null, null, ipAddress, rate);
}
/**
* New Poll access rate.
*
* @param poll
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newPollAccessRate(final Poll poll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, poll, null, ipAddress, rate);
}
/**
* New Survey access rate.
* @param survey
* @param ipAddress
* @param rate
* @return
*/
private AccessRate newSurveyAccessRate(final Survey survey,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, null, survey, ipAddress, rate);
}
/**
*
* @param id
* @return
* @throws EnMeNoResultsFoundException
*/
private TweetPoll getTweetPoll(final Long id) throws EnMeNoResultsFoundException{
return getTweetPollService().getTweetPollById(id);
}
private Integer getSocialAccountsLinksByItem(final TweetPoll tpoll, final Survey survey, final Poll poll, final TypeSearchResult itemType){
final List<TweetPollSavedPublishedStatus> totalAccounts = getTweetPollDao().getLinksByTweetPoll(tpoll, survey, poll, itemType);
return totalAccounts.size();
}
/**
* Get Relevance value by item.
* @param likeVote
* @param dislikeVote
* @param hits
* @param totalComments
* @param totalSocialAccounts
* @param totalNumberVotes
* @param totalHashTagHits
* @return
*/
private long getRelevanceValue(final long likeVote, final long dislikeVote,
final long hits, final long totalComments,
final long totalSocialAccounts, final long totalNumberVotes,
final long totalHashTagHits) {
final long relevanceValue = EnMeUtils.calculateRelevance(likeVote,
dislikeVote, hits, totalComments, totalSocialAccounts,
totalNumberVotes, totalHashTagHits);
log.info("*******************************");
log.info("******* Resume of Process *****");
log.info("-------------------------------");
log.info("| Total like votes : " + likeVote + " |");
log.info("| Total dislike votes : " + dislikeVote + " |");
log.info("| Total hits : " + hits + " |");
log.info("| Total Comments : " + totalComments + " |");
log.info("| Total Social Network : " + totalSocialAccounts + " |");
log.info("| Total Votes : " + totalNumberVotes + " |");
log.info("| Total HashTag hits : " + totalHashTagHits + " |");
log.info("-------------------------------");
log.info("*******************************");
log.info("************ Finished Start Relevance calculate job **************");
return relevanceValue;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#processItemstoCalculateRelevance(java.util.List, java.util.List, java.util.List, java.util.Calendar, java.util.Calendar)
*/
public void processItemstoCalculateRelevance(
final List<TweetPoll> tweetPollList,
final List<Poll> pollList,
final List<Survey> surveyList,
final Calendar datebefore,
final Calendar todayDate) {
long likeVote;
long dislikeVote;
long hits;
long relevance;
long comments;
long socialAccounts;
long numberVotes;
long hashTagHits;
for (TweetPoll tweetPoll : tweetPollList) {
likeVote = tweetPoll.getLikeVote() == null ? 0 : tweetPoll
.getLikeVote();
dislikeVote = tweetPoll.getDislikeVote() == null ? 0
: tweetPoll.getDislikeVote();
hits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
// final Long userId = tweetPoll.getEditorOwner().getUid();
socialAccounts = this.getSocialAccountsLinksByItem(tweetPoll, null, null, TypeSearchResult.TWEETPOLL);
numberVotes = tweetPoll.getNumbervotes();
comments = getTotalCommentsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
log.debug("Total comments by TweetPoll ---->" + comments);
hashTagHits = this.getHashTagHits(tweetPoll.getTweetPollId(), TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits, comments, socialAccounts, numberVotes, hashTagHits);
tweetPoll.setRelevance(relevance);
getTweetPollDao().saveOrUpdate(tweetPoll);
}
for (Poll poll : pollList) {
likeVote = poll.getLikeVote() == null ? 0 : poll.getLikeVote();
dislikeVote = poll.getDislikeVote() == null ? 0 : poll
.getDislikeVote();
hits = poll.getHits() == null ? 0 : poll.getHits();
socialAccounts = this.getSocialAccountsLinksByItem(null, null,
poll, TypeSearchResult.POLL);
numberVotes = poll.getNumbervotes();
comments = getTotalCommentsbyType(poll.getPollId(), TypeSearchResult.POLL);
log.debug("Total Comments by Poll ---->" + comments);
hashTagHits = this.getHashTagHits(poll.getPollId(),
TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits,
comments, socialAccounts, numberVotes, hashTagHits);
poll.setRelevance(relevance);
getPollDao().saveOrUpdate(poll);
}
}
/**
* Get total hash tag hits.
* @param id
* @param filterby
* @return
*/
private Long getHashTagHits(final Long id, final TypeSearchResult filterby){
final Long totalHashTagHits = getFrontEndDao().getTotalHitsbyType(id,
TypeSearchResult.HASHTAG);
return totalHashTagHits;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagHitsbyName(java.lang.String, org.encuestame.utils.enums.TypeSearchResult)
*/
public Long getHashTagHitsbyName(final String tagName, final TypeSearchResult filterBy){
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
final Long hits = this.getHashTagHits(tag.getHashTagId(), TypeSearchResult.HASHTAG);
return hits;
}
/**
* Get total comments by item type {@link TweetPoll}, {@link Poll} or {@link Survey}.
* @param itemId
* @param itemType
* @return
*/
private Long getTotalCommentsbyType(final Long itemId, final TypeSearchResult itemType){
final Long totalComments = getCommentsOperations().getTotalCommentsbyItem(itemId, itemType);
return totalComments;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTotalUsageByHashTag(java.lang.Long, java.lang.Integer, java.lang.Integer, java.lang.String)
*/
public Long getTotalUsageByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
// Validate if tag belongs to hashtag and filter isn't empty.
Long totalUsagebyHashTag = 0L;
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag != null) {
final List<TweetPoll> tweetsbyTag = this.getTweetPollsByHashTag(tagName, initResults, maxResults, filter);
final int totatTweetPolls = tweetsbyTag.size();
final List<Poll> pollsbyTag = this.getPollsByHashTag(tagName, initResults, maxResults, filter);
final int totalPolls = pollsbyTag.size();
final List<Survey> surveysbyTag = this.getSurveysByHashTag(tagName, initResults, maxResults, filter);
final int totalSurveys = surveysbyTag.size();
totalUsagebyHashTag = (long) (totatTweetPolls + totalPolls + totalSurveys);
}
return totalUsagebyHashTag;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getSocialNetworkUseByHashTag(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String)
*/
public Long getSocialNetworkUseByHashTag(final String tagName,
final Integer initResults, final Integer maxResults) {
// 1- Get tweetPoll, Polls o Survey
Long linksbyTweetPoll = 0L;
Long linksbyPoll = 0L;
Long totalSocialLinks = 0L;
linksbyTweetPoll = this.getTweetPollSocialNetworkLinksbyTag(tagName,
initResults, maxResults, TypeSearchResult.TWEETPOLL);
linksbyPoll = this.getPollsSocialNetworkLinksByTag(tagName,
initResults, maxResults, TypeSearchResult.POLL);
totalSocialLinks = linksbyTweetPoll + linksbyPoll;
return totalSocialLinks;
}
/**
* Get polls social network links by tag.
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private Long getPollsSocialNetworkLinksByTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByPoll = 0L;
final List<Poll> polls = this.getPollsByHashTag(tagName, initResults,
maxResults, filter);
for (Poll poll : polls) {
linksbyItem = getTweetPollDao().getSocialLinksByType(null, null,
poll, TypeSearchResult.POLL);
totalLinksByPoll = totalLinksByPoll + linksbyItem;
}
return totalLinksByPoll;
}
/**
* Get tweetPolls social network links by tag
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private Long getTweetPollSocialNetworkLinksbyTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByTweetPoll = 0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName,
initResults, maxResults, filter);
for (TweetPoll tweetPoll : tp) {
// Get total value by links
linksbyItem = getTweetPollDao().getSocialLinksByType(tweetPoll,
null, null, TypeSearchResult.TWEETPOLL);
totalLinksByTweetPoll = totalLinksByTweetPoll + linksbyItem;
}
return totalLinksByTweetPoll;
}
/**
* Get surveys by HashTag.
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<Survey> getSurveysByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Survey> surveysByTag = getSurveyDaoImp()
.getSurveysByHashTagName(tagName, initResults, maxResults,
filter);
return surveysByTag;
}
/**
* Get Polls by HashTag
* @param tagName
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<Poll> getPollsByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Poll> pollsByTag = getPollDao().getPollByHashTagName(
tagName, initResults, maxResults, filter);
return pollsByTag;
}
/**
* Get TweetPolls by hashTag.
* @param tagId
* @param initResults
* @param maxResults
* @param filter
* @return
*/
private List<TweetPoll> getTweetPollsByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
final List<TweetPoll> tweetsbyTag = getTweetPollDao()
.getTweetpollByHashTagName(tagName, initResults, maxResults, filter);
return tweetsbyTag;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagUsedOnItemsVoted(java.lang.String)
*/
public Long getHashTagUsedOnItemsVoted(final String tagName, final Integer initResults, final Integer maxResults){
Long totalVotesbyTweetPoll= 0L;
Long total=0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName, 0, 100, TypeSearchResult.HASHTAG);
for (TweetPoll tweetPoll : tp) {
totalVotesbyTweetPoll = getTweetPollDao().getTotalVotesByTweetPollId(tweetPoll.getTweetPollId());
total = total + totalVotesbyTweetPoll;
}
log.debug("Total HashTag used by Tweetpoll voted: " + total);
return total;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagRanking(java.lang.String)
*/
public List<HashTagRankingBean> getHashTagRanking(final String tagName) {
List<HashTagRanking> hashTagRankingList = getHashTagDao()
.getHashTagRankStats();
final Integer value = 1;
Integer position = 0;
final List<HashTagRankingBean> tagRankingBeanList = new ArrayList<HashTagRankingBean>();
final HashTagRankingBean tagRank = new HashTagRankingBean();
final HashTagRankingBean tagRankBef = new HashTagRankingBean();
final HashTagRankingBean tagRankAfter = new HashTagRankingBean();
final Integer hashTagRankListSize = hashTagRankingList.size() - value;
Integer positionBefore;
Integer positionAfter;
log.debug("Hashtag ranking list --->" + hashTagRankListSize);
for (int i = 0; i < hashTagRankingList.size(); i++) {
if (hashTagRankingList.get(i).getHashTag().getHashTag()
.equals(tagName)) {
// Retrieve hashtag main.
position = i;
tagRank.setAverage(hashTagRankingList.get(i).getAverage());
tagRank.setPosition(i);
tagRank.setTagName(tagName);
tagRank.setRankId(hashTagRankingList.get(i).getRankId());
tagRankingBeanList.add(tagRank);
log.debug("HashTag ranking main ---> "
+ hashTagRankingList.get(i).getHashTag().getHashTag());
log.debug("HashTag ranking main position---> " + position);
positionBefore = position - value;
positionAfter = position + value;
if ((position > 0) && (position < hashTagRankListSize)) {
log.debug(" --- HashTag ranking first option ---");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
} else if ((position > 0) && (position == hashTagRankListSize)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
} else if ((position == 0)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
}
}
}
Collections.sort(tagRankingBeanList);
return tagRankingBeanList;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#retrieveGenericStats(java.lang.String, org.encuestame.utils.enums.TypeSearchResult)
*/
public GenericStatsBean retrieveGenericStats(final String itemId, final TypeSearchResult itemType) throws EnMeNoResultsFoundException{
Long totalHits = 0L;
String createdBy = " ";
Date createdAt = null;
double average= 0;
Long likeDislikeRate = 0L;
Long likeVotes;
Long dislikeVotes;
Long id;
HashMap<Integer, RelativeTimeEnum> relative;
if (itemType.equals(TypeSearchResult.TWEETPOLL)) {
id = new Long(Long.parseLong(itemId));
final TweetPoll tweetPoll = this.getTweetPoll(id);
totalHits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
createdBy = tweetPoll.getEditorOwner().getUsername() == null ? "" : tweetPoll.getEditorOwner().getUsername();
createdAt = tweetPoll.getCreateDate();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = tweetPoll.getLikeVote() == null ? 0L : tweetPoll.getLikeVote();
dislikeVotes = tweetPoll.getDislikeVote() == null ? 0L : tweetPoll.getDislikeVote();
// Like/Dislike Rate = Total Like votes minus total dislike votes.
likeDislikeRate = (likeVotes - dislikeVotes);
} else if (itemType.equals(TypeSearchResult.POLL)) {
id = new Long(Long.parseLong(itemId));
final Poll poll = this.getPoll(id);
totalHits = poll.getHits() == null ? 0 : poll.getHits();
createdBy = poll.getEditorOwner().getUsername() ;
createdAt = poll.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = poll.getLikeVote() == null ? 0L : poll.getLikeVote();
dislikeVotes = poll.getDislikeVote() == null ? 0L : poll.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.SURVEY)) {
id = new Long(Long.parseLong(itemId));
final Survey survey = this.getSurvey(id);
totalHits = survey.getHits();
createdBy = survey.getEditorOwner().getUsername() == null ? " " : survey.getEditorOwner().getUsername();
createdAt = survey.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = survey.getLikeVote();
dislikeVotes = survey.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.HASHTAG)) {
final HashTag tag = getHashTagItem(itemId);
totalHits = tag.getHits();
createdAt = tag.getUpdatedDate();
relative = DateUtil.getRelativeTime(createdAt);
}
final GenericStatsBean genericBean = new GenericStatsBean();
genericBean.setLikeDislikeRate(likeDislikeRate);;
genericBean.setHits(totalHits);
genericBean.setCreatedBy(createdBy);
genericBean.setAverage(average);
genericBean.setCreatedAt(createdAt);
return genericBean;
}
public void retrieveHashTagGraphData(){
}
/**
* Get survey by id.
* @param id
* @return
* @throws EnMeNoResultsFoundException
*/
private Survey getSurvey(final Long id) throws EnMeNoResultsFoundException{
return getSurveyService().getSurveyById(id);
}
/**
* Get Poll by id.
* @param id
* @return
* @throws EnMePollNotFoundException
*/
private Poll getPoll(final Long id) throws EnMePollNotFoundException{
return getPollService().getPollById(id);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTopRatedProfile(java.lang.Boolean)
*/
public List<ProfileRatedTopBean> getTopRatedProfile(final Boolean status)
throws EnMeNoResultsFoundException {
Long topValue = 0L;
Long totalTweetPollPublished;
Long totalPollPublished;
Long total;
final List<UserAccount> users = getSecurityService()
.getUserAccountsAvailable(status);
final List<ProfileRatedTopBean> profiles = ConvertDomainBean
.convertUserAccountListToProfileRated(users);
for (ProfileRatedTopBean profileRatedTopBean : profiles) {
totalTweetPollPublished = getTweetPollDao().getTotalTweetPoll(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
totalPollPublished = getPollDao().getTotalPollsbyUser(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
total = totalTweetPollPublished + totalPollPublished;
topValue = topValue + total;
log.debug("total value asigned to -->" + totalTweetPollPublished);
profileRatedTopBean.setTopValue(topValue);
}
Collections.sort(profiles);
return profiles;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagLinks(org.encuestame.persistence.domain.HashTag)
*/
public List<LinksSocialBean> getHashTagLinks(final HashTag hash) {
final List<TweetPollSavedPublishedStatus> links = getFrontEndDao()
.getLinksByHomeItem(hash, null, null, null, null,
TypeSearchResult.HASHTAG);
log.debug("getTweetPollLinks "+links.size());
return ConvertDomainBean.convertTweetPollSavedPublishedStatus(links);
}
// Total Usage by item.
public void getTotalUsagebyHashTagAndDateRange(){
}
/**
* Create hashTag details stats.
* @param label
* @param value
* @return
*/
private HashTagDetailStats createTagDetailsStats(final String label, final Long value){
final HashTagDetailStats tagDetails = new HashTagDetailStats();
tagDetails.setLabel(label);
tagDetails.setValue(value);
return tagDetails;
}
/**
* Counter items by HashTag.
* @param month
* @param counter
* @return
*/
private Long counterItemsbyHashTag(final int month, Long counter){
switch(month) {
case 1:
counter ++;
break;
case 2:
counter ++;
break;
case 3:
counter ++;
break;
case 4:
counter ++;
break;
case 5:
counter ++;
break;
case 6:
counter ++;
break;
case 7:
counter ++;
break;
case 8:
counter ++;
break;
case 9:
counter ++;
break;
case 10:
counter ++;
break;
case 11:
counter ++;
break;
case 12:
counter ++;
break;
default:
log.debug("Month not found");
}
return counter;
}
/**
*
* @param tpolls
* @param polls
* @param surveys
* @param counter
* @return
*/
private DateTime getAfterOrCurrentlyItemCreationDate(
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counter) {
DateTime monthValue;
if (tpolls != null) {
monthValue = new DateTime(tpolls.get(counter).getCreateDate());
} else if (polls != null) {
monthValue = new DateTime(polls.get(counter).getCreatedAt());
} else {
monthValue = new DateTime(surveys.get(counter).getCreatedAt());
}
return monthValue;
}
private List<HashTagDetailStats> getTagDetail(final List<TweetPoll> tpolls,
final List<Poll> polls, final List<Survey> surveys) {
// Tamano del array segun venga.
int totalList = 0;
List<HashTagDetailStats> statDetail = new ArrayList<HashTagDetailStats>();
if (tpolls != null) {
totalList = tpolls.size();
System.out.println(" Tweetpolls List size --->" + tpolls.size());
} else if (polls != null) {
totalList = polls.size();
} else {
totalList = surveys.size();
}
int counterI = 0;
if (totalList > 0) {
log.debug(" Total items by hashTag ---> " + totalList);
for (int i = 0; i < totalList; i++) {
statDetail = this.addHashTagStatsDetail(totalList, tpolls, polls, surveys, i);
}
} else
log.error("Items by HashTag not found");
return statDetail;
}
private List<HashTagDetailStats> addHashTagStatsDetail(final int totalList,
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counterIValue) {
int month = 0;
Long counterTweetPoll = 0L;
int afterMonth = 0;
int counterAfterMonthValue = 0;
HashTagDetailStats tagDetail = new HashTagDetailStats();
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
DateTime currentlyMonth = this.getAfterOrCurrentlyItemCreationDate(
tpolls, polls, surveys, counterIValue);
month = currentlyMonth.getMonthOfYear();
if (counterIValue < totalList - 1) {
counterAfterMonthValue = counterAfterMonthValue + 1;
DateTime dt2 = this.getAfterOrCurrentlyItemCreationDate(tpolls,
polls, surveys, counterAfterMonthValue);
afterMonth = dt2.getMonthOfYear();
System.out.println(" Mes actual --> " + month + " Mes Posterior --> " + afterMonth);
} else {
counterAfterMonthValue = counterIValue;
afterMonth = 0;
}
counterTweetPoll = this.counterItemsbyHashTag(month, counterTweetPoll);
if (month != afterMonth) {
System.out.println(" \n Added month --> " + month);
tagDetail = this.createTagDetailsStats(String.valueOf(month),
counterTweetPoll);
tagStatsDetail.add(tagDetail);
counterTweetPoll = 0L;
}
return tagStatsDetail;
}
private List<HashTagDetailStats> getTotalTweetPollUsageByHashTagAndDateRange(
final String tagName, final Integer period,
final Integer startResults, final Integer maxResults) {
List<TweetPoll> tweetPollsByHashTag = new ArrayList<TweetPoll>();
List<HashTagDetailStats> tagStatsDetailbyTweetPoll = new ArrayList<HashTagDetailStats>();
tweetPollsByHashTag = getTweetPollDao()
.getTweetPollsbyHashTagNameAndDateRange(tagName, period,
startResults, maxResults);
System.out.println(" Tweetpolls List por HashTag --->" + tweetPollsByHashTag.size());
// Obtiene el detalle de hashtags por tweetpoll.
tagStatsDetailbyTweetPoll = this.getTagDetail(tweetPollsByHashTag,
null, null);
System.out.println(" tagStatsDetailbyTweetPoll --->" + tweetPollsByHashTag.size());
return tagStatsDetailbyTweetPoll;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTotalUsagebyHashTagAndDateRange(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Integer)
*/
public List<HashTagDetailStats> getTotalUsagebyHashTagAndDateRange(
final String hashTagName, final Integer period,
final Integer startResults, final Integer maxResults)
throws EnMeNoResultsFoundException {
final HashTag tag = this.getHashTag(hashTagName, Boolean.TRUE);
// Get tweetPoll List
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
System.out.println("Tag Stats Detail Total --->" + tagStatsDetail);
if (tag != null) {
tagStatsDetail = this.getTotalTweetPollUsageByHashTagAndDateRange(hashTagName, period, startResults, maxResults);
//int month = 0;
//Long counterTweetPoll = 0L;
//int afterMonth = 0;
//int totalList = tweetPollsByHashTag.size();
//int counterI = 0;
}
return tagStatsDetail;
}
/**
* @return the tweetPollService
*/
public TweetPollService getTweetPollService() {
return tweetPollService;
}
/**
* @param tweetPollService the tweetPollService to set
*/
public void setTweetPollService(TweetPollService tweetPollService) {
this.tweetPollService = tweetPollService;
}
/**
* @return the pollService
*/
public PollService getPollService() {
return pollService;
}
/**
* @param pollService the pollService to set
*/
public void setPollService(final PollService pollService) {
this.pollService = pollService;
}
/**
* @return the surveyService
*/
public SurveyService getSurveyService() {
return surveyService;
}
/**
* @param surveyService the surveyService to set
*/
public void setSurveyService(final SurveyService surveyService) {
this.surveyService = surveyService;
}
/**
* @return the securityService
*/
public SecurityOperations getSecurityService() {
return securityService;
}
/**
* @param securityService the securityService to set
*/
public void setSecurityService(SecurityOperations securityService) {
this.securityService = securityService;
}
}
| Test commit
| encuestame-business/src/main/java/org/encuestame/business/service/FrontEndService.java | Test commit | <ide><path>ncuestame-business/src/main/java/org/encuestame/business/service/FrontEndService.java
<ide> */
<ide> package org.encuestame.business.service;
<ide>
<del>import java.io.Serializable;
<ide> import java.util.ArrayList;
<ide> import java.util.Calendar;
<ide> import java.util.Collections;
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.apache.log4j.Logger;
<del>import org.codehaus.jackson.annotate.JsonIgnoreProperties;
<ide> import org.encuestame.core.service.AbstractBaseService;
<ide> import org.encuestame.core.service.imp.IFrontEndService;
<ide> import org.encuestame.core.service.imp.SecurityOperations;
<ide> return monthValue;
<ide> }
<ide>
<add> /**
<add> *
<add> * @param tpolls
<add> * @param polls
<add> * @param surveys
<add> * @return
<add> */
<ide> private List<HashTagDetailStats> getTagDetail(final List<TweetPoll> tpolls,
<ide> final List<Poll> polls, final List<Survey> surveys) {
<ide> // Tamano del array segun venga.
<ide> return statDetail;
<ide> }
<ide>
<del>
<del>
<del>
<del>
<add>
<ide>
<ide> private List<HashTagDetailStats> addHashTagStatsDetail(final int totalList,
<ide> final List<TweetPoll> tpolls, final List<Poll> polls,
<ide> DateTime dt2 = this.getAfterOrCurrentlyItemCreationDate(tpolls,
<ide> polls, surveys, counterAfterMonthValue);
<ide> afterMonth = dt2.getMonthOfYear();
<del> System.out.println(" Mes actual --> " + month + " Mes Posterior --> " + afterMonth);
<add> System.out.println(" Currently month --> " + month + " After month --> " + afterMonth);
<ide> } else {
<ide> counterAfterMonthValue = counterIValue;
<ide> afterMonth = 0; |
|
Java | mit | bcaa9900f0052fe075d3f02456ee6e58ae8b4938 | 0 | stexfires/stexfires,stexfires/stexfires | package stexfires.util.supplier;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import java.util.Random;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import java.util.random.RandomGenerator;
/**
* @author Mathias Kalb
* @since 0.1
*/
public final class RandomBooleanSupplier implements Supplier<Boolean> {
private static final int HUNDRED = 100;
private final RandomGenerator random;
private final int percent;
private final Boolean constantResult;
public RandomBooleanSupplier(int percent) {
this(percent, new Random());
}
public RandomBooleanSupplier(int percent, long seed) {
this(percent, new Random(seed));
}
public RandomBooleanSupplier(int percent, RandomGenerator random) {
Objects.requireNonNull(random);
this.percent = percent;
this.random = random;
if (percent <= 0) {
constantResult = Boolean.FALSE;
} else if (percent >= HUNDRED) {
constantResult = Boolean.TRUE;
} else {
constantResult = null;
}
}
public BooleanSupplier asPrimitiveBooleanSupplier() {
return this::get;
}
@Override
public @NotNull Boolean get() {
return (constantResult != null) ? constantResult : (random.nextInt(HUNDRED) < percent);
}
}
| src/main/java/stexfires/util/supplier/RandomBooleanSupplier.java | package stexfires.util.supplier;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import java.util.Random;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
/**
* @author Mathias Kalb
* @since 0.1
*/
public final class RandomBooleanSupplier implements Supplier<Boolean> {
private static final int HUNDRED = 100;
private final Random random;
private final int percent;
private final Boolean constantResult;
public RandomBooleanSupplier(int percent) {
this(percent, new Random());
}
public RandomBooleanSupplier(int percent, long seed) {
this(percent, new Random(seed));
}
public RandomBooleanSupplier(int percent, Random random) {
Objects.requireNonNull(random);
this.percent = percent;
this.random = random;
if (percent <= 0) {
constantResult = Boolean.FALSE;
} else if (percent >= HUNDRED) {
constantResult = Boolean.TRUE;
} else {
constantResult = null;
}
}
public BooleanSupplier asPrimitiveBooleanSupplier() {
return this::get;
}
@Override
public @NotNull Boolean get() {
return (constantResult != null) ? constantResult : (random.nextInt(HUNDRED) < percent);
}
}
| Use interface RandomGenerator
| src/main/java/stexfires/util/supplier/RandomBooleanSupplier.java | Use interface RandomGenerator | <ide><path>rc/main/java/stexfires/util/supplier/RandomBooleanSupplier.java
<ide> import java.util.Random;
<ide> import java.util.function.BooleanSupplier;
<ide> import java.util.function.Supplier;
<add>import java.util.random.RandomGenerator;
<ide>
<ide> /**
<ide> * @author Mathias Kalb
<ide>
<ide> private static final int HUNDRED = 100;
<ide>
<del> private final Random random;
<add> private final RandomGenerator random;
<ide> private final int percent;
<ide> private final Boolean constantResult;
<ide>
<ide> this(percent, new Random(seed));
<ide> }
<ide>
<del> public RandomBooleanSupplier(int percent, Random random) {
<add> public RandomBooleanSupplier(int percent, RandomGenerator random) {
<ide> Objects.requireNonNull(random);
<ide> this.percent = percent;
<ide> this.random = random; |
|
Java | apache-2.0 | 780a90830a841d668766ff33d8499121c8dbb469 | 0 | blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle | /*
* Copyright 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.gradle.api.internal.initialization.loadercache;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.internal.classloader.ClassLoaderUtils;
import org.gradle.internal.classloader.ClasspathHasher;
import org.gradle.internal.classloader.FilteringClassLoader;
import org.gradle.internal.classloader.HashingClassLoaderFactory;
import org.gradle.internal.classpath.ClassPath;
import org.gradle.internal.concurrent.Stoppable;
import org.gradle.internal.hash.HashCode;
import javax.annotation.Nullable;
import java.util.Map;
public class DefaultClassLoaderCache implements ClassLoaderCache, Stoppable {
private static final Logger LOGGER = Logging.getLogger(DefaultClassLoaderCache.class);
private final Object lock = new Object();
private final Map<ClassLoaderId, CachedClassLoader> byId = Maps.newHashMap();
private final Map<ClassLoaderSpec, CachedClassLoader> bySpec = Maps.newHashMap();
private final ClasspathHasher classpathHasher;
private final HashingClassLoaderFactory classLoaderFactory;
public DefaultClassLoaderCache(HashingClassLoaderFactory classLoaderFactory, ClasspathHasher classpathHasher) {
this.classLoaderFactory = classLoaderFactory;
this.classpathHasher = classpathHasher;
}
@Override
public ClassLoader get(ClassLoaderId id, ClassPath classPath, @Nullable ClassLoader parent, @Nullable FilteringClassLoader.Spec filterSpec) {
return get(id, classPath, parent, filterSpec, null);
}
@Override
public ClassLoader get(ClassLoaderId id, ClassPath classPath, @Nullable ClassLoader parent, @Nullable FilteringClassLoader.Spec filterSpec, HashCode implementationHash) {
if (implementationHash == null) {
implementationHash = classpathHasher.hash(classPath);
}
ManagedClassLoaderSpec spec = new ManagedClassLoaderSpec(parent, classPath, implementationHash, filterSpec);
synchronized (lock) {
CachedClassLoader cachedLoader = byId.get(id);
if (cachedLoader == null || !cachedLoader.is(spec)) {
CachedClassLoader newLoader = getAndRetainLoader(classPath, spec, id);
byId.put(id, newLoader);
if (cachedLoader != null) {
LOGGER.debug("Releasing previous classloader for {}", id);
cachedLoader.release(id);
}
return newLoader.classLoader;
} else {
return cachedLoader.classLoader;
}
}
}
@Override
public <T extends ClassLoader> T put(ClassLoaderId id, T classLoader) {
synchronized (lock) {
remove(id);
ClassLoaderSpec spec = new UnmanagedClassLoaderSpec(classLoader);
CachedClassLoader cachedClassLoader = new CachedClassLoader(classLoader, spec, null);
cachedClassLoader.retain(id);
byId.put(id, cachedClassLoader);
bySpec.put(spec, cachedClassLoader);
}
return classLoader;
}
@Override
public void remove(ClassLoaderId id) {
synchronized (lock) {
CachedClassLoader cachedClassLoader = byId.remove(id);
if (cachedClassLoader != null) {
cachedClassLoader.release(id);
}
}
}
private CachedClassLoader getAndRetainLoader(ClassPath classPath, ManagedClassLoaderSpec spec, ClassLoaderId id) {
CachedClassLoader cachedLoader = bySpec.get(spec);
if (cachedLoader == null) {
ClassLoader classLoader;
CachedClassLoader parentCachedLoader = null;
if (spec.isFiltered()) {
parentCachedLoader = getAndRetainLoader(classPath, spec.unfiltered(), id);
classLoader = classLoaderFactory.createFilteringClassLoader(parentCachedLoader.classLoader, spec.filterSpec);
} else {
classLoader = classLoaderFactory.createChildClassLoader(spec.parent, classPath, spec.implementationHash);
}
cachedLoader = new CachedClassLoader(classLoader, spec, parentCachedLoader);
bySpec.put(spec, cachedLoader);
}
return cachedLoader.retain(id);
}
@Override
public int size() {
synchronized (lock) {
return bySpec.size();
}
}
@Override
public void stop() {
synchronized (lock) {
for (CachedClassLoader cachedClassLoader : byId.values()) {
ClassLoaderUtils.tryClose(cachedClassLoader.classLoader);
}
byId.clear();
bySpec.clear();
}
}
private static abstract class ClassLoaderSpec {
}
private static class UnmanagedClassLoaderSpec extends ClassLoaderSpec {
private final ClassLoader loader;
public UnmanagedClassLoaderSpec(ClassLoader loader) {
this.loader = loader;
}
}
private static class ManagedClassLoaderSpec extends ClassLoaderSpec {
private final ClassLoader parent;
private final ClassPath classPath;
private final HashCode implementationHash;
private final FilteringClassLoader.Spec filterSpec;
public ManagedClassLoaderSpec(ClassLoader parent, ClassPath classPath, HashCode implementationHash, FilteringClassLoader.Spec filterSpec) {
this.parent = parent;
this.classPath = classPath;
this.implementationHash = implementationHash;
this.filterSpec = filterSpec;
}
public ManagedClassLoaderSpec unfiltered() {
return new ManagedClassLoaderSpec(parent, classPath, implementationHash, null);
}
public boolean isFiltered() {
return filterSpec != null;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null || o.getClass() != getClass()) {
return false;
}
ManagedClassLoaderSpec that = (ManagedClassLoaderSpec) o;
return Objects.equal(this.parent, that.parent)
&& this.implementationHash.equals(that.implementationHash)
&& this.classPath.equals(that.classPath)
&& Objects.equal(this.filterSpec, that.filterSpec);
}
@Override
public int hashCode() {
int result = implementationHash.hashCode();
result = 31 * result + classPath.hashCode();
result = 31 * result + (filterSpec != null ? filterSpec.hashCode() : 0);
result = 31 * result + (parent != null ? parent.hashCode() : 0);
return result;
}
}
private class CachedClassLoader {
private final ClassLoader classLoader;
private final ClassLoaderSpec spec;
private final CachedClassLoader parent;
private final Multiset<ClassLoaderId> usedBy = HashMultiset.create();
private CachedClassLoader(ClassLoader classLoader, ClassLoaderSpec spec, @Nullable CachedClassLoader parent) {
this.classLoader = classLoader;
this.spec = spec;
this.parent = parent;
}
public boolean is(ClassLoaderSpec spec) {
return this.spec.equals(spec);
}
public CachedClassLoader retain(ClassLoaderId loaderId) {
usedBy.add(loaderId);
return this;
}
public void release(ClassLoaderId loaderId) {
if (usedBy.isEmpty()) {
throw new IllegalStateException("Cannot release already released classloader: " + classLoader);
}
if (usedBy.remove(loaderId)) {
if (usedBy.isEmpty()) {
if (parent != null) {
parent.release(loaderId);
}
bySpec.remove(spec);
}
} else {
throw new IllegalStateException("Classloader '" + this + "' not used by '" + loaderId + "'");
}
}
}
// Used in org.gradle.api.internal.initialization.loadercache.ClassLoadersCachingIntegrationTest
@SuppressWarnings("UnusedDeclaration")
public void assertInternalIntegrity() {
synchronized (lock) {
Map<ClassLoaderId, CachedClassLoader> orphaned = Maps.newHashMap();
for (Map.Entry<ClassLoaderId, CachedClassLoader> entry : byId.entrySet()) {
if (!bySpec.containsKey(entry.getValue().spec)) {
orphaned.put(entry.getKey(), entry.getValue());
}
}
if (!orphaned.isEmpty()) {
throw new IllegalStateException("The following class loaders are orphaned: " + Joiner.on(",").withKeyValueSeparator(":").join(orphaned));
}
}
}
}
| subprojects/core/src/main/java/org/gradle/api/internal/initialization/loadercache/DefaultClassLoaderCache.java | /*
* Copyright 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.gradle.api.internal.initialization.loadercache;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.internal.classloader.ClassLoaderUtils;
import org.gradle.internal.classloader.ClasspathHasher;
import org.gradle.internal.classloader.FilteringClassLoader;
import org.gradle.internal.classloader.HashingClassLoaderFactory;
import org.gradle.internal.classpath.ClassPath;
import org.gradle.internal.concurrent.Stoppable;
import org.gradle.internal.hash.HashCode;
import javax.annotation.Nullable;
import java.util.Map;
public class DefaultClassLoaderCache implements ClassLoaderCache, Stoppable {
private static final Logger LOGGER = Logging.getLogger(DefaultClassLoaderCache.class);
private final Object lock = new Object();
private final Map<ClassLoaderId, CachedClassLoader> byId = Maps.newHashMap();
private final Map<ClassLoaderSpec, CachedClassLoader> bySpec = Maps.newHashMap();
private final ClasspathHasher classpathHasher;
private final HashingClassLoaderFactory classLoaderFactory;
public DefaultClassLoaderCache(HashingClassLoaderFactory classLoaderFactory, ClasspathHasher classpathHasher) {
this.classLoaderFactory = classLoaderFactory;
this.classpathHasher = classpathHasher;
}
@Override
public ClassLoader get(ClassLoaderId id, ClassPath classPath, @Nullable ClassLoader parent, @Nullable FilteringClassLoader.Spec filterSpec) {
return get(id, classPath, parent, filterSpec, null);
}
@Override
public ClassLoader get(ClassLoaderId id, ClassPath classPath, @Nullable ClassLoader parent, @Nullable FilteringClassLoader.Spec filterSpec, HashCode implementationHash) {
if (implementationHash == null) {
implementationHash = classpathHasher.hash(classPath);
}
ManagedClassLoaderSpec spec = new ManagedClassLoaderSpec(parent, classPath, implementationHash, filterSpec);
synchronized (lock) {
CachedClassLoader cachedLoader = byId.get(id);
if (cachedLoader == null || !cachedLoader.is(spec)) {
CachedClassLoader newLoader = getAndRetainLoader(classPath, spec, id);
byId.put(id, newLoader);
if (cachedLoader != null) {
LOGGER.debug("Releasing previous classloader for {}", id);
cachedLoader.release(id);
}
return newLoader.classLoader;
} else {
return cachedLoader.classLoader;
}
}
}
@Override
public <T extends ClassLoader> T put(ClassLoaderId id, T classLoader) {
synchronized (lock) {
remove(id);
ClassLoaderSpec spec = new UnmanagedClassLoaderSpec(classLoader);
CachedClassLoader cachedClassLoader = new CachedClassLoader(classLoader, spec, null);
cachedClassLoader.retain(id);
byId.put(id, cachedClassLoader);
bySpec.put(spec, cachedClassLoader);
}
return classLoader;
}
@Override
public void remove(ClassLoaderId id) {
synchronized (lock) {
CachedClassLoader cachedClassLoader = byId.remove(id);
if (cachedClassLoader != null) {
cachedClassLoader.release(id);
}
}
}
private CachedClassLoader getAndRetainLoader(ClassPath classPath, ManagedClassLoaderSpec spec, ClassLoaderId id) {
CachedClassLoader cachedLoader = bySpec.get(spec);
if (cachedLoader == null) {
ClassLoader classLoader;
CachedClassLoader parentCachedLoader = null;
if (spec.isFiltered()) {
parentCachedLoader = getAndRetainLoader(classPath, spec.unfiltered(), id);
classLoader = classLoaderFactory.createFilteringClassLoader(parentCachedLoader.classLoader, spec.filterSpec);
} else {
classLoader = classLoaderFactory.createChildClassLoader(spec.parent, classPath, spec.implementationHash);
}
cachedLoader = new CachedClassLoader(classLoader, spec, parentCachedLoader);
bySpec.put(spec, cachedLoader);
}
return cachedLoader.retain(id);
}
@Override
public int size() {
synchronized (lock) {
return bySpec.size();
}
}
@Override
public void stop() {
synchronized (lock) {
for (CachedClassLoader cachedClassLoader : byId.values()) {
ClassLoaderUtils.tryClose(cachedClassLoader.classLoader);
}
byId.clear();
bySpec.clear();
}
}
private static abstract class ClassLoaderSpec {
}
private static class UnmanagedClassLoaderSpec extends ClassLoaderSpec {
private final ClassLoader loader;
public UnmanagedClassLoaderSpec(ClassLoader loader) {
this.loader = loader;
}
}
private static class ManagedClassLoaderSpec extends ClassLoaderSpec {
private final ClassLoader parent;
private final ClassPath classPath;
private final HashCode implementationHash;
private final FilteringClassLoader.Spec filterSpec;
public ManagedClassLoaderSpec(ClassLoader parent, ClassPath classPath, HashCode implementationHash, FilteringClassLoader.Spec filterSpec) {
this.parent = parent;
this.classPath = classPath;
this.implementationHash = implementationHash;
this.filterSpec = filterSpec;
}
public ManagedClassLoaderSpec unfiltered() {
return new ManagedClassLoaderSpec(parent, classPath, implementationHash, null);
}
public boolean isFiltered() {
return filterSpec != null;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
ManagedClassLoaderSpec that = (ManagedClassLoaderSpec) o;
return Objects.equal(this.parent, that.parent)
&& this.implementationHash.equals(that.implementationHash)
&& this.classPath.equals(that.classPath)
&& Objects.equal(this.filterSpec, that.filterSpec);
}
@Override
public int hashCode() {
int result = implementationHash.hashCode();
result = 31 * result + classPath.hashCode();
result = 31 * result + (filterSpec != null ? filterSpec.hashCode() : 0);
result = 31 * result + (parent != null ? parent.hashCode() : 0);
return result;
}
}
private class CachedClassLoader {
private final ClassLoader classLoader;
private final ClassLoaderSpec spec;
private final CachedClassLoader parent;
private final Multiset<ClassLoaderId> usedBy = HashMultiset.create();
private CachedClassLoader(ClassLoader classLoader, ClassLoaderSpec spec, @Nullable CachedClassLoader parent) {
this.classLoader = classLoader;
this.spec = spec;
this.parent = parent;
}
public boolean is(ClassLoaderSpec spec) {
return this.spec.equals(spec);
}
public CachedClassLoader retain(ClassLoaderId loaderId) {
usedBy.add(loaderId);
return this;
}
public void release(ClassLoaderId loaderId) {
if (usedBy.isEmpty()) {
throw new IllegalStateException("Cannot release already released classloader: " + classLoader);
}
if (usedBy.remove(loaderId)) {
if (usedBy.isEmpty()) {
if (parent != null) {
parent.release(loaderId);
}
bySpec.remove(spec);
}
} else {
throw new IllegalStateException("Classloader '" + this + "' not used by '" + loaderId + "'");
}
}
}
// Used in org.gradle.api.internal.initialization.loadercache.ClassLoadersCachingIntegrationTest
@SuppressWarnings("UnusedDeclaration")
public void assertInternalIntegrity() {
synchronized (lock) {
Map<ClassLoaderId, CachedClassLoader> orphaned = Maps.newHashMap();
for (Map.Entry<ClassLoaderId, CachedClassLoader> entry : byId.entrySet()) {
if (!bySpec.containsKey(entry.getValue().spec)) {
orphaned.put(entry.getKey(), entry.getValue());
}
}
if (!orphaned.isEmpty()) {
throw new IllegalStateException("The following class loaders are orphaned: " + Joiner.on(",").withKeyValueSeparator(":").join(orphaned));
}
}
}
}
| Fix ClassLoaderCache keys equals implementation
| subprojects/core/src/main/java/org/gradle/api/internal/initialization/loadercache/DefaultClassLoaderCache.java | Fix ClassLoaderCache keys equals implementation | <ide><path>ubprojects/core/src/main/java/org/gradle/api/internal/initialization/loadercache/DefaultClassLoaderCache.java
<ide> return filterSpec != null;
<ide> }
<ide>
<del> @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
<ide> @Override
<ide> public boolean equals(Object o) {
<add> if (o == this) {
<add> return true;
<add> }
<add> if (o == null || o.getClass() != getClass()) {
<add> return false;
<add> }
<ide> ManagedClassLoaderSpec that = (ManagedClassLoaderSpec) o;
<ide> return Objects.equal(this.parent, that.parent)
<ide> && this.implementationHash.equals(that.implementationHash) |
|
Java | apache-2.0 | fbc7ba72789980fc6e0f730023890f2c66975a86 | 0 | michael-rapp/ChromeLikeTabSwitcher | /*
* Copyright 2016 - 2017 Michael Rapp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.mrapp.android.tabswitcher.example;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.OnApplyWindowInsetsListener;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import de.mrapp.android.tabswitcher.Animation;
import de.mrapp.android.tabswitcher.PeekAnimation;
import de.mrapp.android.tabswitcher.RevealAnimation;
import de.mrapp.android.tabswitcher.Tab;
import de.mrapp.android.tabswitcher.TabSwitcher;
import de.mrapp.android.tabswitcher.TabSwitcherDecorator;
import de.mrapp.android.tabswitcher.TabSwitcherListener;
import de.mrapp.android.util.ViewUtil;
/**
* The example app's main activity.
*
* @author Michael Rapp
*/
public class MainActivity extends AppCompatActivity implements TabSwitcherListener {
/**
* The decorator, which is used to inflate and visualize the tabs of the activity's tab
* switcher.
*/
private class Decorator extends TabSwitcherDecorator {
@NonNull
@Override
public View onInflateView(@NonNull final LayoutInflater inflater,
@Nullable final ViewGroup parent, final int viewType) {
View view;
if (viewType == 0) {
view = inflater.inflate(R.layout.tab_text_view, parent, false);
} else {
view = inflater.inflate(R.layout.tab_edit_text, parent, false);
}
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.tab);
toolbar.setOnMenuItemClickListener(createToolbarMenuListener());
Menu menu = toolbar.getMenu();
TabSwitcher.setupWithMenu(tabSwitcher, menu, createTabSwitcherButtonListener());
return view;
}
@Override
public void onShowTab(@NonNull final Context context,
@NonNull final TabSwitcher tabSwitcher, @NonNull final View view,
@NonNull final Tab tab, final int index, final int viewType,
@Nullable final Bundle savedInstanceState) {
TextView textView = findViewById(android.R.id.title);
textView.setText(tab.getTitle());
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setVisibility(tabSwitcher.isSwitcherShown() ? View.GONE : View.VISIBLE);
if (viewType != 0) {
EditText editText = findViewById(android.R.id.edit);
if (savedInstanceState == null) {
editText.setText(null);
}
editText.requestFocus();
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getViewType(@NonNull final Tab tab, final int index) {
Bundle parameters = tab.getParameters();
return parameters != null ? parameters.getInt(VIEW_TYPE_EXTRA) : 0;
}
}
/**
* The name of the extra, which is used to store the view type of a tab within a bundle.
*/
private static final String VIEW_TYPE_EXTRA = MainActivity.class.getName() + "::ViewType";
/**
* The number of tabs, which are contained by the example app's tab switcher.
*/
private static final int TAB_COUNT = 12;
/**
* The activity's tab switcher.
*/
private TabSwitcher tabSwitcher;
/**
* The activity's snackbar.
*/
private Snackbar snackbar;
/**
* Creates a listener, which allows to apply the window insets to the tab switcher's padding.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnApplyWindowInsetsListener}. The listener may not be nullFG
*/
@NonNull
private OnApplyWindowInsetsListener createWindowInsetsListener() {
return new OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(final View v,
final WindowInsetsCompat insets) {
tabSwitcher.setPadding(insets.getSystemWindowInsetLeft(),
insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(),
insets.getSystemWindowInsetBottom());
return insets;
}
};
}
/**
* Creates and returns a listener, which allows to add a tab to the activity's tab switcher,
* when a button is clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createAddTabListener() {
return new OnClickListener() {
@Override
public void onClick(final View view) {
int index = tabSwitcher.getCount();
Animation animation = createRevealAnimation();
tabSwitcher.addTab(createTab(index), 0, animation);
}
};
}
/**
* Creates and returns a listener, which allows to observe, when an item of the tab switcher's
* toolbar has been clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnMenuItemClickListener}. The listener may not be null
*/
@NonNull
private OnMenuItemClickListener createToolbarMenuListener() {
return new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
switch (item.getItemId()) {
case R.id.add_tab_menu_item:
int index = tabSwitcher.getCount();
Tab tab = createTab(index);
if (tabSwitcher.isSwitcherShown()) {
tabSwitcher.addTab(tab, 0, createRevealAnimation());
} else {
tabSwitcher.addTab(tab, 0, createPeekAnimation());
}
return true;
case R.id.clear_tabs_menu_item:
tabSwitcher.clear();
return true;
default:
return false;
}
}
};
}
/**
* Creates and returns a layout listener, which allows to setup the tab switcher's toolbar menu,
* once the tab switcher has been laid out.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnGlobalLayoutListener}. The listener may not be null
*/
@NonNull
private OnGlobalLayoutListener createTabSwitcherLayoutListener() {
return new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewUtil.removeOnGlobalLayoutListener(tabSwitcher.getViewTreeObserver(), this);
Menu menu = tabSwitcher.getToolbarMenu();
if (menu != null) {
TabSwitcher.setupWithMenu(tabSwitcher, menu, createTabSwitcherButtonListener());
}
}
};
}
/**
* Creates and returns a listener, which allows to toggle the visibility of the tab switcher,
* when a button is clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createTabSwitcherButtonListener() {
return new OnClickListener() {
@Override
public void onClick(final View view) {
tabSwitcher.toggleSwitcherVisibility();
}
};
}
/**
* Creates and returns a listener, which allows to undo the removal of tabs from the tab
* switcher, when the button of the activity's snackbar is clicked.
*
* @param snackbar
* The activity's snackbar as an instance of the class {@link Snackbar}. The snackbar
* may not be null
* @param index
* The index of the first tab, which has been removed, as an {@link Integer} value
* @param tabs
* An array, which contains the tabs, which have been removed, as an array of the type
* {@link Tab}. The array may not be null
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createUndoSnackbarListener(@NonNull final Snackbar snackbar,
final int index,
@NonNull final Tab... tabs) {
return new OnClickListener() {
@Override
public void onClick(final View view) {
snackbar.setAction(null, null);
if (tabSwitcher.isSwitcherShown()) {
tabSwitcher.addAllTabs(tabs, index);
}
}
};
}
/**
* Shows a snackbar, which allows to undo the removal of tabs from the activity's tab switcher.
*
* @param text
* The text of the snackbar as an instance of the type {@link CharSequence}. The text
* may not be null
* @param index
* The index of the first tab, which has been removed, as an {@link Integer} value
* @param tabs
* An array, which contains the tabs, which have been removed, as an array of the type
* {@link Tab}. The array may not be null
*/
private void showUndoSnackbar(@NonNull final CharSequence text, final int index,
@NonNull final Tab... tabs) {
snackbar = Snackbar.make(tabSwitcher, text, Snackbar.LENGTH_LONG).setActionTextColor(
ContextCompat.getColor(this, R.color.snackbar_action_text_color));
snackbar.setAction(R.string.undo, createUndoSnackbarListener(snackbar, index, tabs));
snackbar.show();
}
/**
* Creates a reveal animation, which can be used to add a tab to the activity's tab switcher.
*
* @return The reveal animation, which has been created, as an instance of the class {@link
* Animation}. The animation may not be null
*/
@NonNull
private Animation createRevealAnimation() {
float x = 0;
float y = 0;
View view = getNavigationMenuItem();
if (view != null) {
int[] location = new int[2];
view.getLocationInWindow(location);
x = location[0] + (view.getWidth() / 2f);
y = location[1] + (view.getHeight() / 2f);
}
return new RevealAnimation.Builder().setX(x).setY(y).create();
}
/**
* Creates a peek animation, which can be used to add a tab to the activity's tab switcher.
*
* @return The peek animation, which has been created, as an instance of the class {@link
* Animation}. The animation may not be null
*/
@NonNull
private Animation createPeekAnimation() {
return new PeekAnimation.Builder().setX(tabSwitcher.getWidth() / 2f).create();
}
/**
* Returns the menu item, which shows the navigation icon of the tab switcher's toolbar.
*
* @return The menu item, which shows the navigation icon of the tab switcher's toolbar, as an
* instance of the class {@link View} or null, if no navigation icon is shown
*/
@Nullable
private View getNavigationMenuItem() {
Toolbar[] toolbars = tabSwitcher.getToolbars();
if (toolbars != null) {
Toolbar toolbar = toolbars.length > 1 ? toolbars[1] : toolbars[0];
int size = toolbar.getChildCount();
for (int i = 0; i < size; i++) {
View child = toolbar.getChildAt(i);
if (child instanceof ImageButton) {
return child;
}
}
}
return null;
}
/**
* Creates and returns a tab.
*
* @param index
* The index, the tab should be added at, as an {@link Integer} value
* @return The tab, which has been created, as an instance of the class {@link Tab}. The tab may
* not be null
*/
@NonNull
private Tab createTab(final int index) {
CharSequence title = getString(R.string.tab_title, index + 1);
Tab tab = new Tab(title);
Bundle parameters = new Bundle();
parameters.putInt(VIEW_TYPE_EXTRA, index % 2);
tab.setParameters(parameters);
return tab;
}
@Override
public final void onSwitcherShown(@NonNull final TabSwitcher tabSwitcher) {
}
@Override
public final void onSwitcherHidden(@NonNull final TabSwitcher tabSwitcher) {
if (snackbar != null) {
snackbar.dismiss();
}
}
@Override
public final void onSelectionChanged(@NonNull final TabSwitcher tabSwitcher,
final int selectedTabIndex,
@Nullable final Tab selectedTab) {
}
@Override
public final void onTabAdded(@NonNull final TabSwitcher tabSwitcher, final int index,
@NonNull final Tab tab, @NonNull final Animation animation) {
}
@Override
public final void onTabRemoved(@NonNull final TabSwitcher tabSwitcher, final int index,
@NonNull final Tab tab, @NonNull final Animation animation) {
CharSequence text = getString(R.string.removed_tab_snackbar, tab.getTitle());
showUndoSnackbar(text, index, tab);
}
@Override
public final void onAllTabsRemoved(@NonNull final TabSwitcher tabSwitcher,
@NonNull final Tab[] tabs,
@NonNull final Animation animation) {
CharSequence text = getString(R.string.cleared_tabs_snackbar);
showUndoSnackbar(text, 0, tabs);
}
@Override
protected final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabSwitcher = (TabSwitcher) findViewById(R.id.tab_switcher);
ViewCompat.setOnApplyWindowInsetsListener(tabSwitcher, createWindowInsetsListener());
tabSwitcher.setDecorator(new Decorator());
tabSwitcher.addListener(this);
tabSwitcher.showToolbars(true);
tabSwitcher
.setToolbarNavigationIcon(R.drawable.ic_add_box_white_24dp, createAddTabListener());
tabSwitcher.inflateToolbarMenu(R.menu.tab_switcher, createToolbarMenuListener());
tabSwitcher.getViewTreeObserver()
.addOnGlobalLayoutListener(createTabSwitcherLayoutListener());
for (int i = 0; i < TAB_COUNT; i++) {
tabSwitcher.addTab(createTab(i));
}
}
} | example/src/main/java/de/mrapp/android/tabswitcher/example/MainActivity.java | /*
* Copyright 2016 - 2017 Michael Rapp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.mrapp.android.tabswitcher.example;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.OnApplyWindowInsetsListener;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import de.mrapp.android.tabswitcher.Animation;
import de.mrapp.android.tabswitcher.PeekAnimation;
import de.mrapp.android.tabswitcher.RevealAnimation;
import de.mrapp.android.tabswitcher.Tab;
import de.mrapp.android.tabswitcher.TabSwitcher;
import de.mrapp.android.tabswitcher.TabSwitcherDecorator;
import de.mrapp.android.tabswitcher.TabSwitcherListener;
import de.mrapp.android.util.ViewUtil;
/**
* The example app's main activity.
*
* @author Michael Rapp
*/
public class MainActivity extends AppCompatActivity implements TabSwitcherListener {
/**
* The decorator, which is used to inflate and visualize the tabs of the activity's tab
* switcher.
*/
private class Decorator extends TabSwitcherDecorator {
@NonNull
@Override
public View onInflateView(@NonNull final LayoutInflater inflater,
@Nullable final ViewGroup parent, final int viewType) {
View view;
if (viewType == 0) {
view = inflater.inflate(R.layout.tab_text_view, parent, false);
} else {
view = inflater.inflate(R.layout.tab_edit_text, parent, false);
}
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.tab);
toolbar.setOnMenuItemClickListener(createToolbarMenuListener());
Menu menu = toolbar.getMenu();
TabSwitcher.setupWithMenu(tabSwitcher, menu, createTabSwitcherButtonListener());
return view;
}
@Override
public void onShowTab(@NonNull final Context context,
@NonNull final TabSwitcher tabSwitcher, @NonNull final View view,
@NonNull final Tab tab, final int index, final int viewType,
@Nullable final Bundle savedInstanceState) {
TextView textView = findViewById(android.R.id.title);
textView.setText(tab.getTitle());
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setVisibility(tabSwitcher.isSwitcherShown() ? View.GONE : View.VISIBLE);
if (viewType != 0) {
EditText editText = findViewById(android.R.id.edit);
editText.requestFocus();
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getViewType(@NonNull final Tab tab, final int index) {
Bundle parameters = tab.getParameters();
return parameters != null ? parameters.getInt(VIEW_TYPE_EXTRA) : 0;
}
}
/**
* The name of the extra, which is used to store the view type of a tab within a bundle.
*/
private static final String VIEW_TYPE_EXTRA = MainActivity.class.getName() + "::ViewType";
/**
* The number of tabs, which are contained by the example app's tab switcher.
*/
private static final int TAB_COUNT = 12;
/**
* The activity's tab switcher.
*/
private TabSwitcher tabSwitcher;
/**
* The activity's snackbar.
*/
private Snackbar snackbar;
/**
* Creates a listener, which allows to apply the window insets to the tab switcher's padding.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnApplyWindowInsetsListener}. The listener may not be nullFG
*/
@NonNull
private OnApplyWindowInsetsListener createWindowInsetsListener() {
return new OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(final View v,
final WindowInsetsCompat insets) {
tabSwitcher.setPadding(insets.getSystemWindowInsetLeft(),
insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(),
insets.getSystemWindowInsetBottom());
return insets;
}
};
}
/**
* Creates and returns a listener, which allows to add a tab to the activity's tab switcher,
* when a button is clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createAddTabListener() {
return new OnClickListener() {
@Override
public void onClick(final View view) {
int index = tabSwitcher.getCount();
Animation animation = createRevealAnimation();
tabSwitcher.addTab(createTab(index), 0, animation);
}
};
}
/**
* Creates and returns a listener, which allows to observe, when an item of the tab switcher's
* toolbar has been clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnMenuItemClickListener}. The listener may not be null
*/
@NonNull
private OnMenuItemClickListener createToolbarMenuListener() {
return new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
switch (item.getItemId()) {
case R.id.add_tab_menu_item:
int index = tabSwitcher.getCount();
Tab tab = createTab(index);
if (tabSwitcher.isSwitcherShown()) {
tabSwitcher.addTab(tab, 0, createRevealAnimation());
} else {
tabSwitcher.addTab(tab, 0, createPeekAnimation());
}
return true;
case R.id.clear_tabs_menu_item:
tabSwitcher.clear();
return true;
default:
return false;
}
}
};
}
/**
* Creates and returns a layout listener, which allows to setup the tab switcher's toolbar menu,
* once the tab switcher has been laid out.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnGlobalLayoutListener}. The listener may not be null
*/
@NonNull
private OnGlobalLayoutListener createTabSwitcherLayoutListener() {
return new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewUtil.removeOnGlobalLayoutListener(tabSwitcher.getViewTreeObserver(), this);
Menu menu = tabSwitcher.getToolbarMenu();
if (menu != null) {
TabSwitcher.setupWithMenu(tabSwitcher, menu, createTabSwitcherButtonListener());
}
}
};
}
/**
* Creates and returns a listener, which allows to toggle the visibility of the tab switcher,
* when a button is clicked.
*
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createTabSwitcherButtonListener() {
return new OnClickListener() {
@Override
public void onClick(final View view) {
tabSwitcher.toggleSwitcherVisibility();
}
};
}
/**
* Creates and returns a listener, which allows to undo the removal of tabs from the tab
* switcher, when the button of the activity's snackbar is clicked.
*
* @param snackbar
* The activity's snackbar as an instance of the class {@link Snackbar}. The snackbar
* may not be null
* @param index
* The index of the first tab, which has been removed, as an {@link Integer} value
* @param tabs
* An array, which contains the tabs, which have been removed, as an array of the type
* {@link Tab}. The array may not be null
* @return The listener, which has been created, as an instance of the type {@link
* OnClickListener}. The listener may not be null
*/
@NonNull
private OnClickListener createUndoSnackbarListener(@NonNull final Snackbar snackbar,
final int index,
@NonNull final Tab... tabs) {
return new OnClickListener() {
@Override
public void onClick(final View view) {
snackbar.setAction(null, null);
if (tabSwitcher.isSwitcherShown()) {
tabSwitcher.addAllTabs(tabs, index);
}
}
};
}
/**
* Shows a snackbar, which allows to undo the removal of tabs from the activity's tab switcher.
*
* @param text
* The text of the snackbar as an instance of the type {@link CharSequence}. The text
* may not be null
* @param index
* The index of the first tab, which has been removed, as an {@link Integer} value
* @param tabs
* An array, which contains the tabs, which have been removed, as an array of the type
* {@link Tab}. The array may not be null
*/
private void showUndoSnackbar(@NonNull final CharSequence text, final int index,
@NonNull final Tab... tabs) {
snackbar = Snackbar.make(tabSwitcher, text, Snackbar.LENGTH_LONG).setActionTextColor(
ContextCompat.getColor(this, R.color.snackbar_action_text_color));
snackbar.setAction(R.string.undo, createUndoSnackbarListener(snackbar, index, tabs));
snackbar.show();
}
/**
* Creates a reveal animation, which can be used to add a tab to the activity's tab switcher.
*
* @return The reveal animation, which has been created, as an instance of the class {@link
* Animation}. The animation may not be null
*/
@NonNull
private Animation createRevealAnimation() {
float x = 0;
float y = 0;
View view = getNavigationMenuItem();
if (view != null) {
int[] location = new int[2];
view.getLocationInWindow(location);
x = location[0] + (view.getWidth() / 2f);
y = location[1] + (view.getHeight() / 2f);
}
return new RevealAnimation.Builder().setX(x).setY(y).create();
}
/**
* Creates a peek animation, which can be used to add a tab to the activity's tab switcher.
*
* @return The peek animation, which has been created, as an instance of the class {@link
* Animation}. The animation may not be null
*/
@NonNull
private Animation createPeekAnimation() {
return new PeekAnimation.Builder().setX(tabSwitcher.getWidth() / 2f).create();
}
/**
* Returns the menu item, which shows the navigation icon of the tab switcher's toolbar.
*
* @return The menu item, which shows the navigation icon of the tab switcher's toolbar, as an
* instance of the class {@link View} or null, if no navigation icon is shown
*/
@Nullable
private View getNavigationMenuItem() {
Toolbar[] toolbars = tabSwitcher.getToolbars();
if (toolbars != null) {
Toolbar toolbar = toolbars.length > 1 ? toolbars[1] : toolbars[0];
int size = toolbar.getChildCount();
for (int i = 0; i < size; i++) {
View child = toolbar.getChildAt(i);
if (child instanceof ImageButton) {
return child;
}
}
}
return null;
}
/**
* Creates and returns a tab.
*
* @param index
* The index, the tab should be added at, as an {@link Integer} value
* @return The tab, which has been created, as an instance of the class {@link Tab}. The tab may
* not be null
*/
@NonNull
private Tab createTab(final int index) {
CharSequence title = getString(R.string.tab_title, index + 1);
Tab tab = new Tab(title);
Bundle parameters = new Bundle();
parameters.putInt(VIEW_TYPE_EXTRA, index % 2);
tab.setParameters(parameters);
return tab;
}
@Override
public final void onSwitcherShown(@NonNull final TabSwitcher tabSwitcher) {
}
@Override
public final void onSwitcherHidden(@NonNull final TabSwitcher tabSwitcher) {
if (snackbar != null) {
snackbar.dismiss();
}
}
@Override
public final void onSelectionChanged(@NonNull final TabSwitcher tabSwitcher,
final int selectedTabIndex,
@Nullable final Tab selectedTab) {
}
@Override
public final void onTabAdded(@NonNull final TabSwitcher tabSwitcher, final int index,
@NonNull final Tab tab, @NonNull final Animation animation) {
}
@Override
public final void onTabRemoved(@NonNull final TabSwitcher tabSwitcher, final int index,
@NonNull final Tab tab, @NonNull final Animation animation) {
CharSequence text = getString(R.string.removed_tab_snackbar, tab.getTitle());
showUndoSnackbar(text, index, tab);
}
@Override
public final void onAllTabsRemoved(@NonNull final TabSwitcher tabSwitcher,
@NonNull final Tab[] tabs,
@NonNull final Animation animation) {
CharSequence text = getString(R.string.cleared_tabs_snackbar);
showUndoSnackbar(text, 0, tabs);
}
@Override
protected final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabSwitcher = (TabSwitcher) findViewById(R.id.tab_switcher);
ViewCompat.setOnApplyWindowInsetsListener(tabSwitcher, createWindowInsetsListener());
tabSwitcher.setDecorator(new Decorator());
tabSwitcher.addListener(this);
tabSwitcher.showToolbars(true);
tabSwitcher
.setToolbarNavigationIcon(R.drawable.ic_add_box_white_24dp, createAddTabListener());
tabSwitcher.inflateToolbarMenu(R.menu.tab_switcher, createToolbarMenuListener());
tabSwitcher.getViewTreeObserver()
.addOnGlobalLayoutListener(createTabSwitcherLayoutListener());
for (int i = 0; i < TAB_COUNT; i++) {
tabSwitcher.addTab(createTab(i));
}
}
} | Fixed issue in the example app, which caused the text of EditText widgets to appear in the wrong tabs.
| example/src/main/java/de/mrapp/android/tabswitcher/example/MainActivity.java | Fixed issue in the example app, which caused the text of EditText widgets to appear in the wrong tabs. | <ide><path>xample/src/main/java/de/mrapp/android/tabswitcher/example/MainActivity.java
<ide>
<ide> if (viewType != 0) {
<ide> EditText editText = findViewById(android.R.id.edit);
<add>
<add> if (savedInstanceState == null) {
<add> editText.setText(null);
<add> }
<add>
<ide> editText.requestFocus();
<ide> }
<ide> } |
|
Java | agpl-3.0 | f645ebfa83563324af80333ed826a4fa8cae249b | 0 | RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid | /*
Copyright (C) 2017 - Gareth Edwards / Rapid Information Systems
[email protected]
This file is part of the Rapid Application Platform
Rapid 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. The terms require you
to include the original copyright, and the license notice in all redistributions.
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
in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>.
*/
package com.rapid.server;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.rapid.actions.Logic.Condition;
import com.rapid.core.Action;
import com.rapid.core.Application;
import com.rapid.core.Application.ValueList;
import com.rapid.core.Applications.Versions;
import com.rapid.core.Control;
import com.rapid.core.Event;
import com.rapid.core.Page;
import com.rapid.core.Page.Lock;
import com.rapid.core.Page.RoleControlHtml;
import com.rapid.core.Pages.PageHeader;
import com.rapid.core.Pages.PageHeaders;
import com.rapid.core.Theme;
import com.rapid.core.Workflow;
import com.rapid.core.Workflows;
import com.rapid.data.ConnectionAdapter;
import com.rapid.data.DataFactory;
import com.rapid.data.DataFactory.Parameters;
import com.rapid.data.DatabaseConnection;
import com.rapid.forms.FormAdapter;
import com.rapid.security.SecurityAdapter;
import com.rapid.security.SecurityAdapter.Role;
import com.rapid.security.SecurityAdapter.User;
import com.rapid.utils.Bytes;
import com.rapid.utils.Files;
import com.rapid.utils.Strings;
import com.rapid.utils.XML;
import com.rapid.utils.ZipFile;
public class Designer extends RapidHttpServlet {
private static final long serialVersionUID = 2L;
// this byte buffer is used for reading the post data
byte[] _byteBuffer = new byte[1024];
public Designer() { super(); }
// helper method to set the content type, write, and close the stream for common JSON output
private void sendJsonOutput(HttpServletResponse response, String output) throws IOException {
// set response as json
response.setContentType("application/json");
// get a writer from the response
PrintWriter out = response.getWriter();
// write the output into the response
out.print(output);
// close the writer
out.close();
// send it immediately
out.flush();
}
// print details of an action
private void printActionDetails(Action action, PrintWriter out) {
// print the action
out.print("\t\tAction\t" + action.getId()+ "\n");
// get the properties
Map<String, String> properties = action.getProperties();
// create a sorted list
List<String> sortedKeys = new ArrayList<String>();
// loop them
for (String key : properties.keySet()) {
// add
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop the sorted keys
for (String key : sortedKeys) {
// print the property
out.print("\t\t\t" + key + "\t" + properties.get(key) + "\n");
}
// get a JSONObejct for them
JSONObject jsonAction = new JSONObject(action);
// get it's properties
Iterator<String> keys = jsonAction.keys();
// clear the sorted key list
sortedKeys.clear();
// loop them
while (keys.hasNext()) {
// get the next one
String key = keys.next();
// add it to the list
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop the sorted keys
for (String key : sortedKeys) {
// print it
try {
out.print("\t\t\t" + key + "\t" + jsonAction.get(key) + "\n");
} catch (JSONException e) { }
}
// check child actions
if (action.getChildActions() != null) {
if (action.getChildActions().size() > 0) {
// loop them
for (Action childAction : action.getChildActions()) {
// print the child actions
printActionDetails(childAction, out);
}
}
}
}
// print details of events (used by page and controls)
private void printEventsDetails(List<Event> events, PrintWriter out) {
// check events
if (events!= null) {
if (events.size() > 0) {
// loop them
for (Event event : events) {
// check actions
if (event.getActions() != null) {
if (event.getActions().size() > 0) {
// print the event
out.print("\tEvent\t" + event.getType() + "\n");
// loop the actions
for (Action action : event.getActions()) {
// print the action details
printActionDetails( action, out);
}
}
}
}
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// fake a delay for testing slow servers
// try { Thread.sleep(3000); } catch (InterruptedException e) {}
RapidRequest rapidRequest = new RapidRequest(this, request);
try {
getLogger().debug("Designer GET request : " + request.getQueryString());
String actionName = rapidRequest.getActionName();
String output = "";
// get the rapid application
Application rapidApplication = getApplications().get("rapid");
// check we got one
if (rapidApplication != null) {
// get rapid security
SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();
// check we got some
if (rapidSecurity != null) {
// get the user name
String userName = rapidRequest.getUserName();
// get the rapid user
User rapidUser = rapidSecurity.getUser(rapidRequest);
// check permission
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {
// whether we're trying to avoid caching
boolean noCaching = Boolean.parseBoolean(getServletContext().getInitParameter("noCaching"));
if (noCaching) {
// try and avoid caching
response.setHeader("Expires", "Sat, 15 March 1980 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
if ("getSystemData".equals(actionName)) {
// create a system data object
JSONObject jsonSystemData = new JSONObject();
// add the controls
jsonSystemData.put("controls", getJsonControls());
// add the actions
jsonSystemData.put("actions", getJsonActions());
// add the devices
jsonSystemData.put("devices", getDevices());
// add the local date format
jsonSystemData.put("localDateFormat", getLocalDateFormat());
// look for a controlAndActionSuffix
String controlAndActionSuffix = request.getServletContext().getInitParameter("controlAndActionSuffix");
// update to empty string if not present - this is the default and expected for older versions of the web.xml
if (controlAndActionSuffix == null) controlAndActionSuffix = "";
// add the controlAndActionPrefix
jsonSystemData.put("controlAndActionSuffix", controlAndActionSuffix);
// put into output string
output = jsonSystemData.toString();
// send output as json
sendJsonOutput(response, output);
} else if ("getApps".equals(actionName)) {
// create a json array for holding our apps
JSONArray jsonApps = new JSONArray();
// get a sorted list of the applications
for (String id : getApplications().getIds()) {
// loop the versions
for (String version : getApplications().getVersions(id).keySet()) {
// get the this application version
Application application = getApplications().get(id, version);
// get the security
SecurityAdapter security = application.getSecurityAdapter();
// recreate the request in the name of this app
RapidRequest appRequest = new RapidRequest(this, request, application);
// check the users password
if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) {
// check the users permission to design this application
boolean designPermission = security.checkUserRole(appRequest, Rapid.DESIGN_ROLE);
// if app is rapid do a further check
if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE);
// if we got permssion - add this application to the list
if (designPermission) {
// create a json object
JSONObject jsonApplication = new JSONObject();
// add the details we want
jsonApplication.put("id", application.getId());
jsonApplication.put("name", application.getName());
jsonApplication.put("title", application.getTitle());
// add the object to the collection
jsonApps.put(jsonApplication);
// no need to check any further versions
break;
}
}
}
}
output = jsonApps.toString();
sendJsonOutput(response, output);
} else if ("getVersions".equals(actionName)) {
// create a json array for holding our apps
JSONArray jsonVersions = new JSONArray();
// get the app id
String appId = rapidRequest.getAppId();
// get the versions
Versions versions = getApplications().getVersions(appId);
// if there are any
if (versions != null) {
// loop the list of applications sorted by id (with rapid last)
for (Application application : versions.sort()) {
// get the security
SecurityAdapter security = application.getSecurityAdapter();
// recreate the request in the name of this app
RapidRequest appRequest = new RapidRequest(this, request, application);
// check the users password
if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) {
// check the users permission to design this application
boolean designPermission = application.getSecurityAdapter().checkUserRole(appRequest, Rapid.DESIGN_ROLE);
// if app is rapid do a further check
if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE);
// check the RapidDesign role is present in the users roles for this application
if (designPermission) {
// make a json object for this version
JSONObject jsonVersion = new JSONObject();
// add the app id
jsonVersion.put("id", application.getId());
// add the version
jsonVersion.put("version", application.getVersion());
// add the status
jsonVersion.put("status", application.getStatus());
// add the title
jsonVersion.put("title", application.getTitle());
// add a formAdapter if present
if (application.getIsForm()) jsonVersion.put("isForm", true);
// add whether to show control Ids
jsonVersion.put("showControlIds", application.getShowControlIds());
// add whether to show action Ids
jsonVersion.put("showActionIds", application.getShowActionIds());
// add the web folder so we can update the iframe style sheets
jsonVersion.put("webFolder", Application.getWebFolder(application));
// get the database connections
List<DatabaseConnection> databaseConnections = application.getDatabaseConnections();
// check we have any
if (databaseConnections != null) {
// make an object we're going to return
JSONArray jsonDatabaseConnections = new JSONArray();
// loop the connections
for (DatabaseConnection databaseConnection : databaseConnections) {
// add the connection name
jsonDatabaseConnections.put(databaseConnection.getName());
}
// add the connections to the app
jsonVersion.put("databaseConnections", jsonDatabaseConnections);
}
// make an object we're going to return
JSONArray jsonRoles = new JSONArray();
// retrieve the roles
List<Role> roles = security.getRoles(appRequest);
// check we got some
if (roles != null) {
// create a collection of names
ArrayList<String> roleNames = new ArrayList<String>();
// copy the names in if non-null
for (Role role : roles) if (role.getName() != null) roleNames.add(role.getName());
// sort them
Collections.sort(roleNames);
// loop the sorted connections
for (String roleName : roleNames) {
// only add role if this is the rapid app, or it's not a special rapid permission
if ("rapid".equals(application.getId()) || (!Rapid.ADMIN_ROLE.equals(roleName) && !Rapid.DESIGN_ROLE.equals(roleName)&& !Rapid.SUPER_ROLE.equals(roleName))) jsonRoles.put(roleName);
}
}
// add the security roles to the app
jsonVersion.put("roles", jsonRoles);
// get any value lists
List<ValueList> valueLists = application.getValueLists();
// add all of the value lists
jsonVersion.put("valueLists", valueLists);
// get all the possible json actions
JSONArray jsonActions = getJsonActions();
// make an array for the actions in this app
JSONArray jsonAppActions = new JSONArray();
// get the types used in this app
List<String> actionTypes = application.getActionTypes();
// if we have some
if (actionTypes != null) {
// loop the types used in this app
for (String actionType : actionTypes) {
// loop all the possible actions
for (int i = 0; i < jsonActions.length(); i++) {
// get an instance to the json action
JSONObject jsonAction = jsonActions.getJSONObject(i);
// if this is the type we've been looking for
if (actionType.equals(jsonAction.getString("type"))) {
// create a simple json object for thi action
JSONObject jsonAppAction = new JSONObject();
// add just what we need
jsonAppAction.put("type", jsonAction.getString("type"));
jsonAppAction.put("name", jsonAction.getString("name"));
jsonAppAction.put("visible", jsonAction.optBoolean("visible", true));
// add it to the app actions collection
jsonAppActions.put(jsonAppAction);
// start on the next app action
break;
}
}
}
}
// put the app actions we've just built into the app
jsonVersion.put("actions", jsonAppActions);
// get all the possible json controls
JSONArray jsonControls = getJsonControls();
// make an array for the controls in this app
JSONArray jsonAppControls = new JSONArray();
// get the control types used by this app
List<String> controlTypes = application.getControlTypes();
// if we have some
if (controlTypes != null) {
// loop the types used in this app
for (String controlType : controlTypes) {
// loop all the possible controls
for (int i = 0; i < jsonControls.length(); i++) {
// get an instance to the json control
JSONObject jsonControl = jsonControls.getJSONObject(i);
// if this is the type we've been looking for
if (controlType.equals(jsonControl.getString("type"))) {
// create a simple json object for this control
JSONObject jsonAppControl = new JSONObject();
// add just what we need
jsonAppControl.put("type", jsonControl.getString("type"));
jsonAppControl.put("name", jsonControl.getString("name"));
jsonAppControl.put("image", jsonControl.optString("image"));
jsonAppControl.put("category", jsonControl.optString("category"));
jsonAppControl.put("canUserAdd", jsonControl.optString("canUserAdd"));
// add it to the app controls collection
jsonAppControls.put(jsonAppControl);
// start on the next app control
break;
}
}
}
}
// put the app controls we've just built into the app
jsonVersion.put("controls", jsonAppControls);
// create a json object for the images
JSONArray jsonImages = new JSONArray();
// get the directory in which the control xml files are stored
File dir = new File (application.getWebFolder(getServletContext()));
// create a filter for finding image files
FilenameFilter xmlFilenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".gif") || name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".svg");
}
};
// a array to hold the images as they come out of the filter
List<String> images = new ArrayList<String>();
// loop the image files in the folder
for (File imageFile : dir.listFiles(xmlFilenameFilter)) {
images.add(imageFile.getName());
}
// sort the images
Collections.sort(images);
// loop the sorted images and add to json
for (String image : images) jsonImages.put(image);
// put the images collection we've just built into the app
jsonVersion.put("images", jsonImages);
// create a json array for our style classes
JSONArray jsonStyleClasses = new JSONArray();
// get all of the possible style classes
List<String> styleClasses = application.getStyleClasses();
// if we had some
if (styleClasses != null) {
// loop and add to json array
for (String styleClass : styleClasses) jsonStyleClasses.put(styleClass);
}
// put them into our application object
jsonVersion.put("styleClasses", jsonStyleClasses);
// look for any form adpter
FormAdapter formAdapter = application.getFormAdapter();
// if we got one
if (formAdapter != null) {
// get the type
String formAdapterType = formAdapter.getType();
// get the json form adpater details
JSONArray jsonFormAdapters = getJsonFormAdapters();
// if we got some
if (jsonFormAdapters != null) {
// loop them
for (int i = 0; i < jsonFormAdapters.length(); i++) {
// get this form adapter
JSONObject jsonFormAdapter = jsonFormAdapters.getJSONObject(i);
// if this is the one we want
if (formAdapterType.equals(jsonFormAdapter.optString("type"))) {
// add the properties to the version
jsonVersion.put("canSaveForms", jsonFormAdapter.optBoolean("canSaveForms"));
jsonVersion.put("canGeneratePDF", jsonFormAdapter.optBoolean("canGeneratePDF"));
jsonVersion.put("canSupportIntegrationProperties", jsonFormAdapter.optBoolean("canSupportIntegrationProperties"));
// we're done
break;
}
}
}
}
// put the app into the collection
jsonVersions.put(jsonVersion);
} // design permission
} // check user password
} // versions loop
} // got versions check
output = jsonVersions.toString();
sendJsonOutput(response, output);
} else if ("getPages".equals(actionName)) {
Application application = rapidRequest.getApplication();
if (application == null) {
// send an empty object
output = "{}";
} else {
JSONArray jsonPages = new JSONArray();
String startPageId = "";
Page startPage = application.getStartPage(getServletContext());
if (startPage != null) startPageId = startPage.getId();
// loop the page headers
for (PageHeader pageHeader : application.getPages().getSortedPages()) {
// get the page - yip this means that apps loaded in the designer load all of their pages
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// create a simple json object for the page
JSONObject jsonPage = new JSONObject();
// add simple properties
jsonPage.put("id", page.getId());
jsonPage.put("name", page.getName());
jsonPage.put("title", page.getTitle());
jsonPage.put("label", page.getLabel());
jsonPage.put("simple", page.getSimple());
jsonPage.put("hideHeaderFooter", page.getHideHeaderFooter());
// get a list of page session variables
List<String> pageSessionVariables = page.getSessionVariables();
// add them if there are some
if (pageSessionVariables != null) if (pageSessionVariables.size() > 0) jsonPage.put("sessionVariables", pageSessionVariables);
// assume we don't need to know page visibilty
boolean includePageVisibiltyControls = false;
// if there is a form adapter
if (application.getFormAdapter() != null) {
// set to true
includePageVisibiltyControls = true;
// add visibility conditions
List<Condition> pageVisibilityConditions = page.getVisibilityConditions();
// add them if there are some
if (pageVisibilityConditions != null) if (pageVisibilityConditions.size() > 0) jsonPage.put("visibilityConditions", pageVisibilityConditions);
}
// get a collection of other page controls in this page
JSONArray jsonOtherPageControls = page.getOtherPageControls(this, includePageVisibiltyControls);
// only add the property if there are some
if (jsonOtherPageControls.length() > 0) jsonPage.put("controls", jsonOtherPageControls);
// check if the start page and add property if so
if (startPageId.equals(page.getId())) jsonPage.put("startPage", true);
// add the page to the collection
jsonPages.put(jsonPage);
}
// set the output to the collection turned into a string
output = jsonPages.toString();
} // application check
sendJsonOutput(response, output);
} else if ("getPage".equals(actionName)) {
Application application = rapidRequest.getApplication();
Page page = rapidRequest.getPage();
if (page != null) {
// assume we can't find the user
String userDescription = "unknown";
// get the user
User user = application.getSecurityAdapter().getUser(rapidRequest);
// if we had one and they have a description use it
if (user != null) if (user.getDescription() != null) userDescription = user.getDescription();
// remove any existing page locks for this user
application.removeUserPageLocks(getServletContext(), userName);
// check the page lock (which removes it if it has expired)
page.checkLock();
// if there is no current lock add a fresh one for the current user
if (page.getLock() == null) page.setLock(new Lock(userName, userDescription, new Date()));
// turn it into json
JSONObject jsonPage = new JSONObject(page);
// remove the bodyHtml property as it in the designer
jsonPage.remove("htmlBody");
// remove the rolesHtml property as it is rebuilt in the designer
jsonPage.remove("rolesHtml");
// remove allControls (the single all-control list) it is not required
jsonPage.remove("allControls");
// remove the otherPageControls property as it is sent with getPages
jsonPage.remove("otherPageControls");
// add a nicely formatted lock time
if (page.getLock() != null && jsonPage.optJSONObject("lock") != null) {
// get the date time formatter and format the lock date time
String formattedDateTime = getLocalDateTimeFormatter().format(page.getLock().getDateTime());
// add a special property to the json
jsonPage.getJSONObject("lock").put("formattedDateTime", formattedDateTime);
}
// add the css
jsonPage.put("css", page.getAllCSS(getServletContext(), application));
// add the device as page properties (even though we store this in the app)
jsonPage.put("device", 1);
jsonPage.put("zoom", 1);
jsonPage.put("orientation", "P");
// add the form page type
jsonPage.put("formPageType", page.getFormPageType());
// get any theme
Theme theme = application.getTheme(getServletContext());
// if there was one
if (theme != null) {
// add header html
jsonPage.put("headerHtml", theme.getHeaderHtml());
// add footer html
jsonPage.put("footerHtml", theme.getFooterHtml());
}
// print it to the output
output = jsonPage.toString();
// send as json response
sendJsonOutput(response, output);
}
} else if ("getFlows".equals(actionName)) {
// the JSON array of workflows we are going to return
JSONArray jsonFlows = new JSONArray();
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("id", "1");
jsonFlow.put("name", "Test");
// add it to the array
jsonFlows.put(jsonFlow);
// print it to the output
output = jsonFlows.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("getFlowVersions".equals(actionName)) {
// the JSON array of workflows we are going to return
JSONArray jsonFlows = new JSONArray();
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("version", "1");
jsonFlow.put("status", "0");
// the JSON array of workflows we are going to return
JSONArray jsonActions = new JSONArray();
JSONArray jsonAllActions = getJsonActions();
// loop all actions for now
for (int i = 0; i < jsonAllActions.length(); i++) {
// get all action
JSONObject jsonAllAction = jsonAllActions.getJSONObject(i);
// if it is allowed in workflow
if (jsonAllAction.optBoolean("canUseWorkflow")) {
JSONObject jsonAction = new JSONObject();
jsonAction.put("type", jsonAllActions.getJSONObject(i).getString("type"));
jsonActions.put(jsonAction);
}
}
jsonFlow.put("actions",jsonActions);
// add it to the array
jsonFlows.put(jsonFlow);
// print it to the output
output = jsonFlows.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("getFlow".equals(actionName)) {
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("id", "1");
jsonFlow.put("name", "Test");
// print it to the output
output = jsonFlow.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("checkApp".equals(actionName)) {
String appName = request.getParameter("name");
if (appName != null) {
// retain whether we have an app with this name
boolean exists = getApplications().exists(Files.safeName(appName));
// set the response
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkVersion".equals(actionName)) {
String appName = request.getParameter("name");
String appVersion = request.getParameter("version");
if (appName != null && appVersion != null ) {
// retain whether we have an app with this name
boolean exists = getApplications().exists(Files.safeName(appName), Files.safeName(appVersion));
// set the response
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkPage".equals(actionName)) {
String pageName = request.getParameter("name");
if (pageName != null) {
// retain whether we have an app with this name
boolean pageExists = false;
// get the application
Application application = rapidRequest.getApplication();
if (application != null) {
for (PageHeader page : application.getPages().getSortedPages()) {
if (pageName.toLowerCase().equals(page.getName().toLowerCase())) {
pageExists = true;
break;
}
}
}
// set the output
output = Boolean.toString(pageExists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkWorkflow".equals(actionName)) {
String name = request.getParameter("name");
if (name != null) {
// retain whether we have an app with this name
boolean exists = false;
// get the workflows
Workflows workflows = getWorkflows();
// look for this on
Workflow workflow = workflows.get(Files.safeName(name));
// if we got one
if (workflow != null) exists = true;
// set the output
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("pages".equals(actionName) || "questions".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) {
// set response as text
response.setContentType("text/text");
// get a writer from the response
PrintWriter out = response.getWriter();
// get the application
Application application = rapidRequest.getApplication();
// print the app name and version
out.print(application.getName() + "\t" + application.getVersion() + "\n");
// get the page headers
PageHeaders pageHeaders = application.getPages().getSortedPages();
// loop the page headers
for (PageHeader pageHeader : pageHeaders) {
// get the page
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// get the label
String label = page.getLabel();
// if we got one
if (label == null) {
label = "";
} else {
if (label.length() > 0) label = " - " + label;
}
if ("questions".equals(actionName)) {
out.print(page.getName() + label);
} else {
// print the page name
out.print(page.getId() + " " + page.getName() + label);
}
// check questions, summary, detail
if ("questions".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) {
// print the number of controls
if ("questions".equals(actionName)) {
out.print("\r\n");
} else {
out.print(" - number of controls: " + page.getAllControls().size() + "\r\n");
}
// if detail
if ("detail".equals(actionName)) {
// print the page properties
out.print("Name\t" + page.getName() + "\n");
out.print("Title\t" + page.getTitle() + "\n");
out.print("Description\t" + page.getDescription() + "\n");
out.print("Simple\t" + page.getSimple() + "\n");
out.print("HideHeaderFooter\t" + page.getHideHeaderFooter() + "\n");
}
// if questions
if (!"questions".equals(actionName)) printEventsDetails(page.getEvents(), out);
// get the controls
List<Control> controls = page.getAllControls();
// loop them
for (Control control : controls) {
// get the name
String name = control.getName();
// null check
if (name != null) {
if (name.trim().length() > 0) {
// get the label
label = control.getLabel();
// get the type
String type = control.getType();
// exclude panels, hidden values, and datastores for summary
if ("detail".equals(actionName) || (!"panel".equals(type) && !("hiddenvalue").equals(type) && !("dataStore").equals(type))) {
if ("questions".equals(actionName)) {
// print the control label
if (label != null && !control.getType().contains("button")) out.print("\t" + label + "\n");
} else {
// print the control details
out.print(control.getId() +"\t" + type + "\t" + name + "\t" + label + "\n");
}
// if details
if ("detail".equals(actionName)) {
// get the properties
Map<String, String> properties = control.getProperties();
// get a list we'll sort for them
List<String> sortedKeys = new ArrayList<String>();
// loop them
for (String key : properties.keySet()) {
// add to sorted list
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop them
for (String key : sortedKeys) {
// print the properties
out.print(key + "\t" + properties.get(key) + "\n");
}
// print the event details
printEventsDetails(control.getEvents(), out);
} // detail check
}
}
}
}
} else {
out.print("\n");
}
}
// close the writer
out.close();
// send it immediately
out.flush();
} else if ("export".equals(actionName)) {
// get the application
Application application = rapidRequest.getApplication();
// check we've got one
if (application != null) {
// create the zip file
application.zip(this, rapidRequest, rapidUser, application.getId() + ".zip");
// set the type as a .zip
response.setContentType("application/x-zip-compressed");
// Shows the download dialog
response.setHeader("Content-disposition","attachment; filename=" + application.getId() + ".zip");
// get the file for the zip we're about to create
File zipFile = new File(getServletContext().getRealPath("/WEB-INF/temp/" + application.getId() + ".zip"));
// send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(zipFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
// delete the .zip file
zipFile.delete();
output = "Zip file sent";
} // got application
} else if ("updateids".equals(actionName)) {
// get a writer from the response
PrintWriter out = response.getWriter();
// check we have admin too
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.ADMIN_ROLE)) {
// retain the ServletContext
ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
// get the suffix
String suffix = rapidRequest.getRapidServlet().getControlAndActionSuffix();
// set response as text
response.setContentType("text/text");
// get the application
Application application = rapidRequest.getApplication();
// print the app name and version
out.print("Application : " + application.getName() + "/" + application.getVersion() + "\n");
// get the page headers
PageHeaders pageHeaders = application.getPages().getSortedPages();
// get the pages config folder
File appPagesFolder = new File(application.getConfigFolder(servletContext) + "/pages");
// check it exists
if (appPagesFolder.exists()) {
// loop the page headers
for (PageHeader pageHeader : pageHeaders) {
// get the page
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// print the page name and id
out.print("\nPage : " + page.getName() + "/" + page.getId() + "\n\n");
// loop the files
for (File pageFile : appPagesFolder.listFiles()) {
// if this is a page.xml file
if (pageFile.getName().endsWith(".page.xml")) {
// assume no id's found
// read the copy to a string
String pageXML = Strings.getString(pageFile);
// get all page controls
List<Control> controls = page.getAllControls();
// loop controls
for (Control control : controls) {
// get old/current id
String id = control.getId();
// assume new id will be the same
String newId = id;
// drop suffix if starts with it
if (newId.startsWith(suffix)) newId = newId.substring(suffix.length());
// add suffix to end
newId += suffix;
// check if id in file
if (pageXML.contains(id)) {
// show old and new id
out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n");
// replace
pageXML = pageXML.replace(id, newId);
}
}
// get all page actions
List<Action> actions = page.getAllActions();
// loop actions
for (Action action : actions) {
// get old/current id
String id = action.getId();
// assume new id will be the same
String newId = id;
// drop suffix if starts with it
if (newId.startsWith(suffix)) newId = newId.substring(suffix.length());
// add suffix to end if not there already
if (!newId.endsWith("_" + suffix)) newId += suffix;
// check if id in file
if (pageXML.contains(id)) {
// show old and new id
out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n");
// replace
pageXML = pageXML.replace(id, newId);
}
}
// save it back
Strings.saveString(pageXML, pageFile);
} //page ending check
} // page file loop
} //page loop
// get the application file
File applicationFile = new File(application.getConfigFolder(servletContext) + "/application.xml");
// if it exists
if (applicationFile.exists()) {
// reload the application from file
Application reloadedApplication = Application.load(servletContext, applicationFile, true);
// replace it into the applications collection
getApplications().put(reloadedApplication);
}
} // app pages folder exists
} else {
// not authenticated
response.setStatus(403);
// say so
out.print("Not authorised");
}
// close the writer
out.close();
// send it immediately
out.flush();
} // action name check
} else {
// not authenticated
response.setStatus(403);
} // got design role
} // rapidSecurity != null
} // rapidApplication != null
// log the response
getLogger().debug("Designer GET response : " + output);
} catch (Exception ex) {
getLogger().debug("Designer GET error : " + ex.getMessage(), ex);
sendException(rapidRequest, response, ex);
}
}
private Control createControl(JSONObject jsonControl) throws JSONException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
// instantiate the control with the JSON
Control control = new Control(jsonControl);
// look in the JSON for a validation object
JSONObject jsonValidation = jsonControl.optJSONObject("validation");
// add the validation object if we got one
if (jsonValidation != null) control.setValidation(Control.getValidation(this, jsonValidation));
// look in the JSON for an event array
JSONArray jsonEvents = jsonControl.optJSONArray("events");
// add the events if we found one
if (jsonEvents != null) control.setEvents(Control.getEvents(this, jsonEvents));
// look in the JSON for a styles array
JSONArray jsonStyles = jsonControl.optJSONArray("styles");
// if there were styles
if (jsonStyles != null) control.setStyles(Control.getStyles(this, jsonStyles));
// look in the JSON for any child controls
JSONArray jsonControls = jsonControl.optJSONArray("childControls");
// if there were child controls loop and create controls interatively
if (jsonControls != null) {
for (int i = 0; i < jsonControls.length(); i++) {
control.addChildControl(createControl(jsonControls.getJSONObject(i)));
}
}
// return the control we just made
return control;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RapidRequest rapidRequest = new RapidRequest(this, request);
try {
String output = "";
// read bytes from request body into our own byte array (this means we can deal with images)
InputStream input = request.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (int length = 0; (length = input.read(_byteBuffer)) > -1;) outputStream.write(_byteBuffer, 0, length);
byte[] bodyBytes = outputStream.toByteArray();
// get the rapid application
Application rapidApplication = getApplications().get("rapid");
// check we got one
if (rapidApplication != null) {
// get rapid security
SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();
// check we got some
if (rapidSecurity != null) {
// get user name
String userName = rapidRequest.getUserName();
if (userName == null) userName = "";
// check permission
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {
Application application = rapidRequest.getApplication();
if (application != null) {
if ("savePage".equals(rapidRequest.getActionName())) {
String bodyString = new String(bodyBytes, "UTF-8");
getLogger().debug("Designer POST request : " + request.getQueryString() + " body : " + bodyString);
JSONObject jsonPage = new JSONObject(bodyString);
// instantiate a new blank page
Page newPage = new Page();
// set page properties
newPage.setId(jsonPage.optString("id"));
newPage.setName(jsonPage.optString("name"));
newPage.setTitle(jsonPage.optString("title"));
newPage.setFormPageType(jsonPage.optInt("formPageType"));
newPage.setLabel(jsonPage.optString("label"));
newPage.setDescription(jsonPage.optString("description"));
newPage.setSimple(jsonPage.optBoolean("simple"));
newPage.setHideHeaderFooter(jsonPage.optBoolean("hideHeaderFooter"));
// look in the JSON for an event array
JSONArray jsonEvents = jsonPage.optJSONArray("events");
// add the events if we found one
if (jsonEvents != null) newPage.setEvents(Control.getEvents(this, jsonEvents));
// look in the JSON for a styles array
JSONArray jsonStyles = jsonPage.optJSONArray("styles");
// if there were styles get and save
if (jsonStyles != null) newPage.setStyles(Control.getStyles(this, jsonStyles));
// look in the JSON for a style classes array
JSONArray jsonStyleClasses = jsonPage.optJSONArray("classes");
// if there were style classes
if (jsonStyleClasses != null) {
// start with empty string
String styleClasses = "";
// loop array and build classes list
for (int i = 0; i < jsonStyleClasses.length(); i++) styleClasses += jsonStyleClasses.getString(i) + " ";
// trim for good measure
styleClasses = styleClasses.trim();
// store if something there
if (styleClasses.length() > 0) newPage.setBodyStyleClasses(styleClasses);
}
// if there are child controls from the page loop them and add to the pages control collection
JSONArray jsonControls = jsonPage.optJSONArray("childControls");
if (jsonControls != null) {
for (int i = 0; i < jsonControls.length(); i++) {
// get the JSON control
JSONObject jsonControl = jsonControls.getJSONObject(i);
// call our function so it can go iterative
newPage.addControl(createControl(jsonControl));
}
}
// if there are roles specified for this page
JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
if (jsonUserRoles != null) {
List<String> userRoles = new ArrayList<String>();
for (int i = 0; i < jsonUserRoles.length(); i++) {
// get the JSON role
String jsonUserRole = jsonUserRoles.getString(i);
// add to collection
userRoles.add(jsonUserRole);
}
// assign to page
newPage.setRoles(userRoles);
}
// look in the JSON for a sessionVariables array
JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
// if we found one
if (jsonSessionVariables != null) {
List<String> sessionVariables = new ArrayList<String>();
for (int i = 0; i < jsonSessionVariables.length(); i++) {
sessionVariables.add(jsonSessionVariables.getString(i));
}
newPage.setSessionVariables(sessionVariables);
}
// look in the JSON for a pageVisibilityRules array
JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
// if we found one
if (jsonVisibilityConditions != null) {
List<Condition> visibilityConditions = new ArrayList<Condition>();
for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
visibilityConditions.add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
}
newPage.setVisibilityConditions(visibilityConditions);
}
// look in the JSON for a pageVisibilityRules array is an and or or (default to and)
String jsonConditionsType = jsonPage.optString("conditionsType","and");
// set what we got
newPage.setConditionsType(jsonConditionsType);
// retrieve the html body
String htmlBody = jsonPage.optString("htmlBody");
// if we got one trim it and retain in page
if (htmlBody != null) newPage.setHtmlBody(htmlBody.trim());
// look in the JSON for roleControlhtml
JSONObject jsonRoleControlHtml = jsonPage.optJSONObject("roleControlHtml");
// if we found some add it to the page
if (jsonRoleControlHtml != null) newPage.setRoleControlHtml(new RoleControlHtml(jsonRoleControlHtml));
// fetch a copy of the old page (if there is one)
Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
// if the page's name changed we need to remove it
if (oldPage != null) {
if (!oldPage.getName().equals(newPage.getName())) {
oldPage.delete(this, rapidRequest, application);
}
}
// save the new page to file
newPage.save(this, rapidRequest, application, true);
// get any pages collection (we're only sent it if it's been changed)
JSONArray jsonPages = jsonPage.optJSONArray("pages");
// if we got some
if (jsonPages != null) {
// the start page id
String startPageId = null;
// make a new map for the page orders
Map<String, Integer> pageOrders = new HashMap<String, Integer>();
// loop the page orders
for (int i = 0; i < jsonPages.length(); i++) {
// get the page id
String pageId = jsonPages.getJSONObject(i).getString("id");
// add the order to the map
pageOrders.put(pageId, i);
// retain page id if first one
if (i == 0) startPageId = pageId;
}
// replace the application pageOrders map
application.setPageOrders(pageOrders);
// update the application start page
application.setStartPageId(startPageId);
// save the application and the new orders
application.save(this, rapidRequest, true);
}
boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
if (jsonPageOrderReset) {
// empty the application pageOrders map so everything goes alphabetical
application.setPageOrders(null);
}
// send a positive message
output = "{\"message\":\"Saved!\"}";
// set the response type to json
response.setContentType("application/json");
} else if ("testSQL".equals(rapidRequest.getActionName())) {
// turn the body bytes into a string
String bodyString = new String(bodyBytes, "UTF-8");
JSONObject jsonQuery = new JSONObject(bodyString);
JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");
JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");
Parameters parameters = new Parameters();
if (jsonInputs != null) {
for (int i = 0; i < jsonInputs.length(); i++) parameters.addNull();
}
DatabaseConnection databaseConnection = application.getDatabaseConnections().get(jsonQuery.optInt("databaseConnectionIndex",0));
ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(), application);
DataFactory df = new DataFactory(ca);
int outputs = 0;
// if got some outputs reduce the check count for any duplicates
if (jsonOutputs != null) {
// start with full number of outputs
outputs = jsonOutputs.length();
// retain fields
List<String> fieldList = new ArrayList<String>();
// loop outputs
for (int i = 0; i < jsonOutputs.length(); i++) {
// look for a field
String field = jsonOutputs.getJSONObject(i).optString("field", null);
// if we got one
if (field != null) {
// check if we have it already
if (fieldList.contains(field)) {
// we do so reduce the control count by one
outputs --;
} else {
// we don't have this field yet so remember
fieldList.add(field);
}
}
}
}
String sql = jsonQuery.getString("SQL").trim();
// merge in any parameters
sql = application.insertParameters(getServletContext(), sql);
// some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
sql = sql.replace("\n", " ");
if (outputs == 0) {
if (sql.toLowerCase().startsWith("select")) {
throw new Exception("Select statement should have at least one output");
} else {
df.getPreparedStatement(rapidRequest,sql , parameters);
}
} else {
ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
if (outputs > cols) throw new Exception(outputs + " outputs, but only " + cols + " column" + (cols > 1 ? "s" : "") + " selected");
for (int i = 0; i < outputs; i++) {
JSONObject jsonOutput = jsonOutputs.getJSONObject(i);
String field = jsonOutput.optString("field","");
if (!"".equals(field)) {
field = field.toLowerCase();
boolean gotOutput = false;
for (int j = 0; j < cols; j++) {
String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();
if (field.equals(sqlField)) {
gotOutput = true;
break;
}
}
if (!gotOutput) {
rs.close();
df.close();
throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " is not present in selected columns");
}
}
}
// close the recordset
rs.close();
// close the data factory
df.close();
}
// send a positive message
output = "{\"message\":\"OK\"}";
// set the response type to json
response.setContentType("application/json");
} else if ("uploadImage".equals(rapidRequest.getActionName()) || "import".equals(rapidRequest.getActionName())) {
// get the content type from the request
String contentType = request.getContentType();
// get the position of the boundary from the content type
int boundaryPosition = contentType.indexOf("boundary=");
// derive the start of the meaning data by finding the boundary
String boundary = contentType.substring(boundaryPosition + 10);
// this is the double line break after which the data occurs
byte[] pattern = {0x0D, 0x0A, 0x0D, 0x0A};
// find the position of the double line break
int dataPosition = Bytes.findPattern(bodyBytes, pattern );
// the body header is everything up to the data
String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
// find the position of the filename in the data header
int filenamePosition = header.indexOf("filename=\"");
// extract the file name
String filename = header.substring(filenamePosition + 10, header.indexOf("\"", filenamePosition + 10));
// find the position of the file type in the data header
int fileTypePosition = header.toLowerCase().indexOf("type:");
// extract the file type
String fileType = header.substring(fileTypePosition + 6);
if ("uploadImage".equals(rapidRequest.getActionName())) {
// check the file type
if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif") && !fileType.equals("image/png") && !fileType.equals("image/svg+xml")) throw new Exception("Unsupported file type");
// get the web folder from the application
String path = rapidRequest.getApplication().getWebFolder(getServletContext());
// create a file output stream to save the data to
FileOutputStream fos = new FileOutputStream (path + "/" + filename);
// write the file data to the stream
fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9);
// close the stream
fos.close();
// log the file creation
getLogger().debug("Saved image file " + path + filename);
// create the response with the file name and upload type
output = "{\"file\":\"" + filename + "\",\"type\":\"" + rapidRequest.getActionName() + "\"}";
} else if ("import".equals(rapidRequest.getActionName())) {
// check the file type
if (!"application/x-zip-compressed".equals(fileType) && !"application/zip".equals(fileType)) throw new Exception("Unsupported file type");
// get the name
String appName = request.getParameter("name");
// check we were given one
if (appName == null) throw new Exception("Name must be provided");
// get the version
String appVersion = request.getParameter("version");
// check we were given one
if (appVersion == null) throw new Exception("Version must be provided");
// make the id from the safe and lower case name
String appId = Files.safeName(appName).toLowerCase();
// make the version from the safe and lower case name
appVersion = Files.safeName(appVersion);
// get application destination folder
File appFolderDest = new File(Application.getConfigFolder(getServletContext(), appId, appVersion));
// get web contents destination folder
File webFolderDest = new File(Application.getWebFolder(getServletContext(), appId, appVersion));
// look for an existing application of this name and version
Application existingApplication = getApplications().get(appId, appVersion);
// if we have an existing application
if (existingApplication != null) {
// back it up first
existingApplication.backup(this, rapidRequest, false);
}
// get a file for the temp directory
File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
// create it if not there
if (!tempDir.exists()) tempDir.mkdir();
// the path we're saving to is the temp folder
String path = getServletContext().getRealPath("/WEB-INF/temp/" + appId + ".zip");
// create a file output stream to save the data to
FileOutputStream fos = new FileOutputStream (path);
// write the file data to the stream
fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9);
// close the stream
fos.close();
// log the file creation
getLogger().debug("Saved import file " + path);
// get a file object for the zip file
File zipFile = new File(path);
// load it into a zip file object
ZipFile zip = new ZipFile(zipFile);
// unzip the file
zip.unZip();
// delete the zip file
zipFile.delete();
// unzip folder (for deletion)
File unZipFolder = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId));
// get application folders
File appFolderSource = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
// get web content folders
File webFolderSource = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WebContent" ));
// check we have the right source folders
if (webFolderSource.exists() && appFolderSource.exists()) {
// get application.xml file
File appFileSource = new File (appFolderSource + "/application.xml");
if (appFileSource.exists()) {
// delete the appFolder if it exists
if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest);
// delete the webFolder if it exists
if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest);
// copy application content
Files.copyFolder(appFolderSource, appFolderDest);
// copy web content
Files.copyFolder(webFolderSource, webFolderDest);
try {
// load the new application (but don't initialise, nor load pages)
Application appNew = Application.load(getServletContext(), new File (appFolderDest + "/application.xml"), false);
// update application name
appNew.setName(appName);
// get the old id
String appOldId = appNew.getId();
// make the new id
appId = Files.safeName(appName).toLowerCase();
// update the id
appNew.setId(appId);
// get the old version
String appOldVersion = appNew.getVersion();
// make the new version
appVersion = Files.safeName(appVersion);
// update the version
appNew.setVersion(appVersion);
// update the created date
appNew.setCreatedDate(new Date());
// set the status to In development
appNew.setStatus(Application.STATUS_DEVELOPMENT);
// a map of actions that might be removed from any of the pages
Map<String,Integer> removedActions = new HashMap<String, Integer>();
// look for page files
File pagesFolder = new File(appFolderDest.getAbsolutePath() + "/pages");
// if the folder is there
if (pagesFolder.exists()) {
// create a filter for finding .page.xml files
FilenameFilter xmlFilenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".page.xml");
}
};
// loop the .page.xml files
for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {
// read the file into a string
String fileString = Strings.getString(pageFile);
// prepare a new file string which will update into
String newFileString = null;
// if the old app did not have a version (for backwards compatibility)
if (appOldVersion == null) {
// replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
newFileString = fileString
.replace("applications/" + appOldId + "/", "applications/" + appId + "/" + appVersion + "/")
.replace("~?a=" + appOldId + "&", "~?a=" + appId + "&v=" + appVersion + "&")
.replace("~?a=" + appOldId + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&");
} else {
// replace all properties that appear to have a url, and all created links - note the fix for double encoding
newFileString = fileString
.replace("applications/" + appOldId + "/" + appOldVersion + "/", "applications/" + appId + "/" + appVersion + "/")
.replace("~?a=" + appOldId + "&v=" + appOldVersion + "&", "~?a=" + appId + "&v=" + appVersion + "&")
.replace("~?a=" + appOldId + "&amp;v=" + appOldVersion + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&");
}
// now open the string into a document
Document pageDocument = XML.openDocument(newFileString);
// get an xpath factory
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
// an expression for any attributes with a local name of "type"
XPathExpression expr = xpath.compile("//@*[local-name()='type']");
// get them
NodeList nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET);
// get out system actions
JSONArray jsonActions = getJsonActions();
// if we found any elements with a type attribute and we have system actions
if (nl.getLength() > 0 && jsonActions.length() > 0) {
// a list of action types
List<String> types = new ArrayList<String>();
// loop the json actions
for (int i = 0; i < jsonActions.length(); i++) types.add(jsonActions.getJSONObject(i).optString("type").toLowerCase());
// loop the action attributes we found
for (int i = 0; i < nl.getLength(); i++) {
// get this attribute
Attr a = (Attr) nl.item(i);
// get the value of the type
String type = a.getTextContent().toLowerCase();
// get the element the attribute is in
Node n = a.getOwnerElement();
// if we don't know about this action type
if (!types.contains(type)) {
// get the parent node
Node p = n.getParentNode();
// remove this node
p.removeChild(n);
// if we have removed this type already
if (removedActions.containsKey(type)) {
// increment the entry for this type
removedActions.put(type, removedActions.get(type) + 1);
} else {
// add an entry for this type
removedActions.put(type, 1);
}
} // got type check
} // attribute loop
} // attribute and system action check
// use the transformer to write to disk
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(pageDocument);
StreamResult result = new StreamResult(pageFile);
transformer.transform(source, result);
} // page xml file loop
} // pages folder check
// now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
appNew.initialise(getServletContext(), false);
// get the security for this application
SecurityAdapter security = appNew.getSecurityAdapter();
// if we have one
if (security != null) {
// assume we don't have the user
boolean gotUser = false;
// get the current users record from the adapter
User user = security.getUser(rapidRequest);
// check the current user is present in the app's security adapter
if (user != null) {
// now check the current user password is correct too
if (security.checkUserPassword(rapidRequest, userName, rapidRequest.getUserPassword())) {
// we have the right user with the right password
gotUser = true;
} else {
// remove this user in case there is one with the same name but the password does not match
security.deleteUser(rapidRequest);
}
}
// if we don't have the user
if (!gotUser) {
// get the current user from the Rapid application
User rapidUser = rapidSecurity.getUser(rapidRequest);
// create a new user based on the Rapid user
user = new User(rapidUser);
// add the new user
security.addUser(rapidRequest, user);
}
// add Admin and Design roles for the new user if required
if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE))
security.addUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE);
if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE))
security.addUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE);
}
// if any items were removed
if (removedActions.keySet().size() > 0) {
// a description of what was removed
String removed = "";
// loop the entries
for (String type : removedActions.keySet()) {
int count = removedActions.get(type);
removed += "removed " + count + " " + type + " action" + (count == 1 ? "" : "s") + " on import\n";
}
// get the current description
String description = appNew.getDescription();
// if null set to empty string
if (description == null) description = "";
// add a line break if need be
if (description.length() > 0) description += "\n";
// add the removed
description += removed;
// set it back
appNew.setDescription(description);
}
// reload the pages (actually clears down the pages collection and reloads the headers)
appNew.getPages().loadpages(getServletContext());
// save application (this will also initialise and rebuild the resources)
appNew.save(this, rapidRequest, false);
// add application to the collection
getApplications().put(appNew);
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// send a positive message
output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\"" + appNew.getVersion() + "\"}";
} catch (Exception ex) {
// delete the appFolder if it exists
if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest);
// if the parent is empty delete it too
if (appFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(appFolderDest.getParentFile());
// delete the webFolder if it exists
if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest);
// if the parent is empty delete it too
if (webFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(webFolderDest.getParentFile());
// rethrow exception
throw ex;
}
} else {
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// throw excpetion
throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");
}
} else {
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// throw excpetion
throw new Exception("Must be a valid Rapid file");
}
}
}
getLogger().debug("Designer POST response : " + output);
PrintWriter out = response.getWriter();
out.print(output);
out.close();
} // got an application
} // got rapid design role
} // got rapid security
} // got rapid application
} catch (Exception ex) {
getLogger().error("Designer POST error : ",ex);
sendException(rapidRequest, response, ex);
}
}
}
| src/com/rapid/server/Designer.java | /*
Copyright (C) 2017 - Gareth Edwards / Rapid Information Systems
[email protected]
This file is part of the Rapid Application Platform
Rapid 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. The terms require you
to include the original copyright, and the license notice in all redistributions.
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
in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>.
*/
package com.rapid.server;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.rapid.actions.Logic.Condition;
import com.rapid.core.Action;
import com.rapid.core.Application;
import com.rapid.core.Application.ValueList;
import com.rapid.core.Applications.Versions;
import com.rapid.core.Control;
import com.rapid.core.Event;
import com.rapid.core.Page;
import com.rapid.core.Page.Lock;
import com.rapid.core.Page.RoleControlHtml;
import com.rapid.core.Pages.PageHeader;
import com.rapid.core.Pages.PageHeaders;
import com.rapid.core.Theme;
import com.rapid.core.Workflow;
import com.rapid.core.Workflows;
import com.rapid.data.ConnectionAdapter;
import com.rapid.data.DataFactory;
import com.rapid.data.DataFactory.Parameters;
import com.rapid.data.DatabaseConnection;
import com.rapid.forms.FormAdapter;
import com.rapid.security.SecurityAdapter;
import com.rapid.security.SecurityAdapter.Role;
import com.rapid.security.SecurityAdapter.User;
import com.rapid.utils.Bytes;
import com.rapid.utils.Files;
import com.rapid.utils.Strings;
import com.rapid.utils.XML;
import com.rapid.utils.ZipFile;
public class Designer extends RapidHttpServlet {
private static final long serialVersionUID = 2L;
// this byte buffer is used for reading the post data
byte[] _byteBuffer = new byte[1024];
public Designer() { super(); }
// helper method to set the content type, write, and close the stream for common JSON output
private void sendJsonOutput(HttpServletResponse response, String output) throws IOException {
// set response as json
response.setContentType("application/json");
// get a writer from the response
PrintWriter out = response.getWriter();
// write the output into the response
out.print(output);
// close the writer
out.close();
// send it immediately
out.flush();
}
// print details of an action
private void printActionDetails(Action action, PrintWriter out) {
// print the action
out.print("\t\tAction\t" + action.getId()+ "\n");
// get the properties
Map<String, String> properties = action.getProperties();
// create a sorted list
List<String> sortedKeys = new ArrayList<String>();
// loop them
for (String key : properties.keySet()) {
// add
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop the sorted keys
for (String key : sortedKeys) {
// print the property
out.print("\t\t\t" + key + "\t" + properties.get(key) + "\n");
}
// get a JSONObejct for them
JSONObject jsonAction = new JSONObject(action);
// get it's properties
Iterator<String> keys = jsonAction.keys();
// clear the sorted key list
sortedKeys.clear();
// loop them
while (keys.hasNext()) {
// get the next one
String key = keys.next();
// add it to the list
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop the sorted keys
for (String key : sortedKeys) {
// print it
try {
out.print("\t\t\t" + key + "\t" + jsonAction.get(key) + "\n");
} catch (JSONException e) { }
}
// check child actions
if (action.getChildActions() != null) {
if (action.getChildActions().size() > 0) {
// loop them
for (Action childAction : action.getChildActions()) {
// print the child actions
printActionDetails(childAction, out);
}
}
}
}
// print details of events (used by page and controls)
private void printEventsDetails(List<Event> events, PrintWriter out) {
// check events
if (events!= null) {
if (events.size() > 0) {
// loop them
for (Event event : events) {
// check actions
if (event.getActions() != null) {
if (event.getActions().size() > 0) {
// print the event
out.print("\tEvent\t" + event.getType() + "\n");
// loop the actions
for (Action action : event.getActions()) {
// print the action details
printActionDetails( action, out);
}
}
}
}
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// fake a delay for testing slow servers
// try { Thread.sleep(3000); } catch (InterruptedException e) {}
RapidRequest rapidRequest = new RapidRequest(this, request);
try {
getLogger().debug("Designer GET request : " + request.getQueryString());
String actionName = rapidRequest.getActionName();
String output = "";
// get the rapid application
Application rapidApplication = getApplications().get("rapid");
// check we got one
if (rapidApplication != null) {
// get rapid security
SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();
// check we got some
if (rapidSecurity != null) {
// get the user name
String userName = rapidRequest.getUserName();
// get the rapid user
User rapidUser = rapidSecurity.getUser(rapidRequest);
// check permission
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {
// whether we're trying to avoid caching
boolean noCaching = Boolean.parseBoolean(getServletContext().getInitParameter("noCaching"));
if (noCaching) {
// try and avoid caching
response.setHeader("Expires", "Sat, 15 March 1980 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
if ("getSystemData".equals(actionName)) {
// create a system data object
JSONObject jsonSystemData = new JSONObject();
// add the controls
jsonSystemData.put("controls", getJsonControls());
// add the actions
jsonSystemData.put("actions", getJsonActions());
// add the devices
jsonSystemData.put("devices", getDevices());
// add the local date format
jsonSystemData.put("localDateFormat", getLocalDateFormat());
// look for a controlAndActionSuffix
String controlAndActionSuffix = request.getServletContext().getInitParameter("controlAndActionSuffix");
// update to empty string if not present - this is the default and expected for older versions of the web.xml
if (controlAndActionSuffix == null) controlAndActionSuffix = "";
// add the controlAndActionPrefix
jsonSystemData.put("controlAndActionSuffix", controlAndActionSuffix);
// put into output string
output = jsonSystemData.toString();
// send output as json
sendJsonOutput(response, output);
} else if ("getApps".equals(actionName)) {
// create a json array for holding our apps
JSONArray jsonApps = new JSONArray();
// get a sorted list of the applications
for (String id : getApplications().getIds()) {
// loop the versions
for (String version : getApplications().getVersions(id).keySet()) {
// get the this application version
Application application = getApplications().get(id, version);
// get the security
SecurityAdapter security = application.getSecurityAdapter();
// recreate the request in the name of this app
RapidRequest appRequest = new RapidRequest(this, request, application);
// check the users password
if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) {
// check the users permission to design this application
boolean designPermission = security.checkUserRole(appRequest, Rapid.DESIGN_ROLE);
// if app is rapid do a further check
if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE);
// if we got permssion - add this application to the list
if (designPermission) {
// create a json object
JSONObject jsonApplication = new JSONObject();
// add the details we want
jsonApplication.put("id", application.getId());
jsonApplication.put("name", application.getName());
jsonApplication.put("title", application.getTitle());
// add the object to the collection
jsonApps.put(jsonApplication);
// no need to check any further versions
break;
}
}
}
}
output = jsonApps.toString();
sendJsonOutput(response, output);
} else if ("getVersions".equals(actionName)) {
// create a json array for holding our apps
JSONArray jsonVersions = new JSONArray();
// get the app id
String appId = rapidRequest.getAppId();
// get the versions
Versions versions = getApplications().getVersions(appId);
// if there are any
if (versions != null) {
// loop the list of applications sorted by id (with rapid last)
for (Application application : versions.sort()) {
// get the security
SecurityAdapter security = application.getSecurityAdapter();
// recreate the request in the name of this app
RapidRequest appRequest = new RapidRequest(this, request, application);
// check the users password
if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) {
// check the users permission to design this application
boolean designPermission = application.getSecurityAdapter().checkUserRole(appRequest, Rapid.DESIGN_ROLE);
// if app is rapid do a further check
if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE);
// check the RapidDesign role is present in the users roles for this application
if (designPermission) {
// make a json object for this version
JSONObject jsonVersion = new JSONObject();
// add the app id
jsonVersion.put("id", application.getId());
// add the version
jsonVersion.put("version", application.getVersion());
// add the status
jsonVersion.put("status", application.getStatus());
// add the title
jsonVersion.put("title", application.getTitle());
// add a formAdapter if present
if (application.getIsForm()) jsonVersion.put("isForm", true);
// add whether to show control Ids
jsonVersion.put("showControlIds", application.getShowControlIds());
// add whether to show action Ids
jsonVersion.put("showActionIds", application.getShowActionIds());
// add the web folder so we can update the iframe style sheets
jsonVersion.put("webFolder", Application.getWebFolder(application));
// get the database connections
List<DatabaseConnection> databaseConnections = application.getDatabaseConnections();
// check we have any
if (databaseConnections != null) {
// make an object we're going to return
JSONArray jsonDatabaseConnections = new JSONArray();
// loop the connections
for (DatabaseConnection databaseConnection : databaseConnections) {
// add the connection name
jsonDatabaseConnections.put(databaseConnection.getName());
}
// add the connections to the app
jsonVersion.put("databaseConnections", jsonDatabaseConnections);
}
// make an object we're going to return
JSONArray jsonRoles = new JSONArray();
// retrieve the roles
List<Role> roles = security.getRoles(appRequest);
// check we got some
if (roles != null) {
// create a collection of names
ArrayList<String> roleNames = new ArrayList<String>();
// copy the names in if non-null
for (Role role : roles) if (role.getName() != null) roleNames.add(role.getName());
// sort them
Collections.sort(roleNames);
// loop the sorted connections
for (String roleName : roleNames) {
// only add role if this is the rapid app, or it's not a special rapid permission
if ("rapid".equals(application.getId()) || (!Rapid.ADMIN_ROLE.equals(roleName) && !Rapid.DESIGN_ROLE.equals(roleName)&& !Rapid.SUPER_ROLE.equals(roleName))) jsonRoles.put(roleName);
}
}
// add the security roles to the app
jsonVersion.put("roles", jsonRoles);
// get any value lists
List<ValueList> valueLists = application.getValueLists();
// add all of the value lists
jsonVersion.put("valueLists", valueLists);
// get all the possible json actions
JSONArray jsonActions = getJsonActions();
// make an array for the actions in this app
JSONArray jsonAppActions = new JSONArray();
// get the types used in this app
List<String> actionTypes = application.getActionTypes();
// if we have some
if (actionTypes != null) {
// loop the types used in this app
for (String actionType : actionTypes) {
// loop all the possible actions
for (int i = 0; i < jsonActions.length(); i++) {
// get an instance to the json action
JSONObject jsonAction = jsonActions.getJSONObject(i);
// if this is the type we've been looking for
if (actionType.equals(jsonAction.getString("type"))) {
// create a simple json object for thi action
JSONObject jsonAppAction = new JSONObject();
// add just what we need
jsonAppAction.put("type", jsonAction.getString("type"));
jsonAppAction.put("name", jsonAction.getString("name"));
jsonAppAction.put("visible", jsonAction.optBoolean("visible", true));
// add it to the app actions collection
jsonAppActions.put(jsonAppAction);
// start on the next app action
break;
}
}
}
}
// put the app actions we've just built into the app
jsonVersion.put("actions", jsonAppActions);
// get all the possible json controls
JSONArray jsonControls = getJsonControls();
// make an array for the controls in this app
JSONArray jsonAppControls = new JSONArray();
// get the control types used by this app
List<String> controlTypes = application.getControlTypes();
// if we have some
if (controlTypes != null) {
// loop the types used in this app
for (String controlType : controlTypes) {
// loop all the possible controls
for (int i = 0; i < jsonControls.length(); i++) {
// get an instance to the json control
JSONObject jsonControl = jsonControls.getJSONObject(i);
// if this is the type we've been looking for
if (controlType.equals(jsonControl.getString("type"))) {
// create a simple json object for this control
JSONObject jsonAppControl = new JSONObject();
// add just what we need
jsonAppControl.put("type", jsonControl.getString("type"));
jsonAppControl.put("name", jsonControl.getString("name"));
jsonAppControl.put("image", jsonControl.optString("image"));
jsonAppControl.put("category", jsonControl.optString("category"));
jsonAppControl.put("canUserAdd", jsonControl.optString("canUserAdd"));
// add it to the app controls collection
jsonAppControls.put(jsonAppControl);
// start on the next app control
break;
}
}
}
}
// put the app controls we've just built into the app
jsonVersion.put("controls", jsonAppControls);
// create a json object for the images
JSONArray jsonImages = new JSONArray();
// get the directory in which the control xml files are stored
File dir = new File (application.getWebFolder(getServletContext()));
// create a filter for finding image files
FilenameFilter xmlFilenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".gif") || name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".svg");
}
};
// a array to hold the images as they come out of the filter
List<String> images = new ArrayList<String>();
// loop the image files in the folder
for (File imageFile : dir.listFiles(xmlFilenameFilter)) {
images.add(imageFile.getName());
}
// sort the images
Collections.sort(images);
// loop the sorted images and add to json
for (String image : images) jsonImages.put(image);
// put the images collection we've just built into the app
jsonVersion.put("images", jsonImages);
// create a json array for our style classes
JSONArray jsonStyleClasses = new JSONArray();
// get all of the possible style classes
List<String> styleClasses = application.getStyleClasses();
// if we had some
if (styleClasses != null) {
// loop and add to json array
for (String styleClass : styleClasses) jsonStyleClasses.put(styleClass);
}
// put them into our application object
jsonVersion.put("styleClasses", jsonStyleClasses);
// look for any form adpter
FormAdapter formAdapter = application.getFormAdapter();
// if we got one
if (formAdapter != null) {
// get the type
String formAdapterType = formAdapter.getType();
// get the json form adpater details
JSONArray jsonFormAdapters = getJsonFormAdapters();
// if we got some
if (jsonFormAdapters != null) {
// loop them
for (int i = 0; i < jsonFormAdapters.length(); i++) {
// get this form adapter
JSONObject jsonFormAdapter = jsonFormAdapters.getJSONObject(i);
// if this is the one we want
if (formAdapterType.equals(jsonFormAdapter.optString("type"))) {
// add the properties to the version
jsonVersion.put("canSaveForms", jsonFormAdapter.optBoolean("canSaveForms"));
jsonVersion.put("canGeneratePDF", jsonFormAdapter.optBoolean("canGeneratePDF"));
jsonVersion.put("canSupportIntegrationProperties", jsonFormAdapter.optBoolean("canSupportIntegrationProperties"));
// we're done
break;
}
}
}
}
// put the app into the collection
jsonVersions.put(jsonVersion);
} // design permission
} // check user password
} // versions loop
} // got versions check
output = jsonVersions.toString();
sendJsonOutput(response, output);
} else if ("getPages".equals(actionName)) {
Application application = rapidRequest.getApplication();
if (application == null) {
// send an empty object
output = "{}";
} else {
JSONArray jsonPages = new JSONArray();
String startPageId = "";
Page startPage = application.getStartPage(getServletContext());
if (startPage != null) startPageId = startPage.getId();
// loop the page headers
for (PageHeader pageHeader : application.getPages().getSortedPages()) {
// get the page - yip this means that apps loaded in the designer load all of their pages
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// create a simple json object for the page
JSONObject jsonPage = new JSONObject();
// add simple properties
jsonPage.put("id", page.getId());
jsonPage.put("name", page.getName());
jsonPage.put("title", page.getTitle());
jsonPage.put("label", page.getLabel());
jsonPage.put("simple", page.getSimple());
jsonPage.put("hideHeaderFooter", page.getHideHeaderFooter());
// get a list of page session variables
List<String> pageSessionVariables = page.getSessionVariables();
// add them if there are some
if (pageSessionVariables != null) if (pageSessionVariables.size() > 0) jsonPage.put("sessionVariables", pageSessionVariables);
// assume we don't need to know page visibilty
boolean includePageVisibiltyControls = false;
// if there is a form adapter
if (application.getFormAdapter() != null) {
// set to true
includePageVisibiltyControls = true;
// add visibility conditions
List<Condition> pageVisibilityConditions = page.getVisibilityConditions();
// add them if there are some
if (pageVisibilityConditions != null) if (pageVisibilityConditions.size() > 0) jsonPage.put("visibilityConditions", pageVisibilityConditions);
}
// get a collection of other page controls in this page
JSONArray jsonOtherPageControls = page.getOtherPageControls(this, includePageVisibiltyControls);
// only add the property if there are some
if (jsonOtherPageControls.length() > 0) jsonPage.put("controls", jsonOtherPageControls);
// check if the start page and add property if so
if (startPageId.equals(page.getId())) jsonPage.put("startPage", true);
// add the page to the collection
jsonPages.put(jsonPage);
}
// set the output to the collection turned into a string
output = jsonPages.toString();
} // application check
sendJsonOutput(response, output);
} else if ("getPage".equals(actionName)) {
Application application = rapidRequest.getApplication();
Page page = rapidRequest.getPage();
if (page != null) {
// assume we can't find the user
String userDescription = "unknown";
// get the user
User user = application.getSecurityAdapter().getUser(rapidRequest);
// if we had one and they have a description use it
if (user != null) if (user.getDescription() != null) userDescription = user.getDescription();
// remove any existing page locks for this user
application.removeUserPageLocks(getServletContext(), userName);
// check the page lock (which removes it if it has expired)
page.checkLock();
// if there is no current lock add a fresh one for the current user
if (page.getLock() == null) page.setLock(new Lock(userName, userDescription, new Date()));
// turn it into json
JSONObject jsonPage = new JSONObject(page);
// remove the bodyHtml property as it in the designer
jsonPage.remove("htmlBody");
// remove the rolesHtml property as it is rebuilt in the designer
jsonPage.remove("rolesHtml");
// remove allControls (the single all-control list) it is not required
jsonPage.remove("allControls");
// remove the otherPageControls property as it is sent with getPages
jsonPage.remove("otherPageControls");
// add a nicely formatted lock time
if (page.getLock() != null && jsonPage.optJSONObject("lock") != null) {
// get the date time formatter and format the lock date time
String formattedDateTime = getLocalDateTimeFormatter().format(page.getLock().getDateTime());
// add a special property to the json
jsonPage.getJSONObject("lock").put("formattedDateTime", formattedDateTime);
}
// add the css
jsonPage.put("css", page.getAllCSS(getServletContext(), application));
// add the device as page properties (even though we store this in the app)
jsonPage.put("device", 1);
jsonPage.put("zoom", 1);
jsonPage.put("orientation", "P");
// add the form page type
jsonPage.put("formPageType", page.getFormPageType());
// get any theme
Theme theme = application.getTheme(getServletContext());
// if there was one
if (theme != null) {
// add header html
jsonPage.put("headerHtml", theme.getHeaderHtml());
// add footer html
jsonPage.put("footerHtml", theme.getFooterHtml());
}
// print it to the output
output = jsonPage.toString();
// send as json response
sendJsonOutput(response, output);
}
} else if ("getFlows".equals(actionName)) {
// the JSON array of workflows we are going to return
JSONArray jsonFlows = new JSONArray();
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("id", "1");
jsonFlow.put("name", "Test");
// add it to the array
jsonFlows.put(jsonFlow);
// print it to the output
output = jsonFlows.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("getFlowVersions".equals(actionName)) {
// the JSON array of workflows we are going to return
JSONArray jsonFlows = new JSONArray();
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("version", "1");
jsonFlow.put("status", "0");
// the JSON array of workflows we are going to return
JSONArray jsonActions = new JSONArray();
JSONArray jsonAllActions = getJsonActions();
// loop all actions for now
for (int i = 0; i < jsonAllActions.length(); i++) {
// get all action
JSONObject jsonAllAction = jsonAllActions.getJSONObject(i);
// if it is allowed in workflow
if (jsonAllAction.optBoolean("canUseWorkflow")) {
JSONObject jsonAction = new JSONObject();
jsonAction.put("type", jsonAllActions.getJSONObject(i).getString("type"));
jsonActions.put(jsonAction);
}
}
jsonFlow.put("actions",jsonActions);
// add it to the array
jsonFlows.put(jsonFlow);
// print it to the output
output = jsonFlows.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("getFlow".equals(actionName)) {
// the JSON workflow we are going to return
JSONObject jsonFlow = new JSONObject();
// give it an id and a name
jsonFlow.put("id", "1");
jsonFlow.put("name", "Test");
// print it to the output
output = jsonFlow.toString();
// send as json response
sendJsonOutput(response, output);
} else if ("checkApp".equals(actionName)) {
String appName = request.getParameter("name");
if (appName != null) {
// retain whether we have an app with this name
boolean exists = getApplications().exists(Files.safeName(appName));
// set the response
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkVersion".equals(actionName)) {
String appName = request.getParameter("name");
String appVersion = request.getParameter("version");
if (appName != null && appVersion != null ) {
// retain whether we have an app with this name
boolean exists = getApplications().exists(Files.safeName(appName), Files.safeName(appVersion));
// set the response
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkPage".equals(actionName)) {
String pageName = request.getParameter("name");
if (pageName != null) {
// retain whether we have an app with this name
boolean pageExists = false;
// get the application
Application application = rapidRequest.getApplication();
if (application != null) {
for (PageHeader page : application.getPages().getSortedPages()) {
if (pageName.toLowerCase().equals(page.getName().toLowerCase())) {
pageExists = true;
break;
}
}
}
// set the output
output = Boolean.toString(pageExists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("checkWorkflow".equals(actionName)) {
String name = request.getParameter("name");
if (name != null) {
// retain whether we have an app with this name
boolean exists = false;
// get the workflows
Workflows workflows = getWorkflows();
// look for this on
Workflow workflow = workflows.get(Files.safeName(name));
// if we got one
if (workflow != null) exists = true;
// set the output
output = Boolean.toString(exists);
// send response as json
sendJsonOutput(response, output);
}
} else if ("pages".equals(actionName) || "questions".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) {
// set response as text
response.setContentType("text/text");
// get a writer from the response
PrintWriter out = response.getWriter();
// get the application
Application application = rapidRequest.getApplication();
// print the app name and version
out.print(application.getName() + "\t" + application.getVersion() + "\n");
// get the page headers
PageHeaders pageHeaders = application.getPages().getSortedPages();
// loop the page headers
for (PageHeader pageHeader : pageHeaders) {
// get the page
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// get the label
String label = page.getLabel();
// if we got one
if (label == null) {
label = "";
} else {
if (label.length() > 0) label = " - " + label;
}
if ("questions".equals(actionName)) {
out.print(page.getName() + label);
} else {
// print the page name
out.print(page.getId() + " " + page.getName() + label);
}
// check questions, summary, detail
if ("questions".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) {
// print the number of controls
if ("questions".equals(actionName)) {
out.print("\r\n");
} else {
out.print(" - number of controls: " + page.getAllControls().size() + "\r\n");
}
// if detail
if ("detail".equals(actionName)) {
// print the page properties
out.print("Name\t" + page.getName() + "\n");
out.print("Title\t" + page.getTitle() + "\n");
out.print("Description\t" + page.getDescription() + "\n");
out.print("Simple\t" + page.getSimple() + "\n");
out.print("HideHeaderFooter\t" + page.getHideHeaderFooter() + "\n");
}
// if questions
if (!"questions".equals(actionName)) printEventsDetails(page.getEvents(), out);
// get the controls
List<Control> controls = page.getAllControls();
// loop them
for (Control control : controls) {
// get the name
String name = control.getName();
// null check
if (name != null) {
if (name.trim().length() > 0) {
// get the label
label = control.getLabel();
// get the type
String type = control.getType();
// exclude panels, hidden values, and datastores for summary
if ("detail".equals(actionName) || (!"panel".equals(type) && !("hiddenvalue").equals(type) && !("dataStore").equals(type))) {
if ("questions".equals(actionName)) {
// print the control label
if (label != null && !control.getType().contains("button")) out.print("\t" + label + "\n");
} else {
// print the control details
out.print(control.getId() +"\t" + type + "\t" + name + "\t" + label + "\n");
}
// if details
if ("detail".equals(actionName)) {
// get the properties
Map<String, String> properties = control.getProperties();
// get a list we'll sort for them
List<String> sortedKeys = new ArrayList<String>();
// loop them
for (String key : properties.keySet()) {
// add to sorted list
sortedKeys.add(key);
}
// sort them
Collections.sort(sortedKeys);
// loop them
for (String key : sortedKeys) {
// print the properties
out.print(key + "\t" + properties.get(key) + "\n");
}
// print the event details
printEventsDetails(control.getEvents(), out);
} // detail check
}
}
}
}
} else {
out.print("\n");
}
}
// close the writer
out.close();
// send it immediately
out.flush();
} else if ("export".equals(actionName)) {
// get the application
Application application = rapidRequest.getApplication();
// check we've got one
if (application != null) {
// create the zip file
application.zip(this, rapidRequest, rapidUser, application.getId() + ".zip");
// set the type as a .zip
response.setContentType("application/x-zip-compressed");
// Shows the download dialog
response.setHeader("Content-disposition","attachment; filename=" + application.getId() + ".zip");
// get the file for the zip we're about to create
File zipFile = new File(getServletContext().getRealPath("/WEB-INF/temp/" + application.getId() + ".zip"));
// send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(zipFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
// delete the .zip file
zipFile.delete();
output = "Zip file sent";
} // got application
} else if ("updateids".equals(actionName)) {
// get a writer from the response
PrintWriter out = response.getWriter();
// check we have admin too
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.ADMIN_ROLE)) {
// retain the ServletContext
ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
// get the suffix
String suffix = rapidRequest.getRapidServlet().getControlAndActionSuffix();
// set response as text
response.setContentType("text/text");
// get the application
Application application = rapidRequest.getApplication();
// print the app name and version
out.print("Application : " + application.getName() + "/" + application.getVersion() + "\n");
// get the page headers
PageHeaders pageHeaders = application.getPages().getSortedPages();
// get the pages config folder
File appPagesFolder = new File(application.getConfigFolder(servletContext) + "/pages");
// check it exists
if (appPagesFolder.exists()) {
// loop the page headers
for (PageHeader pageHeader : pageHeaders) {
// get the page
Page page = application.getPages().getPage(getServletContext(), pageHeader.getId());
// print the page name and id
out.print("\nPage : " + page.getName() + "/" + page.getId() + "\n\n");
// loop the files
for (File pageFile : appPagesFolder.listFiles()) {
// if this is a page.xml file
if (pageFile.getName().endsWith(".page.xml")) {
// assume no id's found
// read the copy to a string
String pageXML = Strings.getString(pageFile);
// get all page controls
List<Control> controls = page.getAllControls();
// loop controls
for (Control control : controls) {
// get old/current id
String id = control.getId();
// assume new id will be the same
String newId = id;
// drop suffix if starts with it
if (newId.startsWith(suffix)) newId = newId.substring(suffix.length());
// add suffix to end
newId += suffix;
// check if id in file
if (pageXML.contains(id)) {
// show old and new id
out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n");
// replace
pageXML = pageXML.replace(id, newId);
}
}
// get all page actions
List<Action> actions = page.getAllActions();
// loop actions
for (Action action : actions) {
// get old/current id
String id = action.getId();
// assume new id will be the same
String newId = id;
// drop suffix if starts with it
if (newId.startsWith(suffix)) newId = newId.substring(suffix.length());
// add suffix to end
newId += suffix;
// check if id in file
if (pageXML.contains(id)) {
// show old and new id
out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n");
// replace
pageXML = pageXML.replace(id, newId);
}
}
// save it back
Strings.saveString(pageXML, pageFile);
} //page ending check
} // page file loop
} //page loop
// get the application file
File applicationFile = new File(application.getConfigFolder(servletContext) + "/application.xml");
// if it exists
if (applicationFile.exists()) {
// reload the application from file
Application reloadedApplication = Application.load(servletContext, applicationFile, true);
// replace it into the applications collection
getApplications().put(reloadedApplication);
}
} // app pages folder exists
} else {
// not authenticated
response.setStatus(403);
// say so
out.print("Not authorised");
}
// close the writer
out.close();
// send it immediately
out.flush();
} // action name check
} else {
// not authenticated
response.setStatus(403);
} // got design role
} // rapidSecurity != null
} // rapidApplication != null
// log the response
getLogger().debug("Designer GET response : " + output);
} catch (Exception ex) {
getLogger().debug("Designer GET error : " + ex.getMessage(), ex);
sendException(rapidRequest, response, ex);
}
}
private Control createControl(JSONObject jsonControl) throws JSONException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
// instantiate the control with the JSON
Control control = new Control(jsonControl);
// look in the JSON for a validation object
JSONObject jsonValidation = jsonControl.optJSONObject("validation");
// add the validation object if we got one
if (jsonValidation != null) control.setValidation(Control.getValidation(this, jsonValidation));
// look in the JSON for an event array
JSONArray jsonEvents = jsonControl.optJSONArray("events");
// add the events if we found one
if (jsonEvents != null) control.setEvents(Control.getEvents(this, jsonEvents));
// look in the JSON for a styles array
JSONArray jsonStyles = jsonControl.optJSONArray("styles");
// if there were styles
if (jsonStyles != null) control.setStyles(Control.getStyles(this, jsonStyles));
// look in the JSON for any child controls
JSONArray jsonControls = jsonControl.optJSONArray("childControls");
// if there were child controls loop and create controls interatively
if (jsonControls != null) {
for (int i = 0; i < jsonControls.length(); i++) {
control.addChildControl(createControl(jsonControls.getJSONObject(i)));
}
}
// return the control we just made
return control;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RapidRequest rapidRequest = new RapidRequest(this, request);
try {
String output = "";
// read bytes from request body into our own byte array (this means we can deal with images)
InputStream input = request.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (int length = 0; (length = input.read(_byteBuffer)) > -1;) outputStream.write(_byteBuffer, 0, length);
byte[] bodyBytes = outputStream.toByteArray();
// get the rapid application
Application rapidApplication = getApplications().get("rapid");
// check we got one
if (rapidApplication != null) {
// get rapid security
SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();
// check we got some
if (rapidSecurity != null) {
// get user name
String userName = rapidRequest.getUserName();
if (userName == null) userName = "";
// check permission
if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {
Application application = rapidRequest.getApplication();
if (application != null) {
if ("savePage".equals(rapidRequest.getActionName())) {
String bodyString = new String(bodyBytes, "UTF-8");
getLogger().debug("Designer POST request : " + request.getQueryString() + " body : " + bodyString);
JSONObject jsonPage = new JSONObject(bodyString);
// instantiate a new blank page
Page newPage = new Page();
// set page properties
newPage.setId(jsonPage.optString("id"));
newPage.setName(jsonPage.optString("name"));
newPage.setTitle(jsonPage.optString("title"));
newPage.setFormPageType(jsonPage.optInt("formPageType"));
newPage.setLabel(jsonPage.optString("label"));
newPage.setDescription(jsonPage.optString("description"));
newPage.setSimple(jsonPage.optBoolean("simple"));
newPage.setHideHeaderFooter(jsonPage.optBoolean("hideHeaderFooter"));
// look in the JSON for an event array
JSONArray jsonEvents = jsonPage.optJSONArray("events");
// add the events if we found one
if (jsonEvents != null) newPage.setEvents(Control.getEvents(this, jsonEvents));
// look in the JSON for a styles array
JSONArray jsonStyles = jsonPage.optJSONArray("styles");
// if there were styles get and save
if (jsonStyles != null) newPage.setStyles(Control.getStyles(this, jsonStyles));
// look in the JSON for a style classes array
JSONArray jsonStyleClasses = jsonPage.optJSONArray("classes");
// if there were style classes
if (jsonStyleClasses != null) {
// start with empty string
String styleClasses = "";
// loop array and build classes list
for (int i = 0; i < jsonStyleClasses.length(); i++) styleClasses += jsonStyleClasses.getString(i) + " ";
// trim for good measure
styleClasses = styleClasses.trim();
// store if something there
if (styleClasses.length() > 0) newPage.setBodyStyleClasses(styleClasses);
}
// if there are child controls from the page loop them and add to the pages control collection
JSONArray jsonControls = jsonPage.optJSONArray("childControls");
if (jsonControls != null) {
for (int i = 0; i < jsonControls.length(); i++) {
// get the JSON control
JSONObject jsonControl = jsonControls.getJSONObject(i);
// call our function so it can go iterative
newPage.addControl(createControl(jsonControl));
}
}
// if there are roles specified for this page
JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
if (jsonUserRoles != null) {
List<String> userRoles = new ArrayList<String>();
for (int i = 0; i < jsonUserRoles.length(); i++) {
// get the JSON role
String jsonUserRole = jsonUserRoles.getString(i);
// add to collection
userRoles.add(jsonUserRole);
}
// assign to page
newPage.setRoles(userRoles);
}
// look in the JSON for a sessionVariables array
JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
// if we found one
if (jsonSessionVariables != null) {
List<String> sessionVariables = new ArrayList<String>();
for (int i = 0; i < jsonSessionVariables.length(); i++) {
sessionVariables.add(jsonSessionVariables.getString(i));
}
newPage.setSessionVariables(sessionVariables);
}
// look in the JSON for a pageVisibilityRules array
JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
// if we found one
if (jsonVisibilityConditions != null) {
List<Condition> visibilityConditions = new ArrayList<Condition>();
for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
visibilityConditions.add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
}
newPage.setVisibilityConditions(visibilityConditions);
}
// look in the JSON for a pageVisibilityRules array is an and or or (default to and)
String jsonConditionsType = jsonPage.optString("conditionsType","and");
// set what we got
newPage.setConditionsType(jsonConditionsType);
// retrieve the html body
String htmlBody = jsonPage.optString("htmlBody");
// if we got one trim it and retain in page
if (htmlBody != null) newPage.setHtmlBody(htmlBody.trim());
// look in the JSON for roleControlhtml
JSONObject jsonRoleControlHtml = jsonPage.optJSONObject("roleControlHtml");
// if we found some add it to the page
if (jsonRoleControlHtml != null) newPage.setRoleControlHtml(new RoleControlHtml(jsonRoleControlHtml));
// fetch a copy of the old page (if there is one)
Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
// if the page's name changed we need to remove it
if (oldPage != null) {
if (!oldPage.getName().equals(newPage.getName())) {
oldPage.delete(this, rapidRequest, application);
}
}
// save the new page to file
newPage.save(this, rapidRequest, application, true);
// get any pages collection (we're only sent it if it's been changed)
JSONArray jsonPages = jsonPage.optJSONArray("pages");
// if we got some
if (jsonPages != null) {
// the start page id
String startPageId = null;
// make a new map for the page orders
Map<String, Integer> pageOrders = new HashMap<String, Integer>();
// loop the page orders
for (int i = 0; i < jsonPages.length(); i++) {
// get the page id
String pageId = jsonPages.getJSONObject(i).getString("id");
// add the order to the map
pageOrders.put(pageId, i);
// retain page id if first one
if (i == 0) startPageId = pageId;
}
// replace the application pageOrders map
application.setPageOrders(pageOrders);
// update the application start page
application.setStartPageId(startPageId);
// save the application and the new orders
application.save(this, rapidRequest, true);
}
boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
if (jsonPageOrderReset) {
// empty the application pageOrders map so everything goes alphabetical
application.setPageOrders(null);
}
// send a positive message
output = "{\"message\":\"Saved!\"}";
// set the response type to json
response.setContentType("application/json");
} else if ("testSQL".equals(rapidRequest.getActionName())) {
// turn the body bytes into a string
String bodyString = new String(bodyBytes, "UTF-8");
JSONObject jsonQuery = new JSONObject(bodyString);
JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");
JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");
Parameters parameters = new Parameters();
if (jsonInputs != null) {
for (int i = 0; i < jsonInputs.length(); i++) parameters.addNull();
}
DatabaseConnection databaseConnection = application.getDatabaseConnections().get(jsonQuery.optInt("databaseConnectionIndex",0));
ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(), application);
DataFactory df = new DataFactory(ca);
int outputs = 0;
// if got some outputs reduce the check count for any duplicates
if (jsonOutputs != null) {
// start with full number of outputs
outputs = jsonOutputs.length();
// retain fields
List<String> fieldList = new ArrayList<String>();
// loop outputs
for (int i = 0; i < jsonOutputs.length(); i++) {
// look for a field
String field = jsonOutputs.getJSONObject(i).optString("field", null);
// if we got one
if (field != null) {
// check if we have it already
if (fieldList.contains(field)) {
// we do so reduce the control count by one
outputs --;
} else {
// we don't have this field yet so remember
fieldList.add(field);
}
}
}
}
String sql = jsonQuery.getString("SQL").trim();
// merge in any parameters
sql = application.insertParameters(getServletContext(), sql);
// some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
sql = sql.replace("\n", " ");
if (outputs == 0) {
if (sql.toLowerCase().startsWith("select")) {
throw new Exception("Select statement should have at least one output");
} else {
df.getPreparedStatement(rapidRequest,sql , parameters);
}
} else {
ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
if (outputs > cols) throw new Exception(outputs + " outputs, but only " + cols + " column" + (cols > 1 ? "s" : "") + " selected");
for (int i = 0; i < outputs; i++) {
JSONObject jsonOutput = jsonOutputs.getJSONObject(i);
String field = jsonOutput.optString("field","");
if (!"".equals(field)) {
field = field.toLowerCase();
boolean gotOutput = false;
for (int j = 0; j < cols; j++) {
String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();
if (field.equals(sqlField)) {
gotOutput = true;
break;
}
}
if (!gotOutput) {
rs.close();
df.close();
throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " is not present in selected columns");
}
}
}
// close the recordset
rs.close();
// close the data factory
df.close();
}
// send a positive message
output = "{\"message\":\"OK\"}";
// set the response type to json
response.setContentType("application/json");
} else if ("uploadImage".equals(rapidRequest.getActionName()) || "import".equals(rapidRequest.getActionName())) {
// get the content type from the request
String contentType = request.getContentType();
// get the position of the boundary from the content type
int boundaryPosition = contentType.indexOf("boundary=");
// derive the start of the meaning data by finding the boundary
String boundary = contentType.substring(boundaryPosition + 10);
// this is the double line break after which the data occurs
byte[] pattern = {0x0D, 0x0A, 0x0D, 0x0A};
// find the position of the double line break
int dataPosition = Bytes.findPattern(bodyBytes, pattern );
// the body header is everything up to the data
String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
// find the position of the filename in the data header
int filenamePosition = header.indexOf("filename=\"");
// extract the file name
String filename = header.substring(filenamePosition + 10, header.indexOf("\"", filenamePosition + 10));
// find the position of the file type in the data header
int fileTypePosition = header.toLowerCase().indexOf("type:");
// extract the file type
String fileType = header.substring(fileTypePosition + 6);
if ("uploadImage".equals(rapidRequest.getActionName())) {
// check the file type
if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif") && !fileType.equals("image/png") && !fileType.equals("image/svg+xml")) throw new Exception("Unsupported file type");
// get the web folder from the application
String path = rapidRequest.getApplication().getWebFolder(getServletContext());
// create a file output stream to save the data to
FileOutputStream fos = new FileOutputStream (path + "/" + filename);
// write the file data to the stream
fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9);
// close the stream
fos.close();
// log the file creation
getLogger().debug("Saved image file " + path + filename);
// create the response with the file name and upload type
output = "{\"file\":\"" + filename + "\",\"type\":\"" + rapidRequest.getActionName() + "\"}";
} else if ("import".equals(rapidRequest.getActionName())) {
// check the file type
if (!"application/x-zip-compressed".equals(fileType) && !"application/zip".equals(fileType)) throw new Exception("Unsupported file type");
// get the name
String appName = request.getParameter("name");
// check we were given one
if (appName == null) throw new Exception("Name must be provided");
// get the version
String appVersion = request.getParameter("version");
// check we were given one
if (appVersion == null) throw new Exception("Version must be provided");
// make the id from the safe and lower case name
String appId = Files.safeName(appName).toLowerCase();
// make the version from the safe and lower case name
appVersion = Files.safeName(appVersion);
// get application destination folder
File appFolderDest = new File(Application.getConfigFolder(getServletContext(), appId, appVersion));
// get web contents destination folder
File webFolderDest = new File(Application.getWebFolder(getServletContext(), appId, appVersion));
// look for an existing application of this name and version
Application existingApplication = getApplications().get(appId, appVersion);
// if we have an existing application
if (existingApplication != null) {
// back it up first
existingApplication.backup(this, rapidRequest, false);
}
// get a file for the temp directory
File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
// create it if not there
if (!tempDir.exists()) tempDir.mkdir();
// the path we're saving to is the temp folder
String path = getServletContext().getRealPath("/WEB-INF/temp/" + appId + ".zip");
// create a file output stream to save the data to
FileOutputStream fos = new FileOutputStream (path);
// write the file data to the stream
fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9);
// close the stream
fos.close();
// log the file creation
getLogger().debug("Saved import file " + path);
// get a file object for the zip file
File zipFile = new File(path);
// load it into a zip file object
ZipFile zip = new ZipFile(zipFile);
// unzip the file
zip.unZip();
// delete the zip file
zipFile.delete();
// unzip folder (for deletion)
File unZipFolder = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId));
// get application folders
File appFolderSource = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
// get web content folders
File webFolderSource = new File(getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WebContent" ));
// check we have the right source folders
if (webFolderSource.exists() && appFolderSource.exists()) {
// get application.xml file
File appFileSource = new File (appFolderSource + "/application.xml");
if (appFileSource.exists()) {
// delete the appFolder if it exists
if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest);
// delete the webFolder if it exists
if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest);
// copy application content
Files.copyFolder(appFolderSource, appFolderDest);
// copy web content
Files.copyFolder(webFolderSource, webFolderDest);
try {
// load the new application (but don't initialise, nor load pages)
Application appNew = Application.load(getServletContext(), new File (appFolderDest + "/application.xml"), false);
// update application name
appNew.setName(appName);
// get the old id
String appOldId = appNew.getId();
// make the new id
appId = Files.safeName(appName).toLowerCase();
// update the id
appNew.setId(appId);
// get the old version
String appOldVersion = appNew.getVersion();
// make the new version
appVersion = Files.safeName(appVersion);
// update the version
appNew.setVersion(appVersion);
// update the created date
appNew.setCreatedDate(new Date());
// set the status to In development
appNew.setStatus(Application.STATUS_DEVELOPMENT);
// a map of actions that might be removed from any of the pages
Map<String,Integer> removedActions = new HashMap<String, Integer>();
// look for page files
File pagesFolder = new File(appFolderDest.getAbsolutePath() + "/pages");
// if the folder is there
if (pagesFolder.exists()) {
// create a filter for finding .page.xml files
FilenameFilter xmlFilenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".page.xml");
}
};
// loop the .page.xml files
for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {
// read the file into a string
String fileString = Strings.getString(pageFile);
// prepare a new file string which will update into
String newFileString = null;
// if the old app did not have a version (for backwards compatibility)
if (appOldVersion == null) {
// replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
newFileString = fileString
.replace("applications/" + appOldId + "/", "applications/" + appId + "/" + appVersion + "/")
.replace("~?a=" + appOldId + "&", "~?a=" + appId + "&v=" + appVersion + "&")
.replace("~?a=" + appOldId + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&");
} else {
// replace all properties that appear to have a url, and all created links - note the fix for double encoding
newFileString = fileString
.replace("applications/" + appOldId + "/" + appOldVersion + "/", "applications/" + appId + "/" + appVersion + "/")
.replace("~?a=" + appOldId + "&v=" + appOldVersion + "&", "~?a=" + appId + "&v=" + appVersion + "&")
.replace("~?a=" + appOldId + "&amp;v=" + appOldVersion + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&");
}
// now open the string into a document
Document pageDocument = XML.openDocument(newFileString);
// get an xpath factory
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
// an expression for any attributes with a local name of "type"
XPathExpression expr = xpath.compile("//@*[local-name()='type']");
// get them
NodeList nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET);
// get out system actions
JSONArray jsonActions = getJsonActions();
// if we found any elements with a type attribute and we have system actions
if (nl.getLength() > 0 && jsonActions.length() > 0) {
// a list of action types
List<String> types = new ArrayList<String>();
// loop the json actions
for (int i = 0; i < jsonActions.length(); i++) types.add(jsonActions.getJSONObject(i).optString("type").toLowerCase());
// loop the action attributes we found
for (int i = 0; i < nl.getLength(); i++) {
// get this attribute
Attr a = (Attr) nl.item(i);
// get the value of the type
String type = a.getTextContent().toLowerCase();
// get the element the attribute is in
Node n = a.getOwnerElement();
// if we don't know about this action type
if (!types.contains(type)) {
// get the parent node
Node p = n.getParentNode();
// remove this node
p.removeChild(n);
// if we have removed this type already
if (removedActions.containsKey(type)) {
// increment the entry for this type
removedActions.put(type, removedActions.get(type) + 1);
} else {
// add an entry for this type
removedActions.put(type, 1);
}
} // got type check
} // attribute loop
} // attribute and system action check
// use the transformer to write to disk
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(pageDocument);
StreamResult result = new StreamResult(pageFile);
transformer.transform(source, result);
} // page xml file loop
} // pages folder check
// now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
appNew.initialise(getServletContext(), false);
// get the security for this application
SecurityAdapter security = appNew.getSecurityAdapter();
// if we have one
if (security != null) {
// assume we don't have the user
boolean gotUser = false;
// get the current users record from the adapter
User user = security.getUser(rapidRequest);
// check the current user is present in the app's security adapter
if (user != null) {
// now check the current user password is correct too
if (security.checkUserPassword(rapidRequest, userName, rapidRequest.getUserPassword())) {
// we have the right user with the right password
gotUser = true;
} else {
// remove this user in case there is one with the same name but the password does not match
security.deleteUser(rapidRequest);
}
}
// if we don't have the user
if (!gotUser) {
// get the current user from the Rapid application
User rapidUser = rapidSecurity.getUser(rapidRequest);
// create a new user based on the Rapid user
user = new User(rapidUser);
// add the new user
security.addUser(rapidRequest, user);
}
// add Admin and Design roles for the new user if required
if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE))
security.addUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE);
if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE))
security.addUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE);
}
// if any items were removed
if (removedActions.keySet().size() > 0) {
// a description of what was removed
String removed = "";
// loop the entries
for (String type : removedActions.keySet()) {
int count = removedActions.get(type);
removed += "removed " + count + " " + type + " action" + (count == 1 ? "" : "s") + " on import\n";
}
// get the current description
String description = appNew.getDescription();
// if null set to empty string
if (description == null) description = "";
// add a line break if need be
if (description.length() > 0) description += "\n";
// add the removed
description += removed;
// set it back
appNew.setDescription(description);
}
// reload the pages (actually clears down the pages collection and reloads the headers)
appNew.getPages().loadpages(getServletContext());
// save application (this will also initialise and rebuild the resources)
appNew.save(this, rapidRequest, false);
// add application to the collection
getApplications().put(appNew);
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// send a positive message
output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\"" + appNew.getVersion() + "\"}";
} catch (Exception ex) {
// delete the appFolder if it exists
if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest);
// if the parent is empty delete it too
if (appFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(appFolderDest.getParentFile());
// delete the webFolder if it exists
if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest);
// if the parent is empty delete it too
if (webFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(webFolderDest.getParentFile());
// rethrow exception
throw ex;
}
} else {
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// throw excpetion
throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");
}
} else {
// delete unzip folder
Files.deleteRecurring(unZipFolder);
// throw excpetion
throw new Exception("Must be a valid Rapid file");
}
}
}
getLogger().debug("Designer POST response : " + output);
PrintWriter out = response.getWriter();
out.print(output);
out.close();
} // got an application
} // got rapid design role
} // got rapid security
} // got rapid application
} catch (Exception ex) {
getLogger().error("Designer POST error : ",ex);
sendException(rapidRequest, response, ex);
}
}
}
| updateIds now checks existing suffix | src/com/rapid/server/Designer.java | updateIds now checks existing suffix | <ide><path>rc/com/rapid/server/Designer.java
<ide> // drop suffix if starts with it
<ide> if (newId.startsWith(suffix)) newId = newId.substring(suffix.length());
<ide>
<del> // add suffix to end
<del> newId += suffix;
<add> // add suffix to end if not there already
<add> if (!newId.endsWith("_" + suffix)) newId += suffix;
<ide>
<ide> // check if id in file
<ide> if (pageXML.contains(id)) { |
|
Java | apache-2.0 | 694030ec09d730cd8fe3cb3280f56c43bd8f2d87 | 0 | JNOSQL/diana-driver,JNOSQL/diana-driver | /*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.diana.redis.key;
import org.jnosql.diana.api.key.BucketManagerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.*;
public class RedisMapTest {
private BucketManagerFactory entityManagerFactory;
private Species mammals = new Species("lion", "cow", "dog");
private Species fishes = new Species("redfish", "glassfish");
private Species amphibians = new Species("crododile", "frog");
private Map<String, Species> vertebrates;
@BeforeEach
public void init() {
entityManagerFactory = RedisTestUtils.get();
vertebrates = entityManagerFactory.getMap("vertebrates", String.class, Species.class);
}
@Test
public void shouldPutAndGetMap() {
assertTrue(vertebrates.isEmpty());
assertNotNull(vertebrates.put("mammals", mammals));
Species species = vertebrates.get("mammals");
assertNotNull(species);
assertEquals(species.getAnimals().get(0), mammals.getAnimals().get(0));
assertTrue(vertebrates.size() == 1);
}
@Test
public void shouldVerifyExist() {
vertebrates.put("mammals", mammals);
assertTrue(vertebrates.containsKey("mammals"));
assertFalse(vertebrates.containsKey("redfish"));
assertTrue(vertebrates.containsValue(mammals));
assertFalse(vertebrates.containsValue(fishes));
}
@Test
public void shouldShowKeyAndValues() {
Map<String, Species> vertebratesMap = new HashMap<>();
vertebratesMap.put("mammals", mammals);
vertebratesMap.put("fishes", fishes);
vertebratesMap.put("amphibians", amphibians);
vertebrates.putAll(vertebratesMap);
Set<String> keys = vertebrates.keySet();
Collection<Species> collectionSpecies = vertebrates.values();
assertTrue(keys.size() == 3);
assertTrue(collectionSpecies.size() == 3);
assertNotNull(vertebrates.remove("mammals"));
assertNull(vertebrates.remove("mammals"));
assertNull(vertebrates.get("mammals"));
assertTrue(vertebrates.size() == 2);
}
@Test
public void shouldRemove() {
vertebrates.put("mammals", mammals);
vertebrates.put("fishes", fishes);
vertebrates.put("amphibians", amphibians);
vertebrates.remove("fishes");
assertTrue(vertebrates.size() == 2);
assertThat(vertebrates, not(hasKey(fishes)));
}
@Test
public void shouldClear() {
vertebrates.put("mammals", mammals);
vertebrates.put("fishes", fishes);
vertebrates.clear();
assertTrue(vertebrates.isEmpty());
}
@AfterEach
public void dispose() {
vertebrates.clear();
}
}
| redis-driver/src/test/java/org/jnosql/diana/redis/key/RedisMapTest.java | /*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.diana.redis.key;
import org.jnosql.diana.api.key.BucketManagerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.*;
public class RedisMapTest {
private BucketManagerFactory entityManagerFactory;
private Species mammals = new Species("lion", "cow", "dog");
private Species fishes = new Species("redfish", "glassfish");
private Species amphibians = new Species("crododile", "frog");
private Map<String, Species> vertebrates;
@BeforeEach
public void init() {
entityManagerFactory = RedisTestUtils.get();
vertebrates = entityManagerFactory.getMap("vertebrates", String.class, Species.class);
}
@Test
public void shouldPutAndGetMap() {
assertTrue(vertebrates.isEmpty());
assertNotNull(vertebrates.put("mammals", mammals));
Species species = vertebrates.get("mammals");
assertNotNull(species);
assertEquals(species.getAnimals().get(0), mammals.getAnimals().get(0));
assertTrue(vertebrates.size() == 1);
}
@Test
public void shouldVerifyExist() {
vertebrates.put("mammals", mammals);
assertTrue(vertebrates.containsKey("mammals"));
assertFalse(vertebrates.containsKey("redfish"));
assertTrue(vertebrates.containsValue(mammals));
assertFalse(vertebrates.containsValue(fishes));
}
@Test
public void shouldShowKeyAndValues() {
Map<String, Species> vertebratesMap = new HashMap<>();
vertebratesMap.put("mammals", mammals);
vertebratesMap.put("fishes", fishes);
vertebratesMap.put("amphibians", amphibians);
vertebrates.putAll(vertebratesMap);
Set<String> keys = vertebrates.keySet();
Collection<Species> collectionSpecies = vertebrates.values();
assertTrue(keys.size() == 3);
assertTrue(collectionSpecies.size() == 3);
assertNotNull(vertebrates.remove("mammals"));
assertNull(vertebrates.remove("mammals"));
assertNull(vertebrates.get("mammals"));
assertTrue(vertebrates.size() == 2);
}
@Test
public void shouldRemove() {
vertebrates.put("mammals", mammals);
vertebrates.put("fishes", fishes);
vertebrates.put("amphibians", amphibians);
vertebrates.remove("fishes");
assertTrue(vertebrates.size() == 2);
assertThat(vertebrates, not(hasKey(fishes)));
}
@AfterEach
public void dispose() {
vertebrates.clear();
}
}
| add clear method test on map
Signed-off-by: Lucas Furlaneto <[email protected]>
| redis-driver/src/test/java/org/jnosql/diana/redis/key/RedisMapTest.java | add clear method test on map | <ide><path>edis-driver/src/test/java/org/jnosql/diana/redis/key/RedisMapTest.java
<ide> assertThat(vertebrates, not(hasKey(fishes)));
<ide> }
<ide>
<add> @Test
<add> public void shouldClear() {
<add> vertebrates.put("mammals", mammals);
<add> vertebrates.put("fishes", fishes);
<add>
<add> vertebrates.clear();
<add> assertTrue(vertebrates.isEmpty());
<add> }
<add>
<ide> @AfterEach
<ide> public void dispose() {
<ide> vertebrates.clear(); |
|
Java | apache-2.0 | f23e0cc7409ae324cb92da9101e8b06910341bd1 | 0 | Plonk42/mytracks | /*
* Copyright 2011 Google 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 com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences sharedPreferences;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, sharedPreferences, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
PreferencesUtils.setLong(context, R.string.recording_track_id_key, TRACK_ID);
PreferencesUtils.setLong(context, R.string.selected_track_id_key, TRACK_ID);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
PreferencesUtils.setBoolean(context, R.string.report_speed_key, true);
PreferencesUtils.setBoolean(context, R.string.metric_units_key, true);
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
PreferencesUtils.setBoolean(context, R.string.report_speed_key, false);
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(
sharedPreferences, PreferencesUtils.getKey(context, R.string.report_speed_key));
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
PreferencesUtils.setBoolean(context, R.string.metric_units_key, false);
listener.onSharedPreferenceChanged(
sharedPreferences, PreferencesUtils.getKey(context, R.string.metric_units_key));
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java | /*
* Copyright 2011 Google 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 com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences sharedPreferences;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, sharedPreferences, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
PreferencesUtils.setLong(context, R.string.recording_track_id_key, TRACK_ID);
PreferencesUtils.setLong(context, R.string.selected_track_id_key, TRACK_ID);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(11, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should still be incremental.
locationIterator = new FixedSizeLocationIterator(21, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
PreferencesUtils.setBoolean(context, R.string.report_speed_key, true);
PreferencesUtils.setBoolean(context, R.string.metric_units_key, true);
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
PreferencesUtils.setBoolean(context, R.string.report_speed_key, false);
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(
sharedPreferences, PreferencesUtils.getKey(context, R.string.report_speed_key));
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
PreferencesUtils.setBoolean(context, R.string.metric_units_key, false);
listener.onSharedPreferenceChanged(
sharedPreferences, PreferencesUtils.getKey(context, R.string.metric_units_key));
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| Fix unit test due to changes in 8daac052f042
| MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java | Fix unit test due to changes in 8daac052f042 | <ide><path>yTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java
<ide> dataSources.registerContentObserver(
<ide> eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
<ide>
<del> locationIterator = new FixedSizeLocationIterator(11, 10);
<del> expect(providerUtils.getLocationIterator(
<del> eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
<del> .andReturn(locationIterator);
<del> expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
<del>
<add> locationIterator = new FixedSizeLocationIterator(1, 10, 5);
<add> expect(providerUtils.getLocationIterator(
<add> eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
<add> .andReturn(locationIterator);
<add> expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
<add>
<add> listener1.clearTrackPoints();
<ide> locationIterator.expectLocationsDelivered(listener1);
<ide> listener1.onNewTrackPointsDone();
<ide>
<ide> replay();
<ide>
<ide> hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
<del>
<del> verifyAndReset();
<del>
<del> // Deliver more points - should still be incremental.
<del> locationIterator = new FixedSizeLocationIterator(21, 10, 1);
<del> expect(providerUtils.getLocationIterator(
<del> eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
<del> .andReturn(locationIterator);
<del> expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
<del>
<del> locationIterator.expectLocationsDelivered(listener1);
<del> listener1.onNewTrackPointsDone();
<del>
<del> replay();
<del>
<del> observer.onChange(false);
<ide>
<ide> verifyAndReset();
<ide> } |
|
Java | apache-2.0 | a198dc6cdb01cdfc792cc0d21f06634c3b3d1331 | 0 | igorakkerman/jlib | /*
* jlib - The Free Java Library
*
* http://www.jlib.org
*
* Copyright (c) 2006-2008 Igor Akkerman
*
* jlib is distributed under the
*
* COMMON PUBLIC LICENSE VERSION 1.0
*
* http://www.opensource.org/licenses/cpl1.0.php
*/
package org.jlib.container.sequence;
/**
* Iterator over a {@link InsertSequence}.
*
* @param <Element>
* type of elements held in the {@link Sequence}
*
* @author Igor Akkerman
*/
public interface InsertSequenceIterator<Element>
extends SequenceIterator<Element> {
/**
* <p>
* Inserts the specified Element into the sequence at the current position
* of this Iterator.
* </p>
* <p>
* The Element is inserted immediately before the next Element that would
* have been returned by {@link #next()} and immediately after the previous
* Element that would have been returned by {@link #previous()}.
* </p>
* <p>
* A subsequent call to {@link #next()} would be unaffected, and a
* subsequent call to {@link #previous()} would return the new element.
* </p>
*
* @param element
* Element to insert
*
* @throws IllegalStateException
* if {@link #next()} or {@link #previous()} have not been called
* initially or after the last call to {@link #insert(Object)}
*/
public void insert(Element element)
throws IllegalStateException;
}
| jlib.container/src/main/java/org/jlib/container/sequence/InsertSequenceIterator.java | /*
* jlib - The Free Java Library
*
* http://www.jlib.org
*
* Copyright (c) 2006-2008 Igor Akkerman
*
* jlib is distributed under the
*
* COMMON PUBLIC LICENSE VERSION 1.0
*
* http://www.opensource.org/licenses/cpl1.0.php
*/
package org.jlib.container.sequence;
/**
* Iterator over a {@link InsertSequence}.
*
* @param <Element>
* type of elements held in the {@link Sequence}
*
* @author Igor Akkerman
*/
public interface InsertSequenceIterator<Element>
extends SequenceIterator<Element> {
/**
* <p>
* Inserts the specified Element into the sequence at the current position
* of this Iterator.
* </p>
* <p>
* The Element is inserted immediately before the next Element that would
* have been returned by {@link #next()} and immediately after the previous
* Element that would have been returned by {@link #previous()}.
* </p>
* <p>
* A subsequent call to {@link #next()} would be unaffected, and a
* subsequent call to {@link #previous()} would return the new element.
* </p>
*
* @param element
* Element to insert
*
* @throws IllegalStateException
* if {@link #next()} or {@link #previous()} have not been called
* initially or after the last call to {@link #insert(Object)}
*/
public void insert(Element element)
throws IllegalStateException;
/**
* Returns the traversed {@link InsertSequence}
*
* @return traversed {@link InsertSequence}
*/
@Override
public InsertSequence<Element> getSequence();
}
| Revert "InsertSequenceIterator: getSequence method added"
This reverts commit bef5fcf4751a996195435da243a2f42f63c0ddb1.
| jlib.container/src/main/java/org/jlib/container/sequence/InsertSequenceIterator.java | Revert "InsertSequenceIterator: getSequence method added" | <ide><path>lib.container/src/main/java/org/jlib/container/sequence/InsertSequenceIterator.java
<ide> */
<ide>
<ide> package org.jlib.container.sequence;
<add>
<ide>
<ide> /**
<ide> * Iterator over a {@link InsertSequence}.
<ide> */
<ide> public void insert(Element element)
<ide> throws IllegalStateException;
<del>
<del> /**
<del> * Returns the traversed {@link InsertSequence}
<del> *
<del> * @return traversed {@link InsertSequence}
<del> */
<del> @Override
<del> public InsertSequence<Element> getSequence();
<ide> } |
|
Java | mit | 39337302977e676557195bff70ae63c3caf2c15d | 0 | vicpark/icuc,vicpark/icuc,vicpark/icuc,vicpark/icuc,vicpark/icuc,vicpark/icuc | import com.mathworks.toolbox.javabuilder.*;
import WaveReq.*;
class wave
{
public static void main(String[] args)
{
Object[] result = null;
wavreq wave = null;
if (args.length != (65 + 14))
{
System.out.println("Error: you provided " + args.length + " arguments, must be 1+65+13");
return;
}
try
{
wave = new wavreq();
String fileid = args[0];
// ZERNIKE COEFFICIENTS
float zernikes[] = new float[65];
for (int i = 0; i < 65; i++)
zernikes[i] = Float.parseFloat(args[i+1]);
MWNumericArray coeffs = new MWNumericArray(zernikes, MWClassID.DOUBLE);
// other parameters
float pupilfit = Float.parseFloat(args[66]);
float pupilcalc = Float.parseFloat(args[67]);
// DEFOCUS // RANGE
String defocusArg = args[68];
float defocus = 0;
float defFloatArr[] = new float[25];
// if string has ':' then make array
if (defocusArg.contains(":")) {
// string defocusArg will be of format "a:step:b"
String defocusRanges[] = defocusArg.split(":");
float a = Float.parseFloat(defocusRanges[0]);
float b = Float.parseFloat(defocusRanges[2]);
float step = Float.parseFloat(defocusRanges[1]);
float start = a;
int i = 0;
while (start <= b) {
defFloatArr[i] = start;
start = start + (step);
i = i + 1;
}
// else is a float
} else {
defocus = Float.parseFloat(args[68]);
}
MWNumericArray defocusArray = new MWNumericArray(defFloatArr, MWClassID.DOUBLE);
float wavelength = Float.parseFloat(args[69]);
float pixels = Float.parseFloat(args[70]);
float pupilfieldsize = Float.parseFloat(args[71]);
float lettersize = Float.parseFloat(args[72]);
// choice of graphs
int WF = Integer.parseInt(args[73]);
int PSF = Integer.parseInt(args[74]);
int MTF = Integer.parseInt(args[75]);
int PTF = Integer.parseInt(args[76]);
int MTFL = Integer.parseInt(args[77]);
int CONV = Integer.parseInt(args[78]);
// result fits
if (defocusArg.contains(":")) {
result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
// System.out.println(result);
} else {
result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
}
// result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
// System.out.println(result);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(result);
wave.dispose();
}
}
}
| wave.java | import com.mathworks.toolbox.javabuilder.*;
import WaveReq.*;
class wave
{
public static void main(String[] args)
{
Object[] result = null;
wavreq wave = null;
if (args.length != (65 + 14))
{
System.out.println("Error: you provided " + args.length + " arguments, must be 1+65+13");
return;
}
try
{
wave = new wavreq();
String fileid = args[0];
// ZERNIKE COEFFICIENTS
float zernikes[] = new float[65];
for (int i = 0; i < 65; i++)
zernikes[i] = Float.parseFloat(args[i+1]);
MWNumericArray coeffs = new MWNumericArray(zernikes, MWClassID.DOUBLE);
// other parameters
float pupilfit = Float.parseFloat(args[66]);
float pupilcalc = Float.parseFloat(args[67]);
// DEFOCUS // RANGE
String defocusArg = args[68];
float defocus;
float defFloatArr[] = new float[10];
// if string has ':' then make array
if (defocusArg.contains(":")) {
// string defocusArg will be of format "a:step:b"
String defocusRanges[] = defocusArg.split(":");
float a = Float.parseFloat(defocusRanges[0]);
float b = Float.parseFloat(defocusRanges[2]);
float step = Float.parseFloat(defocusRanges[1]);
float start = a;
while start <= b {
defFloatArr[i] = start;
start = start + (step);
}
// else is a float
} else {
defocus = Float.parseFloat(args[68]);
}
MWNumericArray defocusArray = new MWNumericArray(defFloatArr, MWClassID.DOUBLE);
float wavelength = Float.parseFloat(args[69]);
float pixels = Float.parseFloat(args[70]);
float pupilfieldsize = Float.parseFloat(args[71]);
float lettersize = Float.parseFloat(args[72]);
// choice of graphs
int WF = Integer.parseInt(args[73]);
int PSF = Integer.parseInt(args[74]);
int MTF = Integer.parseInt(args[75]);
int PTF = Integer.parseInt(args[76]);
int MTFL = Integer.parseInt(args[77]);
int CONV = Integer.parseInt(args[78]);
// result fits
result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
// System.out.println(result);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(result);
wave.dispose();
}
}
}
| testing
| wave.java | testing | <ide><path>ave.java
<ide> // DEFOCUS // RANGE
<ide> String defocusArg = args[68];
<ide>
<del> float defocus;
<del> float defFloatArr[] = new float[10];
<add> float defocus = 0;
<add> float defFloatArr[] = new float[25];
<ide>
<ide> // if string has ':' then make array
<ide> if (defocusArg.contains(":")) {
<ide> float b = Float.parseFloat(defocusRanges[2]);
<ide> float step = Float.parseFloat(defocusRanges[1]);
<ide> float start = a;
<del>
<del> while start <= b {
<add> int i = 0;
<add> while (start <= b) {
<ide> defFloatArr[i] = start;
<ide> start = start + (step);
<add> i = i + 1;
<ide> }
<ide> // else is a float
<ide> } else {
<ide> int CONV = Integer.parseInt(args[78]);
<ide>
<ide> // result fits
<del>
<del> result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
<add> if (defocusArg.contains(":")) {
<add> result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
<add> // System.out.println(result);
<add> } else {
<add> result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
<add> }
<add>// result = wave.WaveReq(2, fileid, coeffs, pupilfit, pupilcalc, defocusArray, defocus, wavelength, pixels, pupilfieldsize, lettersize, WF, PSF, MTF, PTF, MTFL, CONV);
<ide> // System.out.println(result);
<ide> }
<ide> catch (Exception e) |
|
Java | lgpl-2.1 | c554a2a0f9c80ba8efee9d82648b23eac3e4f0cd | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /**
*
*/
package org.jetel.component;
import java.io.IOException;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ComponentXMLAttributes;
import org.jetel.util.StringUtils;
import org.jetel.util.SynchronizeUtils;
import sun.text.Normalizer;
/**
* This component creates reference matching key which is
* costructed as combination of signs from given data fields
* @author avackova
*
*/
public class KeyGenerator extends Node {
private static final String XML_KEY_ATTRIBUTE = "key";
public final static String COMPONENT_TYPE = "KEY_GEN";
private final static int WRITE_TO_PORT = 0;
private final static int READ_FROM_PORT = 0;
private final static int LOWER = 0;
private final static int UPPER = 1;
private final static int ALPHA = 0;
private final static int NUMRIC = 1;
private String[] key;
private Key[] keys;
private boolean[][] lowerUpperCase;
private boolean[] removeBlankSpace;
private boolean[][] onlyAlpfaNumeric;
private boolean[] removeDiacritic;
private int[][] fieldMap;
private int outKey;
private InputPort inPort;
private DataRecordMetadata inMetadata;
private OutputPort outPort;
private DataRecordMetadata outMetadata;
private int lenght=0;
private StringBuffer resultString;
private String pom=null;
/**
* @param id
*/
public KeyGenerator(String id, String[] key) {
super(id);
this.key = key;
}
/**
* @param in metadata on input port
* @param out metadata on output port
* @param fieldMap int[in.getNumFields][2] - array in which are stored field's numbers from in and field's numbers on out
* @return number of field in out which does not exist in in
* @throws ComponentNotReadyException
*/
private int mapFields(DataRecordMetadata in,DataRecordMetadata out,int[][] fieldMap) throws ComponentNotReadyException{
if (!(out.getNumFields()==in.getNumFields()+1))
throw new ComponentNotReadyException("Metadata on output does not correspond with metadata on input!");
int r=0;
int i;
for (i=0;i<out.getNumFields();i++){
int j;
for (j=0;j<in.getNumFields();j++){
if (out.getField(i).getName().equals(in.getField(j).getName())){
fieldMap[i][0]=j;
fieldMap[i][1]=i;
break;
}
}
if (j==in.getNumFields())
r=j;
}
return r;
}
/**
* This method fills outRecord with the data from inRecord.
* outRecord has one more field then inRecord; to this field is
* set given value
*
* @param inRecord
* @param outRecord
* @param map - in map[0] are numbers of fields in inRecord
* and in map[1] are corresponding fields in outRecord
* @param num - number of field in outRecord, which is lacking in inRecord
* @param value - value to be set to field number "num"
*/
private void fillOutRecord(DataRecord inRecord,DataRecord outRecord,int[][] map,int num,String value){
for (int i=0;i<map.length;i++){
outRecord.getField(map[i][1]).setValue(inRecord.getField(map[i][0]).getValue());
}
outRecord.getField(num).setValue(value);
}
/**
* This method generates refernece key for input record
*
* @param inRecord
* @param key - fields from which reference key is to be constructed
* @return referenced key for input record
*/
private String generateKey(DataRecord inRecord, Key[] key){
resultString.setLength(0);
for (int i=0;i<keys.length;i++){
try{ //get field value from inRcord
pom=inRecord.getField(keys[i].getName()).getValue().toString();
pom = StringUtils.getOnlyAlpfaNumericChars(pom,onlyAlpfaNumeric[i][ALPHA],onlyAlpfaNumeric[i][NUMRIC]);
if (removeBlankSpace[i]) {
pom = StringUtils.removeBlankSpace(pom);
}
if (removeDiacritic[i]){
pom=StringUtils.removeDiacritic(pom);
}
if (lowerUpperCase[i][LOWER]){
pom=pom.toLowerCase();
}
if (lowerUpperCase[i][UPPER]){
pom=pom.toUpperCase();
}
}catch(NullPointerException ex){//value of field is null
pom="";
}
try {//get substring from the field
if (keys[i].fromBegining){
int start=keys[i].getStart();
resultString.append(pom.substring(start,start+keys[i].getLenght()));
}else{
int end=pom.length();
resultString.append(pom.substring(end-keys[i].getLenght(),end));
}
}catch (StringIndexOutOfBoundsException ex){
//string from the field is shorter then demanded part of the key
//get whole string from the field and add to it spaces
StringBuffer shortPom=new StringBuffer(keys[i].getLenght());
//when keys[i].fromBegining=false there is k=-1
for (int k=keys[i].getStart();k<keys[i].getStart()+pom.length();k++){
if (pom.length()>k){
if (keys[i].fromBegining){
shortPom.append(pom.charAt(k));
}else{
shortPom.insert(0,pom.charAt(pom.length()-2-k));
}
}
}
int offset;
if (!keys[i].fromBegining) {
offset=0;
}else{
offset=shortPom.length();
}
for (int k=shortPom.length();k<keys[i].getLenght();k++){
shortPom.insert(offset,' ');
}
resultString.append(shortPom);
}
}
return resultString.toString();
}
public void run() {
DataRecord inRecord = new DataRecord(inMetadata);
inRecord.init();
DataRecord outRecord = new DataRecord(outMetadata);
outRecord.init();
while (inRecord!=null && runIt) {
try {
inRecord = inPort.readRecord(inRecord);// readRecord(READ_FROM_PORT,inRecord);
if (inRecord!=null) {
fillOutRecord(inRecord,outRecord,fieldMap,outKey,generateKey(inRecord,keys));
outPort.writeRecord(outRecord);
SynchronizeUtils.cloverYield();
}
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
ex.printStackTrace();
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
closeAllOutputPorts();
return;
}
}
broadcastEOF();
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
private void getParam(String param,int i){
String[] pom=param.split(" ");
String keyParam=pom[1];
int start=-1;
int lenght=0;
boolean fromBegining=true;
StringBuffer number=new StringBuffer();
int j=0;
char c=' ';
number.setLength(0);
while (j<keyParam.length() && Character.isDigit(c=keyParam.charAt(j))){
number.append(c);
j++;
}
if (c=='-') {
if (j>0){
start=Integer.parseInt(number.toString())-1;
}else {
fromBegining=false;
}
j++;
}else{
lenght=Integer.parseInt(number.toString());
}
number.setLength(0);
while (j<keyParam.length() && Character.isDigit(c=keyParam.charAt(j))){
number.append(c);
j++;
}
if (number.length()>0) {
lenght=Integer.parseInt(number.toString());
}
if (start>-1){
keys[i] = new Key(pom[0],start,lenght);
}else{
keys[i] = new Key(pom[0],lenght,fromBegining);
}
while (j<keyParam.length()){
c=Character.toLowerCase(keyParam.charAt(j));
switch (c) {
case 'l':lowerUpperCase[i][LOWER] = true;
break;
case 'u':lowerUpperCase[i][UPPER] = true;
break;
case 's':removeBlankSpace[i] = true;
break;
case 'a':onlyAlpfaNumeric[i][ALPHA] = true;
break;
case 'n':onlyAlpfaNumeric[i][NUMRIC] = true;
break;
case 'd':removeDiacritic[i] = true;
}
j++;
}
}
public void init() throws ComponentNotReadyException {
// test that we have one input port and exactly one output
if (inPorts.size() != 1) {
throw new ComponentNotReadyException("One input port has to be defined!");
} else if (outPorts.size() != 1) {
throw new ComponentNotReadyException("One output port has to be defined!");
}
inPort = getInputPort(READ_FROM_PORT);
inMetadata=inPort.getMetadata();
outPort = getOutputPort(WRITE_TO_PORT);
outMetadata=outPort.getMetadata();
fieldMap=new int[inMetadata.getNumFields()][2];
outKey=mapFields(inMetadata,outMetadata,fieldMap);
int length=key.length;
keys=new Key[length];
lowerUpperCase = new boolean[length][2];
removeBlankSpace = new boolean[length];
onlyAlpfaNumeric = new boolean[length][2];
removeDiacritic = new boolean[length];
for (int i=0;i<length;i++){
getParam(key[i],i);
}
length = 0;
for (int i=0;i<keys.length;i++){
lenght+=keys[i].getLenght();
}
resultString=new StringBuffer(lenght);
}
public static Node fromXML(TransformationGraph graph, org.w3c.dom.Node nodeXML) {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
try {
return new KeyGenerator(Node.XML_ID_ATTRIBUTE,xattribs.getString(XML_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
} catch (Exception ex) {
System.err.println(COMPONENT_TYPE + ":" + ((xattribs.exists(XML_ID_ATTRIBUTE)) ? xattribs.getString(Node.XML_ID_ATTRIBUTE) : " unknown ID ") + ":" + ex.getMessage());
return null;
}
}
public boolean checkConfig() {
return true;
}
public String getType(){
return COMPONENT_TYPE;
}
static private class Key{
String name;
int start;
int lenght;
boolean fromBegining;
Key(String name,int start,int length){
this.name=name;
this.start=start;
this.lenght=length;
fromBegining=true;
}
Key(String name,int length,boolean fromBegining){
this.name=name;
this.fromBegining=fromBegining;
this.lenght=length;
if (fromBegining) {
this.start=0;
}else{
this.start=-1;
}
}
public int getLenght() {
return lenght;
}
public String getName() {
return name;
}
public int getStart() {
return start;
}
}
}
| cloveretl.engine/src/org/jetel/component/KeyGenerator.java | /**
*
*/
package org.jetel.component;
import java.io.IOException;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ComponentXMLAttributes;
import org.jetel.util.SynchronizeUtils;
import sun.text.Normalizer;
/**
* This component creates reference matching key which is
* costructed as combination of signs from given data fields
* @author avackova
*
*/
public class KeyGenerator extends Node {
private static final String XML_KEY_ATTRIBUTE = "key";
/** Description of the Field */
public final static String COMPONENT_TYPE = "KEY_GEN";
private final static int WRITE_TO_PORT = 0;
private final static int READ_FROM_PORT = 0;
private final static int LOWER = 0;
private final static int UPPER = 1;
private final static int ALPHA = 0;
private final static int NUMRIC = 1;
private String[] key;
private Key[] keys;
private boolean[][] lowerUpperCase;
private boolean[] removeBlankSpace;
private boolean[][] onlyAlpfaNumeric;
private boolean[] removeDiacritic;
private int[][] fieldMap;
private int outKey;
private InputPort inPort;
private DataRecordMetadata inMetadata;
private OutputPort outPort;
private DataRecordMetadata outMetadata;
int lenght=0;
StringBuffer resultString;
String pom=null;
StringBuffer toRemove = new StringBuffer();
char[] pomChars;
int charRemoved;
/**
* @param id
*/
public KeyGenerator(String id, String[] key) {
super(id);
this.key = key;
}
/**
* @param in metadata on input port
* @param out metadata on output port
* @param fieldMap int[in.getNumFields][2] - array in which are stored field's numbers from in and field's numbers on out
* @return number of field in out which does not exist in in
* @throws ComponentNotReadyException
*/
private int mapFields(DataRecordMetadata in,DataRecordMetadata out,int[][] fieldMap) throws ComponentNotReadyException{
if (!(out.getNumFields()==in.getNumFields()+1))
throw new ComponentNotReadyException("Metadata on output does not correspond with metadata on input!");
int r=0;
int i;
for (i=0;i<out.getNumFields();i++){
int j;
for (j=0;j<in.getNumFields();j++){
if (out.getField(i).getName().equals(in.getField(j).getName())){
fieldMap[i][0]=j;
fieldMap[i][1]=i;
break;
}
}
if (j==in.getNumFields())
r=j;
}
return r;
}
private void fillOutRecord(DataRecord inRecord,DataRecord outRecord,int[][] map,int num,String value){
for (int i=0;i<map.length;i++){
outRecord.getField(map[i][1]).setValue(inRecord.getField(map[i][0]).getValue());
}
outRecord.getField(num).setValue(value);
}
private String generateKey(DataRecord inRecord, Key[] key){
resultString.setLength(0);
for (int i=0;i<keys.length;i++){
try{
toRemove.setLength(0);
toRemove.append(inRecord.getField(keys[i].getName()).getValue().toString());
if (onlyAlpfaNumeric[i][ALPHA] || onlyAlpfaNumeric[i][NUMRIC]){
charRemoved=0;
lenght=toRemove.length();
if (pomChars==null || pomChars.length<lenght) {
pomChars=new char[lenght];
}
toRemove.getChars(0,lenght,pomChars,0);
for (int j=0;j<lenght;j++){
if (onlyAlpfaNumeric[i][ALPHA] && !Character.isLetter(pomChars[j])) {
toRemove.deleteCharAt(j-charRemoved++);
}else if (onlyAlpfaNumeric[i][NUMRIC] && !Character.isDigit(pomChars[j])){
toRemove.deleteCharAt(j-charRemoved++);
}
}
}
if (removeBlankSpace[i]) {
charRemoved=0;
lenght=toRemove.length();
if (pomChars==null || pomChars.length<lenght) {
pomChars=new char[lenght];
}
toRemove.getChars(0,lenght,pomChars,0);
for (int j=0;j<lenght;j++){
if (Character.isWhitespace(pomChars[j])) {
toRemove.deleteCharAt(j-charRemoved++);
}
}
}
pom=toRemove.toString();
if (removeDiacritic[i]){
pom=Normalizer.decompose(pom, false, 0).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
if (lowerUpperCase[i][LOWER]){
pom=pom.toLowerCase();
}
if (lowerUpperCase[i][UPPER]){
pom=pom.toUpperCase();
}
}catch(NullPointerException ex){
pom="";
}
try {
if (keys[i].fromBegining){
int start=keys[i].getStart();
resultString.append(pom.substring(start,start+keys[i].getLenght()));
}else{
int end=pom.length();
resultString.append(pom.substring(end-keys[i].getLenght(),end));
}
}catch (StringIndexOutOfBoundsException ex){
StringBuffer shortPom=new StringBuffer(keys[i].getLenght());
//when keys[i].fromBegining=false there is k=-1
for (int k=keys[i].getStart();k<keys[i].getStart()+pom.length();k++){
if (pom.length()>k){
if (keys[i].fromBegining){
shortPom.append(pom.charAt(k));
}else{
shortPom.insert(0,pom.charAt(pom.length()-2-k));
}
}
}
int offset;
if (!keys[i].fromBegining) {
offset=0;
}else{
offset=shortPom.length();
}
for (int k=shortPom.length();k<keys[i].getLenght();k++){
shortPom.insert(offset,' ');
}
resultString.append(shortPom);
}
}
return resultString.toString();
}
public void run() {
DataRecord inRecord = new DataRecord(inMetadata);
inRecord.init();
DataRecord outRecord = new DataRecord(outMetadata);
outRecord.init();
while (inRecord!=null && runIt) {
try {
inRecord = inPort.readRecord(inRecord);// readRecord(READ_FROM_PORT,inRecord);
if (inRecord!=null) {
fillOutRecord(inRecord,outRecord,fieldMap,outKey,generateKey(inRecord,keys));
outPort.writeRecord(outRecord);
SynchronizeUtils.cloverYield();
}
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
ex.printStackTrace();
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
closeAllOutputPorts();
return;
}
}
broadcastEOF();
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
private void getParam(String param,int i){
String[] pom=param.split(" ");
String keyParam=pom[1];
int start=-1;
int lenght=0;
boolean fromBegining=true;
StringBuffer number=new StringBuffer();
int j=0;
char c=' ';
number.setLength(0);
while (j<keyParam.length() && Character.isDigit(c=keyParam.charAt(j))){
number.append(c);
j++;
}
if (c=='-') {
if (j>0){
start=Integer.parseInt(number.toString())-1;
}else {
fromBegining=false;
}
j++;
}else{
lenght=Integer.parseInt(number.toString());
}
number.setLength(0);
while (j<keyParam.length() && Character.isDigit(c=keyParam.charAt(j))){
number.append(c);
j++;
}
if (number.length()>0) {
lenght=Integer.parseInt(number.toString());
}
if (start>-1){
keys[i] = new Key(pom[0],start,lenght);
}else{
keys[i] = new Key(pom[0],lenght,fromBegining);
}
while (j<keyParam.length()){
c=Character.toLowerCase(keyParam.charAt(j));
switch (c) {
case 'l':lowerUpperCase[i][LOWER] = true;
break;
case 'u':lowerUpperCase[i][UPPER] = true;
break;
case 's':removeBlankSpace[i] = true;
break;
case 'a':onlyAlpfaNumeric[i][ALPHA] = true;
break;
case 'n':onlyAlpfaNumeric[i][NUMRIC] = true;
break;
case 'd':removeDiacritic[i] = true;
}
j++;
}
}
public void init() throws ComponentNotReadyException {
// test that we have one input port and exactly one output
if (inPorts.size() != 1) {
throw new ComponentNotReadyException("One input port has to be defined!");
} else if (outPorts.size() != 1) {
throw new ComponentNotReadyException("One output port has to be defined!");
}
inPort = getInputPort(READ_FROM_PORT);
inMetadata=inPort.getMetadata();
outPort = getOutputPort(WRITE_TO_PORT);
outMetadata=outPort.getMetadata();
fieldMap=new int[inMetadata.getNumFields()][2];
outKey=mapFields(inMetadata,outMetadata,fieldMap);
int length=key.length;
keys=new Key[length];
lowerUpperCase = new boolean[length][2];
removeBlankSpace = new boolean[length];
onlyAlpfaNumeric = new boolean[length][2];
for (int i=0;i<length;i++){
getParam(key[i],i);
}
for (int i=0;i<keys.length;i++){
lenght+=keys[i].getLenght();
}
resultString=new StringBuffer(lenght);
}
public static Node fromXML(TransformationGraph graph, org.w3c.dom.Node nodeXML) {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
try {
return new KeyGenerator(Node.XML_ID_ATTRIBUTE,xattribs.getString(XML_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
} catch (Exception ex) {
System.err.println(COMPONENT_TYPE + ":" + ((xattribs.exists(XML_ID_ATTRIBUTE)) ? xattribs.getString(Node.XML_ID_ATTRIBUTE) : " unknown ID ") + ":" + ex.getMessage());
return null;
}
}
public boolean checkConfig() {
return true;
}
public String getType(){
return COMPONENT_TYPE;
}
static private class Key{
String name;
int start;
int lenght;
boolean fromBegining;
Key(String name,int start,int length){
this.name=name;
this.start=start;
this.lenght=length;
fromBegining=true;
}
Key(String name,int length,boolean fromBegining){
this.name=name;
this.fromBegining=fromBegining;
this.lenght=length;
if (fromBegining) {
this.start=0;
}else{
this.start=-1;
}
}
public int getLenght() {
return lenght;
}
public String getName() {
return name;
}
public int getStart() {
return start;
}
}
}
| some methods mooved to StringUtils class
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@902 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/component/KeyGenerator.java | some methods mooved to StringUtils class | <ide><path>loveretl.engine/src/org/jetel/component/KeyGenerator.java
<ide> import org.jetel.graph.TransformationGraph;
<ide> import org.jetel.metadata.DataRecordMetadata;
<ide> import org.jetel.util.ComponentXMLAttributes;
<add>import org.jetel.util.StringUtils;
<ide> import org.jetel.util.SynchronizeUtils;
<ide>
<ide> import sun.text.Normalizer;
<ide> public class KeyGenerator extends Node {
<ide>
<ide> private static final String XML_KEY_ATTRIBUTE = "key";
<del> /** Description of the Field */
<add>
<ide> public final static String COMPONENT_TYPE = "KEY_GEN";
<ide>
<ide> private final static int WRITE_TO_PORT = 0;
<ide> private OutputPort outPort;
<ide> private DataRecordMetadata outMetadata;
<ide>
<del> int lenght=0;
<del> StringBuffer resultString;
<del> String pom=null;
<del> StringBuffer toRemove = new StringBuffer();
<del> char[] pomChars;
<del> int charRemoved;
<add> private int lenght=0;
<add> private StringBuffer resultString;
<add> private String pom=null;
<ide>
<ide> /**
<ide> * @param id
<ide> return r;
<ide> }
<ide>
<add> /**
<add> * This method fills outRecord with the data from inRecord.
<add> * outRecord has one more field then inRecord; to this field is
<add> * set given value
<add> *
<add> * @param inRecord
<add> * @param outRecord
<add> * @param map - in map[0] are numbers of fields in inRecord
<add> * and in map[1] are corresponding fields in outRecord
<add> * @param num - number of field in outRecord, which is lacking in inRecord
<add> * @param value - value to be set to field number "num"
<add> */
<ide> private void fillOutRecord(DataRecord inRecord,DataRecord outRecord,int[][] map,int num,String value){
<ide> for (int i=0;i<map.length;i++){
<ide> outRecord.getField(map[i][1]).setValue(inRecord.getField(map[i][0]).getValue());
<ide> outRecord.getField(num).setValue(value);
<ide> }
<ide>
<add> /**
<add> * This method generates refernece key for input record
<add> *
<add> * @param inRecord
<add> * @param key - fields from which reference key is to be constructed
<add> * @return referenced key for input record
<add> */
<ide> private String generateKey(DataRecord inRecord, Key[] key){
<ide> resultString.setLength(0);
<ide> for (int i=0;i<keys.length;i++){
<del> try{
<del> toRemove.setLength(0);
<del> toRemove.append(inRecord.getField(keys[i].getName()).getValue().toString());
<del> if (onlyAlpfaNumeric[i][ALPHA] || onlyAlpfaNumeric[i][NUMRIC]){
<del> charRemoved=0;
<del> lenght=toRemove.length();
<del> if (pomChars==null || pomChars.length<lenght) {
<del> pomChars=new char[lenght];
<del> }
<del> toRemove.getChars(0,lenght,pomChars,0);
<del> for (int j=0;j<lenght;j++){
<del> if (onlyAlpfaNumeric[i][ALPHA] && !Character.isLetter(pomChars[j])) {
<del> toRemove.deleteCharAt(j-charRemoved++);
<del> }else if (onlyAlpfaNumeric[i][NUMRIC] && !Character.isDigit(pomChars[j])){
<del> toRemove.deleteCharAt(j-charRemoved++);
<del> }
<del> }
<del> }
<add> try{ //get field value from inRcord
<add> pom=inRecord.getField(keys[i].getName()).getValue().toString();
<add> pom = StringUtils.getOnlyAlpfaNumericChars(pom,onlyAlpfaNumeric[i][ALPHA],onlyAlpfaNumeric[i][NUMRIC]);
<ide> if (removeBlankSpace[i]) {
<del> charRemoved=0;
<del> lenght=toRemove.length();
<del> if (pomChars==null || pomChars.length<lenght) {
<del> pomChars=new char[lenght];
<del> }
<del> toRemove.getChars(0,lenght,pomChars,0);
<del> for (int j=0;j<lenght;j++){
<del> if (Character.isWhitespace(pomChars[j])) {
<del> toRemove.deleteCharAt(j-charRemoved++);
<del> }
<del> }
<del> }
<del> pom=toRemove.toString();
<add> pom = StringUtils.removeBlankSpace(pom);
<add> }
<ide> if (removeDiacritic[i]){
<del> pom=Normalizer.decompose(pom, false, 0).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
<add> pom=StringUtils.removeDiacritic(pom);
<ide> }
<ide> if (lowerUpperCase[i][LOWER]){
<ide> pom=pom.toLowerCase();
<ide> if (lowerUpperCase[i][UPPER]){
<ide> pom=pom.toUpperCase();
<ide> }
<del> }catch(NullPointerException ex){
<add> }catch(NullPointerException ex){//value of field is null
<ide> pom="";
<ide> }
<del> try {
<add> try {//get substring from the field
<ide> if (keys[i].fromBegining){
<ide> int start=keys[i].getStart();
<ide> resultString.append(pom.substring(start,start+keys[i].getLenght()));
<ide> resultString.append(pom.substring(end-keys[i].getLenght(),end));
<ide> }
<ide> }catch (StringIndexOutOfBoundsException ex){
<add> //string from the field is shorter then demanded part of the key
<add> //get whole string from the field and add to it spaces
<ide> StringBuffer shortPom=new StringBuffer(keys[i].getLenght());
<ide> //when keys[i].fromBegining=false there is k=-1
<ide> for (int k=keys[i].getStart();k<keys[i].getStart()+pom.length();k++){
<ide> lowerUpperCase = new boolean[length][2];
<ide> removeBlankSpace = new boolean[length];
<ide> onlyAlpfaNumeric = new boolean[length][2];
<add> removeDiacritic = new boolean[length];
<ide> for (int i=0;i<length;i++){
<ide> getParam(key[i],i);
<ide> }
<add> length = 0;
<ide> for (int i=0;i<keys.length;i++){
<ide> lenght+=keys[i].getLenght();
<ide> } |
|
Java | apache-2.0 | b3c954d462d80937da7442b5c092a6126f577809 | 0 | dotStart/Pandemonium,dotStart/Pandemonium,dotStart/Pandemonium | /*
* Copyright 2017 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.dotstart.pandemonium.effect;
import org.controlsfx.tools.Platform;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import tv.dotstart.pandemonium.process.Process;
/**
* Provides a factory for an effect which may be applied to the program instance or memory in order
* to change the game behavior persistently or temporarily.
*
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
public interface EffectFactory {
/**
* Builds a new effect instance for the specified process.
*/
@Nonnull
Effect build(@Nonnull Process process);
/**
* Retrieves the base localization key which is used to refer to the effects produced by this
* factory within the application UI.
*/
@Nonnull
static String getBaseLocalizationKey(@Nonnull EffectFactory factory) {
return getBaseLocalizationKey(factory.getClass());
}
/**
* Retrieves the base localization key which is used to refer to the effects produced by this
* factory within the application UI.
*/
@Nonnull
static String getBaseLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return "effect." + factory.getName();
}
/**
* Retrieves the description localization key.
*/
@Nonnull
static String getDescriptionLocalizationKey(@Nonnull EffectFactory factory) {
return getDescriptionLocalizationKey(factory.getClass());
}
/**
* Retrieves a game unique identifier which refers to this effect in presets.
*
* This identifier is required to be unique within the namespace of the module and should never
* be reassigned even if an effect is removed and is thus no longer available in the
* definition.
*
* This guarantees correct resolving of effects when effects are added or removed since users
* are able to load presets even when their revisions differ (e.g. all located effects will be
* activated while non-existent effects are skipped).
*/
@Nonnegative
int getEffectId();
/**
* Retrieves the description localization key.
*/
@Nonnull
static String getDescriptionLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return getBaseLocalizationKey(factory) + ".description";
}
/**
* Retrieves a title localization key.
*/
@Nonnull
static String getTitleLocalizationKey(@Nonnull EffectFactory factory) {
return getTitleLocalizationKey(factory.getClass());
}
/**
* Retrieves a title localization key.
*/
@Nonnull
static String getTitleLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return getBaseLocalizationKey(factory) + ".title";
}
/**
* Checks whether this effect is compatible with the supplied platform.
*
* It is generally recommended to only include effects which are available for all platforms
* the
* game is available on as to keep races predictable and fair for all participants.
*
* In addition, the application will warn users when they attempt to load a preset which
* includes effects that aren't supported on the current platform to not produce unexpected
* results.
*/
default boolean isCompatibleWith(@Nonnull Platform platform) {
return true;
}
/**
* Checks whether this effect is compatible with the process and its current state.
*
* When this check returns false, the factory will not be invoked and another effect may be
* generated (depending on the current game preset).
*
* This check is especially useful when a game changes certain states further down the road. For
* instance, this check may be used to apply effects which change weapon information when a
* weapon is in the player's inventory only.
*/
default boolean isCompatibleWith(@Nonnull Process process) {
return true;
}
/**
* Checks whether this effect is compatible with the supplied effect.
*
* When this check returns false, this factory will not be invoked and another effect may be
* generated (depending on the current game preset).
*/
default boolean isCompatibleWith(@Nonnull EffectFactory factory, @Nonnull Effect effect) {
return true;
}
/**
* Checks whether the effects produced by this factory are persistent (e.g. are applied once
* and
* have no need for an inversion).
*
* This is most commonly used when increasing or decreasing values in order to increase or
* decrease the game difficulty.
*/
default boolean isPersistent() {
return false;
}
/**
* Checks whether this effect may stack (e.g. may be applied multiple times at once).
*
* When this method yields true, another instance of this effect may be appended to the list of
* active effects.
*/
default boolean mayStack() {
return false;
}
}
| effect/src/main/java/tv/dotstart/pandemonium/effect/EffectFactory.java | /*
* Copyright 2017 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.dotstart.pandemonium.effect;
import org.controlsfx.tools.Platform;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import tv.dotstart.pandemonium.process.Process;
/**
* Provides a factory for an effect which may be applied to the program instance or memory in order
* to change the game behavior persistently or temporarily.
*
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
public interface EffectFactory {
/**
* Builds a new effect instance for the specified process.
*/
@Nonnull
Effect build(@Nonnull Process process);
/**
* Retrieves the base localization key which is used to refer to the effects produced by this
* factory within the application UI.
*/
@Nonnull
static String getBaseLocalizationKey(@Nonnull EffectFactory factory) {
return getBaseLocalizationKey(factory.getClass());
}
/**
* Retrieves the base localization key which is used to refer to the effects produced by this
* factory within the application UI.
*/
@Nonnull
static String getBaseLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return "effect." + factory.getName();
}
/**
* Retrieves the description localization key.
*/
@Nonnull
static String getDescriptionLocalizationKey(@Nonnull EffectFactory factory) {
return getDescriptionLocalizationKey(factory.getClass());
}
/**
* Retrieves a game unique identifier which refers to this effect in presets.
*
* This identifier is required to be unique within the namespace of the module and should never
* be reassigned even if an effect is removed and is thus no longer available in the
* definition.
*
* This guarantees correct resolving of effects when effects are added or removed since users
* are able to load presets even when their revisions differ (e.g. all located effects will be
* activated while non-existent effects are skipped).
*/
@Nonnegative
int getEffectId();
/**
* Retrieves the description localization key.
*/
@Nonnull
static String getDescriptionLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return getBaseLocalizationKey(factory) + ".description";
}
/**
* Retrieves a title localization key.
*/
@Nonnull
static String getTitleLocalizationKey(@Nonnull EffectFactory factory) {
return getTitleLocalizationKey(factory.getClass());
}
/**
* Retrieves a title localization key.
*/
@Nonnull
static String getTitleLocalizationKey(@Nonnull Class<? extends EffectFactory> factory) {
return getBaseLocalizationKey(factory) + ".title";
}
/**
* Checks whether this effect is compatible with the supplied platform.
*
* It is generally recommended to only include effects which are available for all platforms
* the
* game is available on as to keep races predictable and fair for all participants.
*
* In addition, the application will warn users when they attempt to load a preset which
* includes effects that aren't supported on the current platform to not produce unexpected
* results.
*/
default boolean isCompatibleWith(@Nonnull Platform platform) {
return true;
}
/**
* Checks whether this effect is compatible with the supplied effect.
*
* When this check returns false, this factory will not be invoked and another effect may be
* generated (depending on the current game preset).
*/
default boolean isCompatibleWith(@Nonnull EffectFactory factory, @Nonnull Effect effect) {
return true;
}
/**
* Checks whether the effects produced by this factory are persistent (e.g. are applied once
* and
* have no need for an inversion).
*
* This is most commonly used when increasing or decreasing values in order to increase or
* decrease the game difficulty.
*/
default boolean isPersistent() {
return false;
}
/**
* Checks whether this effect may stack (e.g. may be applied multiple times at once).
*
* When this method yields true, another instance of this effect may be appended to the list of
* active effects.
*/
default boolean mayStack() {
return false;
}
}
| Added a method to evaluate compatibility against a process.
| effect/src/main/java/tv/dotstart/pandemonium/effect/EffectFactory.java | Added a method to evaluate compatibility against a process. | <ide><path>ffect/src/main/java/tv/dotstart/pandemonium/effect/EffectFactory.java
<ide> }
<ide>
<ide> /**
<add> * Checks whether this effect is compatible with the process and its current state.
<add> *
<add> * When this check returns false, the factory will not be invoked and another effect may be
<add> * generated (depending on the current game preset).
<add> *
<add> * This check is especially useful when a game changes certain states further down the road. For
<add> * instance, this check may be used to apply effects which change weapon information when a
<add> * weapon is in the player's inventory only.
<add> */
<add> default boolean isCompatibleWith(@Nonnull Process process) {
<add> return true;
<add> }
<add>
<add> /**
<ide> * Checks whether this effect is compatible with the supplied effect.
<ide> *
<ide> * When this check returns false, this factory will not be invoked and another effect may be |
|
JavaScript | mit | 663598c21c6751fa2d0d646bb2571e3f734f9ef3 | 0 | walmartlabs/costanza | /*global HTMLDocument, Window, console */
this.Costanza = (function() {
"use strict";
function defaultReporter(info, err) {
console.error('Costanza error', info);
}
var reportCallback = defaultReporter,
currentSection = 'global',
_onError,
_setTimeout,
_setInterval,
_addEventListener,
_removeEventListener;
function init(_reportCallback, options) {
reportCallback = _reportCallback || defaultReporter;
if (!window.onerror || !window.onerror._costanza) {
_onError = _onError || window.onerror;
window.onerror = onErrorRoot;
window.addEventListener('error', onError, true);
}
// Allow users to opt out of the native prototype augmentation.
if (options && options.safeMode) {
return;
}
if (!setTimeout._costanza) {
_setTimeout = setTimeout;
window.setTimeout = function(callback, duration) {
return _setTimeout(bind(callback), duration);
};
setTimeout._costanza = true;
}
if (!setInterval._costanza) {
_setInterval = setInterval;
window.setInterval = function(callback, interval) {
return _setInterval(bind(callback), interval);
};
setInterval._costanza = true;
}
if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener._costanza) {
_addEventListener = Element.prototype.addEventListener;
var addEventListener = function(type, callback, useCapture) {
callback._section = callback._section || bind(callback);
_addEventListener.call(this, type, callback._section, useCapture);
};
addEventListener._costanza = true;
Element.prototype.addEventListener = addEventListener;
_removeEventListener = Element.prototype.removeEventListener;
var removeEventListener = function(type, callback, useCapture) {
_removeEventListener.call(this, type, callback._section || callback, useCapture);
};
removeEventListener._costanza = true;
Element.prototype.removeEventListener = removeEventListener;
if (window.HTMLDocument) {
HTMLDocument.prototype.addEventListener = addEventListener;
HTMLDocument.prototype.removeEventListener = removeEventListener;
}
if (window.Window) {
Window.prototype.addEventListener = addEventListener;
Window.prototype.removeEventListener = removeEventListener;
}
}
}
function cleanup() {
reportCallback = defaultReporter;
if (window.onerror && window.onerror._costanza) {
window.onerror = _onError;
window.removeEventListener('error', onError, true);
}
if (setTimeout._costanza) {
window.setTimeout = _setTimeout;
}
if (setInterval._costanza) {
window.setInterval = _setInterval;
}
if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener._costanza) {
Element.prototype.addEventListener = _addEventListener;
Element.prototype.removeEventListener = _removeEventListener;
if (window.HTMLDocument) {
HTMLDocument.prototype.addEventListener = _addEventListener;
HTMLDocument.prototype.removeEventListener = _removeEventListener;
}
if (window.Window) {
Window.prototype.addEventListener = _addEventListener;
Window.prototype.removeEventListener = _removeEventListener;
}
}
}
function bind(name, callback) {
if (!callback) {
callback = name;
name = currentSection;
}
return function() {
var priorSite = currentSection;
try {
currentSection = name;
callback.apply(this, arguments);
} catch (err) {
reportCallback({
type: 'javascript',
section: currentSection,
msg: err.message,
stack: err.stack
}, err);
} finally {
currentSection = priorSite;
}
};
}
function onError(errorMsg, url, lineNumber, error) {
var type = 'javascript';
// Handle ErrorEvent if we receieve it
if (errorMsg && errorMsg.message) {
url = errorMsg.filename;
lineNumber = errorMsg.lineno;
error = errorMsg.error;
errorMsg = errorMsg.message;
}
if (errorMsg === 'Script error.' && !url) {
// Ignore untrackable external errors locally
return;
}
// This is a real event handler vs. the onerror special case.
// Since some browsers decide to treat window.onerror as the error event handler,
// we have to be prepared for either case
if (errorMsg && errorMsg.srcElement) {
// Don't submit duplciate events (and if we weren't already tracking
// it, it probably wasn't that important)
if (errorMsg.defaultPrevented || errorMsg._costanzaHandled) {
return;
}
errorMsg._costanzaHandled = true;
url = url || errorMsg.srcElement.src || errorMsg.srcElement.href;
type = errorMsg.srcElement.tagName.toLowerCase();
errorMsg = 'load-failed';
}
// Error argument added to the spec. Adding support so we can catch this as it rolls out
// http://html5.org/tools/web-apps-tracker?from=8085&to=8086
reportCallback({
section: currentSection,
url: url,
line: lineNumber,
type: type,
// Cast error message to string as it sometimes can come through with objects, particularly DOM objects
// containing circular references.
msg: errorMsg+'',
stack: error && error.stack
}, error);
}
function onErrorRoot(errorMsg, url, lineNumber, error) {
_onError && _onError(errorMsg, url, lineNumber, error);
onError(errorMsg, url, lineNumber, error);
}
onErrorRoot._costanza = true;
return {
init: init,
cleanup: cleanup,
current: function() {
return currentSection;
},
emit: function(info, error) {
reportCallback(info, error);
},
bind: bind,
run: function(name, callback) {
bind(name, callback)();
},
onError: onError
};
})();
| js/costanza.js | /*global HTMLDocument, Window, console */
this.Costanza = (function() {
"use strict";
function defaultReporter(info, err) {
console.error('Costanza error', info);
}
var reportCallback = defaultReporter,
currentSection = 'global',
_onError,
_setTimeout,
_setInterval,
_addEventListener,
_removeEventListener;
function init(_reportCallback, options) {
reportCallback = _reportCallback || defaultReporter;
if (!window.onerror || !window.onerror.errorSite) {
_onError = _onError || window.onerror;
window.onerror = onErrorRoot;
window.addEventListener('error', onError, true);
}
// Allow users to opt out of the native prototype augmentation.
if (options && options.safeMode) {
return;
}
if (!setTimeout.errorSite) {
_setTimeout = setTimeout;
window.setTimeout = function(callback, duration) {
return _setTimeout(bind(callback), duration);
};
setTimeout.errorSite = true;
}
if (!setInterval.errorSite) {
_setInterval = setInterval;
window.setInterval = function(callback, interval) {
return _setInterval(bind(callback), interval);
};
setInterval.errorSite = true;
}
if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener.errorSite) {
_addEventListener = Element.prototype.addEventListener;
var addEventListener = function(type, callback, useCapture) {
callback._section = callback._section || bind(callback);
_addEventListener.call(this, type, callback._section, useCapture);
};
addEventListener.errorSite = true;
Element.prototype.addEventListener = addEventListener;
_removeEventListener = Element.prototype.removeEventListener;
var removeEventListener = function(type, callback, useCapture) {
_removeEventListener.call(this, type, callback._section || callback, useCapture);
};
removeEventListener.errorSite = true;
Element.prototype.removeEventListener = removeEventListener;
if (window.HTMLDocument) {
HTMLDocument.prototype.addEventListener = addEventListener;
HTMLDocument.prototype.removeEventListener = removeEventListener;
}
if (window.Window) {
Window.prototype.addEventListener = addEventListener;
Window.prototype.removeEventListener = removeEventListener;
}
}
}
function cleanup() {
reportCallback = defaultReporter;
if (window.onerror && window.onerror.errorSite) {
window.onerror = _onError;
window.removeEventListener('error', onError, true);
}
if (setTimeout.errorSite) {
window.setTimeout = _setTimeout;
}
if (setInterval.errorSite) {
window.setInterval = _setInterval;
}
if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener.errorSite) {
Element.prototype.addEventListener = _addEventListener;
Element.prototype.removeEventListener = _removeEventListener;
if (window.HTMLDocument) {
HTMLDocument.prototype.addEventListener = _addEventListener;
HTMLDocument.prototype.removeEventListener = _removeEventListener;
}
if (window.Window) {
Window.prototype.addEventListener = _addEventListener;
Window.prototype.removeEventListener = _removeEventListener;
}
}
}
function bind(name, callback) {
if (!callback) {
callback = name;
name = currentSection;
}
return function() {
var priorSite = currentSection;
try {
currentSection = name;
callback.apply(this, arguments);
} catch (err) {
reportCallback({
type: 'javascript',
section: currentSection,
msg: err.message,
stack: err.stack
}, err);
} finally {
currentSection = priorSite;
}
};
}
function onError(errorMsg, url, lineNumber, error) {
var type = 'javascript';
// Handle ErrorEvent if we receieve it
if (errorMsg && errorMsg.message) {
url = errorMsg.filename;
lineNumber = errorMsg.lineno;
error = errorMsg.error;
errorMsg = errorMsg.message;
}
if (errorMsg === 'Script error.' && !url) {
// Ignore untrackable external errors locally
return;
}
// This is a real event handler vs. the onerror special case.
// Since some browsers decide to treat window.onerror as the error event handler,
// we have to be prepared for either case
if (errorMsg && errorMsg.srcElement) {
// Don't submit duplciate events (and if we weren't already tracking
// it, it probably wasn't that important)
if (errorMsg.defaultPrevented || errorMsg.errorSiteHandled) {
return;
}
errorMsg.errorSiteHandled = true;
url = url || errorMsg.srcElement.src || errorMsg.srcElement.href;
type = errorMsg.srcElement.tagName.toLowerCase();
errorMsg = 'load-failed';
}
// Error argument added to the spec. Adding support so we can catch this as it rolls out
// http://html5.org/tools/web-apps-tracker?from=8085&to=8086
reportCallback({
section: currentSection,
url: url,
line: lineNumber,
type: type,
// Cast error message to string as it sometimes can come through with objects, particularly DOM objects
// containing circular references.
msg: errorMsg+'',
stack: error && error.stack
}, error);
}
function onErrorRoot(errorMsg, url, lineNumber, error) {
_onError && _onError(errorMsg, url, lineNumber, error);
onError(errorMsg, url, lineNumber, error);
}
onErrorRoot.errorSite = true;
return {
init: init,
cleanup: cleanup,
current: function() {
return currentSection;
},
emit: function(info, error) {
reportCallback(info, error);
},
bind: bind,
run: function(name, callback) {
bind(name, callback)();
},
onError: onError
};
})();
| Rename errorSite flag | js/costanza.js | Rename errorSite flag | <ide><path>s/costanza.js
<ide> function init(_reportCallback, options) {
<ide> reportCallback = _reportCallback || defaultReporter;
<ide>
<del> if (!window.onerror || !window.onerror.errorSite) {
<add> if (!window.onerror || !window.onerror._costanza) {
<ide> _onError = _onError || window.onerror;
<ide> window.onerror = onErrorRoot;
<ide>
<ide> return;
<ide> }
<ide>
<del> if (!setTimeout.errorSite) {
<add> if (!setTimeout._costanza) {
<ide> _setTimeout = setTimeout;
<ide> window.setTimeout = function(callback, duration) {
<ide> return _setTimeout(bind(callback), duration);
<ide> };
<del> setTimeout.errorSite = true;
<add> setTimeout._costanza = true;
<ide> }
<ide>
<del> if (!setInterval.errorSite) {
<add> if (!setInterval._costanza) {
<ide> _setInterval = setInterval;
<ide> window.setInterval = function(callback, interval) {
<ide> return _setInterval(bind(callback), interval);
<ide> };
<del> setInterval.errorSite = true;
<add> setInterval._costanza = true;
<ide> }
<ide>
<del> if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener.errorSite) {
<add> if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener._costanza) {
<ide> _addEventListener = Element.prototype.addEventListener;
<ide> var addEventListener = function(type, callback, useCapture) {
<ide> callback._section = callback._section || bind(callback);
<ide> _addEventListener.call(this, type, callback._section, useCapture);
<ide> };
<del> addEventListener.errorSite = true;
<add> addEventListener._costanza = true;
<ide> Element.prototype.addEventListener = addEventListener;
<ide>
<ide> _removeEventListener = Element.prototype.removeEventListener;
<ide> var removeEventListener = function(type, callback, useCapture) {
<ide> _removeEventListener.call(this, type, callback._section || callback, useCapture);
<ide> };
<del> removeEventListener.errorSite = true;
<add> removeEventListener._costanza = true;
<ide> Element.prototype.removeEventListener = removeEventListener;
<ide>
<ide> if (window.HTMLDocument) {
<ide> }
<ide> function cleanup() {
<ide> reportCallback = defaultReporter;
<del> if (window.onerror && window.onerror.errorSite) {
<add> if (window.onerror && window.onerror._costanza) {
<ide> window.onerror = _onError;
<ide>
<ide> window.removeEventListener('error', onError, true);
<ide> }
<del> if (setTimeout.errorSite) {
<add> if (setTimeout._costanza) {
<ide> window.setTimeout = _setTimeout;
<ide> }
<del> if (setInterval.errorSite) {
<add> if (setInterval._costanza) {
<ide> window.setInterval = _setInterval;
<ide> }
<del> if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener.errorSite) {
<add> if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener._costanza) {
<ide> Element.prototype.addEventListener = _addEventListener;
<ide> Element.prototype.removeEventListener = _removeEventListener;
<ide>
<ide> if (errorMsg && errorMsg.srcElement) {
<ide> // Don't submit duplciate events (and if we weren't already tracking
<ide> // it, it probably wasn't that important)
<del> if (errorMsg.defaultPrevented || errorMsg.errorSiteHandled) {
<add> if (errorMsg.defaultPrevented || errorMsg._costanzaHandled) {
<ide> return;
<ide> }
<ide>
<del> errorMsg.errorSiteHandled = true;
<add> errorMsg._costanzaHandled = true;
<ide> url = url || errorMsg.srcElement.src || errorMsg.srcElement.href;
<ide> type = errorMsg.srcElement.tagName.toLowerCase();
<ide> errorMsg = 'load-failed';
<ide> _onError && _onError(errorMsg, url, lineNumber, error);
<ide> onError(errorMsg, url, lineNumber, error);
<ide> }
<del> onErrorRoot.errorSite = true;
<add> onErrorRoot._costanza = true;
<ide>
<ide> return {
<ide> init: init, |
|
Java | apache-2.0 | f086cfd46f5cc5ef73ac6188dca870ad7447d505 | 0 | jam891/omim,dobriy-eeh/omim,65apps/omim,bykoianko/omim,AlexanderMatveenko/omim,edl00k/omim,lydonchandra/omim,dkorolev/omim,vladon/omim,wersoo/omim,VladiMihaylenko/omim,dkorolev/omim,lydonchandra/omim,darina/omim,dobriy-eeh/omim,goblinr/omim,VladiMihaylenko/omim,Transtech/omim,dobriy-eeh/omim,programming086/omim,stangls/omim,TimurTarasenko/omim,kw217/omim,vasilenkomike/omim,dkorolev/omim,TimurTarasenko/omim,Komzpa/omim,Endika/omim,trashkalmar/omim,darina/omim,andrewshadura/omim,milchakov/omim,programming086/omim,kw217/omim,dkorolev/omim,vasilenkomike/omim,alexzatsepin/omim,darina/omim,felipebetancur/omim,igrechuhin/omim,kw217/omim,Saicheg/omim,VladiMihaylenko/omim,lydonchandra/omim,alexzatsepin/omim,syershov/omim,albertshift/omim,simon247/omim,rokuz/omim,ygorshenin/omim,mapsme/omim,VladiMihaylenko/omim,wersoo/omim,UdjinM6/omim,bykoianko/omim,augmify/omim,Transtech/omim,andrewshadura/omim,alexzatsepin/omim,lydonchandra/omim,UdjinM6/omim,stangls/omim,syershov/omim,mgsergio/omim,vasilenkomike/omim,dkorolev/omim,Transtech/omim,simon247/omim,jam891/omim,gardster/omim,mgsergio/omim,matsprea/omim,andrewshadura/omim,bykoianko/omim,Volcanoscar/omim,yunikkk/omim,dobriy-eeh/omim,lydonchandra/omim,lydonchandra/omim,Transtech/omim,vasilenkomike/omim,augmify/omim,Zverik/omim,syershov/omim,trashkalmar/omim,goblinr/omim,AlexanderMatveenko/omim,ygorshenin/omim,alexzatsepin/omim,ygorshenin/omim,krasin/omim,jam891/omim,jam891/omim,krasin/omim,lydonchandra/omim,therearesomewhocallmetim/omim,augmify/omim,victorbriz/omim,Saicheg/omim,dkorolev/omim,stangls/omim,Zverik/omim,dobriy-eeh/omim,VladiMihaylenko/omim,65apps/omim,Zverik/omim,mpimenov/omim,TimurTarasenko/omim,mpimenov/omim,Saicheg/omim,stangls/omim,darina/omim,victorbriz/omim,UdjinM6/omim,Transtech/omim,simon247/omim,65apps/omim,felipebetancur/omim,Zverik/omim,vasilenkomike/omim,bykoianko/omim,UdjinM6/omim,sidorov-panda/omim,ygorshenin/omim,Saicheg/omim,felipebetancur/omim,VladiMihaylenko/omim,albertshift/omim,augmify/omim,65apps/omim,vng/omim,igrechuhin/omim,mapsme/omim,programming086/omim,krasin/omim,victorbriz/omim,felipebetancur/omim,darina/omim,ygorshenin/omim,victorbriz/omim,vladon/omim,andrewshadura/omim,ygorshenin/omim,Zverik/omim,albertshift/omim,stangls/omim,dobriy-eeh/omim,victorbriz/omim,bykoianko/omim,Saicheg/omim,felipebetancur/omim,trashkalmar/omim,AlexanderMatveenko/omim,syershov/omim,TimurTarasenko/omim,syershov/omim,syershov/omim,therearesomewhocallmetim/omim,AlexanderMatveenko/omim,krasin/omim,programming086/omim,mpimenov/omim,mapsme/omim,dkorolev/omim,sidorov-panda/omim,sidorov-panda/omim,kw217/omim,vng/omim,syershov/omim,therearesomewhocallmetim/omim,rokuz/omim,ygorshenin/omim,VladiMihaylenko/omim,jam891/omim,krasin/omim,Komzpa/omim,Saicheg/omim,trashkalmar/omim,Komzpa/omim,darina/omim,65apps/omim,simon247/omim,milchakov/omim,milchakov/omim,simon247/omim,therearesomewhocallmetim/omim,darina/omim,trashkalmar/omim,victorbriz/omim,yunikkk/omim,krasin/omim,victorbriz/omim,yunikkk/omim,mapsme/omim,kw217/omim,sidorov-panda/omim,bykoianko/omim,matsprea/omim,simon247/omim,simon247/omim,vng/omim,vasilenkomike/omim,krasin/omim,igrechuhin/omim,krasin/omim,rokuz/omim,Transtech/omim,mpimenov/omim,Saicheg/omim,kw217/omim,rokuz/omim,edl00k/omim,darina/omim,Zverik/omim,andrewshadura/omim,therearesomewhocallmetim/omim,alexzatsepin/omim,vladon/omim,therearesomewhocallmetim/omim,lydonchandra/omim,TimurTarasenko/omim,vng/omim,programming086/omim,Volcanoscar/omim,lydonchandra/omim,albertshift/omim,bykoianko/omim,vladon/omim,edl00k/omim,stangls/omim,mapsme/omim,edl00k/omim,Endika/omim,TimurTarasenko/omim,Volcanoscar/omim,matsprea/omim,ygorshenin/omim,igrechuhin/omim,trashkalmar/omim,milchakov/omim,dobriy-eeh/omim,goblinr/omim,UdjinM6/omim,matsprea/omim,VladiMihaylenko/omim,yunikkk/omim,vasilenkomike/omim,Endika/omim,wersoo/omim,goblinr/omim,bykoianko/omim,programming086/omim,gardster/omim,Endika/omim,gardster/omim,albertshift/omim,UdjinM6/omim,therearesomewhocallmetim/omim,65apps/omim,AlexanderMatveenko/omim,Zverik/omim,ygorshenin/omim,milchakov/omim,vasilenkomike/omim,mgsergio/omim,goblinr/omim,edl00k/omim,UdjinM6/omim,andrewshadura/omim,trashkalmar/omim,dobriy-eeh/omim,milchakov/omim,kw217/omim,andrewshadura/omim,rokuz/omim,kw217/omim,alexzatsepin/omim,wersoo/omim,igrechuhin/omim,igrechuhin/omim,simon247/omim,augmify/omim,gardster/omim,igrechuhin/omim,felipebetancur/omim,rokuz/omim,VladiMihaylenko/omim,Transtech/omim,mpimenov/omim,stangls/omim,syershov/omim,mgsergio/omim,goblinr/omim,augmify/omim,goblinr/omim,vng/omim,sidorov-panda/omim,Volcanoscar/omim,mgsergio/omim,vng/omim,Endika/omim,albertshift/omim,guard163/omim,vladon/omim,Zverik/omim,Zverik/omim,mapsme/omim,augmify/omim,alexzatsepin/omim,milchakov/omim,65apps/omim,vasilenkomike/omim,vladon/omim,programming086/omim,edl00k/omim,ygorshenin/omim,albertshift/omim,vng/omim,wersoo/omim,bykoianko/omim,milchakov/omim,milchakov/omim,darina/omim,dkorolev/omim,mapsme/omim,dobriy-eeh/omim,Saicheg/omim,gardster/omim,Volcanoscar/omim,UdjinM6/omim,dobriy-eeh/omim,mapsme/omim,edl00k/omim,programming086/omim,matsprea/omim,albertshift/omim,kw217/omim,victorbriz/omim,yunikkk/omim,ygorshenin/omim,yunikkk/omim,vladon/omim,TimurTarasenko/omim,AlexanderMatveenko/omim,rokuz/omim,stangls/omim,krasin/omim,wersoo/omim,TimurTarasenko/omim,wersoo/omim,vng/omim,rokuz/omim,goblinr/omim,mpimenov/omim,yunikkk/omim,gardster/omim,goblinr/omim,vasilenkomike/omim,Volcanoscar/omim,mapsme/omim,felipebetancur/omim,VladiMihaylenko/omim,vladon/omim,mpimenov/omim,alexzatsepin/omim,edl00k/omim,Volcanoscar/omim,UdjinM6/omim,darina/omim,65apps/omim,mpimenov/omim,UdjinM6/omim,alexzatsepin/omim,syershov/omim,AlexanderMatveenko/omim,goblinr/omim,vng/omim,augmify/omim,Transtech/omim,Komzpa/omim,programming086/omim,dobriy-eeh/omim,rokuz/omim,jam891/omim,65apps/omim,Volcanoscar/omim,dkorolev/omim,trashkalmar/omim,milchakov/omim,albertshift/omim,bykoianko/omim,Zverik/omim,kw217/omim,augmify/omim,matsprea/omim,syershov/omim,jam891/omim,darina/omim,guard163/omim,bykoianko/omim,krasin/omim,gardster/omim,gardster/omim,Volcanoscar/omim,therearesomewhocallmetim/omim,sidorov-panda/omim,stangls/omim,trashkalmar/omim,65apps/omim,Transtech/omim,syershov/omim,mgsergio/omim,Saicheg/omim,VladiMihaylenko/omim,goblinr/omim,vng/omim,guard163/omim,Volcanoscar/omim,mpimenov/omim,sidorov-panda/omim,igrechuhin/omim,Transtech/omim,Endika/omim,mapsme/omim,Komzpa/omim,darina/omim,dkorolev/omim,Komzpa/omim,mpimenov/omim,guard163/omim,sidorov-panda/omim,VladiMihaylenko/omim,mapsme/omim,guard163/omim,guard163/omim,matsprea/omim,65apps/omim,milchakov/omim,dobriy-eeh/omim,Zverik/omim,AlexanderMatveenko/omim,TimurTarasenko/omim,wersoo/omim,Endika/omim,dobriy-eeh/omim,milchakov/omim,guard163/omim,alexzatsepin/omim,milchakov/omim,igrechuhin/omim,trashkalmar/omim,simon247/omim,mgsergio/omim,darina/omim,felipebetancur/omim,bykoianko/omim,alexzatsepin/omim,mgsergio/omim,programming086/omim,felipebetancur/omim,stangls/omim,mpimenov/omim,edl00k/omim,Komzpa/omim,sidorov-panda/omim,Transtech/omim,mgsergio/omim,gardster/omim,vladon/omim,stangls/omim,andrewshadura/omim,yunikkk/omim,AlexanderMatveenko/omim,guard163/omim,Zverik/omim,yunikkk/omim,victorbriz/omim,albertshift/omim,yunikkk/omim,VladiMihaylenko/omim,mgsergio/omim,ygorshenin/omim,andrewshadura/omim,felipebetancur/omim,guard163/omim,victorbriz/omim,simon247/omim,yunikkk/omim,rokuz/omim,mapsme/omim,bykoianko/omim,mapsme/omim,goblinr/omim,AlexanderMatveenko/omim,Komzpa/omim,goblinr/omim,alexzatsepin/omim,guard163/omim,TimurTarasenko/omim,Endika/omim,matsprea/omim,jam891/omim,wersoo/omim,syershov/omim,Komzpa/omim,edl00k/omim,Endika/omim,andrewshadura/omim,jam891/omim,mpimenov/omim,trashkalmar/omim,therearesomewhocallmetim/omim,igrechuhin/omim,Saicheg/omim,jam891/omim,matsprea/omim,Transtech/omim,mgsergio/omim,syershov/omim,rokuz/omim,therearesomewhocallmetim/omim,rokuz/omim,lydonchandra/omim,mpimenov/omim,Komzpa/omim,sidorov-panda/omim,Endika/omim,trashkalmar/omim,alexzatsepin/omim,vladon/omim,Zverik/omim,wersoo/omim,gardster/omim,mgsergio/omim,matsprea/omim,rokuz/omim,augmify/omim | package com.mapswithme.country;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.MWMApplication;
import com.mapswithme.maps.MapStorage;
import com.mapswithme.maps.MapStorage.Index;
import com.mapswithme.maps.R;
import com.mapswithme.maps.guides.GuideInfo;
import com.mapswithme.maps.guides.GuidesUtils;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.statistics.Statistics;
/// ListView adapter
class DownloadAdapter extends BaseAdapter
{
/// @name Different row types.
//@{
private static final int TYPE_GROUP = 0;
private static final int TYPE_COUNTRY_GROUP = 1;
private static final int TYPE_COUNTRY_IN_PROCESS = 2;
private static final int TYPE_COUNTRY_READY = 3;
private static final int TYPE_COUNTRY_NOT_DOWNLOADED = 4;
private static final int TYPES_COUNT = 5;
//@}
private final LayoutInflater mInflater;
private final Activity mContext;
private int mSlotID = 0;
final MapStorage mStorage;
private Index mIdx = new Index();
private DownloadAdapter.CountryItem[] mItems = null;
private final ExecutorService executor =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private final boolean mHasGoogleStore;
private class CountryItem
{
public final String mName;
public final Index mCountryIdx;
public final String mFlag;
/// @see constants in MapStorage
private Future<Integer> mStatusFuture;
public CountryItem(MapStorage storage, Index idx)
{
mCountryIdx = idx;
mName = storage.countryName(idx);
final String flag = storage.countryFlag(idx);
// The aapt can't process resources with name "do". Hack with renaming.
mFlag = flag.equals("do") ? "do_hack" : flag;
updateStatus(storage, idx);
}
public int getStatus()
{
try
{
return mStatusFuture.get();
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
public void updateStatus(final MapStorage storage, final Index idx)
{
mStatusFuture = executor.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
if (idx.getCountry() == -1 || (idx.getRegion() == -1 && mFlag.length() == 0))
return MapStorage.GROUP;
else if (idx.getRegion() == -1 && storage.countriesCount(idx) > 0)
return MapStorage.COUNTRY;
else
return storage.countryStatus(idx);
}});
}
public int getTextColor()
{
switch (getStatus())
{
case MapStorage.ON_DISK: return 0xFF333333;
case MapStorage.ON_DISK_OUT_OF_DATE: return 0xFF000000;
case MapStorage.NOT_DOWNLOADED: return 0xFF999999;
case MapStorage.DOWNLOAD_FAILED: return 0xFFFF0000;
case MapStorage.DOWNLOADING: return 0xFF342BB6;
case MapStorage.IN_QUEUE: return 0xFF5B94DE;
default: return 0xFF000000;
}
}
/// Get item type for list view representation;
public int getType()
{
switch (getStatus())
{
case MapStorage.GROUP: return TYPE_GROUP;
case MapStorage.COUNTRY: return TYPE_COUNTRY_GROUP;
case MapStorage.NOT_DOWNLOADED: return TYPE_COUNTRY_NOT_DOWNLOADED;
case MapStorage.ON_DISK:
case MapStorage.ON_DISK_OUT_OF_DATE:
return TYPE_COUNTRY_READY;
default : return TYPE_COUNTRY_IN_PROCESS;
}
}
}
public DownloadAdapter(Activity context)
{
mStorage = MWMApplication.get().getMapStorage();
mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHasGoogleStore = Utils.hasAnyGoogleStoreInstalled();
fillList();
}
/// Fill list for current m_group and m_country.
private void fillList()
{
final int count = mStorage.countriesCount(mIdx);
if (count > 0)
{
mItems = new DownloadAdapter.CountryItem[count];
for (int i = 0; i < count; ++i)
mItems[i] = new CountryItem(mStorage, mIdx.getChild(i));
}
notifyDataSetChanged();
}
/// Process list item click.
public void onItemClick(int position, View view)
{
if (mItems[position].getStatus() < 0)
{
// expand next level
mIdx = mIdx.getChild(position);
fillList();
}
else
{
if (getItemViewType(position) == TYPE_COUNTRY_READY)
showCountry(getItem(position).mCountryIdx);
else
onCountryMenuClicked(position, getItem(position), view);
}
}
private void showNotEnoughFreeSpaceDialog(String spaceNeeded, String countryName)
{
final Dialog dlg = new AlertDialog.Builder(mContext)
.setMessage(String.format(mContext.getString(R.string.free_space_for_country), spaceNeeded, countryName))
.setNegativeButton(mContext.getString(R.string.close), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
}
})
.create();
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
private boolean hasFreeSpace(long size)
{
return MWMApplication.get().hasFreeSpace(size);
}
private void processNotDownloaded(final Index idx, final String name)
{
final long size = mStorage.countryRemoteSizeInBytes(idx);
if (!hasFreeSpace(size + MB))
showNotEnoughFreeSpaceDialog(getSizeString(size), name);
else
{
mStorage.downloadCountry(idx);
Statistics.INSTANCE.trackCountryDownload(mContext);
}
}
private void processDownloading(final Index idx, final String name)
{
// Confirm canceling
final Dialog dlg = new AlertDialog.Builder(mContext)
.setTitle(name)
.setPositiveButton(R.string.cancel_download, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
mStorage.deleteCountry(idx);
dlg.dismiss();
}
})
.create();
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
private void processOutOfDate(final Index idx, final String name)
{
final long remoteSize = mStorage.countryRemoteSizeInBytes(idx);
if (!hasFreeSpace(remoteSize + MB))
showNotEnoughFreeSpaceDialog(getSizeString(remoteSize), name);
else
{
mStorage.downloadCountry(idx);
Statistics.INSTANCE.trackCountryUpdate(mContext);
}
}
private void processOnDisk(final Index idx, final String name)
{
// Confirm deleting
new AlertDialog.Builder(mContext)
.setTitle(name)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
mStorage.deleteCountry(idx);
Statistics.INSTANCE.trackCountryDeleted(mContext);
dlg.dismiss();
}
})
.create()
.show();
}
private void updateStatuses()
{
for (int i = 0; i < mItems.length; ++i)
{
final Index idx = mIdx.getChild(i);
if (idx.isValid())
mItems[i].updateStatus(mStorage, idx);
}
}
/// @name Process routine from parent Activity.
//@{
/// @return true If "back" was processed.
public boolean onBackPressed()
{
// we are on the root level already - return
if (mIdx.isRoot())
return false;
// go to the parent level
mIdx = mIdx.getParent();
fillList();
return true;
}
public void onResume(MapStorage.Listener listener)
{
if (mSlotID == 0)
mSlotID = mStorage.subscribe(listener);
// update actual statuses for items after resuming activity
updateStatuses();
notifyDataSetChanged();
}
public void onPause()
{
if (mSlotID != 0)
{
mStorage.unsubscribe(mSlotID);
mSlotID = 0;
}
}
//@}
@Override
public int getItemViewType(int position)
{
return mItems[position].getType();
}
@Override
public int getViewTypeCount()
{
return TYPES_COUNT;
}
@Override
public int getCount()
{
return (mItems != null ? mItems.length : 0);
}
@Override
public DownloadAdapter.CountryItem getItem(int position)
{
return mItems[position];
}
@Override
public long getItemId(int position)
{
return position;
}
private static class ViewHolder
{
public TextView mName = null;
public ImageView mFlag = null;
public ImageView mGuide = null;
public ProgressBar mProgress = null;
public View mCountryMenu = null;
void initFromView(View v)
{
mName = (TextView) v.findViewById(R.id.title);
mFlag = (ImageView) v.findViewById(R.id.country_flag);
mGuide = (ImageView) v.findViewById(R.id.guide_available);
mCountryMenu = v.findViewById(R.id.country_menu);
mProgress = (ProgressBar) v.findViewById(R.id.download_progress);
}
}
private String formatStringWithSize(int strID, Index index)
{
return mContext.getString(strID, getSizeString(mStorage.countryRemoteSizeInBytes(index)));
}
private void setFlag(int position, ImageView v)
{
final String strID = mItems[position].mFlag;
int id = -1;
try
{
// works faster than 'getIdentifier()'
id = R.drawable.class.getField(strID).getInt(null);
if (id > 0)
v.setImageResource(id);
else
Log.e(DownloadUI.TAG, "Failed to get resource id from: " + strID);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final int type = getItemViewType(position);
if (convertView == null)
{
holder = new ViewHolder();
switch (type)
{
case TYPE_GROUP:
convertView = mInflater.inflate(R.layout.download_item_group, null);
holder.initFromView(convertView);
break;
case TYPE_COUNTRY_GROUP:
convertView = mInflater.inflate(R.layout.download_item_country_group, null);
holder.initFromView(convertView);
break;
case TYPE_COUNTRY_IN_PROCESS:
case TYPE_COUNTRY_READY:
case TYPE_COUNTRY_NOT_DOWNLOADED:
convertView = mInflater.inflate(R.layout.download_item_country, null);
holder.initFromView(convertView);
break;
}
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
// for everything that has flag: regions + countries
if (type != TYPE_GROUP)
{
setFlag(position, holder.mFlag);
// this part if only for downloadable items
if (type != TYPE_COUNTRY_GROUP)
{
populateForGuide(position, holder);
setUpProgress(holder, type, position);
// set country menu click listener
final View fView = holder.mCountryMenu;
holder.mCountryMenu.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
onCountryMenuClicked(position, getItem(position), fView);
}
});
}
}
setItemText(position, holder);
convertView.setBackgroundResource(R.drawable.list_selector_holo_light);
final View fview = convertView;
convertView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
onItemClick(position, fview);
}
});
return convertView;
}
private void setUpProgress(DownloadAdapter.ViewHolder holder, int type, int position)
{
if (type == TYPE_COUNTRY_IN_PROCESS && getItem(position).getStatus() != MapStorage.DOWNLOAD_FAILED)
{
holder.mProgress.setProgress(0);
UiUtils.show(holder.mProgress);
}
else
UiUtils.invisible(holder.mProgress);
}
private void setItemText(int position, DownloadAdapter.ViewHolder holder)
{
// set texts
holder.mName.setText(mItems[position].mName);
holder.mName.setTextColor(mItems[position].getTextColor());
}
private void populateForGuide(int position, DownloadAdapter.ViewHolder holder)
{
if (mHasGoogleStore)
{
final CountryItem item = getItem(position);
final GuideInfo gi = Framework.getGuideInfoForIndex(item.mCountryIdx);
if (gi != null)
UiUtils.show(holder.mGuide);
else
UiUtils.hide(holder.mGuide);
}
}
/// Get list item position by index(g, c, r).
/// @return -1 If no such item in display list.
private int getItemPosition(Index idx)
{
if (mIdx.isChild(idx))
{
final int position = idx.getPosition();
if (position >= 0 && position < mItems.length)
return position;
else
Log.e(DownloadUI.TAG, "Incorrect item position for: " + idx.toString());
}
return -1;
}
/// @return Current country status (@see MapStorage).
public int onCountryStatusChanged(Index idx)
{
final int position = getItemPosition(idx);
if (position != -1)
{
mItems[position].updateStatus(mStorage, idx);
// use this hard reset, because of caching different ViewHolders according to item's type
notifyDataSetChanged();
return mItems[position].getStatus();
}
return MapStorage.UNKNOWN;
}
public void onCountryProgress(ListView list, Index idx, long current, long total)
{
final int position = getItemPosition(idx);
if (position != -1)
{
// do update only one item's view; don't call notifyDataSetChanged
final View v = list.getChildAt(position - list.getFirstVisiblePosition());
if (v != null)
{
final DownloadAdapter.ViewHolder holder = (DownloadAdapter.ViewHolder) v.getTag();
holder.mProgress.setProgress((int) (current*100/total));
}
}
}
private void showCountry(final Index countryIndex)
{
mStorage.showCountry(countryIndex);
mContext.finish();
}
private void onCountryMenuClicked(int position, final CountryItem countryItem, View anchor)
{
final int MENU_DELETE = 0;
final int MENU_UPDATE = 1;
final int MENU_GUIDE = 3;
final int MENU_DOWNLOAD = 4;
final int MENU_CANCEL = 5;
final int status = countryItem.getStatus();
final Index countryIndex = countryItem.mCountryIdx;
final String name = countryItem.mName;
final OnMenuItemClickListener menuItemClickListener = new OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
final int id = item.getItemId();
if (MENU_DELETE == id)
processOnDisk(countryIndex, name);
else if (MENU_UPDATE == id)
processOutOfDate(countryIndex, name);
else if (MENU_GUIDE == id)
GuidesUtils.openOrDownloadGuide(Framework.getGuideInfoForIndex(countryIndex), mContext);
else if (MENU_DOWNLOAD == id)
processNotDownloaded(countryIndex, name);
else if (MENU_CANCEL == id)
processDownloading(countryIndex, name);
else
return false;
return true;
}
};
anchor.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
{
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
menu.setHeaderTitle(countryItem.mName);
if (status == MapStorage.ON_DISK || status == MapStorage.ON_DISK_OUT_OF_DATE)
menu.add(0, MENU_DELETE, MENU_DELETE, mContext.getString(R.string.delete))
.setOnMenuItemClickListener(menuItemClickListener);
if (status == MapStorage.ON_DISK_OUT_OF_DATE)
{
final String titleUpdate = formatStringWithSize(R.string.update_mb_or_kb, countryIndex);
menu.add(0, MENU_UPDATE, MENU_UPDATE, titleUpdate)
.setOnMenuItemClickListener(menuItemClickListener);
}
if (status == MapStorage.DOWNLOADING || status == MapStorage.IN_QUEUE)
menu.add(0, MENU_CANCEL, MENU_CANCEL, mContext.getString(R.string.cancel_download))
.setOnMenuItemClickListener(menuItemClickListener);
if (mHasGoogleStore)
{
final GuideInfo info = Framework.getGuideInfoForIndex(countryItem.mCountryIdx);
if (info != null)
menu.add(0, MENU_GUIDE, MENU_GUIDE, info.mTitle) // TODO: add translation
.setOnMenuItemClickListener(menuItemClickListener);
}
if (status == MapStorage.NOT_DOWNLOADED || status == MapStorage.DOWNLOAD_FAILED)
{
final String titleDownload = formatStringWithSize(R.string.download_mb_or_kb, countryIndex);
menu.add(0, MENU_DOWNLOAD, MENU_DOWNLOAD, titleDownload)
.setOnMenuItemClickListener(menuItemClickListener);
}
}
});
anchor.showContextMenu();
anchor.setOnCreateContextMenuListener(null);
}
private String getSizeString(long size)
{
if (size > MB)
return (size + 512 * 1024) / MB + " " + mContext.getString(R.string.mb);
else
return (size + 1023) / 1024 + " " + mContext.getString(R.string.kb);
}
private final static long MB = 1024 * 1024;
} | android/src/com/mapswithme/country/DownloadAdapter.java | package com.mapswithme.country;
import java.lang.reflect.Field;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.MWMApplication;
import com.mapswithme.maps.MapStorage;
import com.mapswithme.maps.MapStorage.Index;
import com.mapswithme.maps.R;
import com.mapswithme.maps.guides.GuideInfo;
import com.mapswithme.maps.guides.GuidesUtils;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.statistics.Statistics;
/// ListView adapter
class DownloadAdapter extends BaseAdapter
{
/// @name Different row types.
//@{
private static final int TYPE_GROUP = 0;
private static final int TYPE_COUNTRY_GROUP = 1;
private static final int TYPE_COUNTRY_IN_PROCESS = 2;
private static final int TYPE_COUNTRY_READY = 3;
private static final int TYPE_COUNTRY_NOT_DOWNLOADED = 4;
private static final int TYPES_COUNT = 5;
//@}
private final LayoutInflater mInflater;
private final Activity mContext;
private int mSlotID = 0;
final MapStorage mStorage;
private Index mIdx = new Index();
private DownloadAdapter.CountryItem[] mItems = null;
private final boolean mHasGoogleStore;
private static class CountryItem
{
public final String mName;
public final Index mCountryIdx;
public final String mFlag;
/// @see constants in MapStorage
public int mStatus;
public CountryItem(MapStorage storage, Index idx)
{
mCountryIdx = idx;
mName = storage.countryName(idx);
final String flag = storage.countryFlag(idx);
// The aapt can't process resources with name "do". Hack with renaming.
mFlag = flag.equals("do") ? "do_hack" : flag;
updateStatus(storage, idx);
}
public void updateStatus(MapStorage storage, Index idx)
{
if (idx.getCountry() == -1 || (idx.getRegion() == -1 && mFlag.length() == 0))
mStatus = MapStorage.GROUP;
else if (idx.getRegion() == -1 && storage.countriesCount(idx) > 0)
mStatus = MapStorage.COUNTRY;
else
mStatus = storage.countryStatus(idx);
}
public int getTextColor()
{
switch (mStatus)
{
case MapStorage.ON_DISK: return 0xFF333333;
case MapStorage.ON_DISK_OUT_OF_DATE: return 0xFF000000;
case MapStorage.NOT_DOWNLOADED: return 0xFF999999;
case MapStorage.DOWNLOAD_FAILED: return 0xFFFF0000;
case MapStorage.DOWNLOADING: return 0xFF342BB6;
case MapStorage.IN_QUEUE: return 0xFF5B94DE;
default: return 0xFF000000;
}
}
/// Get item type for list view representation;
public int getType()
{
switch (mStatus)
{
case MapStorage.GROUP: return TYPE_GROUP;
case MapStorage.COUNTRY: return TYPE_COUNTRY_GROUP;
case MapStorage.NOT_DOWNLOADED: return TYPE_COUNTRY_NOT_DOWNLOADED;
case MapStorage.ON_DISK:
case MapStorage.ON_DISK_OUT_OF_DATE:
return TYPE_COUNTRY_READY;
default : return TYPE_COUNTRY_IN_PROCESS;
}
}
}
public DownloadAdapter(Activity context)
{
mStorage = MWMApplication.get().getMapStorage();
mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHasGoogleStore = Utils.hasAnyGoogleStoreInstalled();
fillList();
}
/// Fill list for current m_group and m_country.
private void fillList()
{
final int count = mStorage.countriesCount(mIdx);
if (count > 0)
{
mItems = new DownloadAdapter.CountryItem[count];
for (int i = 0; i < count; ++i)
mItems[i] = new CountryItem(mStorage, mIdx.getChild(i));
}
notifyDataSetChanged();
}
/// Process list item click.
public void onItemClick(int position, View view)
{
if (mItems[position].mStatus < 0)
{
// expand next level
mIdx = mIdx.getChild(position);
fillList();
}
else
{
if (getItemViewType(position) == TYPE_COUNTRY_READY)
showCountry(getItem(position).mCountryIdx);
else
onCountryMenuClicked(position, getItem(position), view);
}
}
private void showNotEnoughFreeSpaceDialog(String spaceNeeded, String countryName)
{
final Dialog dlg = new AlertDialog.Builder(mContext)
.setMessage(String.format(mContext.getString(R.string.free_space_for_country), spaceNeeded, countryName))
.setNegativeButton(mContext.getString(R.string.close), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
}
})
.create();
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
private boolean hasFreeSpace(long size)
{
return MWMApplication.get().hasFreeSpace(size);
}
private void processNotDownloaded(final Index idx, final String name)
{
final long size = mStorage.countryRemoteSizeInBytes(idx);
if (!hasFreeSpace(size + MB))
showNotEnoughFreeSpaceDialog(getSizeString(size), name);
else
{
mStorage.downloadCountry(idx);
Statistics.INSTANCE.trackCountryDownload(mContext);
}
}
private void processDownloading(final Index idx, final String name)
{
// Confirm canceling
final Dialog dlg = new AlertDialog.Builder(mContext)
.setTitle(name)
.setPositiveButton(R.string.cancel_download, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
mStorage.deleteCountry(idx);
dlg.dismiss();
}
})
.create();
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
private void processOutOfDate(final Index idx, final String name)
{
final long remoteSize = mStorage.countryRemoteSizeInBytes(idx);
if (!hasFreeSpace(remoteSize + MB))
showNotEnoughFreeSpaceDialog(getSizeString(remoteSize), name);
else
{
mStorage.downloadCountry(idx);
Statistics.INSTANCE.trackCountryUpdate(mContext);
}
}
private void processOnDisk(final Index idx, final String name)
{
// Confirm deleting
new AlertDialog.Builder(mContext)
.setTitle(name)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
mStorage.deleteCountry(idx);
Statistics.INSTANCE.trackCountryDeleted(mContext);
dlg.dismiss();
}
})
.create()
.show();
}
private void updateStatuses()
{
for (int i = 0; i < mItems.length; ++i)
{
final Index idx = mIdx.getChild(i);
if (idx.isValid())
mItems[i].updateStatus(mStorage, idx);
}
}
/// @name Process routine from parent Activity.
//@{
/// @return true If "back" was processed.
public boolean onBackPressed()
{
// we are on the root level already - return
if (mIdx.isRoot())
return false;
// go to the parent level
mIdx = mIdx.getParent();
fillList();
return true;
}
public void onResume(MapStorage.Listener listener)
{
if (mSlotID == 0)
mSlotID = mStorage.subscribe(listener);
// update actual statuses for items after resuming activity
updateStatuses();
notifyDataSetChanged();
}
public void onPause()
{
if (mSlotID != 0)
{
mStorage.unsubscribe(mSlotID);
mSlotID = 0;
}
}
//@}
@Override
public int getItemViewType(int position)
{
return mItems[position].getType();
}
@Override
public int getViewTypeCount()
{
return TYPES_COUNT;
}
@Override
public int getCount()
{
return (mItems != null ? mItems.length : 0);
}
@Override
public DownloadAdapter.CountryItem getItem(int position)
{
return mItems[position];
}
@Override
public long getItemId(int position)
{
return position;
}
private static class ViewHolder
{
public TextView mName = null;
public ImageView mFlag = null;
public ImageView mGuide = null;
public ProgressBar mProgress = null;
public View mCountryMenu = null;
void initFromView(View v)
{
mName = (TextView) v.findViewById(R.id.title);
mFlag = (ImageView) v.findViewById(R.id.country_flag);
mGuide = (ImageView) v.findViewById(R.id.guide_available);
mCountryMenu = v.findViewById(R.id.country_menu);
mProgress = (ProgressBar) v.findViewById(R.id.download_progress);
}
}
private String formatStringWithSize(int strID, Index index)
{
return mContext.getString(strID, getSizeString(mStorage.countryRemoteSizeInBytes(index)));
}
private void setFlag(int position, ImageView v)
{
final String strID = mItems[position].mFlag;
int id = -1;
try
{
// works faster than 'getIdentifier()'
id = R.drawable.class.getField(strID).getInt(null);
if (id > 0)
v.setImageResource(id);
else
Log.e(DownloadUI.TAG, "Failed to get resource id from: " + strID);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final int type = getItemViewType(position);
if (convertView == null)
{
holder = new ViewHolder();
switch (type)
{
case TYPE_GROUP:
convertView = mInflater.inflate(R.layout.download_item_group, null);
holder.initFromView(convertView);
break;
case TYPE_COUNTRY_GROUP:
convertView = mInflater.inflate(R.layout.download_item_country_group, null);
holder.initFromView(convertView);
break;
case TYPE_COUNTRY_IN_PROCESS:
case TYPE_COUNTRY_READY:
case TYPE_COUNTRY_NOT_DOWNLOADED:
convertView = mInflater.inflate(R.layout.download_item_country, null);
holder.initFromView(convertView);
break;
}
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
// for everything that has flag: regions + countries
if (type != TYPE_GROUP)
{
setFlag(position, holder.mFlag);
// this part if only for downloadable items
if (type != TYPE_COUNTRY_GROUP)
{
populateForGuide(position, holder);
setUpProgress(holder, type, position);
// set country menu click listener
final View fView = holder.mCountryMenu;
holder.mCountryMenu.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
onCountryMenuClicked(position, getItem(position), fView);
}
});
}
}
setItemText(position, holder);
convertView.setBackgroundResource(R.drawable.list_selector_holo_light);
final View fview = convertView;
convertView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
onItemClick(position, fview);
}
});
return convertView;
}
private void setUpProgress(DownloadAdapter.ViewHolder holder, int type, int position)
{
if (type == TYPE_COUNTRY_IN_PROCESS && getItem(position).mStatus != MapStorage.DOWNLOAD_FAILED)
{
holder.mProgress.setProgress(0);
UiUtils.show(holder.mProgress);
}
else
UiUtils.invisible(holder.mProgress);
}
private void setItemText(int position, DownloadAdapter.ViewHolder holder)
{
// set texts
holder.mName.setText(mItems[position].mName);
holder.mName.setTextColor(mItems[position].getTextColor());
}
private void populateForGuide(int position, DownloadAdapter.ViewHolder holder)
{
if (mHasGoogleStore)
{
final CountryItem item = getItem(position);
final GuideInfo gi = Framework.getGuideInfoForIndex(item.mCountryIdx);
if (gi != null)
UiUtils.show(holder.mGuide);
else
UiUtils.hide(holder.mGuide);
}
}
/// Get list item position by index(g, c, r).
/// @return -1 If no such item in display list.
private int getItemPosition(Index idx)
{
if (mIdx.isChild(idx))
{
final int position = idx.getPosition();
if (position >= 0 && position < mItems.length)
return position;
else
Log.e(DownloadUI.TAG, "Incorrect item position for: " + idx.toString());
}
return -1;
}
/// @return Current country status (@see MapStorage).
public int onCountryStatusChanged(Index idx)
{
final int position = getItemPosition(idx);
if (position != -1)
{
mItems[position].updateStatus(mStorage, idx);
// use this hard reset, because of caching different ViewHolders according to item's type
notifyDataSetChanged();
return mItems[position].mStatus;
}
return MapStorage.UNKNOWN;
}
public void onCountryProgress(ListView list, Index idx, long current, long total)
{
final int position = getItemPosition(idx);
if (position != -1)
{
// do update only one item's view; don't call notifyDataSetChanged
final View v = list.getChildAt(position - list.getFirstVisiblePosition());
if (v != null)
{
final DownloadAdapter.ViewHolder holder = (DownloadAdapter.ViewHolder) v.getTag();
holder.mProgress.setProgress((int) (current*100/total));
}
}
}
private void showCountry(final Index countryIndex)
{
mStorage.showCountry(countryIndex);
mContext.finish();
}
private void onCountryMenuClicked(int position, final CountryItem countryItem, View anchor)
{
final int MENU_DELETE = 0;
final int MENU_UPDATE = 1;
final int MENU_GUIDE = 3;
final int MENU_DOWNLOAD = 4;
final int MENU_CANCEL = 5;
final int status = countryItem.mStatus;
final Index countryIndex = countryItem.mCountryIdx;
final String name = countryItem.mName;
final OnMenuItemClickListener menuItemClickListener = new OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
final int id = item.getItemId();
if (MENU_DELETE == id)
processOnDisk(countryIndex, name);
else if (MENU_UPDATE == id)
processOutOfDate(countryIndex, name);
else if (MENU_GUIDE == id)
GuidesUtils.openOrDownloadGuide(Framework.getGuideInfoForIndex(countryIndex), mContext);
else if (MENU_DOWNLOAD == id)
processNotDownloaded(countryIndex, name);
else if (MENU_CANCEL == id)
processDownloading(countryIndex, name);
else
return false;
return true;
}
};
anchor.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
{
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
menu.setHeaderTitle(countryItem.mName);
if (status == MapStorage.ON_DISK || status == MapStorage.ON_DISK_OUT_OF_DATE)
menu.add(0, MENU_DELETE, MENU_DELETE, mContext.getString(R.string.delete))
.setOnMenuItemClickListener(menuItemClickListener);
if (status == MapStorage.ON_DISK_OUT_OF_DATE)
{
final String titleUpdate = formatStringWithSize(R.string.update_mb_or_kb, countryIndex);
menu.add(0, MENU_UPDATE, MENU_UPDATE, titleUpdate)
.setOnMenuItemClickListener(menuItemClickListener);
}
if (status == MapStorage.DOWNLOADING || status == MapStorage.IN_QUEUE)
menu.add(0, MENU_CANCEL, MENU_CANCEL, mContext.getString(R.string.cancel_download))
.setOnMenuItemClickListener(menuItemClickListener);
if (mHasGoogleStore)
{
final GuideInfo info = Framework.getGuideInfoForIndex(countryItem.mCountryIdx);
if (info != null)
menu.add(0, MENU_GUIDE, MENU_GUIDE, info.mTitle) // TODO: add translation
.setOnMenuItemClickListener(menuItemClickListener);
}
if (status == MapStorage.NOT_DOWNLOADED || status == MapStorage.DOWNLOAD_FAILED)
{
final String titleDownload = formatStringWithSize(R.string.download_mb_or_kb, countryIndex);
menu.add(0, MENU_DOWNLOAD, MENU_DOWNLOAD, titleDownload)
.setOnMenuItemClickListener(menuItemClickListener);
}
}
});
anchor.showContextMenu();
anchor.setOnCreateContextMenuListener(null);
}
private String getSizeString(long size)
{
if (size > MB)
return (size + 512 * 1024) / MB + " " + mContext.getString(R.string.mb);
else
return (size + 1023) / 1024 + " " + mContext.getString(R.string.kb);
}
private final static long MB = 1024 * 1024;
} | [AND] Async status load.
| android/src/com/mapswithme/country/DownloadAdapter.java | [AND] Async status load. | <ide><path>ndroid/src/com/mapswithme/country/DownloadAdapter.java
<ide> package com.mapswithme.country;
<ide>
<del>import java.lang.reflect.Field;
<add>import java.util.concurrent.Callable;
<add>import java.util.concurrent.ExecutorService;
<add>import java.util.concurrent.Executors;
<add>import java.util.concurrent.Future;
<ide>
<ide> import android.app.Activity;
<ide> import android.app.AlertDialog;
<ide> import android.app.Dialog;
<ide> import android.content.Context;
<ide> import android.content.DialogInterface;
<del>import android.content.res.Resources;
<ide> import android.util.Log;
<ide> import android.view.ContextMenu;
<ide> import android.view.ContextMenu.ContextMenuInfo;
<ide> private Index mIdx = new Index();
<ide>
<ide> private DownloadAdapter.CountryItem[] mItems = null;
<add> private final ExecutorService executor =
<add> Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
<ide>
<ide> private final boolean mHasGoogleStore;
<ide>
<ide>
<del> private static class CountryItem
<add> private class CountryItem
<ide> {
<ide> public final String mName;
<ide> public final Index mCountryIdx;
<ide> public final String mFlag;
<ide>
<ide> /// @see constants in MapStorage
<del> public int mStatus;
<add> private Future<Integer> mStatusFuture;
<ide>
<ide> public CountryItem(MapStorage storage, Index idx)
<ide> {
<ide> updateStatus(storage, idx);
<ide> }
<ide>
<del> public void updateStatus(MapStorage storage, Index idx)
<del> {
<del> if (idx.getCountry() == -1 || (idx.getRegion() == -1 && mFlag.length() == 0))
<del> mStatus = MapStorage.GROUP;
<del> else if (idx.getRegion() == -1 && storage.countriesCount(idx) > 0)
<del> mStatus = MapStorage.COUNTRY;
<del> else
<del> mStatus = storage.countryStatus(idx);
<add> public int getStatus()
<add> {
<add> try
<add> {
<add> return mStatusFuture.get();
<add> }
<add> catch (final Exception e)
<add> {
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> public void updateStatus(final MapStorage storage, final Index idx)
<add> {
<add> mStatusFuture = executor.submit(new Callable<Integer>()
<add> {
<add> @Override
<add> public Integer call() throws Exception
<add> {
<add> if (idx.getCountry() == -1 || (idx.getRegion() == -1 && mFlag.length() == 0))
<add> return MapStorage.GROUP;
<add> else if (idx.getRegion() == -1 && storage.countriesCount(idx) > 0)
<add> return MapStorage.COUNTRY;
<add> else
<add> return storage.countryStatus(idx);
<add> }});
<ide> }
<ide>
<ide> public int getTextColor()
<ide> {
<del> switch (mStatus)
<add> switch (getStatus())
<ide> {
<ide> case MapStorage.ON_DISK: return 0xFF333333;
<ide> case MapStorage.ON_DISK_OUT_OF_DATE: return 0xFF000000;
<ide> /// Get item type for list view representation;
<ide> public int getType()
<ide> {
<del> switch (mStatus)
<add> switch (getStatus())
<ide> {
<ide> case MapStorage.GROUP: return TYPE_GROUP;
<ide> case MapStorage.COUNTRY: return TYPE_COUNTRY_GROUP;
<ide> /// Process list item click.
<ide> public void onItemClick(int position, View view)
<ide> {
<del> if (mItems[position].mStatus < 0)
<add> if (mItems[position].getStatus() < 0)
<ide> {
<ide> // expand next level
<ide> mIdx = mIdx.getChild(position);
<ide>
<ide> private void setUpProgress(DownloadAdapter.ViewHolder holder, int type, int position)
<ide> {
<del> if (type == TYPE_COUNTRY_IN_PROCESS && getItem(position).mStatus != MapStorage.DOWNLOAD_FAILED)
<add> if (type == TYPE_COUNTRY_IN_PROCESS && getItem(position).getStatus() != MapStorage.DOWNLOAD_FAILED)
<ide> {
<ide> holder.mProgress.setProgress(0);
<ide> UiUtils.show(holder.mProgress);
<ide> // use this hard reset, because of caching different ViewHolders according to item's type
<ide> notifyDataSetChanged();
<ide>
<del> return mItems[position].mStatus;
<add> return mItems[position].getStatus();
<ide> }
<ide>
<ide> return MapStorage.UNKNOWN;
<ide> final int MENU_DOWNLOAD = 4;
<ide> final int MENU_CANCEL = 5;
<ide>
<del> final int status = countryItem.mStatus;
<add> final int status = countryItem.getStatus();
<ide> final Index countryIndex = countryItem.mCountryIdx;
<ide> final String name = countryItem.mName;
<ide> |
|
Java | mit | error: pathspec 'sandbox/src/test/java/ru/stqa/pft/homework/PointTest.java' did not match any file(s) known to git
| 38a934338a32ffa25f1d2536e14de07a2a994682 | 1 | lerchy/java_pft | package ru.stqa.pft.homework;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by vgagarin on 24.11.2016.
*/
public class PointTest {
@Test
public void testDistance(){
Point p1 = new Point(2.0, 1.0);
Point p2 = new Point(6.0, 4.0);
Assert.assertEquals(p1.distance(p2), 5.0);
}
}
| sandbox/src/test/java/ru/stqa/pft/homework/PointTest.java | test class PointTest added
| sandbox/src/test/java/ru/stqa/pft/homework/PointTest.java | test class PointTest added | <ide><path>andbox/src/test/java/ru/stqa/pft/homework/PointTest.java
<add>package ru.stqa.pft.homework;
<add>
<add>import org.testng.Assert;
<add>import org.testng.annotations.Test;
<add>
<add>/**
<add> * Created by vgagarin on 24.11.2016.
<add> */
<add>public class PointTest {
<add>
<add> @Test
<add> public void testDistance(){
<add> Point p1 = new Point(2.0, 1.0);
<add> Point p2 = new Point(6.0, 4.0);
<add> Assert.assertEquals(p1.distance(p2), 5.0);
<add> }
<add>} |
|
Java | apache-2.0 | 171775e92bb1a8e9a2de73f253bfa37738596c88 | 0 | linux-on-ibm-z/snappy-java,linux-on-ibm-z/snappy-java,asonipsl/snappy-java,linux-on-ibm-z/snappy-java,asonipsl/snappy-java,linux-on-ibm-z/snappy-java,asonipsl/snappy-java,asonipsl/snappy-java,asonipsl/snappy-java,linux-on-ibm-z/snappy-java,xerial/snappy-java,xerial/snappy-java,xerial/snappy-java,xerial/snappy-java | /*--------------------------------------------------------------------------
* Copyright 2011 Taro L. Saito
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// snappy-java Project
//
// SnappyLoader.java
// Since: 2011/03/29
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.snappy;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.UUID;
/**
* <b>Internal only - Do not use this class.</b> This class loads a native
* library of snappy-java (snappyjava.dll, libsnappy.so, etc.) according to the
* user platform (<i>os.name</i> and <i>os.arch</i>). The natively compiled
* libraries bundled to snappy-java contain the codes of the original snappy and
* JNI programs to access Snappy.
*
* In default, no configuration is required to use snappy-java, but you can load
* your own native library created by 'make native' command.
*
* This SnappyLoader searches for native libraries (snappyjava.dll,
* libsnappy.so, etc.) in the following order:
* <ol>
* <li>If system property <i>org.xerial.snappy.use.systemlib</i> is set to true,
* lookup folders specified by <i>java.lib.path</i> system property (This is the
* default path that JVM searches for native libraries)
* <li>(System property: <i>org.xerial.snappy.lib.path</i>)/(System property:
* <i>org.xerial.lib.name</i>)
* <li>One of the libraries embedded in snappy-java-(version).jar extracted into
* (System property: <i>java.io.tempdir</i>). If
* <i>org.xerial.snappy.tempdir</i> is set, use this folder instead of
* <i>java.io.tempdir</i>.
* </ol>
*
* <p>
* If you do not want to use folder <i>java.io.tempdir</i>, set the System
* property <i>org.xerial.snappy.tempdir</i>. For example, to use
* <i>/tmp/leo</i> as a temporary folder to copy native libraries, use -D option
* of JVM:
*
* <pre>
* <code>
* java -Dorg.xerial.snappy.tempdir="/tmp/leo" ...
* </code>
* </pre>
*
* </p>
*
* @author leo
*
*/
public class SnappyLoader
{
public static final String SNAPPY_SYSTEM_PROPERTIES_FILE = "org-xerial-snappy.properties";
public static final String KEY_SNAPPY_LIB_PATH = "org.xerial.snappy.lib.path";
public static final String KEY_SNAPPY_LIB_NAME = "org.xerial.snappy.lib.name";
public static final String KEY_SNAPPY_TEMPDIR = "org.xerial.snappy.tempdir";
public static final String KEY_SNAPPY_USE_SYSTEMLIB = "org.xerial.snappy.use.systemlib";
public static final String KEY_SNAPPY_DISABLE_BUNDLED_LIBS = "org.xerial.snappy.disable.bundled.libs"; // Depreciated, but preserved for backward compatibility
private static volatile boolean isLoaded = false;
private static volatile SnappyNative api = null;
private static File nativeLibFile = null;
static void cleanUpExtractedNativeLib() {
if(nativeLibFile != null && nativeLibFile.exists())
nativeLibFile.delete();
}
/**
* Set the api instance.
*
* @param nativeCode
*/
static synchronized void setApi(SnappyNative nativeCode)
{
api = nativeCode;
}
/**
* load system properties when configuration file of the name
* {@link #SNAPPY_SYSTEM_PROPERTIES_FILE} is found
*/
private static void loadSnappySystemProperties() {
try {
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(SNAPPY_SYSTEM_PROPERTIES_FILE);
if (is == null)
return; // no configuration file is found
// Load property file
Properties props = new Properties();
props.load(is);
is.close();
Enumeration< ? > names = props.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (name.startsWith("org.xerial.snappy.")) {
if (System.getProperty(name) == null) {
System.setProperty(name, props.getProperty(name));
}
}
}
}
catch (Throwable ex) {
System.err.println("Could not load '" + SNAPPY_SYSTEM_PROPERTIES_FILE + "' from classpath: "
+ ex.toString());
}
}
static {
loadSnappySystemProperties();
}
static synchronized SnappyNative load()
{
if (api != null)
return api;
try {
loadNativeLibrary();
setApi(new SnappyNative());
isLoaded = true;
}
catch (Exception e) {
e.printStackTrace();
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, e.getMessage());
}
return api;
}
/**
* Load a native library of snappy-java
*/
private static void loadNativeLibrary() {
nativeLibFile = findNativeLibrary();
if (nativeLibFile != null) {
// Load extracted or specified snappyjava native library.
System.load(nativeLibFile.getAbsolutePath());
}
else {
// Load preinstalled snappyjava (in the path -Djava.library.path)
System.loadLibrary("snappyjava");
}
}
private static boolean contentsEquals(InputStream in1, InputStream in2) throws IOException {
if(!(in1 instanceof BufferedInputStream)) {
in1 = new BufferedInputStream(in1);
}
if(!(in2 instanceof BufferedInputStream)) {
in2 = new BufferedInputStream(in2);
}
int ch = in1.read();
while(ch != -1) {
int ch2 = in2.read();
if(ch != ch2)
return false;
ch = in1.read();
}
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extract the specified library file to the target folder
*
* @param libFolderForCurrentOS
* @param libraryFileName
* @param targetFolder
* @return
*/
private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Attach UUID to the native library file to ensure multiple class loaders can read the libsnappy-java multiple times.
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("snappy-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
// Delete extracted lib file on exit.
extractedLibFile.deleteOnExit();
try {
// Extract a native library file into the target directory
InputStream reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
if(writer != null)
writer.close();
if(reader != null)
reader.close();
}
// Set executable (x) flag to enable Java to load the native library
if (!System.getProperty("os.name").contains("Windows")) {
try {
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
// Use following methods added since Java6 (If discarding Java5 is acceptable)
//extractedLibFile.setReadable(true);
//extractedLibFile.setWritable(true, true);
//extractedLibFile.setExecutable(true);
}
catch (Throwable e) {}
}
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn))
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, String.format("Failed to write a native library file at %s", extractedLibFile));
}
finally {
if(nativeIn != null)
nativeIn.close();
if(extractedLibIn != null)
extractedLibIn.close();
}
}
return new File(targetFolder, extractedLibFileName);
}
catch (IOException e) {
e.printStackTrace(System.err);
return null;
}
}
static File findNativeLibrary() {
boolean useSystemLib = Boolean.parseBoolean(System.getProperty(KEY_SNAPPY_USE_SYSTEMLIB, "false"));
boolean disabledBundledLibs = Boolean
.parseBoolean(System.getProperty(KEY_SNAPPY_DISABLE_BUNDLED_LIBS, "false"));
if (useSystemLib || disabledBundledLibs)
return null; // Use a pre-installed libsnappyjava
// Try to load the library in org.xerial.snappy.lib.path */
String snappyNativeLibraryPath = System.getProperty(KEY_SNAPPY_LIB_PATH);
String snappyNativeLibraryName = System.getProperty(KEY_SNAPPY_LIB_NAME);
// Resolve the library file name with a suffix (e.g., dll, .so, etc.)
if (snappyNativeLibraryName == null)
snappyNativeLibraryName = System.mapLibraryName("snappyjava");
if (snappyNativeLibraryPath != null) {
File nativeLib = new File(snappyNativeLibraryPath, snappyNativeLibraryName);
if (nativeLib.exists())
return nativeLib;
}
// Load an OS-dependent native library inside a jar file
snappyNativeLibraryPath = "/org/xerial/snappy/native/" + OSInfo.getNativeLibFolderPathForCurrentOS();
boolean hasNativeLib = hasResource(snappyNativeLibraryPath + "/" + snappyNativeLibraryName);
if(!hasNativeLib) {
if(OSInfo.getOSName().equals("Mac")) {
// Fix for openjdk7 for Mac
String altName = "libsnappyjava.jnilib";
if(hasResource(snappyNativeLibraryPath + "/" + altName)) {
snappyNativeLibraryName = altName;
hasNativeLib = true;
}
}
}
if(!hasNativeLib) {
String errorMessage = String.format("no native library is found for os.name=%s and os.arch=%s", OSInfo.getOSName(), OSInfo.getArchName());
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, errorMessage);
}
// Temporary folder for the native lib. Use the value of org.xerial.snappy.tempdir or java.io.tmpdir
String tempFolder = new File(System.getProperty(KEY_SNAPPY_TEMPDIR,
System.getProperty("java.io.tmpdir"))).getAbsolutePath();
// Extract and load a native library inside the jar file
return extractLibraryFile(snappyNativeLibraryPath, snappyNativeLibraryName, tempFolder);
}
private static boolean hasResource(String path) {
return SnappyLoader.class.getResource(path) != null;
}
/**
* Get the snappy-java version by reading pom.properties embedded in jar.
* This version data is used as a suffix of a dll file extracted from the
* jar.
*
* @return the version string
*/
public static String getVersion() {
URL versionFile = SnappyLoader.class
.getResource("/META-INF/maven/org.xerial.snappy/snappy-java/pom.properties");
if (versionFile == null)
versionFile = SnappyLoader.class.getResource("/org/xerial/snappy/VERSION");
String version = "unknown";
try {
if (versionFile != null) {
Properties versionData = new Properties();
versionData.load(versionFile.openStream());
version = versionData.getProperty("version", version);
if (version.equals("unknown"))
version = versionData.getProperty("VERSION", version);
version = version.trim().replaceAll("[^0-9M\\.]", "");
}
}
catch (IOException e) {
System.err.println(e);
}
return version;
}
}
| src/main/java/org/xerial/snappy/SnappyLoader.java | /*--------------------------------------------------------------------------
* Copyright 2011 Taro L. Saito
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// snappy-java Project
//
// SnappyLoader.java
// Since: 2011/03/29
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.snappy;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.UUID;
/**
* <b>Internal only - Do not use this class.</b> This class loads a native
* library of snappy-java (snappyjava.dll, libsnappy.so, etc.) according to the
* user platform (<i>os.name</i> and <i>os.arch</i>). The natively compiled
* libraries bundled to snappy-java contain the codes of the original snappy and
* JNI programs to access Snappy.
*
* In default, no configuration is required to use snappy-java, but you can load
* your own native library created by 'make native' command.
*
* This SnappyLoader searches for native libraries (snappyjava.dll,
* libsnappy.so, etc.) in the following order:
* <ol>
* <li>If system property <i>org.xerial.snappy.use.systemlib</i> is set to true,
* lookup folders specified by <i>java.lib.path</i> system property (This is the
* default path that JVM searches for native libraries)
* <li>(System property: <i>org.xerial.snappy.lib.path</i>)/(System property:
* <i>org.xerial.lib.name</i>)
* <li>One of the libraries embedded in snappy-java-(version).jar extracted into
* (System property: <i>java.io.tempdir</i>). If
* <i>org.xerial.snappy.tempdir</i> is set, use this folder instead of
* <i>java.io.tempdir</i>.
* </ol>
*
* <p>
* If you do not want to use folder <i>java.io.tempdir</i>, set the System
* property <i>org.xerial.snappy.tempdir</i>. For example, to use
* <i>/tmp/leo</i> as a temporary folder to copy native libraries, use -D option
* of JVM:
*
* <pre>
* <code>
* java -Dorg.xerial.snappy.tempdir="/tmp/leo" ...
* </code>
* </pre>
*
* </p>
*
* @author leo
*
*/
public class SnappyLoader
{
public static final String SNAPPY_SYSTEM_PROPERTIES_FILE = "org-xerial-snappy.properties";
public static final String KEY_SNAPPY_LIB_PATH = "org.xerial.snappy.lib.path";
public static final String KEY_SNAPPY_LIB_NAME = "org.xerial.snappy.lib.name";
public static final String KEY_SNAPPY_TEMPDIR = "org.xerial.snappy.tempdir";
public static final String KEY_SNAPPY_USE_SYSTEMLIB = "org.xerial.snappy.use.systemlib";
public static final String KEY_SNAPPY_DISABLE_BUNDLED_LIBS = "org.xerial.snappy.disable.bundled.libs"; // Depreciated, but preserved for backward compatibility
private static volatile boolean isLoaded = false;
private static volatile SnappyNative api = null;
private static File nativeLibFile = null;
static void cleanUpExtractedNativeLib() {
if(nativeLibFile != null && nativeLibFile.exists())
nativeLibFile.delete();
}
/**
* Set the api instance.
*
* @param nativeCode
*/
static synchronized void setApi(SnappyNative nativeCode)
{
api = nativeCode;
}
/**
* load system properties when configuration file of the name
* {@link #SNAPPY_SYSTEM_PROPERTIES_FILE} is found
*/
private static void loadSnappySystemProperties() {
try {
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(SNAPPY_SYSTEM_PROPERTIES_FILE);
if (is == null)
return; // no configuration file is found
// Load property file
Properties props = new Properties();
props.load(is);
is.close();
Enumeration< ? > names = props.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (name.startsWith("org.xerial.snappy.")) {
if (System.getProperty(name) == null) {
System.setProperty(name, props.getProperty(name));
}
}
}
}
catch (Throwable ex) {
System.err.println("Could not load '" + SNAPPY_SYSTEM_PROPERTIES_FILE + "' from classpath: "
+ ex.toString());
}
}
static {
loadSnappySystemProperties();
}
static synchronized SnappyNative load()
{
if (api != null)
return api;
try {
loadNativeLibrary();
setApi(new SnappyNative());
isLoaded = true;
}
catch (Exception e) {
e.printStackTrace();
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, e.getMessage());
}
return api;
}
/**
* Load a native library of snappy-java
*/
private static void loadNativeLibrary() {
nativeLibFile = findNativeLibrary();
if (nativeLibFile != null) {
// Load extracted or specified snappyjava native library.
System.load(nativeLibFile.getAbsolutePath());
}
else {
// Load preinstalled snappyjava (in the path -Djava.library.path)
System.loadLibrary("snappyjava");
}
}
private static boolean contentsEquals(InputStream in1, InputStream in2) throws IOException {
if(!(in1 instanceof BufferedInputStream)) {
in1 = new BufferedInputStream(in1);
}
if(!(in2 instanceof BufferedInputStream)) {
in2 = new BufferedInputStream(in2);
}
int ch = in1.read();
while(ch != -1) {
int ch2 = in2.read();
if(ch != ch2)
return false;
ch = in1.read();
}
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extract the specified library file to the target folder
*
* @param libFolderForCurrentOS
* @param libraryFileName
* @param targetFolder
* @return
*/
private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Attach UUID to the native library file to ensure multiple class loaders can read the libsnappy-java multiple times.
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("snappy-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
// Delete extracted lib file on exit.
extractedLibFile.deleteOnExit();
try {
// Extract a native library file into the target directory
InputStream reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
if(writer != null)
writer.close();
if(reader != null)
reader.close();
}
// Set executable (x) flag to enable Java to load the native library
if (!System.getProperty("os.name").contains("Windows")) {
try {
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e) {}
}
// Check the contents
{
InputStream nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn))
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, String.format("Failed to write a native library file at %s", extractedLibFile));
}
finally {
if(nativeIn != null)
nativeIn.close();
if(extractedLibIn != null)
extractedLibIn.close();
}
}
return new File(targetFolder, extractedLibFileName);
}
catch (IOException e) {
e.printStackTrace(System.err);
return null;
}
}
static File findNativeLibrary() {
boolean useSystemLib = Boolean.parseBoolean(System.getProperty(KEY_SNAPPY_USE_SYSTEMLIB, "false"));
boolean disabledBundledLibs = Boolean
.parseBoolean(System.getProperty(KEY_SNAPPY_DISABLE_BUNDLED_LIBS, "false"));
if (useSystemLib || disabledBundledLibs)
return null; // Use a pre-installed libsnappyjava
// Try to load the library in org.xerial.snappy.lib.path */
String snappyNativeLibraryPath = System.getProperty(KEY_SNAPPY_LIB_PATH);
String snappyNativeLibraryName = System.getProperty(KEY_SNAPPY_LIB_NAME);
// Resolve the library file name with a suffix (e.g., dll, .so, etc.)
if (snappyNativeLibraryName == null)
snappyNativeLibraryName = System.mapLibraryName("snappyjava");
if (snappyNativeLibraryPath != null) {
File nativeLib = new File(snappyNativeLibraryPath, snappyNativeLibraryName);
if (nativeLib.exists())
return nativeLib;
}
// Load an OS-dependent native library inside a jar file
snappyNativeLibraryPath = "/org/xerial/snappy/native/" + OSInfo.getNativeLibFolderPathForCurrentOS();
boolean hasNativeLib = hasResource(snappyNativeLibraryPath + "/" + snappyNativeLibraryName);
if(!hasNativeLib) {
if(OSInfo.getOSName().equals("Mac")) {
// Fix for openjdk7 for Mac
String altName = "libsnappyjava.jnilib";
if(hasResource(snappyNativeLibraryPath + "/" + altName)) {
snappyNativeLibraryName = altName;
hasNativeLib = true;
}
}
}
if(!hasNativeLib) {
String errorMessage = String.format("no native library is found for os.name=%s and os.arch=%s", OSInfo.getOSName(), OSInfo.getArchName());
throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, errorMessage);
}
// Temporary folder for the native lib. Use the value of org.xerial.snappy.tempdir or java.io.tmpdir
String tempFolder = new File(System.getProperty(KEY_SNAPPY_TEMPDIR,
System.getProperty("java.io.tmpdir"))).getAbsolutePath();
// Extract and load a native library inside the jar file
return extractLibraryFile(snappyNativeLibraryPath, snappyNativeLibraryName, tempFolder);
}
private static boolean hasResource(String path) {
return SnappyLoader.class.getResource(path) != null;
}
/**
* Get the snappy-java version by reading pom.properties embedded in jar.
* This version data is used as a suffix of a dll file extracted from the
* jar.
*
* @return the version string
*/
public static String getVersion() {
URL versionFile = SnappyLoader.class
.getResource("/META-INF/maven/org.xerial.snappy/snappy-java/pom.properties");
if (versionFile == null)
versionFile = SnappyLoader.class.getResource("/org/xerial/snappy/VERSION");
String version = "unknown";
try {
if (versionFile != null) {
Properties versionData = new Properties();
versionData.load(versionFile.openStream());
version = versionData.getProperty("version", version);
if (version.equals("unknown"))
version = versionData.getProperty("VERSION", version);
version = version.trim().replaceAll("[^0-9M\\.]", "");
}
}
catch (IOException e) {
System.err.println(e);
}
return version;
}
}
| Add a file permission setting code sample for Java6
| src/main/java/org/xerial/snappy/SnappyLoader.java | Add a file permission setting code sample for Java6 | <ide><path>rc/main/java/org/xerial/snappy/SnappyLoader.java
<ide> File extractedLibFile = new File(targetFolder, extractedLibFileName);
<ide> // Delete extracted lib file on exit.
<ide> extractedLibFile.deleteOnExit();
<add>
<ide> try {
<del>
<ide> // Extract a native library file into the target directory
<ide> InputStream reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
<ide> FileOutputStream writer = new FileOutputStream(extractedLibFile);
<ide> try {
<ide> Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
<ide> .waitFor();
<add>
<add> // Use following methods added since Java6 (If discarding Java5 is acceptable)
<add> //extractedLibFile.setReadable(true);
<add> //extractedLibFile.setWritable(true, true);
<add> //extractedLibFile.setExecutable(true);
<ide> }
<ide> catch (Throwable e) {}
<ide> }
<ide>
<del> // Check the contents
<add>
<add> // Check whether the contents are properly copied from the resource folder
<ide> {
<ide> InputStream nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath);
<ide> InputStream extractedLibIn = new FileInputStream(extractedLibFile); |
|
Java | mit | f44ee2638c2ab22a9c8324be3415f065f4890179 | 0 | jonestimd/swing-extensions | // The MIT License (MIT)
//
// Copyright (c) 2017 Timothy D. Jones
//
// 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.
package io.github.jonestimd.swing.component;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.Format;
import java.text.ParseException;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import io.github.jonestimd.swing.validation.ValidatedTextField;
import io.github.jonestimd.swing.validation.Validator;
/**
* Provides the text field ({@link ValidatedTextField}) for an editable {@link BeanListComboBox}.
* Uses {@link Format#parseObject(String)} to create an item from the input text.
* @param <T> {@link BeanListComboBox} list item class
*/
public class BeanListComboBoxEditor<T> extends BasicComboBoxEditor {
private ComboBoxModel<T> model;
private Format format;
private PrefixSelector<T> prefixSelector;
private boolean autoSelecting = false;
private DocumentListener documentHandler = new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
documentChange();
}
public void insertUpdate(DocumentEvent e) {
documentChange();
}
public void removeUpdate(DocumentEvent e) {
}
};
/**
* Create a combo box editor with the default {@link PrefixSelector} (first match alphabetically).
*/
public BeanListComboBoxEditor(JComboBox<T> comboBox, Format format, Validator<String> validator) {
this(comboBox, format, validator, new FormatPrefixSelector<>(format));
}
public BeanListComboBoxEditor(JComboBox<T> comboBox, Format format, Validator<String> validator, PrefixSelector<T> prefixSelector) {
this.model = comboBox.getModel();
this.format = format;
this.prefixSelector = prefixSelector;
editor = new BorderlessTextField("", 9, validator);
editor.getDocument().addDocumentListener(documentHandler);
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (e.getOppositeComponent() != comboBox && getItem() != null) {
editor.setText(itemToString(getItem()));
}
}
});
}
public boolean isAutoSelecting() {
return autoSelecting;
}
@Override
public ValidatedTextField getEditorComponent() {
return (ValidatedTextField) super.getEditorComponent();
}
@Override
public void setItem(Object anObject) {
super.setItem(anObject == null ? null : format.format(anObject));
}
@Override
public T getItem() {
return getItem((String) super.getItem());
}
public boolean isNew(Object item) {
return item != null && indexOf(format.format(item)) < 0;
}
@SuppressWarnings("unchecked")
protected T getItem(String displayText) {
if (displayText != null && displayText.length() > 0) {
int index = indexOf(displayText);
return (index >= 0 ? model.getElementAt(index) : parseInput(displayText));
}
return null;
}
@SuppressWarnings("unchecked")
protected T parseInput(String displayText) {
try {
return (T) format.parseObject(displayText);
} catch (ParseException ex) {
return null;
}
}
private int indexOf(String displayText) {
for (int i = 0; i < model.getSize(); i++) {
if (displayText.equalsIgnoreCase(format.format(model.getElementAt(i)))) {
return i;
}
}
return -1;
}
protected String itemToString(Object item) {
return item == null ? null : format.format(item);
}
@SuppressWarnings("unchecked")
protected String getFirstMatch(String displayText) {
Object item = prefixSelector.selectMatch(model, displayText);
if (item != null) {
autoSelecting = true;
model.setSelectedItem(item);
autoSelecting = false;
return format.format(item);
}
return null;
}
private void documentChange() {
String text = editor.getText();
((ValidatedTextField) editor).validateValue();
String selected = itemToString(model.getSelectedItem());
if (text.length() > 0 && (selected == null || !selected.equalsIgnoreCase(text))) {
SwingUtilities.invokeLater(this::autoComplete);
}
}
private void autoComplete() {
if (editor.getSelectedText() == null) {
autoCompleteFirstMatch(editor.getText());
}
}
private void autoCompleteFirstMatch(String text) {
if (text.length() > 0) {
String match = getFirstMatch(text);
if (match != null) {
editor.getDocument().removeDocumentListener(documentHandler);
editor.setText(text + match.substring(text.length()));
editor.setCaretPosition(text.length());
editor.setSelectionStart(text.length());
editor.setSelectionEnd(match.length());
editor.getDocument().addDocumentListener(documentHandler);
}
}
}
private class BorderlessTextField extends ValidatedTextField {
public BorderlessTextField(String value, int columns, Validator<String> validator) {
super(validator);
setText(value == null ? "" : value);
setColumns(columns);
}
// workaround for 4530952
@Override
public void setText(String s) {
if (!getText().equals(s)) {
super.setText(s);
}
}
@Override
public void setBorder(Border b) {
if (!(b instanceof javax.swing.plaf.UIResource)) {
super.setBorder(b);
}
}
@Override
public void validateValue() {
super.validateValue();
if (getToolTipText() == null) {
if (getValidationMessages() == null) {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
else {
ToolTipManager.sharedInstance().registerComponent(this);
}
}
}
}
} | src/main/java/io/github/jonestimd/swing/component/BeanListComboBoxEditor.java | // Copyright (c) 2016 Timothy D. Jones
//
// 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.
package io.github.jonestimd.swing.component;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.Format;
import java.text.ParseException;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import io.github.jonestimd.swing.validation.ValidatedTextField;
import io.github.jonestimd.swing.validation.Validator;
/**
* Provides the text field ({@link ValidatedTextField}) for an editable {@link BeanListComboBox}.
* Uses {@link Format#parseObject(String)} to create an item from the input text.
* @param <T> {@link BeanListComboBox} list item class
*/
public class BeanListComboBoxEditor<T> extends BasicComboBoxEditor {
private ComboBoxModel<T> model;
private Format format;
private PrefixSelector<T> prefixSelector;
private boolean autoSelecting = false;
private DocumentListener documentHandler = new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
documentChange();
}
public void insertUpdate(DocumentEvent e) {
documentChange();
}
public void removeUpdate(DocumentEvent e) {
}
};
/**
* Create a combo box editor with the default {@link PrefixSelector} (first match alphabetically).
*/
public BeanListComboBoxEditor(JComboBox<T> comboBox, Format format, Validator<String> validator) {
this(comboBox, format, validator, new FormatPrefixSelector<>(format));
}
public BeanListComboBoxEditor(JComboBox<T> comboBox, Format format, Validator<String> validator, PrefixSelector<T> prefixSelector) {
this.model = comboBox.getModel();
this.format = format;
this.prefixSelector = prefixSelector;
editor = new BorderlessTextField("", 9, validator);
editor.getDocument().addDocumentListener(documentHandler);
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (e.getOppositeComponent() != comboBox && getItem() != null) {
editor.setText(itemToString(getItem()));
}
}
});
}
public boolean isAutoSelecting() {
return autoSelecting;
}
@Override
public ValidatedTextField getEditorComponent() {
return (ValidatedTextField) super.getEditorComponent();
}
@Override
public void setItem(Object anObject) {
super.setItem(anObject == null ? null : format.format(anObject));
}
@Override
public T getItem() {
return getItem((String) super.getItem());
}
public boolean isNew(Object item) {
return item != null && indexOf(format.format(item)) < 0;
}
@SuppressWarnings("unchecked")
protected T getItem(String displayText) {
if (displayText != null && displayText.length() > 0) {
int index = indexOf(displayText);
return (index >= 0 ? model.getElementAt(index) : parseInput(displayText));
}
return null;
}
@SuppressWarnings("unchecked")
protected T parseInput(String displayText) {
try {
return (T) format.parseObject(displayText);
} catch (ParseException ex) {
return null;
}
}
private int indexOf(String displayText) {
for (int i = 0; i < model.getSize(); i++) {
if (displayText.equalsIgnoreCase(format.format(model.getElementAt(i)))) {
return i;
}
}
return -1;
}
protected String itemToString(Object item) {
return item == null ? null : format.format(item);
}
@SuppressWarnings("unchecked")
protected String getFirstMatch(String displayText) {
Object item = prefixSelector.selectMatch(model, displayText);
if (item != null) {
autoSelecting = true;
model.setSelectedItem(item);
autoSelecting = false;
return format.format(item);
}
return null;
}
private void documentChange() {
String text = editor.getText();
((ValidatedTextField) editor).validateValue();
String selected = itemToString(model.getSelectedItem());
if (text.length() > 0 && (selected == null || !selected.equalsIgnoreCase(text))) {
SwingUtilities.invokeLater(this::autoComplete);
}
}
private void autoComplete() {
if (editor.getSelectedText() == null) {
autoCompleteFirstMatch(editor.getText());
}
}
private void autoCompleteFirstMatch(String text) {
if (text.length() > 0) {
String match = getFirstMatch(text);
if (match != null) {
editor.getDocument().removeDocumentListener(documentHandler);
editor.setText(text + match.substring(text.length()));
editor.setCaretPosition(text.length());
editor.setSelectionStart(text.length());
editor.setSelectionEnd(match.length());
editor.getDocument().addDocumentListener(documentHandler);
}
}
}
private class BorderlessTextField extends ValidatedTextField {
public BorderlessTextField(String value, int columns, Validator<String> validator) {
super(validator);
setText(value == null ? "" : value);
setColumns(columns);
}
// workaround for 4530952
@Override
public void setText(String s) {
if (!getText().equals(s)) {
super.setText(s);
}
}
@Override
public void setBorder(Border b) {
if (!(b instanceof UIResource)) {
super.setBorder(b);
}
}
@Override
public void validateValue() {
super.validateValue();
if (getToolTipText() == null) {
if (getValidationMessages() == null) {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
else {
ToolTipManager.sharedInstance().registerComponent(this);
}
}
}
}
} | Fix border on editable combo box in a table
| src/main/java/io/github/jonestimd/swing/component/BeanListComboBoxEditor.java | Fix border on editable combo box in a table | <ide><path>rc/main/java/io/github/jonestimd/swing/component/BeanListComboBoxEditor.java
<del>// Copyright (c) 2016 Timothy D. Jones
<add>// The MIT License (MIT)
<add>//
<add>// Copyright (c) 2017 Timothy D. Jones
<ide> //
<ide> // Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> // of this software and associated documentation files (the "Software"), to deal
<ide>
<ide> @Override
<ide> public void setBorder(Border b) {
<del> if (!(b instanceof UIResource)) {
<add> if (!(b instanceof javax.swing.plaf.UIResource)) {
<ide> super.setBorder(b);
<ide> }
<ide> } |
|
Java | apache-2.0 | e2f47871d17351dae7555a48e0cd4d3dbe2ab2e2 | 0 | mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver | // 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 com.cloud.api.query;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.affinity.AffinityGroupDomainMapVO;
import org.apache.cloudstack.affinity.AffinityGroupResponse;
import org.apache.cloudstack.affinity.AffinityGroupVMMapVO;
import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd;
import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd;
import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
import org.apache.cloudstack.api.command.user.iso.ListIsosCmd;
import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd;
import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd;
import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd;
import org.apache.cloudstack.api.command.user.project.ListProjectsCmd;
import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd;
import org.apache.cloudstack.api.command.user.tag.ListTagsCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd;
import org.apache.cloudstack.api.command.user.vm.ListVMsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
import org.apache.cloudstack.api.response.AccountResponse;
import org.apache.cloudstack.api.response.AsyncJobResponse;
import org.apache.cloudstack.api.response.DiskOfferingResponse;
import org.apache.cloudstack.api.response.DomainRouterResponse;
import org.apache.cloudstack.api.response.EventResponse;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import org.apache.cloudstack.api.response.InstanceGroupResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.ProjectAccountResponse;
import org.apache.cloudstack.api.response.ProjectInvitationResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.api.response.ResourceDetailResponse;
import org.apache.cloudstack.api.response.ResourceTagResponse;
import org.apache.cloudstack.api.response.SecurityGroupResponse;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.api.response.TemplateResponse;
import org.apache.cloudstack.api.response.UserResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.VolumeResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
import org.apache.cloudstack.query.QueryService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.query.dao.AccountJoinDao;
import com.cloud.api.query.dao.AffinityGroupJoinDao;
import com.cloud.api.query.dao.AsyncJobJoinDao;
import com.cloud.api.query.dao.DataCenterJoinDao;
import com.cloud.api.query.dao.DiskOfferingJoinDao;
import com.cloud.api.query.dao.DomainRouterJoinDao;
import com.cloud.api.query.dao.HostJoinDao;
import com.cloud.api.query.dao.ImageStoreJoinDao;
import com.cloud.api.query.dao.InstanceGroupJoinDao;
import com.cloud.api.query.dao.ProjectAccountJoinDao;
import com.cloud.api.query.dao.ProjectInvitationJoinDao;
import com.cloud.api.query.dao.ProjectJoinDao;
import com.cloud.api.query.dao.ResourceTagJoinDao;
import com.cloud.api.query.dao.SecurityGroupJoinDao;
import com.cloud.api.query.dao.ServiceOfferingJoinDao;
import com.cloud.api.query.dao.StoragePoolJoinDao;
import com.cloud.api.query.dao.TemplateJoinDao;
import com.cloud.api.query.dao.UserAccountJoinDao;
import com.cloud.api.query.dao.UserVmJoinDao;
import com.cloud.api.query.dao.VolumeJoinDao;
import com.cloud.api.query.vo.AccountJoinVO;
import com.cloud.api.query.vo.AffinityGroupJoinVO;
import com.cloud.api.query.vo.AsyncJobJoinVO;
import com.cloud.api.query.vo.DataCenterJoinVO;
import com.cloud.api.query.vo.DiskOfferingJoinVO;
import com.cloud.api.query.vo.DomainRouterJoinVO;
import com.cloud.api.query.vo.EventJoinVO;
import com.cloud.api.query.vo.HostJoinVO;
import com.cloud.api.query.vo.ImageStoreJoinVO;
import com.cloud.api.query.vo.InstanceGroupJoinVO;
import com.cloud.api.query.vo.ProjectAccountJoinVO;
import com.cloud.api.query.vo.ProjectInvitationJoinVO;
import com.cloud.api.query.vo.ProjectJoinVO;
import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.SecurityGroupJoinVO;
import com.cloud.api.query.vo.ServiceOfferingJoinVO;
import com.cloud.api.query.vo.StoragePoolJoinVO;
import com.cloud.api.query.vo.TemplateJoinVO;
import com.cloud.api.query.vo.UserAccountJoinVO;
import com.cloud.api.query.vo.UserVmJoinVO;
import com.cloud.api.query.vo.VolumeJoinVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DedicatedResourceVO;
import com.cloud.dc.dao.DedicatedResourceDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.dao.EventJoinDao;
import com.cloud.exception.CloudAuthenticationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.dao.NetworkDomainVO;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.security.SecurityGroupVMMapVO;
import com.cloud.network.security.dao.SecurityGroupVMMapDao;
import com.cloud.org.Grouping;
import com.cloud.projects.Project;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.projects.ProjectInvitation;
import com.cloud.projects.ProjectManager;
import com.cloud.projects.dao.ProjectAccountDao;
import com.cloud.projects.dao.ProjectDao;
import com.cloud.resource.ResourceManager;
import com.cloud.server.Criteria;
import com.cloud.server.ResourceMetaDataService;
import com.cloud.server.ResourceTag;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.server.TaggedResourceService;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeDetailVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDetailsDao;
import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.DomainManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicDetailVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDetailDao;
import com.cloud.vm.dao.UserVmDao;
@Component
@Local(value = { QueryService.class })
public class QueryManagerImpl extends ManagerBase implements QueryService {
public static final Logger s_logger = Logger.getLogger(QueryManagerImpl.class);
// public static ViewResponseHelper _responseGenerator;
@Inject
private AccountManager _accountMgr;
@Inject
private ProjectManager _projectMgr;
@Inject
private DomainDao _domainDao;
@Inject
private UserAccountJoinDao _userAccountJoinDao;
@Inject
private EventJoinDao _eventJoinDao;
@Inject
private ResourceTagJoinDao _resourceTagJoinDao;
@Inject
private InstanceGroupJoinDao _vmGroupJoinDao;
@Inject
private UserVmJoinDao _userVmJoinDao;
@Inject
private UserVmDao _userVmDao;
@Inject
private SecurityGroupJoinDao _securityGroupJoinDao;
@Inject
private SecurityGroupVMMapDao _securityGroupVMMapDao;
@Inject
private DomainRouterJoinDao _routerJoinDao;
@Inject
private ProjectInvitationJoinDao _projectInvitationJoinDao;
@Inject
private ProjectJoinDao _projectJoinDao;
@Inject
private ProjectDao _projectDao;
@Inject
private ProjectAccountDao _projectAccountDao;
@Inject
private ProjectAccountJoinDao _projectAccountJoinDao;
@Inject
private HostJoinDao _hostJoinDao;
@Inject
private VolumeJoinDao _volumeJoinDao;
@Inject
private AccountDao _accountDao;
@Inject
private ConfigurationDao _configDao;
@Inject
private AccountJoinDao _accountJoinDao;
@Inject
private AsyncJobJoinDao _jobJoinDao;
@Inject
private StoragePoolJoinDao _poolJoinDao;
@Inject
private ImageStoreJoinDao _imageStoreJoinDao;
@Inject
private DiskOfferingJoinDao _diskOfferingJoinDao;
@Inject
private ServiceOfferingJoinDao _srvOfferingJoinDao;
@Inject
private ServiceOfferingDao _srvOfferingDao;
@Inject
private DataCenterJoinDao _dcJoinDao;
@Inject
private DomainRouterDao _routerDao;
@Inject
private VolumeDetailsDao _volumeDetailDao;
@Inject
private NicDetailDao _nicDetailDao;
@Inject
private HighAvailabilityManager _haMgr;
@Inject
private VMTemplateDao _templateDao;
@Inject
private TemplateJoinDao _templateJoinDao;
@Inject
ResourceManager _resourceMgr;
@Inject
private ResourceMetaDataService _resourceMetaDataMgr;
@Inject
private TaggedResourceService _taggedResourceMgr;
@Inject
AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
private AffinityGroupJoinDao _affinityGroupJoinDao;
@Inject
private DedicatedResourceDao _dedicatedDao;
@Inject
DomainManager _domainMgr;
@Inject
AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
/*
* (non-Javadoc)
*
* @see
* com.cloud.api.query.QueryService#searchForUsers(org.apache.cloudstack
* .api.command.admin.user.ListUsersCmd)
*/
@Override
public ListResponse<UserResponse> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException {
Pair<List<UserAccountJoinVO>, Integer> result = searchForUsersInternal(cmd);
ListResponse<UserResponse> response = new ListResponse<UserResponse>();
List<UserResponse> userResponses = ViewResponseHelper.createUserResponse(result.first().toArray(
new UserAccountJoinVO[result.first().size()]));
response.setResponses(userResponses, result.second());
return response;
}
private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd)
throws PermissionDeniedException {
Account caller = UserContext.current().getCaller();
// TODO: Integrate with ACL checkAccess refactoring
Long domainId = cmd.getDomainId();
if (domainId != null) {
Domain domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by id=" + domainId);
}
_accountMgr.checkAccess(caller, domain);
} else {
// default domainId to the caller's domain
domainId = caller.getDomainId();
}
Filter searchFilter = new Filter(UserAccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
Long id = cmd.getId();
Object username = cmd.getUsername();
Object type = cmd.getAccountType();
Object accountName = cmd.getAccountName();
Object state = cmd.getState();
Object keyword = cmd.getKeyword();
SearchBuilder<UserAccountJoinVO> sb = _userAccountJoinDao.createSearchBuilder();
sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE);
if (id != null && id == 1) {
// system user should NOT be searchable
List<UserAccountJoinVO> emptyList = new ArrayList<UserAccountJoinVO>();
return new Pair<List<UserAccountJoinVO>, Integer>(emptyList, 0);
} else if (id != null) {
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
} else {
// this condition is used to exclude system user from the search
// results
sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ);
}
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
if ((accountName == null) && (domainId != null)) {
sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
SearchCriteria<UserAccountJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<UserAccountJoinVO> ssc = _userAccountJoinDao.createSearchCriteria();
ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("username", SearchCriteria.Op.SC, ssc);
}
if (username != null) {
sc.setParameters("username", username);
}
if (id != null) {
sc.setParameters("id", id);
} else {
// Don't return system user, search builder with NEQ
sc.setParameters("id", 1);
}
if (type != null) {
sc.setParameters("type", type);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
if (domainId != null) {
sc.setParameters("domainId", domainId);
}
} else if (domainId != null) {
DomainVO domainVO = _domainDao.findById(domainId);
sc.setParameters("domainPath", domainVO.getPath() + "%");
}
if (state != null) {
sc.setParameters("state", state);
}
return _userAccountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<EventResponse> searchForEvents(ListEventsCmd cmd) {
Pair<List<EventJoinVO>, Integer> result = searchForEventsInternal(cmd);
ListResponse<EventResponse> response = new ListResponse<EventResponse>();
List<EventResponse> eventResponses = ViewResponseHelper.createEventResponse(result.first().toArray(
new EventJoinVO[result.first().size()]));
response.setResponses(eventResponses, result.second());
return response;
}
private Pair<List<EventJoinVO>, Integer> searchForEventsInternal(ListEventsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Long id = cmd.getId();
String type = cmd.getType();
String level = cmd.getLevel();
Date startDate = cmd.getStartDate();
Date endDate = cmd.getEndDate();
String keyword = cmd.getKeyword();
Integer entryTime = cmd.getEntryTime();
Integer duration = cmd.getDuration();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<EventJoinVO> sb = _eventJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE);
sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ);
sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ);
sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
sb.and("archived", sb.entity().getArchived(), SearchCriteria.Op.EQ);
SearchCriteria<EventJoinVO> sc = sb.create();
// building ACL condition
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (keyword != null) {
SearchCriteria<EventJoinVO> ssc = _eventJoinDao.createSearchCriteria();
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("level", SearchCriteria.Op.SC, ssc);
}
if (level != null) {
sc.setParameters("levelEQ", level);
}
if (type != null) {
sc.setParameters("type", type);
}
if (startDate != null && endDate != null) {
sc.setParameters("createDateB", startDate, endDate);
} else if (startDate != null) {
sc.setParameters("createDateG", startDate);
} else if (endDate != null) {
sc.setParameters("createDateL", endDate);
}
sc.setParameters("archived", false);
Pair<List<EventJoinVO>, Integer> eventPair = null;
// event_view will not have duplicate rows for each event, so
// searchAndCount should be good enough.
if ((entryTime != null) && (duration != null)) {
// TODO: waiting for response from dev list, logic is mystery to
// me!!
/*
* if (entryTime <= duration) { throw new
* InvalidParameterValueException
* ("Entry time must be greater than duration"); } Calendar calMin =
* Calendar.getInstance(); Calendar calMax = Calendar.getInstance();
* calMin.add(Calendar.SECOND, -entryTime);
* calMax.add(Calendar.SECOND, -duration); Date minTime =
* calMin.getTime(); Date maxTime = calMax.getTime();
*
* sc.setParameters("state", com.cloud.event.Event.State.Completed);
* sc.setParameters("startId", 0); sc.setParameters("createDate",
* minTime, maxTime); List<EventJoinVO> startedEvents =
* _eventJoinDao.searchAllEvents(sc, searchFilter);
* List<EventJoinVO> pendingEvents = new ArrayList<EventJoinVO>();
* for (EventVO event : startedEvents) { EventVO completedEvent =
* _eventDao.findCompletedEvent(event.getId()); if (completedEvent
* == null) { pendingEvents.add(event); } } return pendingEvents;
*/
} else {
eventPair = _eventJoinDao.searchAndCount(sc, searchFilter);
}
return eventPair;
}
@Override
public ListResponse<ResourceTagResponse> listTags(ListTagsCmd cmd) {
Pair<List<ResourceTagJoinVO>, Integer> tags = listTagsInternal(cmd);
ListResponse<ResourceTagResponse> response = new ListResponse<ResourceTagResponse>();
List<ResourceTagResponse> tagResponses = ViewResponseHelper.createResourceTagResponse(false, tags.first()
.toArray(new ResourceTagJoinVO[tags.first().size()]));
response.setResponses(tagResponses, tags.second());
return response;
}
private Pair<List<ResourceTagJoinVO>, Integer> listTagsInternal(ListTagsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
String key = cmd.getKey();
String value = cmd.getValue();
String resourceId = cmd.getResourceId();
String resourceType = cmd.getResourceType();
String customerName = cmd.getCustomer();
boolean listAll = cmd.listAll();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, listAll, false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(ResourceTagJoinVO.class, "resourceType", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<ResourceTagJoinVO> sb = _resourceTagJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ);
sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ);
if (resourceId != null) {
sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ);
sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ);
sb.cp();
}
sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ);
// now set the SC criteria...
SearchCriteria<ResourceTagJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (key != null) {
sc.setParameters("key", key);
}
if (value != null) {
sc.setParameters("value", value);
}
if (resourceId != null) {
sc.setParameters("resourceId", resourceId);
sc.setParameters("resourceUuid", resourceId);
}
if (resourceType != null) {
sc.setParameters("resourceType", resourceType);
}
if (customerName != null) {
sc.setParameters("customer", customerName);
}
Pair<List<ResourceTagJoinVO>, Integer> result = _resourceTagJoinDao.searchAndCount(sc, searchFilter);
return result;
}
@Override
public ListResponse<InstanceGroupResponse> searchForVmGroups(ListVMGroupsCmd cmd) {
Pair<List<InstanceGroupJoinVO>, Integer> groups = searchForVmGroupsInternal(cmd);
ListResponse<InstanceGroupResponse> response = new ListResponse<InstanceGroupResponse>();
List<InstanceGroupResponse> grpResponses = ViewResponseHelper.createInstanceGroupResponse(groups.first()
.toArray(new InstanceGroupJoinVO[groups.first().size()]));
response.setResponses(grpResponses, groups.second());
return response;
}
private Pair<List<InstanceGroupJoinVO>, Integer> searchForVmGroupsInternal(ListVMGroupsCmd cmd) {
Long id = cmd.getId();
String name = cmd.getGroupName();
String keyword = cmd.getKeyword();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(InstanceGroupJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<InstanceGroupJoinVO> sb = _vmGroupJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
SearchCriteria<InstanceGroupJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<InstanceGroupJoinVO> ssc = _vmGroupJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
return _vmGroupJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<UserVmResponse> searchForUserVMs(ListVMsCmd cmd) {
Pair<List<UserVmJoinVO>, Integer> result = searchForUserVMsInternal(cmd);
ListResponse<UserVmResponse> response = new ListResponse<UserVmResponse>();
List<UserVmResponse> vmResponses = ViewResponseHelper.createUserVmResponse("virtualmachine", cmd.getDetails(),
result.first().toArray(new UserVmJoinVO[result.first().size()]));
response.setResponses(vmResponses, result.second());
return response;
}
private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsInternal(ListVMsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
String hypervisor = cmd.getHypervisor();
boolean listAll = cmd.listAll();
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, listAll, false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal());
// Criteria c = new Criteria(null, Boolean.FALSE, cmd.getStartIndex(),
// cmd.getPageSizeVal()); //version without default sorting
c.addCriteria(Criteria.KEYWORD, cmd.getKeyword());
c.addCriteria(Criteria.ID, cmd.getId());
c.addCriteria(Criteria.NAME, cmd.getName());
c.addCriteria(Criteria.STATE, cmd.getState());
c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId());
c.addCriteria(Criteria.GROUPID, cmd.getGroupId());
c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork());
c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId());
c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId());
c.addCriteria(Criteria.ISO_ID, cmd.getIsoId());
c.addCriteria(Criteria.VPC_ID, cmd.getVpcId());
c.addCriteria(Criteria.AFFINITY_GROUP_ID, cmd.getAffinityGroupId());
if (domainId != null) {
c.addCriteria(Criteria.DOMAINID, domainId);
}
if (HypervisorType.getType(hypervisor) != HypervisorType.None) {
c.addCriteria(Criteria.HYPERVISOR, hypervisor);
} else if (hypervisor != null) {
throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor);
}
// ignore these search requests if it's not an admin
if (_accountMgr.isAdmin(caller.getType())) {
c.addCriteria(Criteria.PODID, cmd.getPodId());
c.addCriteria(Criteria.HOSTID, cmd.getHostId());
c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId());
}
if (!permittedAccounts.isEmpty()) {
c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray());
}
c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType()));
return searchForUserVMsByCriteria(c, caller, domainId, isRecursive, permittedAccounts, listAll,
listProjectResourcesCriteria, tags);
}
private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsByCriteria(Criteria c, Account caller, Long domainId,
boolean isRecursive, List<Long> permittedAccounts, boolean listAll,
ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(),
c.getLimit());
// first search distinct vm id by using query criteria and pagination
SearchBuilder<UserVmJoinVO> sb = _userVmJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
Object id = c.getCriteria(Criteria.ID);
Object name = c.getCriteria(Criteria.NAME);
Object state = c.getCriteria(Criteria.STATE);
Object notState = c.getCriteria(Criteria.NOTSTATE);
Object zoneId = c.getCriteria(Criteria.DATACENTERID);
Object pod = c.getCriteria(Criteria.PODID);
Object hostId = c.getCriteria(Criteria.HOSTID);
Object hostName = c.getCriteria(Criteria.HOSTNAME);
Object keyword = c.getCriteria(Criteria.KEYWORD);
Object isAdmin = c.getCriteria(Criteria.ISADMIN);
assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table.";
Object groupId = c.getCriteria(Criteria.GROUPID);
Object networkId = c.getCriteria(Criteria.NETWORKID);
Object hypervisor = c.getCriteria(Criteria.HYPERVISOR);
Object storageId = c.getCriteria(Criteria.STORAGE_ID);
Object templateId = c.getCriteria(Criteria.TEMPLATE_ID);
Object isoId = c.getCriteria(Criteria.ISO_ID);
Object vpcId = c.getCriteria(Criteria.VPC_ID);
Object affinityGroupId = c.getCriteria(Criteria.AFFINITY_GROUP_ID);
sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ);
sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ);
sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
if (groupId != null && (Long) groupId != -1) {
sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
}
if (networkId != null) {
sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
}
if (vpcId != null && networkId == null) {
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
}
if (storageId != null) {
sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ);
}
if (affinityGroupId != null) {
sb.and("affinityGroupId", sb.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
}
// populate the search criteria with the values passed in
SearchCriteria<UserVmJoinVO> sc = sb.create();
// building ACL condition
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (tags != null && !tags.isEmpty()) {
SearchCriteria<UserVmJoinVO> tagSc = _userVmJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<UserVmJoinVO> tsc = _userVmJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (groupId != null && (Long) groupId != -1) {
sc.setParameters("instanceGroupId", groupId);
}
if (keyword != null) {
SearchCriteria<UserVmJoinVO> ssc = _userVmJoinDao.createSearchCriteria();
ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.EQ, keyword);
sc.addAnd("displayName", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (templateId != null) {
sc.setParameters("templateId", templateId);
}
if (isoId != null) {
sc.setParameters("isoId", isoId);
}
if (networkId != null) {
sc.setParameters("networkId", networkId);
}
if (vpcId != null && networkId == null) {
sc.setParameters("vpcId", vpcId);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (state != null) {
if (notState != null && (Boolean) notState == true) {
sc.setParameters("stateNEQ", state);
} else {
sc.setParameters("stateEQ", state);
}
}
if (hypervisor != null) {
sc.setParameters("hypervisorType", hypervisor);
}
// Don't show Destroyed and Expunging vms to the end user
if ((isAdmin != null) && ((Boolean) isAdmin != true)) {
sc.setParameters("stateNIN", "Destroyed", "Expunging");
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
if (state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (pod != null) {
sc.setParameters("podId", pod);
if (state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (hostId != null) {
sc.setParameters("hostIdEQ", hostId);
} else {
if (hostName != null) {
sc.setParameters("hostName", hostName);
}
}
if (storageId != null) {
sc.setParameters("poolId", storageId);
}
if (affinityGroupId != null) {
sc.setParameters("affinityGroupId", affinityGroupId);
}
// search vm details by ids
Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVmPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueVmPair;
}
List<UserVmJoinVO> uniqueVms = uniqueVmPair.first();
Long[] vmIds = new Long[uniqueVms.size()];
int i = 0;
for (UserVmJoinVO v : uniqueVms) {
vmIds[i++] = v.getId();
}
List<UserVmJoinVO> vms = _userVmJoinDao.searchByIds(vmIds);
return new Pair<List<UserVmJoinVO>, Integer>(vms, count);
}
@Override
public ListResponse<SecurityGroupResponse> searchForSecurityGroups(ListSecurityGroupsCmd cmd) {
Pair<List<SecurityGroupJoinVO>, Integer> result = searchForSecurityGroupsInternal(cmd);
ListResponse<SecurityGroupResponse> response = new ListResponse<SecurityGroupResponse>();
List<SecurityGroupResponse> routerResponses = ViewResponseHelper.createSecurityGroupResponses(result.first());
response.setResponses(routerResponses, result.second());
return response;
}
private Pair<List<SecurityGroupJoinVO>, Integer> searchForSecurityGroupsInternal(ListSecurityGroupsCmd cmd)
throws PermissionDeniedException, InvalidParameterValueException {
Account caller = UserContext.current().getCaller();
Long instanceId = cmd.getVirtualMachineId();
String securityGroup = cmd.getSecurityGroupName();
Long id = cmd.getId();
Object keyword = cmd.getKeyword();
List<Long> permittedAccounts = new ArrayList<Long>();
Map<String, String> tags = cmd.getTags();
if (instanceId != null) {
UserVmVO userVM = _userVmDao.findById(instanceId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance "
+ instanceId + "; instance not found.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal());
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(SecurityGroupJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<SecurityGroupJoinVO> sb = _securityGroupJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
SearchCriteria<SecurityGroupJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (tags != null && !tags.isEmpty()) {
SearchCriteria<SecurityGroupJoinVO> tagSc = _securityGroupJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<SecurityGroupJoinVO> tsc = _securityGroupJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (securityGroup != null) {
sc.setParameters("name", securityGroup);
}
if (keyword != null) {
SearchCriteria<SecurityGroupJoinVO> ssc = _securityGroupJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
// search security group together with rules
Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueSgPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueSgPair;
}
List<SecurityGroupJoinVO> uniqueSgs = uniqueSgPair.first();
Long[] sgIds = new Long[uniqueSgs.size()];
int i = 0;
for (SecurityGroupJoinVO v : uniqueSgs) {
sgIds[i++] = v.getId();
}
List<SecurityGroupJoinVO> sgs = _securityGroupJoinDao.searchByIds(sgIds);
return new Pair<List<SecurityGroupJoinVO>, Integer>(sgs, count);
}
private Pair<List<SecurityGroupJoinVO>, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) {
Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize);
Pair<List<SecurityGroupVMMapVO>, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf);
Integer count = sgVmMappingPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return new Pair<List<SecurityGroupJoinVO>, Integer>(new ArrayList<SecurityGroupJoinVO>(), count);
}
List<SecurityGroupVMMapVO> sgVmMappings = sgVmMappingPair.first();
Long[] sgIds = new Long[sgVmMappings.size()];
int i = 0;
for (SecurityGroupVMMapVO sgVm : sgVmMappings) {
sgIds[i++] = sgVm.getSecurityGroupId();
}
List<SecurityGroupJoinVO> sgs = _securityGroupJoinDao.searchByIds(sgIds);
return new Pair<List<SecurityGroupJoinVO>, Integer>(sgs, count);
}
@Override
public ListResponse<DomainRouterResponse> searchForRouters(ListRoutersCmd cmd) {
Pair<List<DomainRouterJoinVO>, Integer> result = searchForRoutersInternal(cmd, cmd.getId(), cmd.getRouterName(),
cmd.getState(), cmd.getZoneId(), cmd.getPodId(), cmd.getHostId(), cmd.getKeyword(), cmd.getNetworkId(),
cmd.getVpcId(), cmd.getForVpc(), cmd.getRole());
ListResponse<DomainRouterResponse> response = new ListResponse<DomainRouterResponse>();
List<DomainRouterResponse> routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first()
.toArray(new DomainRouterJoinVO[result.first().size()]));
response.setResponses(routerResponses, result.second());
return response;
}
@Override
public ListResponse<DomainRouterResponse> searchForInternalLbVms(ListInternalLBVMsCmd cmd) {
Pair<List<DomainRouterJoinVO>, Integer> result = searchForRoutersInternal(cmd, cmd.getId(), cmd.getRouterName(),
cmd.getState(), cmd.getZoneId(), cmd.getPodId(), cmd.getHostId(), cmd.getKeyword(), cmd.getNetworkId(),
cmd.getVpcId(), cmd.getForVpc(), cmd.getRole());
ListResponse<DomainRouterResponse> response = new ListResponse<DomainRouterResponse>();
List<DomainRouterResponse> routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first()
.toArray(new DomainRouterJoinVO[result.first().size()]));
response.setResponses(routerResponses, result.second());
return response;
}
private Pair<List<DomainRouterJoinVO>, Integer> searchForRoutersInternal(BaseListProjectAndAccountResourcesCmd cmd, Long id,
String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
// Filter searchFilter = new Filter(DomainRouterJoinVO.class, null,
// true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<DomainRouterJoinVO> sb = _routerJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids to get
// number of
// records with
// pagination
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("name", sb.entity().getInstanceName(), SearchCriteria.Op.LIKE);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ);
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
if (forVpc != null) {
if (forVpc) {
sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL);
} else {
sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL);
}
}
if (networkId != null) {
sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
}
SearchCriteria<DomainRouterJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<DomainRouterJoinVO> ssc = _routerJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("instanceName", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (id != null) {
sc.setParameters("id", id);
}
if (state != null) {
sc.setParameters("state", state);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
if (hostId != null) {
sc.setParameters("hostId", hostId);
}
if (networkId != null) {
sc.setParameters("networkId", networkId);
}
if (vpcId != null) {
sc.setParameters("vpcId", vpcId);
}
if (role != null) {
sc.setParameters("role", role);
}
// search VR details by ids
Pair<List<DomainRouterJoinVO>, Integer> uniqueVrPair = _routerJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVrPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueVrPair;
}
List<DomainRouterJoinVO> uniqueVrs = uniqueVrPair.first();
Long[] vrIds = new Long[uniqueVrs.size()];
int i = 0;
for (DomainRouterJoinVO v : uniqueVrs) {
vrIds[i++] = v.getId();
}
List<DomainRouterJoinVO> vrs = _routerJoinDao.searchByIds(vrIds);
return new Pair<List<DomainRouterJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ProjectResponse> listProjects(ListProjectsCmd cmd) {
Pair<List<ProjectJoinVO>, Integer> projects = listProjectsInternal(cmd);
ListResponse<ProjectResponse> response = new ListResponse<ProjectResponse>();
List<ProjectResponse> projectResponses = ViewResponseHelper.createProjectResponse(projects.first().toArray(
new ProjectJoinVO[projects.first().size()]));
response.setResponses(projectResponses, projects.second());
return response;
}
private Pair<List<ProjectJoinVO>, Integer> listProjectsInternal(ListProjectsCmd cmd) {
Long id = cmd.getId();
String name = cmd.getName();
String displayText = cmd.getDisplayText();
String state = cmd.getState();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
String keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
boolean listAll = cmd.listAll();
boolean isRecursive = cmd.isRecursive();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
Long accountId = null;
String path = null;
Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize);
SearchBuilder<ProjectJoinVO> sb = _projectJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
if (_accountMgr.isAdmin(caller.getType())) {
if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
if (owner == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName
+ " in domain " + domainId);
}
accountId = owner.getId();
}
} else { // domainId == null
if (accountName != null) {
throw new InvalidParameterValueException("could not find account " + accountName
+ " because domain is not specified");
}
}
} else {
if (accountName != null && !accountName.equals(caller.getAccountName())) {
throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized");
}
if (domainId != null && domainId.equals(caller.getDomainId())) {
throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized");
}
accountId = caller.getId();
}
if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) {
accountId = caller.getId();
} else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) {
DomainVO domain = _domainDao.findById(caller.getDomainId());
path = domain.getPath();
}
if (path != null) {
sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
if (accountId != null) {
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
}
SearchCriteria<ProjectJoinVO> sc = sb.create();
if (id != null) {
sc.addAnd("id", Op.EQ, id);
}
if (domainId != null && !isRecursive) {
sc.addAnd("domainId", Op.EQ, domainId);
}
if (name != null) {
sc.addAnd("name", Op.EQ, name);
}
if (displayText != null) {
sc.addAnd("displayText", Op.EQ, displayText);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (state != null) {
sc.addAnd("state", Op.EQ, state);
}
if (keyword != null) {
SearchCriteria<ProjectJoinVO> ssc = _projectJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (path != null) {
sc.setParameters("domainPath", path);
}
// search distinct projects to get count
Pair<List<ProjectJoinVO>, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniquePrjPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniquePrjPair;
}
List<ProjectJoinVO> uniquePrjs = uniquePrjPair.first();
Long[] prjIds = new Long[uniquePrjs.size()];
int i = 0;
for (ProjectJoinVO v : uniquePrjs) {
prjIds[i++] = v.getId();
}
List<ProjectJoinVO> prjs = _projectJoinDao.searchByIds(prjIds);
return new Pair<List<ProjectJoinVO>, Integer>(prjs, count);
}
@Override
public ListResponse<ProjectInvitationResponse> listProjectInvitations(ListProjectInvitationsCmd cmd) {
Pair<List<ProjectInvitationJoinVO>, Integer> invites = listProjectInvitationsInternal(cmd);
ListResponse<ProjectInvitationResponse> response = new ListResponse<ProjectInvitationResponse>();
List<ProjectInvitationResponse> projectInvitationResponses = ViewResponseHelper
.createProjectInvitationResponse(invites.first().toArray(
new ProjectInvitationJoinVO[invites.first().size()]));
response.setResponses(projectInvitationResponses, invites.second());
return response;
}
public Pair<List<ProjectInvitationJoinVO>, Integer> listProjectInvitationsInternal(ListProjectInvitationsCmd cmd) {
Long id = cmd.getId();
Long projectId = cmd.getProjectId();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
String state = cmd.getState();
boolean activeOnly = cmd.isActiveOnly();
Long startIndex = cmd.getStartIndex();
Long pageSizeVal = cmd.getPageSizeVal();
boolean isRecursive = cmd.isRecursive();
boolean listAll = cmd.listAll();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts,
domainIdRecursiveListProject, listAll, true);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(ProjectInvitationJoinVO.class, "id", true, startIndex, pageSizeVal);
SearchBuilder<ProjectInvitationJoinVO> sb = _projectInvitationJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
SearchCriteria<ProjectInvitationJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (projectId != null) {
sc.setParameters("projectId", projectId);
}
if (state != null) {
sc.setParameters("state", state);
}
if (id != null) {
sc.setParameters("id", id);
}
if (activeOnly) {
sc.setParameters("state", ProjectInvitation.State.Pending);
sc.setParameters("created",
new Date((DateUtil.currentGMTTime().getTime()) - _projectMgr.getInvitationTimeout()));
}
return _projectInvitationJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ProjectAccountResponse> listProjectAccounts(ListProjectAccountsCmd cmd) {
Pair<List<ProjectAccountJoinVO>, Integer> projectAccounts = listProjectAccountsInternal(cmd);
ListResponse<ProjectAccountResponse> response = new ListResponse<ProjectAccountResponse>();
List<ProjectAccountResponse> projectResponses = ViewResponseHelper.createProjectAccountResponse(projectAccounts
.first().toArray(new ProjectAccountJoinVO[projectAccounts.first().size()]));
response.setResponses(projectResponses, projectAccounts.second());
return response;
}
public Pair<List<ProjectAccountJoinVO>, Integer> listProjectAccountsInternal(ListProjectAccountsCmd cmd) {
long projectId = cmd.getProjectId();
String accountName = cmd.getAccountName();
String role = cmd.getRole();
Long startIndex = cmd.getStartIndex();
Long pageSizeVal = cmd.getPageSizeVal();
// long projectId, String accountName, String role, Long startIndex,
// Long pageSizeVal) {
Account caller = UserContext.current().getCaller();
// check that the project exists
Project project = _projectDao.findById(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find the project id=" + projectId);
}
// verify permissions - only accounts belonging to the project can list
// project's account
if (!_accountMgr.isAdmin(caller.getType())
&& _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) {
throw new PermissionDeniedException("Account " + caller
+ " is not authorized to list users of the project id=" + projectId);
}
Filter searchFilter = new Filter(ProjectAccountJoinVO.class, "id", false, startIndex, pageSizeVal);
SearchBuilder<ProjectAccountJoinVO> sb = _projectAccountJoinDao.createSearchBuilder();
sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ);
sb.and("projectId", sb.entity().getProjectId(), Op.EQ);
SearchBuilder<AccountVO> accountSearch;
if (accountName != null) {
sb.and("accountName", sb.entity().getAccountName(), Op.EQ);
}
SearchCriteria<ProjectAccountJoinVO> sc = sb.create();
sc.setParameters("projectId", projectId);
if (role != null) {
sc.setParameters("accountRole", role);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
}
return _projectAccountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<HostResponse> searchForServers(ListHostsCmd cmd) {
// FIXME: do we need to support list hosts with VmId, maybe we should
// create another command just for this
// Right now it is handled separately outside this QueryService
s_logger.debug(">>>Searching for hosts>>>");
Pair<List<HostJoinVO>, Integer> hosts = searchForServersInternal(cmd);
ListResponse<HostResponse> response = new ListResponse<HostResponse>();
s_logger.debug(">>>Generating Response>>>");
List<HostResponse> hostResponses = ViewResponseHelper.createHostResponse(cmd.getDetails(), hosts.first()
.toArray(new HostJoinVO[hosts.first().size()]));
response.setResponses(hostResponses, hosts.second());
return response;
}
public Pair<List<HostJoinVO>, Integer> searchForServersInternal(ListHostsCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object name = cmd.getHostName();
Object type = cmd.getType();
Object state = cmd.getState();
Object pod = cmd.getPodId();
Object cluster = cmd.getClusterId();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Object resourceState = cmd.getResourceState();
Object haHosts = cmd.getHaHost();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(HostJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<HostJoinVO> sb = _hostJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.LIKE);
sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ);
sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
String haTag = _haMgr.getHaTag();
if (haHosts != null && haTag != null && !haTag.isEmpty()) {
if ((Boolean) haHosts) {
sb.and("tag", sb.entity().getTag(), SearchCriteria.Op.EQ);
} else {
sb.and().op("tag", sb.entity().getTag(), SearchCriteria.Op.NEQ);
sb.or("tagNull", sb.entity().getTag(), SearchCriteria.Op.NULL);
sb.cp();
}
}
SearchCriteria<HostJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<HostJoinVO> ssc = _hostJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("status", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (type != null) {
sc.setParameters("type", "%" + type);
}
if (state != null) {
sc.setParameters("status", state);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (pod != null) {
sc.setParameters("podId", pod);
}
if (cluster != null) {
sc.setParameters("clusterId", cluster);
}
if (resourceState != null) {
sc.setParameters("resourceState", resourceState);
}
if (haHosts != null && haTag != null && !haTag.isEmpty()) {
sc.setJoinParameters("hostTagSearch", "tag", haTag);
}
// search host details by ids
Pair<List<HostJoinVO>, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueHostPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueHostPair;
}
List<HostJoinVO> uniqueHosts = uniqueHostPair.first();
Long[] hostIds = new Long[uniqueHosts.size()];
int i = 0;
for (HostJoinVO v : uniqueHosts) {
hostIds[i++] = v.getId();
}
List<HostJoinVO> hosts = _hostJoinDao.searchByIds(hostIds);
return new Pair<List<HostJoinVO>, Integer>(hosts, count);
}
@Override
public ListResponse<VolumeResponse> searchForVolumes(ListVolumesCmd cmd) {
Pair<List<VolumeJoinVO>, Integer> result = searchForVolumesInternal(cmd);
ListResponse<VolumeResponse> response = new ListResponse<VolumeResponse>();
List<VolumeResponse> volumeResponses = ViewResponseHelper.createVolumeResponse(result.first().toArray(
new VolumeJoinVO[result.first().size()]));
response.setResponses(volumeResponses, result.second());
return response;
}
private Pair<List<VolumeJoinVO>, Integer> searchForVolumesInternal(ListVolumesCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Long id = cmd.getId();
Long vmInstanceId = cmd.getVirtualMachineId();
String name = cmd.getVolumeName();
String keyword = cmd.getKeyword();
String type = cmd.getType();
Map<String, String> tags = cmd.getTags();
Long zoneId = cmd.getZoneId();
Long podId = null;
if (_accountMgr.isAdmin(caller.getType())) {
podId = cmd.getPodId();
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(VolumeJoinVO.class, "created", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
// hack for now, this should be done better but due to needing a join I
// opted to
// do this quickly and worry about making it pretty later
SearchBuilder<VolumeJoinVO> sb = _volumeJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids to get
// number of
// records with
// pagination
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE);
sb.and("instanceId", sb.entity().getVmId(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
// Only return volumes that are not destroyed
sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("systemUse", sb.entity().isSystemUse(), SearchCriteria.Op.NEQ);
// display UserVM volumes only
sb.and().op("type", sb.entity().getVmType(), SearchCriteria.Op.NIN);
sb.or("nulltype", sb.entity().getVmType(), SearchCriteria.Op.NULL);
sb.cp();
// now set the SC criteria...
SearchCriteria<VolumeJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<VolumeJoinVO> ssc = _volumeJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.setParameters("name", name);
}
sc.setParameters("systemUse", 1);
if (tags != null && !tags.isEmpty()) {
SearchCriteria<VolumeJoinVO> tagSc = _volumeJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<VolumeJoinVO> tsc = _volumeJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (type != null) {
sc.setParameters("volumeType", "%" + type + "%");
}
if (vmInstanceId != null) {
sc.setParameters("instanceId", vmInstanceId);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
// Don't return DomR and ConsoleProxy volumes
sc.setParameters("type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm,
VirtualMachine.Type.DomainRouter);
// Only return volumes that are not destroyed
sc.setParameters("state", Volume.State.Destroy);
// search Volume details by ids
Pair<List<VolumeJoinVO>, Integer> uniqueVolPair = _volumeJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVolPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueVolPair;
}
List<VolumeJoinVO> uniqueVols = uniqueVolPair.first();
Long[] vrIds = new Long[uniqueVols.size()];
int i = 0;
for (VolumeJoinVO v : uniqueVols) {
vrIds[i++] = v.getId();
}
List<VolumeJoinVO> vrs = _volumeJoinDao.searchByIds(vrIds);
return new Pair<List<VolumeJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<AccountResponse> searchForAccounts(ListAccountsCmd cmd) {
Pair<List<AccountJoinVO>, Integer> result = searchForAccountsInternal(cmd);
ListResponse<AccountResponse> response = new ListResponse<AccountResponse>();
List<AccountResponse> accountResponses = ViewResponseHelper.createAccountResponse(result.first().toArray(
new AccountJoinVO[result.first().size()]));
response.setResponses(accountResponses, result.second());
return response;
}
private Pair<List<AccountJoinVO>, Integer> searchForAccountsInternal(ListAccountsCmd cmd) {
Account caller = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
Long accountId = cmd.getId();
String accountName = cmd.getSearchName();
boolean isRecursive = cmd.isRecursive();
boolean listAll = cmd.listAll();
Boolean listForDomain = false;
if (accountId != null) {
Account account = _accountDao.findById(accountId);
if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Unable to find account by id " + accountId);
}
_accountMgr.checkAccess(caller, null, true, account);
}
if (domainId != null) {
Domain domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
Account account = _accountDao.findActiveAccount(accountName, domainId);
if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Unable to find account by name " + accountName
+ " in domain " + domainId);
}
_accountMgr.checkAccess(caller, null, true, account);
}
}
if (accountId == null) {
if (_accountMgr.isAdmin(caller.getType()) && listAll && domainId == null) {
listForDomain = true;
isRecursive = true;
if (domainId == null) {
domainId = caller.getDomainId();
}
} else if (_accountMgr.isAdmin(caller.getType()) && domainId != null) {
listForDomain = true;
} else {
accountId = caller.getAccountId();
}
}
Filter searchFilter = new Filter(AccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
Object type = cmd.getAccountType();
Object state = cmd.getState();
Object isCleanupRequired = cmd.isCleanupRequired();
Object keyword = cmd.getKeyword();
SearchBuilder<AccountJoinVO> sb = _accountJoinDao.createSearchBuilder();
sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("needsCleanup", sb.entity().isNeedsCleanup(), SearchCriteria.Op.EQ);
sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ);
sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ);
if (listForDomain && isRecursive) {
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
SearchCriteria<AccountJoinVO> sc = sb.create();
sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM);
if (keyword != null) {
SearchCriteria<AccountJoinVO> ssc = _accountJoinDao.createSearchCriteria();
ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("accountName", SearchCriteria.Op.SC, ssc);
}
if (type != null) {
sc.setParameters("type", type);
}
if (state != null) {
sc.setParameters("state", state);
}
if (isCleanupRequired != null) {
sc.setParameters("needsCleanup", isCleanupRequired);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
}
// don't return account of type project to the end user
sc.setParameters("typeNEQ", 5);
if (accountId != null) {
sc.setParameters("id", accountId);
}
if (listForDomain) {
if (isRecursive) {
Domain domain = _domainDao.findById(domainId);
sc.setParameters("path", domain.getPath() + "%");
} else {
sc.setParameters("domainId", domainId);
}
}
return _accountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<AsyncJobResponse> searchForAsyncJobs(ListAsyncJobsCmd cmd) {
Pair<List<AsyncJobJoinVO>, Integer> result = searchForAsyncJobsInternal(cmd);
ListResponse<AsyncJobResponse> response = new ListResponse<AsyncJobResponse>();
List<AsyncJobResponse> jobResponses = ViewResponseHelper.createAsyncJobResponse(result.first().toArray(
new AsyncJobJoinVO[result.first().size()]));
response.setResponses(jobResponses, result.second());
return response;
}
private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<AsyncJobJoinVO> sb = _jobJoinDao.createSearchBuilder();
sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
SearchBuilder<AccountVO> accountSearch = null;
boolean accountJoinIsDone = false;
if (permittedAccounts.isEmpty() && domainId != null) {
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
accountJoinIsDone = true;
}
if (listProjectResourcesCriteria != null) {
if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
} else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
}
if (!accountJoinIsDone) {
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
}
Object keyword = cmd.getKeyword();
Object startDate = cmd.getStartDate();
SearchCriteria<AsyncJobJoinVO> sc = sb.create();
if (listProjectResourcesCriteria != null) {
sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
}
if (!permittedAccounts.isEmpty()) {
sc.setParameters("accountIdIN", permittedAccounts.toArray());
} else if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
if (isRecursive) {
sc.setParameters("path", domain.getPath() + "%");
} else {
sc.setParameters("domainId", domainId);
}
}
if (keyword != null) {
sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%");
}
if (startDate != null) {
sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
}
return _jobJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<StoragePoolResponse> searchForStoragePools(ListStoragePoolsCmd cmd) {
Pair<List<StoragePoolJoinVO>, Integer> result = searchForStoragePoolsInternal(cmd);
ListResponse<StoragePoolResponse> response = new ListResponse<StoragePoolResponse>();
List<StoragePoolResponse> poolResponses = ViewResponseHelper.createStoragePoolResponse(result.first().toArray(
new StoragePoolJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<StoragePoolJoinVO>, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) {
ScopeType scopeType = null;
if (cmd.getScope() != null) {
try {
scopeType = Enum.valueOf(ScopeType.class, cmd.getScope().toUpperCase());
} catch (Exception e) {
throw new InvalidParameterValueException("Invalid scope type: " + cmd.getScope());
}
}
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoragePoolName();
Object path = cmd.getPath();
Object pod = cmd.getPodId();
Object cluster = cmd.getClusterId();
Object address = cmd.getIpAddress();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(StoragePoolJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<StoragePoolJoinVO> sb = _poolJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getPath(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ);
sb.and("hostAddress", sb.entity().getHostAddress(), SearchCriteria.Op.EQ);
sb.and("scope", sb.entity().getScope(), SearchCriteria.Op.EQ);
SearchCriteria<StoragePoolJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<StoragePoolJoinVO> ssc = _poolJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("poolType", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (path != null) {
sc.setParameters("path", path);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (pod != null) {
sc.setParameters("podId", pod);
}
if (address != null) {
sc.setParameters("hostAddress", address);
}
if (cluster != null) {
sc.setParameters("clusterId", cluster);
}
if (scopeType != null) {
sc.setParameters("scope", scopeType.toString());
}
// search Pool details by ids
Pair<List<StoragePoolJoinVO>, Integer> uniquePoolPair = _poolJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniquePoolPair.second();
if (count.intValue() == 0) {
// empty result
return uniquePoolPair;
}
List<StoragePoolJoinVO> uniquePools = uniquePoolPair.first();
Long[] vrIds = new Long[uniquePools.size()];
int i = 0;
for (StoragePoolJoinVO v : uniquePools) {
vrIds[i++] = v.getId();
}
List<StoragePoolJoinVO> vrs = _poolJoinDao.searchByIds(vrIds);
return new Pair<List<StoragePoolJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ImageStoreResponse> searchForImageStores(ListImageStoresCmd cmd) {
Pair<List<ImageStoreJoinVO>, Integer> result = searchForImageStoresInternal(cmd);
ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
new ImageStoreJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<ImageStoreJoinVO>, Integer> searchForImageStoresInternal(ListImageStoresCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoreName();
String provider = cmd.getProvider();
String protocol = cmd.getProtocol();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
SearchCriteria<ImageStoreJoinVO> sc = sb.create();
sc.setParameters("role", DataStoreRole.Image);
if (keyword != null) {
SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (provider != null) {
sc.setParameters("provider", provider);
}
if (protocol != null) {
sc.setParameters("protocol", protocol);
}
// search Store details by ids
Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueStorePair.second();
if (count.intValue() == 0) {
// empty result
return uniqueStorePair;
}
List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
Long[] vrIds = new Long[uniqueStores.size()];
int i = 0;
for (ImageStoreJoinVO v : uniqueStores) {
vrIds[i++] = v.getId();
}
List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ImageStoreResponse> searchForSecondaryStagingStores(ListSecondaryStagingStoresCmd cmd) {
Pair<List<ImageStoreJoinVO>, Integer> result = searchForCacheStoresInternal(cmd);
ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
new ImageStoreJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<ImageStoreJoinVO>, Integer> searchForCacheStoresInternal(ListSecondaryStagingStoresCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoreName();
String provider = cmd.getProvider();
String protocol = cmd.getProtocol();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
SearchCriteria<ImageStoreJoinVO> sc = sb.create();
sc.setParameters("role", DataStoreRole.ImageCache);
if (keyword != null) {
SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (provider != null) {
sc.setParameters("provider", provider);
}
if (protocol != null) {
sc.setParameters("protocol", protocol);
}
// search Store details by ids
Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueStorePair.second();
if (count.intValue() == 0) {
// empty result
return uniqueStorePair;
}
List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
Long[] vrIds = new Long[uniqueStores.size()];
int i = 0;
for (ImageStoreJoinVO v : uniqueStores) {
vrIds[i++] = v.getId();
}
List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<DiskOfferingResponse> searchForDiskOfferings(ListDiskOfferingsCmd cmd) {
Pair<List<DiskOfferingJoinVO>, Integer> result = searchForDiskOfferingsInternal(cmd);
ListResponse<DiskOfferingResponse> response = new ListResponse<DiskOfferingResponse>();
List<DiskOfferingResponse> offeringResponses = ViewResponseHelper.createDiskOfferingResponse(result.first()
.toArray(new DiskOfferingJoinVO[result.first().size()]));
response.setResponses(offeringResponses, result.second());
return response;
}
private Pair<List<DiskOfferingJoinVO>, Integer> searchForDiskOfferingsInternal(ListDiskOfferingsCmd cmd) {
// Note
// The list method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will list all offerings
// 2. For domainAdmin and regular users, we will list everything in
// their domains+parent domains ... all the way
// till
// root
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchCriteria<DiskOfferingJoinVO> sc = _diskOfferingJoinDao.createSearchCriteria();
Account account = UserContext.current().getCaller();
Object name = cmd.getDiskOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long domainId = cmd.getDomainId();
// Keeping this logic consistent with domain specific zones
// if a domainId is provided, we just return the disk offering
// associated with this domain
if (domainId != null) {
if (account.getType() == Account.ACCOUNT_TYPE_ADMIN || isPermissible(account.getDomainId(), domainId)) {
// check if the user's domain == do's domain || user's domain is
// a child of so's domain for non-root users
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
} else {
throw new PermissionDeniedException("The account:" + account.getAccountName()
+ " does not fall in the same domain hierarchy as the disk offering");
}
}
List<Long> domainIds = null;
// For non-root users, only return all offerings for the user's domain,
// and everything above till root
if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
|| account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// find all domain Id up to root domain for this account
domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
SearchCriteria<DiskOfferingJoinVO> spc = _diskOfferingJoinDao.createSearchCriteria();
spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
spc.addOr("domainId", SearchCriteria.Op.NULL); // include public
// offering as where
sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); // non-root
// users should
// not see
// system
// offering at
// all
}
if (keyword != null) {
SearchCriteria<DiskOfferingJoinVO> ssc = _diskOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
// FIXME: disk offerings should search back up the hierarchy for
// available disk offerings...
/*
* sb.addAnd("domainId", sb.entity().getDomainId(),
* SearchCriteria.Op.EQ); if (domainId != null) {
* SearchBuilder<DomainVO> domainSearch =
* _domainDao.createSearchBuilder(); domainSearch.addAnd("path",
* domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
* sb.join("domainSearch", domainSearch, sb.entity().getDomainId(),
* domainSearch.entity().getId()); }
*/
// FIXME: disk offerings should search back up the hierarchy for
// available disk offerings...
/*
* if (domainId != null) { sc.setParameters("domainId", domainId); //
* //DomainVO domain = _domainDao.findById((Long)domainId); // // I want
* to join on user_vm.domain_id = domain.id where domain.path like
* 'foo%' //sc.setJoinParameters("domainSearch", "path",
* domain.getPath() + "%"); // }
*/
return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ServiceOfferingResponse> searchForServiceOfferings(ListServiceOfferingsCmd cmd) {
Pair<List<ServiceOfferingJoinVO>, Integer> result = searchForServiceOfferingsInternal(cmd);
ListResponse<ServiceOfferingResponse> response = new ListResponse<ServiceOfferingResponse>();
List<ServiceOfferingResponse> offeringResponses = ViewResponseHelper.createServiceOfferingResponse(result
.first().toArray(new ServiceOfferingJoinVO[result.first().size()]));
response.setResponses(offeringResponses, result.second());
return response;
}
private Pair<List<ServiceOfferingJoinVO>, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) {
// Note
// The list method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will list all offerings
// 2. For domainAdmin and regular users, we will list everything in
// their domains+parent domains ... all the way
// till
// root
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
Account caller = UserContext.current().getCaller();
Object name = cmd.getServiceOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long vmId = cmd.getVirtualMachineId();
Long domainId = cmd.getDomainId();
Boolean isSystem = cmd.getIsSystem();
String vmTypeStr = cmd.getSystemVmType();
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) {
throw new InvalidParameterValueException("Only ROOT admins can access system's offering");
}
// Keeping this logic consistent with domain specific zones
// if a domainId is provided, we just return the so associated with this
// domain
if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
// check if the user's domain == so's domain || user's domain is a
// child of so's domain
if (!isPermissible(caller.getDomainId(), domainId)) {
throw new PermissionDeniedException("The account:" + caller.getAccountName()
+ " does not fall in the same domain hierarchy as the service offering");
}
}
// boolean includePublicOfferings = false;
if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
|| caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// For non-root users.
if (isSystem) {
throw new InvalidParameterValueException("Only root admins can access system's offering");
}
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(caller.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + caller.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ caller.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
SearchCriteria<ServiceOfferingJoinVO> spc = _srvOfferingJoinDao.createSearchCriteria();
spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
spc.addOr("domainId", SearchCriteria.Op.NULL); // include public
// offering as where
sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
} else {
// for root users
if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin
throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering");
}
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
}
if (keyword != null) {
SearchCriteria<ServiceOfferingJoinVO> ssc = _srvOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
} else if (vmId != null) {
UserVmVO vmInstance = _userVmDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException(
"unable to find a virtual machine with specified id");
ex.addProxyObject(vmId.toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
ServiceOfferingVO offering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId());
// Only return offerings with the same Guest IP type and storage
// pool preference
// sc.addAnd("guestIpType", SearchCriteria.Op.EQ,
// offering.getGuestIpType());
sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage());
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (isSystem != null) {
// note that for non-root users, isSystem is always false when
// control comes to here
sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (vmTypeStr != null) {
sc.addAnd("vm_type", SearchCriteria.Op.EQ, vmTypeStr);
}
return _srvOfferingJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ZoneResponse> listDataCenters(ListZonesByCmd cmd) {
Pair<List<DataCenterJoinVO>, Integer> result = listDataCentersInternal(cmd);
ListResponse<ZoneResponse> response = new ListResponse<ZoneResponse>();
List<ZoneResponse> dcResponses = ViewResponseHelper.createDataCenterResponse(cmd.getShowCapacities(), result
.first().toArray(new DataCenterJoinVO[result.first().size()]));
response.setResponses(dcResponses, result.second());
return response;
}
private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesByCmd cmd) {
Account account = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
Long id = cmd.getId();
String keyword = cmd.getKeyword();
String name = cmd.getName();
String networkType = cmd.getNetworkType();
Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<DataCenterJoinVO> sc = _dcJoinDao.createSearchCriteria();
if (networkType != null) {
sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
} else if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
} else {
if (keyword != null) {
SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
/*
* List all resources due to Explicit Dedication except the
* dedicated resources of other account
*/
if (domainId != null && account.getType() == Account.ACCOUNT_TYPE_ADMIN) { //
// for domainId != null // right now, we made the decision to
// only
// / list zones associated // with this domain, private zone
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
} else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) {
// it was decided to return all zones for the user's domain, and
// everything above till root
// list all zones belonging to this domain, and all of its
// parents
// check the parent, if not null, add zones for that parent to
// list
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domain", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN,
dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
} else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN
|| account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// it was decided to return all zones for the domain admin, and
// everything above till root, as well as zones till the domain
// leaf
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
// find all domain Ids till leaf
List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(),
domainRecord.getId());
for (DomainVO domain : allChildDomains) {
domainIds.add(domain.getId());
}
// then find all domain Id up to root domain for this account
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domain", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN,
dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
}
// handle available=FALSE option, only return zones with at least
// one VM running there
Boolean available = cmd.isAvailable();
if (account != null) {
if ((available != null) && Boolean.FALSE.equals(available)) {
Set<Long> dcIds = new HashSet<Long>(); // data centers with
// at least one VM
// running
List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
for (DomainRouterVO router : routers) {
dcIds.add(router.getDataCenterId());
}
if (dcIds.size() == 0) {
return new Pair<List<DataCenterJoinVO>, Integer>(new ArrayList<DataCenterJoinVO>(), 0);
} else {
sc.addAnd("idIn", SearchCriteria.Op.IN, dcIds.toArray());
}
}
}
}
return _dcJoinDao.searchAndCount(sc, searchFilter);
}
private List<Long> removeDedicatedZoneNotSuitabe(List<Long> domainIds) {
// remove dedicated zone of other domain
List<Long> dedicatedZoneIds = new ArrayList<Long>();
List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listZonesNotInDomainIds(domainIds);
for (DedicatedResourceVO dr : dedicatedResources) {
if (dr != null) {
dedicatedZoneIds.add(dr.getDataCenterId());
}
}
return dedicatedZoneIds;
}
// This method is used for permissions check for both disk and service
// offerings
private boolean isPermissible(Long accountDomainId, Long offeringDomainId) {
if (accountDomainId.equals(offeringDomainId)) {
return true; // account and service offering in same domain
}
DomainVO domainRecord = _domainDao.findById(accountDomainId);
if (domainRecord != null) {
while (true) {
if (domainRecord.getId() == offeringDomainId) {
return true;
}
// try and move on to the next domain
if (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
return false;
}
@Override
public ListResponse<TemplateResponse> listTemplates(ListTemplatesCmd cmd) {
Pair<List<TemplateJoinVO>, Integer> result = searchForTemplatesInternal(cmd);
ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
List<TemplateResponse> templateResponses = ViewResponseHelper.createTemplateResponse(result.first().toArray(
new TemplateJoinVO[result.first().size()]));
response.setResponses(templateResponses, result.second());
return response;
}
private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) {
TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
boolean listAll = false;
if (templateFilter != null && templateFilter == TemplateFilter.all) {
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+ " can be specified by admin only");
}
listAll = true;
}
List<Long> permittedAccountIds = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
domainIdRecursiveListProject, listAll, false);
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null,
cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr,
cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
}
private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name,
String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize,
Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria,
Map<String, String> tags) {
VMTemplateVO template = null;
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair()); // select distinct (templateId, zoneId) pair
SearchCriteria<TemplateJoinVO> sc = sb.create();
// verify templateId parameter and specially handle it
if (templateId != null) {
template = _templateDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("Please specify a valid template ID.");
}// If ISO requested then it should be ISO.
if (isIso && template.getFormat() != ImageFormat.ISO) {
s_logger.error("Template Id " + templateId + " is not an ISO");
InvalidParameterValueException ex = new InvalidParameterValueException(
"Specified Template Id is not an ISO");
ex.addProxyObject(template.getUuid(), "templateId");
throw ex;
}// If ISO not requested then it shouldn't be an ISO.
if (!isIso && template.getFormat() == ImageFormat.ISO) {
s_logger.error("Incorrect format of the template id " + templateId);
InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format "
+ template.getFormat() + " of the specified template id");
ex.addProxyObject(template.getUuid(), "templateId");
throw ex;
}
// if template is not public, perform permission check here
if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
Account owner = _accountMgr.getAccount(template.getAccountId());
_accountMgr.checkAccess(caller, null, true, owner);
}
// if templateId is specified, then we will just use the id to
// search and ignore other query parameters
sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
} else {
DomainVO domain = null;
if (!permittedAccounts.isEmpty()) {
domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
} else {
domain = _domainDao.findById(DomainVO.ROOT_DOMAIN);
}
List<HypervisorType> hypers = null;
if (!isIso) {
hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
}
// add criteria for project or not
if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
} else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
}
// add criteria for domain path in case of domain admin
if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable)
&& (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
}
List<Long> relatedDomainIds = new ArrayList<Long>();
List<Long> permittedAccountIds = new ArrayList<Long>();
if (!permittedAccounts.isEmpty()) {
for (Account account : permittedAccounts) {
permittedAccountIds.add(account.getId());
DomainVO accountDomain = _domainDao.findById(account.getDomainId());
// get all parent domain ID's all the way till root domain
DomainVO domainTreeNode = accountDomain;
relatedDomainIds.add(domainTreeNode.getId());
while (domainTreeNode.getParent() != null) {
domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
relatedDomainIds.add(domainTreeNode.getId());
}
// get all child domain ID's
if (_accountMgr.isAdmin(account.getType())) {
List<DomainVO> allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(),
accountDomain.getId());
for (DomainVO childDomain : allChildDomains) {
relatedDomainIds.add(childDomain.getId());
}
}
}
}
if (!isIso) {
// add hypervisor criteria for template case
if (hypers != null && !hypers.isEmpty()) {
String[] relatedHypers = new String[hypers.size()];
for (int i = 0; i < hypers.size(); i++) {
relatedHypers[i] = hypers.get(i).toString();
}
sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
}
}
// control different template filters
if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
if (templateFilter == TemplateFilter.featured) {
sc.addAnd("featured", SearchCriteria.Op.EQ, true);
} else {
sc.addAnd("featured", SearchCriteria.Op.EQ, false);
}
if (!permittedAccounts.isEmpty()) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
scc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
}
} else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
if (!permittedAccounts.isEmpty()) {
sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
}
} else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
sc.addAnd("accountId", SearchCriteria.Op.SC, scc);
} else if (templateFilter == TemplateFilter.executable) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
if (!permittedAccounts.isEmpty()) {
scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
}
sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
}
// add tags criteria
if (tags != null && !tags.isEmpty()) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
int count = 0;
for (String key : tags.keySet()) {
SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
scTag.addAnd("tagKey", SearchCriteria.Op.EQ, key);
scTag.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
if (isIso) {
scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.ISO);
} else {
scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.Template);
}
scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
count++;
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
}
// other criteria
if (keyword != null) {
sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
} else if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (isIso) {
sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
} else {
sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
}
if (!hyperType.equals(HypervisorType.None)) {
sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
}
if (bootable != null) {
sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
}
if (onlyReady) {
SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
sc.addAnd("state", SearchCriteria.Op.SC, readySc);
}
if (!showDomr) {
// excluding system template
sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
}
}
if (zoneId != null) {
SearchCriteria<TemplateJoinVO> zoneSc = _templateJoinDao.createSearchCriteria();
zoneSc.addOr("dataCenterId", SearchCriteria.Op.EQ, zoneId);
zoneSc.addOr("dataStoreScope", SearchCriteria.Op.EQ, ScopeType.REGION);
// handle the case where xs-tools.iso and vmware-tools.iso do not
// have data_center information in template_view
SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
zoneSc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
sc.addAnd("dataCenterId", SearchCriteria.Op.SC, zoneSc);
}
// don't return removed template, this should not be needed since we
// changed annotation for removed field in TemplateJoinVO.
// sc.addAnd("removed", SearchCriteria.Op.NULL);
// search unique templates and find details by Ids
Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueTmplPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueTmplPair;
}
List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
String[] tzIds = new String[uniqueTmpls.size()];
int i = 0;
for (TemplateJoinVO v : uniqueTmpls) {
tzIds[i++] = v.getTempZonePair();
}
List<TemplateJoinVO> vrs = _templateJoinDao.searchByTemplateZonePair(tzIds);
return new Pair<List<TemplateJoinVO>, Integer>(vrs, count);
// TODO: revisit the special logic for iso search in
// VMTemplateDaoImpl.searchForTemplates and understand why we need to
// specially handle ISO. The original logic is very twisted and no idea
// about what the code was doing.
}
@Override
public ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd) {
Pair<List<TemplateJoinVO>, Integer> result = searchForIsosInternal(cmd);
ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
List<TemplateResponse> templateResponses = ViewResponseHelper.createIsoResponse(result.first().toArray(
new TemplateJoinVO[result.first().size()]));
response.setResponses(templateResponses, result.second());
return response;
}
private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(ListIsosCmd cmd) {
TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
boolean listAll = false;
if (isoFilter != null && isoFilter == TemplateFilter.all) {
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+ " can be specified by admin only");
}
listAll = true;
}
List<Long> permittedAccountIds = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
domainIdRecursiveListProject, listAll, false);
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true,
cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true,
cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
}
@Override
public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
boolean listAll, Long startIndex, Long pageSize) {
Pair<List<AffinityGroupJoinVO>, Integer> result = listAffinityGroupsInternal(affinityGroupId,
affinityGroupName, affinityGroupType, vmId, accountName, domainId, isRecursive, listAll, startIndex,
pageSize);
ListResponse<AffinityGroupResponse> response = new ListResponse<AffinityGroupResponse>();
List<AffinityGroupResponse> agResponses = ViewResponseHelper.createAffinityGroupResponses(result.first());
response.setResponses(agResponses, result.second());
return response;
}
public Pair<List<AffinityGroupJoinVO>, Integer> listAffinityGroupsInternal(Long affinityGroupId,
String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId,
boolean isRecursive, boolean listAll, Long startIndex, Long pageSize) {
Account caller = UserContext.current().getCaller();
Long accountId = caller.getAccountId();
if (vmId != null) {
UserVmVO userVM = _userVmDao.findById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance "
+ vmId + "; instance not found.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
return listAffinityGroupsByVM(vmId.longValue(), startIndex, pageSize);
}
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, null, permittedAccounts,
domainIdRecursiveListProject, listAll, true);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(AffinityGroupJoinVO.class, "id", true, startIndex, pageSize);
SearchCriteria<AffinityGroupJoinVO> sc = buildAffinityGroupSearchCriteria(domainId, isRecursive,
permittedAccounts, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType);
Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc,
searchFilter);
// search group details by ids
List<AffinityGroupJoinVO> vrs = new ArrayList<AffinityGroupJoinVO>();
Integer count = uniqueGroupsPair.second();
if (count.intValue() != 0) {
List<AffinityGroupJoinVO> uniqueGroups = uniqueGroupsPair.first();
Long[] vrIds = new Long[uniqueGroups.size()];
int i = 0;
for (AffinityGroupJoinVO v : uniqueGroups) {
vrIds[i++] = v.getId();
}
vrs = _affinityGroupJoinDao.searchByIds(vrIds);
}
if (!permittedAccounts.isEmpty()) {
// add domain level affinity groups
if (domainId != null) {
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
} else {
for (Long permAcctId : permittedAccounts) {
Account permittedAcct = _accountDao.findById(permAcctId);
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(
null, isRecursive, new ArrayList<Long>(),
listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId()));
}
}
} else if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
// list all domain level affinity groups for the domain admin case
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
}
return new Pair<List<AffinityGroupJoinVO>, Integer>(vrs, vrs.size());
}
private SearchCriteria<AffinityGroupJoinVO> buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive,
List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria,
Long affinityGroupId, String affinityGroupName, String affinityGroupType) {
SearchBuilder<AffinityGroupJoinVO> groupSearch = _affinityGroupJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(groupSearch, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
groupSearch.select(null, Func.DISTINCT, groupSearch.entity().getId()); // select
// distinct
SearchCriteria<AffinityGroupJoinVO> sc = groupSearch.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (affinityGroupId != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, affinityGroupId);
}
if (affinityGroupName != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, affinityGroupName);
}
if (affinityGroupType != null) {
sc.addAnd("type", SearchCriteria.Op.EQ, affinityGroupType);
}
return sc;
}
private Pair<List<AffinityGroupJoinVO>, Integer> listAffinityGroupsByVM(long vmId, long pageInd, long pageSize) {
Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize);
Pair<List<AffinityGroupVMMapVO>, Integer> agVmMappingPair = _affinityGroupVMMapDao.listByInstanceId(vmId, sf);
Integer count = agVmMappingPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return new Pair<List<AffinityGroupJoinVO>, Integer>(new ArrayList<AffinityGroupJoinVO>(), count);
}
List<AffinityGroupVMMapVO> agVmMappings = agVmMappingPair.first();
Long[] agIds = new Long[agVmMappings.size()];
int i = 0;
for (AffinityGroupVMMapVO agVm : agVmMappings) {
agIds[i++] = agVm.getAffinityGroupId();
}
List<AffinityGroupJoinVO> ags = _affinityGroupJoinDao.searchByIds(agIds);
return new Pair<List<AffinityGroupJoinVO>, Integer>(ags, count);
}
private List<AffinityGroupJoinVO> listDomainLevelAffinityGroups(
SearchCriteria<AffinityGroupJoinVO> sc, Filter searchFilter, long domainId) {
List<Long> affinityGroupIds = new ArrayList<Long>();
Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId);
List<AffinityGroupDomainMapVO> maps = _affinityGroupDomainMapDao.listByDomain(allowedDomains.toArray());
for (AffinityGroupDomainMapVO map : maps) {
boolean subdomainAccess = map.isSubdomainAccess();
if (map.getDomainId() == domainId || subdomainAccess) {
affinityGroupIds.add(map.getAffinityGroupId());
}
}
if (!affinityGroupIds.isEmpty()) {
SearchCriteria<AffinityGroupJoinVO> domainSC = _affinityGroupJoinDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, affinityGroupIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc,
searchFilter);
// search group by ids
Integer count = uniqueGroupsPair.second();
if (count.intValue() == 0) {
// empty result
return new ArrayList<AffinityGroupJoinVO>();
}
List<AffinityGroupJoinVO> uniqueGroups = uniqueGroupsPair.first();
Long[] vrIds = new Long[uniqueGroups.size()];
int i = 0;
for (AffinityGroupJoinVO v : uniqueGroups) {
vrIds[i++] = v.getId();
}
List<AffinityGroupJoinVO> vrs = _affinityGroupJoinDao.searchByIds(vrIds);
return vrs;
} else {
return new ArrayList<AffinityGroupJoinVO>();
}
}
@Override
public List<ResourceDetailResponse> listResource(ListResourceDetailsCmd cmd) {
String key = cmd.getKey();
ResourceTag.TaggedResourceType resourceType = cmd.getResourceType();
String resourceId = cmd.getResourceId();
Long id = _taggedResourceMgr.getResourceId(resourceId, resourceType);
if (resourceType == ResourceTag.TaggedResourceType.Volume) {
List<VolumeDetailVO> volumeDetailList;
if (key == null) {
volumeDetailList = _volumeDetailDao.findDetails(id);
} else {
VolumeDetailVO volumeDetail = _volumeDetailDao.findDetail(id, key);
volumeDetailList = new LinkedList<VolumeDetailVO>();
volumeDetailList.add(volumeDetail);
}
List<ResourceDetailResponse> volumeDetailResponseList = new ArrayList<ResourceDetailResponse>();
for (VolumeDetailVO volumeDetail : volumeDetailList) {
ResourceDetailResponse volumeDetailResponse = new ResourceDetailResponse();
volumeDetailResponse.setResourceId(id.toString());
volumeDetailResponse.setName(volumeDetail.getName());
volumeDetailResponse.setValue(volumeDetail.getValue());
volumeDetailResponse.setResourceType(ResourceTag.TaggedResourceType.Volume.toString());
volumeDetailResponse.setObjectName("volumedetail");
volumeDetailResponseList.add(volumeDetailResponse);
}
return volumeDetailResponseList;
} else {
List<NicDetailVO> nicDetailList;
if (key == null) {
nicDetailList = _nicDetailDao.findDetails(id);
} else {
NicDetailVO nicDetail = _nicDetailDao.findDetail(id, key);
nicDetailList = new LinkedList<NicDetailVO>();
nicDetailList.add(nicDetail);
}
List<ResourceDetailResponse> nicDetailResponseList = new ArrayList<ResourceDetailResponse>();
for (NicDetailVO nicDetail : nicDetailList) {
ResourceDetailResponse nicDetailResponse = new ResourceDetailResponse();
// String uuid = ApiDBUtils.findN
nicDetailResponse.setName(nicDetail.getName());
nicDetailResponse.setValue(nicDetail.getValue());
nicDetailResponse.setResourceType(ResourceTag.TaggedResourceType.Nic.toString());
nicDetailResponse.setObjectName("nicdetail");
nicDetailResponseList.add(nicDetailResponse);
}
return nicDetailResponseList;
}
}
}
| server/src/com/cloud/api/query/QueryManagerImpl.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 com.cloud.api.query;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.affinity.AffinityGroupDomainMapVO;
import org.apache.cloudstack.affinity.AffinityGroupResponse;
import org.apache.cloudstack.affinity.AffinityGroupVMMapVO;
import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd;
import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd;
import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
import org.apache.cloudstack.api.command.user.iso.ListIsosCmd;
import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd;
import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd;
import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd;
import org.apache.cloudstack.api.command.user.project.ListProjectsCmd;
import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd;
import org.apache.cloudstack.api.command.user.tag.ListTagsCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd;
import org.apache.cloudstack.api.command.user.vm.ListVMsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
import org.apache.cloudstack.api.response.AccountResponse;
import org.apache.cloudstack.api.response.AsyncJobResponse;
import org.apache.cloudstack.api.response.DiskOfferingResponse;
import org.apache.cloudstack.api.response.DomainRouterResponse;
import org.apache.cloudstack.api.response.EventResponse;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import org.apache.cloudstack.api.response.InstanceGroupResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.ProjectAccountResponse;
import org.apache.cloudstack.api.response.ProjectInvitationResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.api.response.ResourceDetailResponse;
import org.apache.cloudstack.api.response.ResourceTagResponse;
import org.apache.cloudstack.api.response.SecurityGroupResponse;
import org.apache.cloudstack.api.response.ServiceOfferingResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.api.response.TemplateResponse;
import org.apache.cloudstack.api.response.UserResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.VolumeResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
import org.apache.cloudstack.query.QueryService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.query.dao.AccountJoinDao;
import com.cloud.api.query.dao.AffinityGroupJoinDao;
import com.cloud.api.query.dao.AsyncJobJoinDao;
import com.cloud.api.query.dao.DataCenterJoinDao;
import com.cloud.api.query.dao.DiskOfferingJoinDao;
import com.cloud.api.query.dao.DomainRouterJoinDao;
import com.cloud.api.query.dao.HostJoinDao;
import com.cloud.api.query.dao.ImageStoreJoinDao;
import com.cloud.api.query.dao.InstanceGroupJoinDao;
import com.cloud.api.query.dao.ProjectAccountJoinDao;
import com.cloud.api.query.dao.ProjectInvitationJoinDao;
import com.cloud.api.query.dao.ProjectJoinDao;
import com.cloud.api.query.dao.ResourceTagJoinDao;
import com.cloud.api.query.dao.SecurityGroupJoinDao;
import com.cloud.api.query.dao.ServiceOfferingJoinDao;
import com.cloud.api.query.dao.StoragePoolJoinDao;
import com.cloud.api.query.dao.TemplateJoinDao;
import com.cloud.api.query.dao.UserAccountJoinDao;
import com.cloud.api.query.dao.UserVmJoinDao;
import com.cloud.api.query.dao.VolumeJoinDao;
import com.cloud.api.query.vo.AccountJoinVO;
import com.cloud.api.query.vo.AffinityGroupJoinVO;
import com.cloud.api.query.vo.AsyncJobJoinVO;
import com.cloud.api.query.vo.DataCenterJoinVO;
import com.cloud.api.query.vo.DiskOfferingJoinVO;
import com.cloud.api.query.vo.DomainRouterJoinVO;
import com.cloud.api.query.vo.EventJoinVO;
import com.cloud.api.query.vo.HostJoinVO;
import com.cloud.api.query.vo.ImageStoreJoinVO;
import com.cloud.api.query.vo.InstanceGroupJoinVO;
import com.cloud.api.query.vo.ProjectAccountJoinVO;
import com.cloud.api.query.vo.ProjectInvitationJoinVO;
import com.cloud.api.query.vo.ProjectJoinVO;
import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.SecurityGroupJoinVO;
import com.cloud.api.query.vo.ServiceOfferingJoinVO;
import com.cloud.api.query.vo.StoragePoolJoinVO;
import com.cloud.api.query.vo.TemplateJoinVO;
import com.cloud.api.query.vo.UserAccountJoinVO;
import com.cloud.api.query.vo.UserVmJoinVO;
import com.cloud.api.query.vo.VolumeJoinVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DedicatedResourceVO;
import com.cloud.dc.dao.DedicatedResourceDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.dao.EventJoinDao;
import com.cloud.exception.CloudAuthenticationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.dao.NetworkDomainVO;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.security.SecurityGroupVMMapVO;
import com.cloud.network.security.dao.SecurityGroupVMMapDao;
import com.cloud.org.Grouping;
import com.cloud.projects.Project;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.projects.ProjectInvitation;
import com.cloud.projects.ProjectManager;
import com.cloud.projects.dao.ProjectAccountDao;
import com.cloud.projects.dao.ProjectDao;
import com.cloud.resource.ResourceManager;
import com.cloud.server.Criteria;
import com.cloud.server.ResourceMetaDataService;
import com.cloud.server.ResourceTag;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.server.TaggedResourceService;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeDetailVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDetailsDao;
import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.DomainManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicDetailVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDetailDao;
import com.cloud.vm.dao.UserVmDao;
@Component
@Local(value = { QueryService.class })
public class QueryManagerImpl extends ManagerBase implements QueryService {
public static final Logger s_logger = Logger.getLogger(QueryManagerImpl.class);
// public static ViewResponseHelper _responseGenerator;
@Inject
private AccountManager _accountMgr;
@Inject
private ProjectManager _projectMgr;
@Inject
private DomainDao _domainDao;
@Inject
private UserAccountJoinDao _userAccountJoinDao;
@Inject
private EventJoinDao _eventJoinDao;
@Inject
private ResourceTagJoinDao _resourceTagJoinDao;
@Inject
private InstanceGroupJoinDao _vmGroupJoinDao;
@Inject
private UserVmJoinDao _userVmJoinDao;
@Inject
private UserVmDao _userVmDao;
@Inject
private SecurityGroupJoinDao _securityGroupJoinDao;
@Inject
private SecurityGroupVMMapDao _securityGroupVMMapDao;
@Inject
private DomainRouterJoinDao _routerJoinDao;
@Inject
private ProjectInvitationJoinDao _projectInvitationJoinDao;
@Inject
private ProjectJoinDao _projectJoinDao;
@Inject
private ProjectDao _projectDao;
@Inject
private ProjectAccountDao _projectAccountDao;
@Inject
private ProjectAccountJoinDao _projectAccountJoinDao;
@Inject
private HostJoinDao _hostJoinDao;
@Inject
private VolumeJoinDao _volumeJoinDao;
@Inject
private AccountDao _accountDao;
@Inject
private ConfigurationDao _configDao;
@Inject
private AccountJoinDao _accountJoinDao;
@Inject
private AsyncJobJoinDao _jobJoinDao;
@Inject
private StoragePoolJoinDao _poolJoinDao;
@Inject
private ImageStoreJoinDao _imageStoreJoinDao;
@Inject
private DiskOfferingJoinDao _diskOfferingJoinDao;
@Inject
private ServiceOfferingJoinDao _srvOfferingJoinDao;
@Inject
private ServiceOfferingDao _srvOfferingDao;
@Inject
private DataCenterJoinDao _dcJoinDao;
@Inject
private DomainRouterDao _routerDao;
@Inject
private VolumeDetailsDao _volumeDetailDao;
@Inject
private NicDetailDao _nicDetailDao;
@Inject
private HighAvailabilityManager _haMgr;
@Inject
private VMTemplateDao _templateDao;
@Inject
private TemplateJoinDao _templateJoinDao;
@Inject
ResourceManager _resourceMgr;
@Inject
private ResourceMetaDataService _resourceMetaDataMgr;
@Inject
private TaggedResourceService _taggedResourceMgr;
@Inject
AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
private AffinityGroupJoinDao _affinityGroupJoinDao;
@Inject
private DedicatedResourceDao _dedicatedDao;
@Inject
DomainManager _domainMgr;
@Inject
AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
/*
* (non-Javadoc)
*
* @see
* com.cloud.api.query.QueryService#searchForUsers(org.apache.cloudstack
* .api.command.admin.user.ListUsersCmd)
*/
@Override
public ListResponse<UserResponse> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException {
Pair<List<UserAccountJoinVO>, Integer> result = searchForUsersInternal(cmd);
ListResponse<UserResponse> response = new ListResponse<UserResponse>();
List<UserResponse> userResponses = ViewResponseHelper.createUserResponse(result.first().toArray(
new UserAccountJoinVO[result.first().size()]));
response.setResponses(userResponses, result.second());
return response;
}
private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd)
throws PermissionDeniedException {
Account caller = UserContext.current().getCaller();
// TODO: Integrate with ACL checkAccess refactoring
Long domainId = cmd.getDomainId();
if (domainId != null) {
Domain domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by id=" + domainId);
}
_accountMgr.checkAccess(caller, domain);
} else {
// default domainId to the caller's domain
domainId = caller.getDomainId();
}
Filter searchFilter = new Filter(UserAccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
Long id = cmd.getId();
Object username = cmd.getUsername();
Object type = cmd.getAccountType();
Object accountName = cmd.getAccountName();
Object state = cmd.getState();
Object keyword = cmd.getKeyword();
SearchBuilder<UserAccountJoinVO> sb = _userAccountJoinDao.createSearchBuilder();
sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE);
if (id != null && id == 1) {
// system user should NOT be searchable
List<UserAccountJoinVO> emptyList = new ArrayList<UserAccountJoinVO>();
return new Pair<List<UserAccountJoinVO>, Integer>(emptyList, 0);
} else if (id != null) {
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
} else {
// this condition is used to exclude system user from the search
// results
sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ);
}
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
if ((accountName == null) && (domainId != null)) {
sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
SearchCriteria<UserAccountJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<UserAccountJoinVO> ssc = _userAccountJoinDao.createSearchCriteria();
ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("username", SearchCriteria.Op.SC, ssc);
}
if (username != null) {
sc.setParameters("username", username);
}
if (id != null) {
sc.setParameters("id", id);
} else {
// Don't return system user, search builder with NEQ
sc.setParameters("id", 1);
}
if (type != null) {
sc.setParameters("type", type);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
if (domainId != null) {
sc.setParameters("domainId", domainId);
}
} else if (domainId != null) {
DomainVO domainVO = _domainDao.findById(domainId);
sc.setParameters("domainPath", domainVO.getPath() + "%");
}
if (state != null) {
sc.setParameters("state", state);
}
return _userAccountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<EventResponse> searchForEvents(ListEventsCmd cmd) {
Pair<List<EventJoinVO>, Integer> result = searchForEventsInternal(cmd);
ListResponse<EventResponse> response = new ListResponse<EventResponse>();
List<EventResponse> eventResponses = ViewResponseHelper.createEventResponse(result.first().toArray(
new EventJoinVO[result.first().size()]));
response.setResponses(eventResponses, result.second());
return response;
}
private Pair<List<EventJoinVO>, Integer> searchForEventsInternal(ListEventsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Long id = cmd.getId();
String type = cmd.getType();
String level = cmd.getLevel();
Date startDate = cmd.getStartDate();
Date endDate = cmd.getEndDate();
String keyword = cmd.getKeyword();
Integer entryTime = cmd.getEntryTime();
Integer duration = cmd.getDuration();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<EventJoinVO> sb = _eventJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE);
sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ);
sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ);
sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
sb.and("archived", sb.entity().getArchived(), SearchCriteria.Op.EQ);
SearchCriteria<EventJoinVO> sc = sb.create();
// building ACL condition
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (keyword != null) {
SearchCriteria<EventJoinVO> ssc = _eventJoinDao.createSearchCriteria();
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("level", SearchCriteria.Op.SC, ssc);
}
if (level != null) {
sc.setParameters("levelEQ", level);
}
if (type != null) {
sc.setParameters("type", type);
}
if (startDate != null && endDate != null) {
sc.setParameters("createDateB", startDate, endDate);
} else if (startDate != null) {
sc.setParameters("createDateG", startDate);
} else if (endDate != null) {
sc.setParameters("createDateL", endDate);
}
sc.setParameters("archived", false);
Pair<List<EventJoinVO>, Integer> eventPair = null;
// event_view will not have duplicate rows for each event, so
// searchAndCount should be good enough.
if ((entryTime != null) && (duration != null)) {
// TODO: waiting for response from dev list, logic is mystery to
// me!!
/*
* if (entryTime <= duration) { throw new
* InvalidParameterValueException
* ("Entry time must be greater than duration"); } Calendar calMin =
* Calendar.getInstance(); Calendar calMax = Calendar.getInstance();
* calMin.add(Calendar.SECOND, -entryTime);
* calMax.add(Calendar.SECOND, -duration); Date minTime =
* calMin.getTime(); Date maxTime = calMax.getTime();
*
* sc.setParameters("state", com.cloud.event.Event.State.Completed);
* sc.setParameters("startId", 0); sc.setParameters("createDate",
* minTime, maxTime); List<EventJoinVO> startedEvents =
* _eventJoinDao.searchAllEvents(sc, searchFilter);
* List<EventJoinVO> pendingEvents = new ArrayList<EventJoinVO>();
* for (EventVO event : startedEvents) { EventVO completedEvent =
* _eventDao.findCompletedEvent(event.getId()); if (completedEvent
* == null) { pendingEvents.add(event); } } return pendingEvents;
*/
} else {
eventPair = _eventJoinDao.searchAndCount(sc, searchFilter);
}
return eventPair;
}
@Override
public ListResponse<ResourceTagResponse> listTags(ListTagsCmd cmd) {
Pair<List<ResourceTagJoinVO>, Integer> tags = listTagsInternal(cmd);
ListResponse<ResourceTagResponse> response = new ListResponse<ResourceTagResponse>();
List<ResourceTagResponse> tagResponses = ViewResponseHelper.createResourceTagResponse(false, tags.first()
.toArray(new ResourceTagJoinVO[tags.first().size()]));
response.setResponses(tagResponses, tags.second());
return response;
}
private Pair<List<ResourceTagJoinVO>, Integer> listTagsInternal(ListTagsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
String key = cmd.getKey();
String value = cmd.getValue();
String resourceId = cmd.getResourceId();
String resourceType = cmd.getResourceType();
String customerName = cmd.getCustomer();
boolean listAll = cmd.listAll();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, listAll, false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(ResourceTagJoinVO.class, "resourceType", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<ResourceTagJoinVO> sb = _resourceTagJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ);
sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ);
if (resourceId != null) {
sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ);
sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ);
sb.cp();
}
sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ);
// now set the SC criteria...
SearchCriteria<ResourceTagJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (key != null) {
sc.setParameters("key", key);
}
if (value != null) {
sc.setParameters("value", value);
}
if (resourceId != null) {
sc.setParameters("resourceId", resourceId);
sc.setParameters("resourceUuid", resourceId);
}
if (resourceType != null) {
sc.setParameters("resourceType", resourceType);
}
if (customerName != null) {
sc.setParameters("customer", customerName);
}
Pair<List<ResourceTagJoinVO>, Integer> result = _resourceTagJoinDao.searchAndCount(sc, searchFilter);
return result;
}
@Override
public ListResponse<InstanceGroupResponse> searchForVmGroups(ListVMGroupsCmd cmd) {
Pair<List<InstanceGroupJoinVO>, Integer> groups = searchForVmGroupsInternal(cmd);
ListResponse<InstanceGroupResponse> response = new ListResponse<InstanceGroupResponse>();
List<InstanceGroupResponse> grpResponses = ViewResponseHelper.createInstanceGroupResponse(groups.first()
.toArray(new InstanceGroupJoinVO[groups.first().size()]));
response.setResponses(grpResponses, groups.second());
return response;
}
private Pair<List<InstanceGroupJoinVO>, Integer> searchForVmGroupsInternal(ListVMGroupsCmd cmd) {
Long id = cmd.getId();
String name = cmd.getGroupName();
String keyword = cmd.getKeyword();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(InstanceGroupJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<InstanceGroupJoinVO> sb = _vmGroupJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
SearchCriteria<InstanceGroupJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<InstanceGroupJoinVO> ssc = _vmGroupJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
return _vmGroupJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<UserVmResponse> searchForUserVMs(ListVMsCmd cmd) {
Pair<List<UserVmJoinVO>, Integer> result = searchForUserVMsInternal(cmd);
ListResponse<UserVmResponse> response = new ListResponse<UserVmResponse>();
List<UserVmResponse> vmResponses = ViewResponseHelper.createUserVmResponse("virtualmachine", cmd.getDetails(),
result.first().toArray(new UserVmJoinVO[result.first().size()]));
response.setResponses(vmResponses, result.second());
return response;
}
private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsInternal(ListVMsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
String hypervisor = cmd.getHypervisor();
boolean listAll = cmd.listAll();
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, listAll, false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal());
// Criteria c = new Criteria(null, Boolean.FALSE, cmd.getStartIndex(),
// cmd.getPageSizeVal()); //version without default sorting
c.addCriteria(Criteria.KEYWORD, cmd.getKeyword());
c.addCriteria(Criteria.ID, cmd.getId());
c.addCriteria(Criteria.NAME, cmd.getName());
c.addCriteria(Criteria.STATE, cmd.getState());
c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId());
c.addCriteria(Criteria.GROUPID, cmd.getGroupId());
c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork());
c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId());
c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId());
c.addCriteria(Criteria.ISO_ID, cmd.getIsoId());
c.addCriteria(Criteria.VPC_ID, cmd.getVpcId());
c.addCriteria(Criteria.AFFINITY_GROUP_ID, cmd.getAffinityGroupId());
if (domainId != null) {
c.addCriteria(Criteria.DOMAINID, domainId);
}
if (HypervisorType.getType(hypervisor) != HypervisorType.None) {
c.addCriteria(Criteria.HYPERVISOR, hypervisor);
} else if (hypervisor != null) {
throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor);
}
// ignore these search requests if it's not an admin
if (_accountMgr.isAdmin(caller.getType())) {
c.addCriteria(Criteria.PODID, cmd.getPodId());
c.addCriteria(Criteria.HOSTID, cmd.getHostId());
c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId());
}
if (!permittedAccounts.isEmpty()) {
c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray());
}
c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType()));
return searchForUserVMsByCriteria(c, caller, domainId, isRecursive, permittedAccounts, listAll,
listProjectResourcesCriteria, tags);
}
private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsByCriteria(Criteria c, Account caller, Long domainId,
boolean isRecursive, List<Long> permittedAccounts, boolean listAll,
ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(),
c.getLimit());
// first search distinct vm id by using query criteria and pagination
SearchBuilder<UserVmJoinVO> sb = _userVmJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
Object id = c.getCriteria(Criteria.ID);
Object name = c.getCriteria(Criteria.NAME);
Object state = c.getCriteria(Criteria.STATE);
Object notState = c.getCriteria(Criteria.NOTSTATE);
Object zoneId = c.getCriteria(Criteria.DATACENTERID);
Object pod = c.getCriteria(Criteria.PODID);
Object hostId = c.getCriteria(Criteria.HOSTID);
Object hostName = c.getCriteria(Criteria.HOSTNAME);
Object keyword = c.getCriteria(Criteria.KEYWORD);
Object isAdmin = c.getCriteria(Criteria.ISADMIN);
assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table.";
Object groupId = c.getCriteria(Criteria.GROUPID);
Object networkId = c.getCriteria(Criteria.NETWORKID);
Object hypervisor = c.getCriteria(Criteria.HYPERVISOR);
Object storageId = c.getCriteria(Criteria.STORAGE_ID);
Object templateId = c.getCriteria(Criteria.TEMPLATE_ID);
Object isoId = c.getCriteria(Criteria.ISO_ID);
Object vpcId = c.getCriteria(Criteria.VPC_ID);
Object affinityGroupId = c.getCriteria(Criteria.AFFINITY_GROUP_ID);
sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ);
sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ);
sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
if (groupId != null && (Long) groupId != -1) {
sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
}
if (networkId != null) {
sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
}
if (vpcId != null && networkId == null) {
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
}
if (storageId != null) {
sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ);
}
if (affinityGroupId != null) {
sb.and("affinityGroupId", sb.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
}
// populate the search criteria with the values passed in
SearchCriteria<UserVmJoinVO> sc = sb.create();
// building ACL condition
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (tags != null && !tags.isEmpty()) {
SearchCriteria<UserVmJoinVO> tagSc = _userVmJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<UserVmJoinVO> tsc = _userVmJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (groupId != null && (Long) groupId != -1) {
sc.setParameters("instanceGroupId", groupId);
}
if (keyword != null) {
SearchCriteria<UserVmJoinVO> ssc = _userVmJoinDao.createSearchCriteria();
ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.EQ, keyword);
sc.addAnd("displayName", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (templateId != null) {
sc.setParameters("templateId", templateId);
}
if (isoId != null) {
sc.setParameters("isoId", isoId);
}
if (networkId != null) {
sc.setParameters("networkId", networkId);
}
if (vpcId != null && networkId == null) {
sc.setParameters("vpcId", vpcId);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (state != null) {
if (notState != null && (Boolean) notState == true) {
sc.setParameters("stateNEQ", state);
} else {
sc.setParameters("stateEQ", state);
}
}
if (hypervisor != null) {
sc.setParameters("hypervisorType", hypervisor);
}
// Don't show Destroyed and Expunging vms to the end user
if ((isAdmin != null) && ((Boolean) isAdmin != true)) {
sc.setParameters("stateNIN", "Destroyed", "Expunging");
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
if (state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (pod != null) {
sc.setParameters("podId", pod);
if (state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (hostId != null) {
sc.setParameters("hostIdEQ", hostId);
} else {
if (hostName != null) {
sc.setParameters("hostName", hostName);
}
}
if (storageId != null) {
sc.setParameters("poolId", storageId);
}
if (affinityGroupId != null) {
sc.setParameters("affinityGroupId", affinityGroupId);
}
// search vm details by ids
Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVmPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueVmPair;
}
List<UserVmJoinVO> uniqueVms = uniqueVmPair.first();
Long[] vmIds = new Long[uniqueVms.size()];
int i = 0;
for (UserVmJoinVO v : uniqueVms) {
vmIds[i++] = v.getId();
}
List<UserVmJoinVO> vms = _userVmJoinDao.searchByIds(vmIds);
return new Pair<List<UserVmJoinVO>, Integer>(vms, count);
}
@Override
public ListResponse<SecurityGroupResponse> searchForSecurityGroups(ListSecurityGroupsCmd cmd) {
Pair<List<SecurityGroupJoinVO>, Integer> result = searchForSecurityGroupsInternal(cmd);
ListResponse<SecurityGroupResponse> response = new ListResponse<SecurityGroupResponse>();
List<SecurityGroupResponse> routerResponses = ViewResponseHelper.createSecurityGroupResponses(result.first());
response.setResponses(routerResponses, result.second());
return response;
}
private Pair<List<SecurityGroupJoinVO>, Integer> searchForSecurityGroupsInternal(ListSecurityGroupsCmd cmd)
throws PermissionDeniedException, InvalidParameterValueException {
Account caller = UserContext.current().getCaller();
Long instanceId = cmd.getVirtualMachineId();
String securityGroup = cmd.getSecurityGroupName();
Long id = cmd.getId();
Object keyword = cmd.getKeyword();
List<Long> permittedAccounts = new ArrayList<Long>();
Map<String, String> tags = cmd.getTags();
if (instanceId != null) {
UserVmVO userVM = _userVmDao.findById(instanceId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance "
+ instanceId + "; instance not found.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal());
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(SecurityGroupJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchBuilder<SecurityGroupJoinVO> sb = _securityGroupJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
SearchCriteria<SecurityGroupJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (tags != null && !tags.isEmpty()) {
SearchCriteria<SecurityGroupJoinVO> tagSc = _securityGroupJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<SecurityGroupJoinVO> tsc = _securityGroupJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (securityGroup != null) {
sc.setParameters("name", securityGroup);
}
if (keyword != null) {
SearchCriteria<SecurityGroupJoinVO> ssc = _securityGroupJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
// search security group together with rules
Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueSgPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueSgPair;
}
List<SecurityGroupJoinVO> uniqueSgs = uniqueSgPair.first();
Long[] sgIds = new Long[uniqueSgs.size()];
int i = 0;
for (SecurityGroupJoinVO v : uniqueSgs) {
sgIds[i++] = v.getId();
}
List<SecurityGroupJoinVO> sgs = _securityGroupJoinDao.searchByIds(sgIds);
return new Pair<List<SecurityGroupJoinVO>, Integer>(sgs, count);
}
private Pair<List<SecurityGroupJoinVO>, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) {
Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize);
Pair<List<SecurityGroupVMMapVO>, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf);
Integer count = sgVmMappingPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return new Pair<List<SecurityGroupJoinVO>, Integer>(new ArrayList<SecurityGroupJoinVO>(), count);
}
List<SecurityGroupVMMapVO> sgVmMappings = sgVmMappingPair.first();
Long[] sgIds = new Long[sgVmMappings.size()];
int i = 0;
for (SecurityGroupVMMapVO sgVm : sgVmMappings) {
sgIds[i++] = sgVm.getSecurityGroupId();
}
List<SecurityGroupJoinVO> sgs = _securityGroupJoinDao.searchByIds(sgIds);
return new Pair<List<SecurityGroupJoinVO>, Integer>(sgs, count);
}
@Override
public ListResponse<DomainRouterResponse> searchForRouters(ListRoutersCmd cmd) {
Pair<List<DomainRouterJoinVO>, Integer> result = searchForRoutersInternal(cmd, cmd.getId(), cmd.getRouterName(),
cmd.getState(), cmd.getZoneId(), cmd.getPodId(), cmd.getHostId(), cmd.getKeyword(), cmd.getNetworkId(),
cmd.getVpcId(), cmd.getForVpc(), cmd.getRole());
ListResponse<DomainRouterResponse> response = new ListResponse<DomainRouterResponse>();
List<DomainRouterResponse> routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first()
.toArray(new DomainRouterJoinVO[result.first().size()]));
response.setResponses(routerResponses, result.second());
return response;
}
@Override
public ListResponse<DomainRouterResponse> searchForInternalLbVms(ListInternalLBVMsCmd cmd) {
Pair<List<DomainRouterJoinVO>, Integer> result = searchForRoutersInternal(cmd, cmd.getId(), cmd.getRouterName(),
cmd.getState(), cmd.getZoneId(), cmd.getPodId(), cmd.getHostId(), cmd.getKeyword(), cmd.getNetworkId(),
cmd.getVpcId(), cmd.getForVpc(), cmd.getRole());
ListResponse<DomainRouterResponse> response = new ListResponse<DomainRouterResponse>();
List<DomainRouterResponse> routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first()
.toArray(new DomainRouterJoinVO[result.first().size()]));
response.setResponses(routerResponses, result.second());
return response;
}
private Pair<List<DomainRouterJoinVO>, Integer> searchForRoutersInternal(BaseListProjectAndAccountResourcesCmd cmd, Long id,
String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id", true, cmd.getStartIndex(),
cmd.getPageSizeVal());
// Filter searchFilter = new Filter(DomainRouterJoinVO.class, null,
// true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<DomainRouterJoinVO> sb = _routerJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids to get
// number of
// records with
// pagination
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("name", sb.entity().getInstanceName(), SearchCriteria.Op.LIKE);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ);
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
if (forVpc != null) {
if (forVpc) {
sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL);
} else {
sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL);
}
}
if (networkId != null) {
sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
}
SearchCriteria<DomainRouterJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<DomainRouterJoinVO> ssc = _routerJoinDao.createSearchCriteria();
ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("hostName", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (id != null) {
sc.setParameters("id", id);
}
if (state != null) {
sc.setParameters("state", state);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
if (hostId != null) {
sc.setParameters("hostId", hostId);
}
if (networkId != null) {
sc.setParameters("networkId", networkId);
}
if (vpcId != null) {
sc.setParameters("vpcId", vpcId);
}
if (role != null) {
sc.setParameters("role", role);
}
// search VR details by ids
Pair<List<DomainRouterJoinVO>, Integer> uniqueVrPair = _routerJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVrPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueVrPair;
}
List<DomainRouterJoinVO> uniqueVrs = uniqueVrPair.first();
Long[] vrIds = new Long[uniqueVrs.size()];
int i = 0;
for (DomainRouterJoinVO v : uniqueVrs) {
vrIds[i++] = v.getId();
}
List<DomainRouterJoinVO> vrs = _routerJoinDao.searchByIds(vrIds);
return new Pair<List<DomainRouterJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ProjectResponse> listProjects(ListProjectsCmd cmd) {
Pair<List<ProjectJoinVO>, Integer> projects = listProjectsInternal(cmd);
ListResponse<ProjectResponse> response = new ListResponse<ProjectResponse>();
List<ProjectResponse> projectResponses = ViewResponseHelper.createProjectResponse(projects.first().toArray(
new ProjectJoinVO[projects.first().size()]));
response.setResponses(projectResponses, projects.second());
return response;
}
private Pair<List<ProjectJoinVO>, Integer> listProjectsInternal(ListProjectsCmd cmd) {
Long id = cmd.getId();
String name = cmd.getName();
String displayText = cmd.getDisplayText();
String state = cmd.getState();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
String keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
boolean listAll = cmd.listAll();
boolean isRecursive = cmd.isRecursive();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
Long accountId = null;
String path = null;
Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize);
SearchBuilder<ProjectJoinVO> sb = _projectJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
if (_accountMgr.isAdmin(caller.getType())) {
if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
if (owner == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName
+ " in domain " + domainId);
}
accountId = owner.getId();
}
} else { // domainId == null
if (accountName != null) {
throw new InvalidParameterValueException("could not find account " + accountName
+ " because domain is not specified");
}
}
} else {
if (accountName != null && !accountName.equals(caller.getAccountName())) {
throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized");
}
if (domainId != null && domainId.equals(caller.getDomainId())) {
throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized");
}
accountId = caller.getId();
}
if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) {
accountId = caller.getId();
} else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) {
DomainVO domain = _domainDao.findById(caller.getDomainId());
path = domain.getPath();
}
if (path != null) {
sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
if (accountId != null) {
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
}
SearchCriteria<ProjectJoinVO> sc = sb.create();
if (id != null) {
sc.addAnd("id", Op.EQ, id);
}
if (domainId != null && !isRecursive) {
sc.addAnd("domainId", Op.EQ, domainId);
}
if (name != null) {
sc.addAnd("name", Op.EQ, name);
}
if (displayText != null) {
sc.addAnd("displayText", Op.EQ, displayText);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (state != null) {
sc.addAnd("state", Op.EQ, state);
}
if (keyword != null) {
SearchCriteria<ProjectJoinVO> ssc = _projectJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (path != null) {
sc.setParameters("domainPath", path);
}
// search distinct projects to get count
Pair<List<ProjectJoinVO>, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniquePrjPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniquePrjPair;
}
List<ProjectJoinVO> uniquePrjs = uniquePrjPair.first();
Long[] prjIds = new Long[uniquePrjs.size()];
int i = 0;
for (ProjectJoinVO v : uniquePrjs) {
prjIds[i++] = v.getId();
}
List<ProjectJoinVO> prjs = _projectJoinDao.searchByIds(prjIds);
return new Pair<List<ProjectJoinVO>, Integer>(prjs, count);
}
@Override
public ListResponse<ProjectInvitationResponse> listProjectInvitations(ListProjectInvitationsCmd cmd) {
Pair<List<ProjectInvitationJoinVO>, Integer> invites = listProjectInvitationsInternal(cmd);
ListResponse<ProjectInvitationResponse> response = new ListResponse<ProjectInvitationResponse>();
List<ProjectInvitationResponse> projectInvitationResponses = ViewResponseHelper
.createProjectInvitationResponse(invites.first().toArray(
new ProjectInvitationJoinVO[invites.first().size()]));
response.setResponses(projectInvitationResponses, invites.second());
return response;
}
public Pair<List<ProjectInvitationJoinVO>, Integer> listProjectInvitationsInternal(ListProjectInvitationsCmd cmd) {
Long id = cmd.getId();
Long projectId = cmd.getProjectId();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
String state = cmd.getState();
boolean activeOnly = cmd.isActiveOnly();
Long startIndex = cmd.getStartIndex();
Long pageSizeVal = cmd.getPageSizeVal();
boolean isRecursive = cmd.isRecursive();
boolean listAll = cmd.listAll();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts,
domainIdRecursiveListProject, listAll, true);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(ProjectInvitationJoinVO.class, "id", true, startIndex, pageSizeVal);
SearchBuilder<ProjectInvitationJoinVO> sb = _projectInvitationJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
SearchCriteria<ProjectInvitationJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (projectId != null) {
sc.setParameters("projectId", projectId);
}
if (state != null) {
sc.setParameters("state", state);
}
if (id != null) {
sc.setParameters("id", id);
}
if (activeOnly) {
sc.setParameters("state", ProjectInvitation.State.Pending);
sc.setParameters("created",
new Date((DateUtil.currentGMTTime().getTime()) - _projectMgr.getInvitationTimeout()));
}
return _projectInvitationJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ProjectAccountResponse> listProjectAccounts(ListProjectAccountsCmd cmd) {
Pair<List<ProjectAccountJoinVO>, Integer> projectAccounts = listProjectAccountsInternal(cmd);
ListResponse<ProjectAccountResponse> response = new ListResponse<ProjectAccountResponse>();
List<ProjectAccountResponse> projectResponses = ViewResponseHelper.createProjectAccountResponse(projectAccounts
.first().toArray(new ProjectAccountJoinVO[projectAccounts.first().size()]));
response.setResponses(projectResponses, projectAccounts.second());
return response;
}
public Pair<List<ProjectAccountJoinVO>, Integer> listProjectAccountsInternal(ListProjectAccountsCmd cmd) {
long projectId = cmd.getProjectId();
String accountName = cmd.getAccountName();
String role = cmd.getRole();
Long startIndex = cmd.getStartIndex();
Long pageSizeVal = cmd.getPageSizeVal();
// long projectId, String accountName, String role, Long startIndex,
// Long pageSizeVal) {
Account caller = UserContext.current().getCaller();
// check that the project exists
Project project = _projectDao.findById(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find the project id=" + projectId);
}
// verify permissions - only accounts belonging to the project can list
// project's account
if (!_accountMgr.isAdmin(caller.getType())
&& _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) {
throw new PermissionDeniedException("Account " + caller
+ " is not authorized to list users of the project id=" + projectId);
}
Filter searchFilter = new Filter(ProjectAccountJoinVO.class, "id", false, startIndex, pageSizeVal);
SearchBuilder<ProjectAccountJoinVO> sb = _projectAccountJoinDao.createSearchBuilder();
sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ);
sb.and("projectId", sb.entity().getProjectId(), Op.EQ);
SearchBuilder<AccountVO> accountSearch;
if (accountName != null) {
sb.and("accountName", sb.entity().getAccountName(), Op.EQ);
}
SearchCriteria<ProjectAccountJoinVO> sc = sb.create();
sc.setParameters("projectId", projectId);
if (role != null) {
sc.setParameters("accountRole", role);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
}
return _projectAccountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<HostResponse> searchForServers(ListHostsCmd cmd) {
// FIXME: do we need to support list hosts with VmId, maybe we should
// create another command just for this
// Right now it is handled separately outside this QueryService
s_logger.debug(">>>Searching for hosts>>>");
Pair<List<HostJoinVO>, Integer> hosts = searchForServersInternal(cmd);
ListResponse<HostResponse> response = new ListResponse<HostResponse>();
s_logger.debug(">>>Generating Response>>>");
List<HostResponse> hostResponses = ViewResponseHelper.createHostResponse(cmd.getDetails(), hosts.first()
.toArray(new HostJoinVO[hosts.first().size()]));
response.setResponses(hostResponses, hosts.second());
return response;
}
public Pair<List<HostJoinVO>, Integer> searchForServersInternal(ListHostsCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object name = cmd.getHostName();
Object type = cmd.getType();
Object state = cmd.getState();
Object pod = cmd.getPodId();
Object cluster = cmd.getClusterId();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Object resourceState = cmd.getResourceState();
Object haHosts = cmd.getHaHost();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(HostJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<HostJoinVO> sb = _hostJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.LIKE);
sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ);
sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
String haTag = _haMgr.getHaTag();
if (haHosts != null && haTag != null && !haTag.isEmpty()) {
if ((Boolean) haHosts) {
sb.and("tag", sb.entity().getTag(), SearchCriteria.Op.EQ);
} else {
sb.and().op("tag", sb.entity().getTag(), SearchCriteria.Op.NEQ);
sb.or("tagNull", sb.entity().getTag(), SearchCriteria.Op.NULL);
sb.cp();
}
}
SearchCriteria<HostJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<HostJoinVO> ssc = _hostJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("status", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (type != null) {
sc.setParameters("type", "%" + type);
}
if (state != null) {
sc.setParameters("status", state);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (pod != null) {
sc.setParameters("podId", pod);
}
if (cluster != null) {
sc.setParameters("clusterId", cluster);
}
if (resourceState != null) {
sc.setParameters("resourceState", resourceState);
}
if (haHosts != null && haTag != null && !haTag.isEmpty()) {
sc.setJoinParameters("hostTagSearch", "tag", haTag);
}
// search host details by ids
Pair<List<HostJoinVO>, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueHostPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueHostPair;
}
List<HostJoinVO> uniqueHosts = uniqueHostPair.first();
Long[] hostIds = new Long[uniqueHosts.size()];
int i = 0;
for (HostJoinVO v : uniqueHosts) {
hostIds[i++] = v.getId();
}
List<HostJoinVO> hosts = _hostJoinDao.searchByIds(hostIds);
return new Pair<List<HostJoinVO>, Integer>(hosts, count);
}
@Override
public ListResponse<VolumeResponse> searchForVolumes(ListVolumesCmd cmd) {
Pair<List<VolumeJoinVO>, Integer> result = searchForVolumesInternal(cmd);
ListResponse<VolumeResponse> response = new ListResponse<VolumeResponse>();
List<VolumeResponse> volumeResponses = ViewResponseHelper.createVolumeResponse(result.first().toArray(
new VolumeJoinVO[result.first().size()]));
response.setResponses(volumeResponses, result.second());
return response;
}
private Pair<List<VolumeJoinVO>, Integer> searchForVolumesInternal(ListVolumesCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Long id = cmd.getId();
Long vmInstanceId = cmd.getVirtualMachineId();
String name = cmd.getVolumeName();
String keyword = cmd.getKeyword();
String type = cmd.getType();
Map<String, String> tags = cmd.getTags();
Long zoneId = cmd.getZoneId();
Long podId = null;
if (_accountMgr.isAdmin(caller.getType())) {
podId = cmd.getPodId();
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(VolumeJoinVO.class, "created", false, cmd.getStartIndex(),
cmd.getPageSizeVal());
// hack for now, this should be done better but due to needing a join I
// opted to
// do this quickly and worry about making it pretty later
SearchBuilder<VolumeJoinVO> sb = _volumeJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids to get
// number of
// records with
// pagination
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE);
sb.and("instanceId", sb.entity().getVmId(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
// Only return volumes that are not destroyed
sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("systemUse", sb.entity().isSystemUse(), SearchCriteria.Op.NEQ);
// display UserVM volumes only
sb.and().op("type", sb.entity().getVmType(), SearchCriteria.Op.NIN);
sb.or("nulltype", sb.entity().getVmType(), SearchCriteria.Op.NULL);
sb.cp();
// now set the SC criteria...
SearchCriteria<VolumeJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (keyword != null) {
SearchCriteria<VolumeJoinVO> ssc = _volumeJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.setParameters("name", name);
}
sc.setParameters("systemUse", 1);
if (tags != null && !tags.isEmpty()) {
SearchCriteria<VolumeJoinVO> tagSc = _volumeJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<VolumeJoinVO> tsc = _volumeJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (type != null) {
sc.setParameters("volumeType", "%" + type + "%");
}
if (vmInstanceId != null) {
sc.setParameters("instanceId", vmInstanceId);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
// Don't return DomR and ConsoleProxy volumes
sc.setParameters("type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm,
VirtualMachine.Type.DomainRouter);
// Only return volumes that are not destroyed
sc.setParameters("state", Volume.State.Destroy);
// search Volume details by ids
Pair<List<VolumeJoinVO>, Integer> uniqueVolPair = _volumeJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueVolPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueVolPair;
}
List<VolumeJoinVO> uniqueVols = uniqueVolPair.first();
Long[] vrIds = new Long[uniqueVols.size()];
int i = 0;
for (VolumeJoinVO v : uniqueVols) {
vrIds[i++] = v.getId();
}
List<VolumeJoinVO> vrs = _volumeJoinDao.searchByIds(vrIds);
return new Pair<List<VolumeJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<AccountResponse> searchForAccounts(ListAccountsCmd cmd) {
Pair<List<AccountJoinVO>, Integer> result = searchForAccountsInternal(cmd);
ListResponse<AccountResponse> response = new ListResponse<AccountResponse>();
List<AccountResponse> accountResponses = ViewResponseHelper.createAccountResponse(result.first().toArray(
new AccountJoinVO[result.first().size()]));
response.setResponses(accountResponses, result.second());
return response;
}
private Pair<List<AccountJoinVO>, Integer> searchForAccountsInternal(ListAccountsCmd cmd) {
Account caller = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
Long accountId = cmd.getId();
String accountName = cmd.getSearchName();
boolean isRecursive = cmd.isRecursive();
boolean listAll = cmd.listAll();
Boolean listForDomain = false;
if (accountId != null) {
Account account = _accountDao.findById(accountId);
if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Unable to find account by id " + accountId);
}
_accountMgr.checkAccess(caller, null, true, account);
}
if (domainId != null) {
Domain domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
Account account = _accountDao.findActiveAccount(accountName, domainId);
if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Unable to find account by name " + accountName
+ " in domain " + domainId);
}
_accountMgr.checkAccess(caller, null, true, account);
}
}
if (accountId == null) {
if (_accountMgr.isAdmin(caller.getType()) && listAll && domainId == null) {
listForDomain = true;
isRecursive = true;
if (domainId == null) {
domainId = caller.getDomainId();
}
} else if (_accountMgr.isAdmin(caller.getType()) && domainId != null) {
listForDomain = true;
} else {
accountId = caller.getAccountId();
}
}
Filter searchFilter = new Filter(AccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
Object type = cmd.getAccountType();
Object state = cmd.getState();
Object isCleanupRequired = cmd.isCleanupRequired();
Object keyword = cmd.getKeyword();
SearchBuilder<AccountJoinVO> sb = _accountJoinDao.createSearchBuilder();
sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
sb.and("needsCleanup", sb.entity().isNeedsCleanup(), SearchCriteria.Op.EQ);
sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ);
sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ);
if (listForDomain && isRecursive) {
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
SearchCriteria<AccountJoinVO> sc = sb.create();
sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM);
if (keyword != null) {
SearchCriteria<AccountJoinVO> ssc = _accountJoinDao.createSearchCriteria();
ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("accountName", SearchCriteria.Op.SC, ssc);
}
if (type != null) {
sc.setParameters("type", type);
}
if (state != null) {
sc.setParameters("state", state);
}
if (isCleanupRequired != null) {
sc.setParameters("needsCleanup", isCleanupRequired);
}
if (accountName != null) {
sc.setParameters("accountName", accountName);
}
// don't return account of type project to the end user
sc.setParameters("typeNEQ", 5);
if (accountId != null) {
sc.setParameters("id", accountId);
}
if (listForDomain) {
if (isRecursive) {
Domain domain = _domainDao.findById(domainId);
sc.setParameters("path", domain.getPath() + "%");
} else {
sc.setParameters("domainId", domainId);
}
}
return _accountJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<AsyncJobResponse> searchForAsyncJobs(ListAsyncJobsCmd cmd) {
Pair<List<AsyncJobJoinVO>, Integer> result = searchForAsyncJobsInternal(cmd);
ListResponse<AsyncJobResponse> response = new ListResponse<AsyncJobResponse>();
List<AsyncJobResponse> jobResponses = ViewResponseHelper.createAsyncJobResponse(result.first().toArray(
new AsyncJobJoinVO[result.first().size()]));
response.setResponses(jobResponses, result.second());
return response;
}
private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts,
domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<AsyncJobJoinVO> sb = _jobJoinDao.createSearchBuilder();
sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
SearchBuilder<AccountVO> accountSearch = null;
boolean accountJoinIsDone = false;
if (permittedAccounts.isEmpty() && domainId != null) {
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
accountJoinIsDone = true;
}
if (listProjectResourcesCriteria != null) {
if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
} else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
}
if (!accountJoinIsDone) {
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
}
}
Object keyword = cmd.getKeyword();
Object startDate = cmd.getStartDate();
SearchCriteria<AsyncJobJoinVO> sc = sb.create();
if (listProjectResourcesCriteria != null) {
sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
}
if (!permittedAccounts.isEmpty()) {
sc.setParameters("accountIdIN", permittedAccounts.toArray());
} else if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
if (isRecursive) {
sc.setParameters("path", domain.getPath() + "%");
} else {
sc.setParameters("domainId", domainId);
}
}
if (keyword != null) {
sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%");
}
if (startDate != null) {
sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
}
return _jobJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<StoragePoolResponse> searchForStoragePools(ListStoragePoolsCmd cmd) {
Pair<List<StoragePoolJoinVO>, Integer> result = searchForStoragePoolsInternal(cmd);
ListResponse<StoragePoolResponse> response = new ListResponse<StoragePoolResponse>();
List<StoragePoolResponse> poolResponses = ViewResponseHelper.createStoragePoolResponse(result.first().toArray(
new StoragePoolJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<StoragePoolJoinVO>, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) {
ScopeType scopeType = null;
if (cmd.getScope() != null) {
try {
scopeType = Enum.valueOf(ScopeType.class, cmd.getScope().toUpperCase());
} catch (Exception e) {
throw new InvalidParameterValueException("Invalid scope type: " + cmd.getScope());
}
}
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoragePoolName();
Object path = cmd.getPath();
Object pod = cmd.getPodId();
Object cluster = cmd.getClusterId();
Object address = cmd.getIpAddress();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(StoragePoolJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<StoragePoolJoinVO> sb = _poolJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("path", sb.entity().getPath(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ);
sb.and("hostAddress", sb.entity().getHostAddress(), SearchCriteria.Op.EQ);
sb.and("scope", sb.entity().getScope(), SearchCriteria.Op.EQ);
SearchCriteria<StoragePoolJoinVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<StoragePoolJoinVO> ssc = _poolJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("poolType", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (path != null) {
sc.setParameters("path", path);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (pod != null) {
sc.setParameters("podId", pod);
}
if (address != null) {
sc.setParameters("hostAddress", address);
}
if (cluster != null) {
sc.setParameters("clusterId", cluster);
}
if (scopeType != null) {
sc.setParameters("scope", scopeType.toString());
}
// search Pool details by ids
Pair<List<StoragePoolJoinVO>, Integer> uniquePoolPair = _poolJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniquePoolPair.second();
if (count.intValue() == 0) {
// empty result
return uniquePoolPair;
}
List<StoragePoolJoinVO> uniquePools = uniquePoolPair.first();
Long[] vrIds = new Long[uniquePools.size()];
int i = 0;
for (StoragePoolJoinVO v : uniquePools) {
vrIds[i++] = v.getId();
}
List<StoragePoolJoinVO> vrs = _poolJoinDao.searchByIds(vrIds);
return new Pair<List<StoragePoolJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ImageStoreResponse> searchForImageStores(ListImageStoresCmd cmd) {
Pair<List<ImageStoreJoinVO>, Integer> result = searchForImageStoresInternal(cmd);
ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
new ImageStoreJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<ImageStoreJoinVO>, Integer> searchForImageStoresInternal(ListImageStoresCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoreName();
String provider = cmd.getProvider();
String protocol = cmd.getProtocol();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
SearchCriteria<ImageStoreJoinVO> sc = sb.create();
sc.setParameters("role", DataStoreRole.Image);
if (keyword != null) {
SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (provider != null) {
sc.setParameters("provider", provider);
}
if (protocol != null) {
sc.setParameters("protocol", protocol);
}
// search Store details by ids
Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueStorePair.second();
if (count.intValue() == 0) {
// empty result
return uniqueStorePair;
}
List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
Long[] vrIds = new Long[uniqueStores.size()];
int i = 0;
for (ImageStoreJoinVO v : uniqueStores) {
vrIds[i++] = v.getId();
}
List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<ImageStoreResponse> searchForSecondaryStagingStores(ListSecondaryStagingStoresCmd cmd) {
Pair<List<ImageStoreJoinVO>, Integer> result = searchForCacheStoresInternal(cmd);
ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
new ImageStoreJoinVO[result.first().size()]));
response.setResponses(poolResponses, result.second());
return response;
}
private Pair<List<ImageStoreJoinVO>, Integer> searchForCacheStoresInternal(ListSecondaryStagingStoresCmd cmd) {
Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
Object id = cmd.getId();
Object name = cmd.getStoreName();
String provider = cmd.getProvider();
String protocol = cmd.getProtocol();
Object keyword = cmd.getKeyword();
Long startIndex = cmd.getStartIndex();
Long pageSize = cmd.getPageSizeVal();
Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
// ids
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
SearchCriteria<ImageStoreJoinVO> sc = sb.create();
sc.setParameters("role", DataStoreRole.ImageCache);
if (keyword != null) {
SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.setParameters("id", id);
}
if (name != null) {
sc.setParameters("name", name);
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (provider != null) {
sc.setParameters("provider", provider);
}
if (protocol != null) {
sc.setParameters("protocol", protocol);
}
// search Store details by ids
Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueStorePair.second();
if (count.intValue() == 0) {
// empty result
return uniqueStorePair;
}
List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
Long[] vrIds = new Long[uniqueStores.size()];
int i = 0;
for (ImageStoreJoinVO v : uniqueStores) {
vrIds[i++] = v.getId();
}
List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
}
@Override
public ListResponse<DiskOfferingResponse> searchForDiskOfferings(ListDiskOfferingsCmd cmd) {
Pair<List<DiskOfferingJoinVO>, Integer> result = searchForDiskOfferingsInternal(cmd);
ListResponse<DiskOfferingResponse> response = new ListResponse<DiskOfferingResponse>();
List<DiskOfferingResponse> offeringResponses = ViewResponseHelper.createDiskOfferingResponse(result.first()
.toArray(new DiskOfferingJoinVO[result.first().size()]));
response.setResponses(offeringResponses, result.second());
return response;
}
private Pair<List<DiskOfferingJoinVO>, Integer> searchForDiskOfferingsInternal(ListDiskOfferingsCmd cmd) {
// Note
// The list method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will list all offerings
// 2. For domainAdmin and regular users, we will list everything in
// their domains+parent domains ... all the way
// till
// root
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchCriteria<DiskOfferingJoinVO> sc = _diskOfferingJoinDao.createSearchCriteria();
Account account = UserContext.current().getCaller();
Object name = cmd.getDiskOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long domainId = cmd.getDomainId();
// Keeping this logic consistent with domain specific zones
// if a domainId is provided, we just return the disk offering
// associated with this domain
if (domainId != null) {
if (account.getType() == Account.ACCOUNT_TYPE_ADMIN || isPermissible(account.getDomainId(), domainId)) {
// check if the user's domain == do's domain || user's domain is
// a child of so's domain for non-root users
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
} else {
throw new PermissionDeniedException("The account:" + account.getAccountName()
+ " does not fall in the same domain hierarchy as the disk offering");
}
}
List<Long> domainIds = null;
// For non-root users, only return all offerings for the user's domain,
// and everything above till root
if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
|| account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// find all domain Id up to root domain for this account
domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
SearchCriteria<DiskOfferingJoinVO> spc = _diskOfferingJoinDao.createSearchCriteria();
spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
spc.addOr("domainId", SearchCriteria.Op.NULL); // include public
// offering as where
sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); // non-root
// users should
// not see
// system
// offering at
// all
}
if (keyword != null) {
SearchCriteria<DiskOfferingJoinVO> ssc = _diskOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
// FIXME: disk offerings should search back up the hierarchy for
// available disk offerings...
/*
* sb.addAnd("domainId", sb.entity().getDomainId(),
* SearchCriteria.Op.EQ); if (domainId != null) {
* SearchBuilder<DomainVO> domainSearch =
* _domainDao.createSearchBuilder(); domainSearch.addAnd("path",
* domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
* sb.join("domainSearch", domainSearch, sb.entity().getDomainId(),
* domainSearch.entity().getId()); }
*/
// FIXME: disk offerings should search back up the hierarchy for
// available disk offerings...
/*
* if (domainId != null) { sc.setParameters("domainId", domainId); //
* //DomainVO domain = _domainDao.findById((Long)domainId); // // I want
* to join on user_vm.domain_id = domain.id where domain.path like
* 'foo%' //sc.setJoinParameters("domainSearch", "path",
* domain.getPath() + "%"); // }
*/
return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ServiceOfferingResponse> searchForServiceOfferings(ListServiceOfferingsCmd cmd) {
Pair<List<ServiceOfferingJoinVO>, Integer> result = searchForServiceOfferingsInternal(cmd);
ListResponse<ServiceOfferingResponse> response = new ListResponse<ServiceOfferingResponse>();
List<ServiceOfferingResponse> offeringResponses = ViewResponseHelper.createServiceOfferingResponse(result
.first().toArray(new ServiceOfferingJoinVO[result.first().size()]));
response.setResponses(offeringResponses, result.second());
return response;
}
private Pair<List<ServiceOfferingJoinVO>, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) {
// Note
// The list method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will list all offerings
// 2. For domainAdmin and regular users, we will list everything in
// their domains+parent domains ... all the way
// till
// root
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
cmd.getPageSizeVal());
SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
Account caller = UserContext.current().getCaller();
Object name = cmd.getServiceOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long vmId = cmd.getVirtualMachineId();
Long domainId = cmd.getDomainId();
Boolean isSystem = cmd.getIsSystem();
String vmTypeStr = cmd.getSystemVmType();
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) {
throw new InvalidParameterValueException("Only ROOT admins can access system's offering");
}
// Keeping this logic consistent with domain specific zones
// if a domainId is provided, we just return the so associated with this
// domain
if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
// check if the user's domain == so's domain || user's domain is a
// child of so's domain
if (!isPermissible(caller.getDomainId(), domainId)) {
throw new PermissionDeniedException("The account:" + caller.getAccountName()
+ " does not fall in the same domain hierarchy as the service offering");
}
}
// boolean includePublicOfferings = false;
if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
|| caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// For non-root users.
if (isSystem) {
throw new InvalidParameterValueException("Only root admins can access system's offering");
}
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(caller.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + caller.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ caller.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
SearchCriteria<ServiceOfferingJoinVO> spc = _srvOfferingJoinDao.createSearchCriteria();
spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
spc.addOr("domainId", SearchCriteria.Op.NULL); // include public
// offering as where
sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
} else {
// for root users
if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin
throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering");
}
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
}
if (keyword != null) {
SearchCriteria<ServiceOfferingJoinVO> ssc = _srvOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
} else if (vmId != null) {
UserVmVO vmInstance = _userVmDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException(
"unable to find a virtual machine with specified id");
ex.addProxyObject(vmId.toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
ServiceOfferingVO offering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId());
// Only return offerings with the same Guest IP type and storage
// pool preference
// sc.addAnd("guestIpType", SearchCriteria.Op.EQ,
// offering.getGuestIpType());
sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage());
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (isSystem != null) {
// note that for non-root users, isSystem is always false when
// control comes to here
sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (vmTypeStr != null) {
sc.addAnd("vm_type", SearchCriteria.Op.EQ, vmTypeStr);
}
return _srvOfferingJoinDao.searchAndCount(sc, searchFilter);
}
@Override
public ListResponse<ZoneResponse> listDataCenters(ListZonesByCmd cmd) {
Pair<List<DataCenterJoinVO>, Integer> result = listDataCentersInternal(cmd);
ListResponse<ZoneResponse> response = new ListResponse<ZoneResponse>();
List<ZoneResponse> dcResponses = ViewResponseHelper.createDataCenterResponse(cmd.getShowCapacities(), result
.first().toArray(new DataCenterJoinVO[result.first().size()]));
response.setResponses(dcResponses, result.second());
return response;
}
private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesByCmd cmd) {
Account account = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
Long id = cmd.getId();
String keyword = cmd.getKeyword();
String name = cmd.getName();
String networkType = cmd.getNetworkType();
Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<DataCenterJoinVO> sc = _dcJoinDao.createSearchCriteria();
if (networkType != null) {
sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
} else if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
} else {
if (keyword != null) {
SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
/*
* List all resources due to Explicit Dedication except the
* dedicated resources of other account
*/
if (domainId != null && account.getType() == Account.ACCOUNT_TYPE_ADMIN) { //
// for domainId != null // right now, we made the decision to
// only
// / list zones associated // with this domain, private zone
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
} else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) {
// it was decided to return all zones for the user's domain, and
// everything above till root
// list all zones belonging to this domain, and all of its
// parents
// check the parent, if not null, add zones for that parent to
// list
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domain", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN,
dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
} else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN
|| account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// it was decided to return all zones for the domain admin, and
// everything above till root, as well as zones till the domain
// leaf
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:"
+ account.getAccountName());
}
domainIds.add(domainRecord.getId());
// find all domain Ids till leaf
List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(),
domainRecord.getId());
for (DomainVO domain : allChildDomains) {
domainIds.add(domain.getId());
}
// then find all domain Id up to root domain for this account
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domain", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN,
dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
}
// handle available=FALSE option, only return zones with at least
// one VM running there
Boolean available = cmd.isAvailable();
if (account != null) {
if ((available != null) && Boolean.FALSE.equals(available)) {
Set<Long> dcIds = new HashSet<Long>(); // data centers with
// at least one VM
// running
List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
for (DomainRouterVO router : routers) {
dcIds.add(router.getDataCenterId());
}
if (dcIds.size() == 0) {
return new Pair<List<DataCenterJoinVO>, Integer>(new ArrayList<DataCenterJoinVO>(), 0);
} else {
sc.addAnd("idIn", SearchCriteria.Op.IN, dcIds.toArray());
}
}
}
}
return _dcJoinDao.searchAndCount(sc, searchFilter);
}
private List<Long> removeDedicatedZoneNotSuitabe(List<Long> domainIds) {
// remove dedicated zone of other domain
List<Long> dedicatedZoneIds = new ArrayList<Long>();
List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listZonesNotInDomainIds(domainIds);
for (DedicatedResourceVO dr : dedicatedResources) {
if (dr != null) {
dedicatedZoneIds.add(dr.getDataCenterId());
}
}
return dedicatedZoneIds;
}
// This method is used for permissions check for both disk and service
// offerings
private boolean isPermissible(Long accountDomainId, Long offeringDomainId) {
if (accountDomainId.equals(offeringDomainId)) {
return true; // account and service offering in same domain
}
DomainVO domainRecord = _domainDao.findById(accountDomainId);
if (domainRecord != null) {
while (true) {
if (domainRecord.getId() == offeringDomainId) {
return true;
}
// try and move on to the next domain
if (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
return false;
}
@Override
public ListResponse<TemplateResponse> listTemplates(ListTemplatesCmd cmd) {
Pair<List<TemplateJoinVO>, Integer> result = searchForTemplatesInternal(cmd);
ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
List<TemplateResponse> templateResponses = ViewResponseHelper.createTemplateResponse(result.first().toArray(
new TemplateJoinVO[result.first().size()]));
response.setResponses(templateResponses, result.second());
return response;
}
private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) {
TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
boolean listAll = false;
if (templateFilter != null && templateFilter == TemplateFilter.all) {
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+ " can be specified by admin only");
}
listAll = true;
}
List<Long> permittedAccountIds = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
domainIdRecursiveListProject, listAll, false);
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null,
cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr,
cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
}
private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name,
String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize,
Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria,
Map<String, String> tags) {
VMTemplateVO template = null;
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair()); // select distinct (templateId, zoneId) pair
SearchCriteria<TemplateJoinVO> sc = sb.create();
// verify templateId parameter and specially handle it
if (templateId != null) {
template = _templateDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("Please specify a valid template ID.");
}// If ISO requested then it should be ISO.
if (isIso && template.getFormat() != ImageFormat.ISO) {
s_logger.error("Template Id " + templateId + " is not an ISO");
InvalidParameterValueException ex = new InvalidParameterValueException(
"Specified Template Id is not an ISO");
ex.addProxyObject(template.getUuid(), "templateId");
throw ex;
}// If ISO not requested then it shouldn't be an ISO.
if (!isIso && template.getFormat() == ImageFormat.ISO) {
s_logger.error("Incorrect format of the template id " + templateId);
InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format "
+ template.getFormat() + " of the specified template id");
ex.addProxyObject(template.getUuid(), "templateId");
throw ex;
}
// if template is not public, perform permission check here
if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
Account owner = _accountMgr.getAccount(template.getAccountId());
_accountMgr.checkAccess(caller, null, true, owner);
}
// if templateId is specified, then we will just use the id to
// search and ignore other query parameters
sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
} else {
DomainVO domain = null;
if (!permittedAccounts.isEmpty()) {
domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
} else {
domain = _domainDao.findById(DomainVO.ROOT_DOMAIN);
}
List<HypervisorType> hypers = null;
if (!isIso) {
hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
}
// add criteria for project or not
if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
} else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
}
// add criteria for domain path in case of domain admin
if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable)
&& (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
}
List<Long> relatedDomainIds = new ArrayList<Long>();
List<Long> permittedAccountIds = new ArrayList<Long>();
if (!permittedAccounts.isEmpty()) {
for (Account account : permittedAccounts) {
permittedAccountIds.add(account.getId());
DomainVO accountDomain = _domainDao.findById(account.getDomainId());
// get all parent domain ID's all the way till root domain
DomainVO domainTreeNode = accountDomain;
relatedDomainIds.add(domainTreeNode.getId());
while (domainTreeNode.getParent() != null) {
domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
relatedDomainIds.add(domainTreeNode.getId());
}
// get all child domain ID's
if (_accountMgr.isAdmin(account.getType())) {
List<DomainVO> allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(),
accountDomain.getId());
for (DomainVO childDomain : allChildDomains) {
relatedDomainIds.add(childDomain.getId());
}
}
}
}
if (!isIso) {
// add hypervisor criteria for template case
if (hypers != null && !hypers.isEmpty()) {
String[] relatedHypers = new String[hypers.size()];
for (int i = 0; i < hypers.size(); i++) {
relatedHypers[i] = hypers.get(i).toString();
}
sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
}
}
// control different template filters
if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
if (templateFilter == TemplateFilter.featured) {
sc.addAnd("featured", SearchCriteria.Op.EQ, true);
} else {
sc.addAnd("featured", SearchCriteria.Op.EQ, false);
}
if (!permittedAccounts.isEmpty()) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
scc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
}
} else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
if (!permittedAccounts.isEmpty()) {
sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
}
} else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
sc.addAnd("accountId", SearchCriteria.Op.SC, scc);
} else if (templateFilter == TemplateFilter.executable) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
if (!permittedAccounts.isEmpty()) {
scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
}
sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
}
// add tags criteria
if (tags != null && !tags.isEmpty()) {
SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
int count = 0;
for (String key : tags.keySet()) {
SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
scTag.addAnd("tagKey", SearchCriteria.Op.EQ, key);
scTag.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
if (isIso) {
scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.ISO);
} else {
scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.Template);
}
scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
count++;
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
}
// other criteria
if (keyword != null) {
sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
} else if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (isIso) {
sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
} else {
sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
}
if (!hyperType.equals(HypervisorType.None)) {
sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
}
if (bootable != null) {
sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
}
if (onlyReady) {
SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
sc.addAnd("state", SearchCriteria.Op.SC, readySc);
}
if (!showDomr) {
// excluding system template
sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
}
}
if (zoneId != null) {
SearchCriteria<TemplateJoinVO> zoneSc = _templateJoinDao.createSearchCriteria();
zoneSc.addOr("dataCenterId", SearchCriteria.Op.EQ, zoneId);
zoneSc.addOr("dataStoreScope", SearchCriteria.Op.EQ, ScopeType.REGION);
// handle the case where xs-tools.iso and vmware-tools.iso do not
// have data_center information in template_view
SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
zoneSc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
sc.addAnd("dataCenterId", SearchCriteria.Op.SC, zoneSc);
}
// don't return removed template, this should not be needed since we
// changed annotation for removed field in TemplateJoinVO.
// sc.addAnd("removed", SearchCriteria.Op.NULL);
// search unique templates and find details by Ids
Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueTmplPair.second();
if (count.intValue() == 0) {
// empty result
return uniqueTmplPair;
}
List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
String[] tzIds = new String[uniqueTmpls.size()];
int i = 0;
for (TemplateJoinVO v : uniqueTmpls) {
tzIds[i++] = v.getTempZonePair();
}
List<TemplateJoinVO> vrs = _templateJoinDao.searchByTemplateZonePair(tzIds);
return new Pair<List<TemplateJoinVO>, Integer>(vrs, count);
// TODO: revisit the special logic for iso search in
// VMTemplateDaoImpl.searchForTemplates and understand why we need to
// specially handle ISO. The original logic is very twisted and no idea
// about what the code was doing.
}
@Override
public ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd) {
Pair<List<TemplateJoinVO>, Integer> result = searchForIsosInternal(cmd);
ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
List<TemplateResponse> templateResponses = ViewResponseHelper.createIsoResponse(result.first().toArray(
new TemplateJoinVO[result.first().size()]));
response.setResponses(templateResponses, result.second());
return response;
}
private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(ListIsosCmd cmd) {
TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
Long id = cmd.getId();
Map<String, String> tags = cmd.getTags();
Account caller = UserContext.current().getCaller();
boolean listAll = false;
if (isoFilter != null && isoFilter == TemplateFilter.all) {
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+ " can be specified by admin only");
}
listAll = true;
}
List<Long> permittedAccountIds = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
domainIdRecursiveListProject, listAll, false);
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true,
cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true,
cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
}
@Override
public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
boolean listAll, Long startIndex, Long pageSize) {
Pair<List<AffinityGroupJoinVO>, Integer> result = listAffinityGroupsInternal(affinityGroupId,
affinityGroupName, affinityGroupType, vmId, accountName, domainId, isRecursive, listAll, startIndex,
pageSize);
ListResponse<AffinityGroupResponse> response = new ListResponse<AffinityGroupResponse>();
List<AffinityGroupResponse> agResponses = ViewResponseHelper.createAffinityGroupResponses(result.first());
response.setResponses(agResponses, result.second());
return response;
}
public Pair<List<AffinityGroupJoinVO>, Integer> listAffinityGroupsInternal(Long affinityGroupId,
String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId,
boolean isRecursive, boolean listAll, Long startIndex, Long pageSize) {
Account caller = UserContext.current().getCaller();
Long accountId = caller.getAccountId();
if (vmId != null) {
UserVmVO userVM = _userVmDao.findById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance "
+ vmId + "; instance not found.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
return listAffinityGroupsByVM(vmId.longValue(), startIndex, pageSize);
}
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, null, permittedAccounts,
domainIdRecursiveListProject, listAll, true);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(AffinityGroupJoinVO.class, "id", true, startIndex, pageSize);
SearchCriteria<AffinityGroupJoinVO> sc = buildAffinityGroupSearchCriteria(domainId, isRecursive,
permittedAccounts, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType);
Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc,
searchFilter);
// search group details by ids
List<AffinityGroupJoinVO> vrs = new ArrayList<AffinityGroupJoinVO>();
Integer count = uniqueGroupsPair.second();
if (count.intValue() != 0) {
List<AffinityGroupJoinVO> uniqueGroups = uniqueGroupsPair.first();
Long[] vrIds = new Long[uniqueGroups.size()];
int i = 0;
for (AffinityGroupJoinVO v : uniqueGroups) {
vrIds[i++] = v.getId();
}
vrs = _affinityGroupJoinDao.searchByIds(vrIds);
}
if (!permittedAccounts.isEmpty()) {
// add domain level affinity groups
if (domainId != null) {
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
} else {
for (Long permAcctId : permittedAccounts) {
Account permittedAcct = _accountDao.findById(permAcctId);
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(
null, isRecursive, new ArrayList<Long>(),
listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId()));
}
}
} else if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
// list all domain level affinity groups for the domain admin case
SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
affinityGroupType);
vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
}
return new Pair<List<AffinityGroupJoinVO>, Integer>(vrs, vrs.size());
}
private SearchCriteria<AffinityGroupJoinVO> buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive,
List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria,
Long affinityGroupId, String affinityGroupName, String affinityGroupType) {
SearchBuilder<AffinityGroupJoinVO> groupSearch = _affinityGroupJoinDao.createSearchBuilder();
_accountMgr.buildACLViewSearchBuilder(groupSearch, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
groupSearch.select(null, Func.DISTINCT, groupSearch.entity().getId()); // select
// distinct
SearchCriteria<AffinityGroupJoinVO> sc = groupSearch.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
listProjectResourcesCriteria);
if (affinityGroupId != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, affinityGroupId);
}
if (affinityGroupName != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, affinityGroupName);
}
if (affinityGroupType != null) {
sc.addAnd("type", SearchCriteria.Op.EQ, affinityGroupType);
}
return sc;
}
private Pair<List<AffinityGroupJoinVO>, Integer> listAffinityGroupsByVM(long vmId, long pageInd, long pageSize) {
Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize);
Pair<List<AffinityGroupVMMapVO>, Integer> agVmMappingPair = _affinityGroupVMMapDao.listByInstanceId(vmId, sf);
Integer count = agVmMappingPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return new Pair<List<AffinityGroupJoinVO>, Integer>(new ArrayList<AffinityGroupJoinVO>(), count);
}
List<AffinityGroupVMMapVO> agVmMappings = agVmMappingPair.first();
Long[] agIds = new Long[agVmMappings.size()];
int i = 0;
for (AffinityGroupVMMapVO agVm : agVmMappings) {
agIds[i++] = agVm.getAffinityGroupId();
}
List<AffinityGroupJoinVO> ags = _affinityGroupJoinDao.searchByIds(agIds);
return new Pair<List<AffinityGroupJoinVO>, Integer>(ags, count);
}
private List<AffinityGroupJoinVO> listDomainLevelAffinityGroups(
SearchCriteria<AffinityGroupJoinVO> sc, Filter searchFilter, long domainId) {
List<Long> affinityGroupIds = new ArrayList<Long>();
Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId);
List<AffinityGroupDomainMapVO> maps = _affinityGroupDomainMapDao.listByDomain(allowedDomains.toArray());
for (AffinityGroupDomainMapVO map : maps) {
boolean subdomainAccess = map.isSubdomainAccess();
if (map.getDomainId() == domainId || subdomainAccess) {
affinityGroupIds.add(map.getAffinityGroupId());
}
}
if (!affinityGroupIds.isEmpty()) {
SearchCriteria<AffinityGroupJoinVO> domainSC = _affinityGroupJoinDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, affinityGroupIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc,
searchFilter);
// search group by ids
Integer count = uniqueGroupsPair.second();
if (count.intValue() == 0) {
// empty result
return new ArrayList<AffinityGroupJoinVO>();
}
List<AffinityGroupJoinVO> uniqueGroups = uniqueGroupsPair.first();
Long[] vrIds = new Long[uniqueGroups.size()];
int i = 0;
for (AffinityGroupJoinVO v : uniqueGroups) {
vrIds[i++] = v.getId();
}
List<AffinityGroupJoinVO> vrs = _affinityGroupJoinDao.searchByIds(vrIds);
return vrs;
} else {
return new ArrayList<AffinityGroupJoinVO>();
}
}
@Override
public List<ResourceDetailResponse> listResource(ListResourceDetailsCmd cmd) {
String key = cmd.getKey();
ResourceTag.TaggedResourceType resourceType = cmd.getResourceType();
String resourceId = cmd.getResourceId();
Long id = _taggedResourceMgr.getResourceId(resourceId, resourceType);
if (resourceType == ResourceTag.TaggedResourceType.Volume) {
List<VolumeDetailVO> volumeDetailList;
if (key == null) {
volumeDetailList = _volumeDetailDao.findDetails(id);
} else {
VolumeDetailVO volumeDetail = _volumeDetailDao.findDetail(id, key);
volumeDetailList = new LinkedList<VolumeDetailVO>();
volumeDetailList.add(volumeDetail);
}
List<ResourceDetailResponse> volumeDetailResponseList = new ArrayList<ResourceDetailResponse>();
for (VolumeDetailVO volumeDetail : volumeDetailList) {
ResourceDetailResponse volumeDetailResponse = new ResourceDetailResponse();
volumeDetailResponse.setResourceId(id.toString());
volumeDetailResponse.setName(volumeDetail.getName());
volumeDetailResponse.setValue(volumeDetail.getValue());
volumeDetailResponse.setResourceType(ResourceTag.TaggedResourceType.Volume.toString());
volumeDetailResponse.setObjectName("volumedetail");
volumeDetailResponseList.add(volumeDetailResponse);
}
return volumeDetailResponseList;
} else {
List<NicDetailVO> nicDetailList;
if (key == null) {
nicDetailList = _nicDetailDao.findDetails(id);
} else {
NicDetailVO nicDetail = _nicDetailDao.findDetail(id, key);
nicDetailList = new LinkedList<NicDetailVO>();
nicDetailList.add(nicDetail);
}
List<ResourceDetailResponse> nicDetailResponseList = new ArrayList<ResourceDetailResponse>();
for (NicDetailVO nicDetail : nicDetailList) {
ResourceDetailResponse nicDetailResponse = new ResourceDetailResponse();
// String uuid = ApiDBUtils.findN
nicDetailResponse.setName(nicDetail.getName());
nicDetailResponse.setValue(nicDetail.getValue());
nicDetailResponse.setResourceType(ResourceTag.TaggedResourceType.Nic.toString());
nicDetailResponse.setObjectName("nicdetail");
nicDetailResponseList.add(nicDetailResponse);
}
return nicDetailResponseList;
}
}
}
| CLOUDSTACK-4296: fix a similar issue
| server/src/com/cloud/api/query/QueryManagerImpl.java | CLOUDSTACK-4296: fix a similar issue | <ide><path>erver/src/com/cloud/api/query/QueryManagerImpl.java
<ide>
<ide> if (keyword != null) {
<ide> SearchCriteria<DomainRouterJoinVO> ssc = _routerJoinDao.createSearchCriteria();
<del> ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
<add> ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
<ide> ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
<ide> ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
<ide>
<del> sc.addAnd("hostName", SearchCriteria.Op.SC, ssc);
<add> sc.addAnd("instanceName", SearchCriteria.Op.SC, ssc);
<ide> }
<ide>
<ide> if (name != null) { |
|
JavaScript | mit | cbd56a8c5b1bba23d7e35e52262da54965eaf9d1 | 0 | epimorphics/ukhpi,epimorphics/ukhpi,epimorphics/ukhpi,epimorphics/ukhpi | /** Component for showing the queried index data as a set of graphs */
import _ from 'lodash';
import Raven from 'raven-js';
import { axisBottom, axisLeft } from 'd3-axis';
import { extent, bisector } from 'd3-array';
import { format } from 'd3-format';
import { scaleLinear, scaleTime } from 'd3-scale';
import { mouse, select } from 'd3-selection';
import { line, symbol, symbolCircle, symbolDiamond, symbolStar,
symbolTriangle, symbolSquare } from 'd3-shape';
import { timeMonth } from 'd3-time';
import { timeFormat } from 'd3-time-format';
import { interpolateNumber } from 'd3-interpolate';
import { asCurrency, formatValue } from '../lib/values';
const SERIES_MARKER = [
symbolCircle,
symbolDiamond,
symbolSquare,
symbolStar,
symbolTriangle,
];
/** Move line markers this many days along the x-axis, per series */
const MARKER_OFFSET = {
mult: 6,
constant: 2,
};
const oneDecimalPlace = format('.2g');
const GRAPH_OPTIONS = {
averagePrice: {
cssClass: 'average-price',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
tickFormat(d) { return asCurrency(d); },
byPropertyType: true,
},
housePriceIndex: {
cssClass: 'house-price-index',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
byPropertyType: true,
},
percentageChange: {
cssClass: 'percentage-monthly-change',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
symmetricalYAxis: true,
tickFormat(d) { return `${oneDecimalPlace(d)}%`; },
byPropertyType: true,
},
percentageAnnualChange: {
cssClass: 'percentage-annual-change',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
symmetricalYAxis: true,
tickFormat(d) { return `${oneDecimalPlace(d)}%`; },
byPropertyType: true,
},
salesVolume: {
cssClass: 'sales-volume',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
byPropertyType: false,
},
};
const GRAPH_PADDING = {
top: 20,
right: 25,
bottom: 30,
left: 65,
};
GRAPH_PADDING.horizontal = GRAPH_PADDING.left + GRAPH_PADDING.right;
GRAPH_PADDING.vertical = GRAPH_PADDING.top + GRAPH_PADDING.bottom;
const MIN_XAXIS_MONTHS = 8;
/* Helper functions */
/** Create or re-create the root SVG node that the graph will be drawn into */
function drawGraphRoot(graphConfig) {
const { elementId } = graphConfig;
const svgRoot = select(`#${elementId}`);
svgRoot.select('g').remove();
const rootElem = svgRoot
.append('g')
.attr('transform', `translate(${GRAPH_PADDING.left},${GRAPH_PADDING.top})`);
return { svgRoot, rootElem };
}
/** @return True if the given statistic is selected for display */
function isSelectedStatistic(statistic, graphConfig) {
return graphConfig.selectedStatistics[statistic.slug || statistic];
}
/** @return The currently visible statistics */
function visibleStatistics(graphConfig) {
return graphConfig.theme.statistics.filter(stat => isSelectedStatistic(stat, graphConfig));
}
/** @return The range of values in the projection of the selected statistics */
function calculateValueRange(projection, graphConfig) {
let [min, max] = [0.0, 1.0];
_.each(graphConfig.theme.statistics, (statistic) => {
if (isSelectedStatistic(statistic, graphConfig)) {
const yDomain = projection[statistic.slug].map(datum => datum.y);
const [lo, hi] = extent(yDomain);
min = Math.min(min, lo);
max = Math.max(max, hi);
}
});
if (graphConfig.symmetricalYAxis) {
const largest = Math.max(Math.abs(min), Math.abs(max));
[min, max] = [largest * -1.0, largest];
}
return [min, max];
}
/** Create a pair of scales to range across the height and width of the viewport
* for the root node, minus the surrounding padding */
function createScales(graphConfig) {
const parentWidth = graphConfig.svgRoot.node().parentNode.offsetWidth;
const parentHeight = graphConfig.svgRoot.node().parentNode.offsetHeight;
const xScale = scaleTime().nice(timeMonth);
const width = parentWidth - GRAPH_PADDING.horizontal;
xScale.domain(graphConfig.dateRange).nice();
xScale.range([0, width]);
const yScale = scaleLinear();
const height = parentHeight - GRAPH_PADDING.vertical;
yScale.domain(graphConfig.valueRange).nice();
yScale.range([height, 0]);
return {
x: xScale, y: yScale, width, height,
};
}
/** Create x and y axes, given the scales and options for tick formatting etc */
function createAxes(scales, graphConfig) {
let xAxis = axisBottom(scales.x)
.tickPadding(5)
.tickFormat(timeFormat('%b %Y'));
xAxis = xAxis.ticks(Math.min(graphConfig.period, MIN_XAXIS_MONTHS));
let yAxis = axisLeft(scales.y)
.ticks(graphConfig.ticksCount)
.tickPadding(8)
.tickSizeInner(-1 * scales.width);
if (graphConfig.tickFormat) {
yAxis = yAxis.tickFormat(graphConfig.tickFormat);
}
return { x: xAxis, y: yAxis };
}
/** Configure the axes for the graph */
function configureAxes(graphConfig) {
const scales = createScales(graphConfig);
const axes = createAxes(scales, graphConfig);
return {
scales,
axes,
};
}
function translateCmd(x, y) {
return `translate(${parseInt(x, 10)},${parseInt(y, 10)})`;
}
/** Draw the graph axes onto the SVG element */
function drawAxes(graphConfig) {
graphConfig.rootElem
.append('g')
.attr('class', 'x axis')
.attr('transform', translateCmd(0, graphConfig.scales.height))
.call(graphConfig.axes.x);
graphConfig.rootElem
.append('g')
.attr('class', 'y axis')
.call(graphConfig.axes.y);
if (_.isNaN(graphConfig.scales.y(0))) {
return;
}
if (graphConfig.symmetricalYAxis) {
graphConfig.rootElem
.append('svg:line')
.attr('class', 'y axis supplemental')
.attr('x1', 0)
.attr('x2', graphConfig.scales.width)
.attr('y1', graphConfig.scales.y(0))
.attr('y2', graphConfig.scales.y(0));
}
}
/** Draw a marker to distinguish a series other than by colour */
function drawPoints(series, index, graphConfig) {
const { scales } = graphConfig;
if (series.length < 1) {
return;
}
const { x: x0, y: y0 } = series[0];
const { y: y1 } = series.length > 1 ? series[1] : series[0];
const interpolation = interpolateNumber(y0, y1);
// create a point that progressively further from the y-axis
const xDelta = new Date(x0);
const delta = (index * MARKER_OFFSET.mult) + MARKER_OFFSET.constant;
const iDelta = delta / 31; // interpolation requires a number on [0, 1.0]
if (series.length > 1) {
xDelta.setDate(xDelta.getDate() + delta);
}
const cssClass = `point v-graph-${index}`;
graphConfig.rootElem
.selectAll(cssClass)
.data([{ x: xDelta, y: interpolation(iDelta) }])
.enter()
.append('path')
.attr('class', cssClass)
.attr('d', (d, i) => symbol().type(SERIES_MARKER[index])(d, i))
.attr('transform', d => translateCmd(scales.x(d.x), scales.y(d.y)));
}
/** Draw an SVG path representing the selected indicator as a line */
function drawLine(series, index, graphConfig) {
const { x, y } = graphConfig.scales;
const ln = line()
.x(d => x(d.x))
.y(d => y(d.y));
graphConfig.rootElem
.append('path')
.datum(series)
.attr('class', `line v-graph-${index}`)
.attr('d', ln);
}
/** Draw the lines or other forms used to portray the data series */
function drawGraphLines(series, index, graphConfig) {
switch (graphConfig.graphType) {
case 'lineAndPoints':
drawPoints(series, index, graphConfig);
drawLine(series, index, graphConfig);
break;
default:
Raven.captureMessage(`Unknown graph type: ${graphConfig.graphType}`);
}
}
const bisectDate = bisector(d => d.x).left;
function formatStatistic(indicator, statistic, value) {
const abbrev = {
all: 'all ',
det: 'det. ',
sem: 's.det. ',
ter: 'terr. ',
fla: 'f/m. ',
}[statistic.slug];
return (abbrev || statistic.label) + formatValue(indicator + statistic, value);
}
function xTrackLabel(statistic, projection, graphConfig, d) {
const series = projection[statistic.slug];
const value = _.find(series, { x: d.x });
return formatStatistic(graphConfig.indicatorId, statistic, value && value.y);
}
/** Track mouse movement and update the overlay */
function onXTrackMouseMove(projection, graphConfig, xTrack) {
const aSeries = _.first(_.values(projection));
if (_.isEmpty(aSeries)) {
return;
}
const { x } = graphConfig.scales;
const x0 = x.invert(mouse(graphConfig.rootElem.node())[0]);
const i = bisectDate(aSeries, x0, 1);
const d0 = aSeries[i - 1];
const d1 = aSeries[i];
const d = (d1 && (x0 - d0.x > d1.x - x0)) ? d1 : d0;
xTrack.attr('transform', translateCmd(x(d.x), -10));
const dateLabel = timeFormat('%b %Y')(d.x);
const labeller = (() => (statistic => xTrackLabel(statistic, projection, graphConfig, d)))();
const label = `${dateLabel}: ${_.map(visibleStatistics(graphConfig), labeller).join(', ')}`;
const labelElem = xTrack.select('text');
const txtLen = labelElem
.text(label)
.node()
.getComputedTextLength();
const maxLeft = graphConfig.scales.width - txtLen;
const delta = maxLeft - x(d.x);
if (delta < 0) {
labelElem.attr('transform', translateCmd(delta, 0));
} else {
labelElem.attr('transform', translateCmd(0, 0));
}
}
/** Prepare the elements necessary to draw the overlay, and set event listeners */
function prepareOverlay(projection, graphConfig) {
const xTrack = graphConfig
.rootElem
.append('g')
.attr('class', 'o-x-track__g')
.style('display', 'none');
xTrack
.append('rect')
.attr('class', 'o-x-track')
.attr('height', graphConfig.scales.height)
.attr('width', 0.5)
.attr('stroke-dasharray', '5,5')
.attr('y', 10);
xTrack
.append('text')
.attr('class', 'o-x-track__title')
.attr('y', 0)
.append('dy', '0.35em');
graphConfig
.rootElem
.append('rect')
.attr('class', 'o-graph-overlay')
.attr('width', graphConfig.scales.width)
.attr('height', graphConfig.scales.height)
.on('mouseover', () => { xTrack.style('display', null); })
.on('mouseout', () => { xTrack.style('display', 'none'); })
.on('mousemove', (() =>
() => { onXTrackMouseMove(projection, graphConfig, xTrack); }
)());
}
/** Generate a warning when there is no data to display */
function warnNoData(graphConfig) {
const label = graphConfig.theme.label.toLocaleLowerCase();
const location = graphConfig.location.labels.en;
graphConfig
.rootElem
.append('text')
.attr('x', 35)
.attr('y', 50)
.text(`Sorry, there is no ${label} data available for ${location}. Please select a different location.`)
.attr('font-size', '15px')
.attr('font-style', 'italic')
.attr('fill', '#303030');
}
export default function drawGraph(projection, options) {
let nPoints = 0;
const graphConfig = Object.assign({}, GRAPH_OPTIONS[options.indicatorId], options);
Object.assign(graphConfig, drawGraphRoot(graphConfig));
graphConfig.valueRange = calculateValueRange(projection, graphConfig);
Object.assign(graphConfig, configureAxes(graphConfig));
drawAxes(graphConfig);
prepareOverlay(projection, graphConfig);
_.each(_.keys(projection), (slug, index) => {
const series = projection[slug];
if (series.length > 0 && isSelectedStatistic(slug, graphConfig)) {
drawGraphLines(series, index, graphConfig);
nPoints += series.length;
}
});
if (nPoints === 0) {
warnNoData(graphConfig);
}
}
| app/javascript/presenters/data-graph.js | /** Component for showing the queried index data as a set of graphs */
import _ from 'lodash';
import Raven from 'raven-js';
import { axisBottom, axisLeft } from 'd3-axis';
import { extent, bisector } from 'd3-array';
import { format } from 'd3-format';
import { scaleLinear, scaleTime } from 'd3-scale';
import { mouse, select } from 'd3-selection';
import { line, symbol, symbolCircle, symbolDiamond, symbolStar,
symbolTriangle, symbolSquare } from 'd3-shape';
import { timeMonth } from 'd3-time';
import { timeFormat } from 'd3-time-format';
import { interpolateNumber } from 'd3-interpolate';
import { asCurrency, formatValue } from '../lib/values';
const SERIES_MARKER = [
symbolCircle,
symbolDiamond,
symbolSquare,
symbolStar,
symbolTriangle,
];
/** Move line markers this many days along the x-axis, per series */
const MARKER_OFFSET = {
mult: 6,
constant: 2,
};
const oneDecimalPlace = format('.2g');
const GRAPH_OPTIONS = {
averagePrice: {
cssClass: 'average-price',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
tickFormat(d) { return asCurrency(d); },
byPropertyType: true,
},
housePriceIndex: {
cssClass: 'house-price-index',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
byPropertyType: true,
},
percentageChange: {
cssClass: 'percentage-monthly-change',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
symmetricalYAxis: true,
tickFormat(d) { return `${oneDecimalPlace(d)}%`; },
byPropertyType: true,
},
percentageAnnualChange: {
cssClass: 'percentage-annual-change',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
symmetricalYAxis: true,
tickFormat(d) { return `${oneDecimalPlace(d)}%`; },
byPropertyType: true,
},
salesVolume: {
cssClass: 'sales-volume',
ticksCount: 5,
yDomain: '',
graphType: 'lineAndPoints',
byPropertyType: false,
},
};
const GRAPH_PADDING = {
top: 20,
right: 25,
bottom: 30,
left: 65,
};
GRAPH_PADDING.horizontal = GRAPH_PADDING.left + GRAPH_PADDING.right;
GRAPH_PADDING.vertical = GRAPH_PADDING.top + GRAPH_PADDING.bottom;
const MIN_XAXIS_MONTHS = 8;
/* Helper functions */
/** Create or re-create the root SVG node that the graph will be drawn into */
function drawGraphRoot(graphConfig) {
const { elementId } = graphConfig;
const svgRoot = select(`#${elementId}`);
svgRoot.select('g').remove();
const rootElem = svgRoot
.append('g')
.attr('transform', `translate(${GRAPH_PADDING.left},${GRAPH_PADDING.top})`);
return { svgRoot, rootElem };
}
/** @return True if the given statistic is selected for display */
function isSelectedStatistic(statistic, graphConfig) {
return graphConfig.selectedStatistics[statistic.slug || statistic];
}
/** @return The currently visible statistics */
function visibleStatistics(graphConfig) {
return graphConfig.theme.statistics.filter(stat => isSelectedStatistic(stat, graphConfig));
}
/** @return The range of values in the projection of the selected statistics */
function calculateValueRange(projection, graphConfig) {
let [min, max] = [0.0, 1.0];
_.each(graphConfig.theme.statistics, (statistic) => {
if (isSelectedStatistic(statistic, graphConfig)) {
const yDomain = projection[statistic.slug].map(datum => datum.y);
const [lo, hi] = extent(yDomain);
min = Math.min(min, lo);
max = Math.max(max, hi);
}
});
if (graphConfig.symmetricalYAxis) {
const largest = Math.max(Math.abs(min), Math.abs(max));
[min, max] = [largest * -1.0, largest];
}
return [min, max];
}
/** Create a pair of scales to range across the height and width of the viewport
* for the root node, minus the surrounding padding */
function createScales(graphConfig) {
const parentWidth = graphConfig.svgRoot.node().parentNode.offsetWidth;
const parentHeight = graphConfig.svgRoot.node().parentNode.offsetHeight;
const xScale = scaleTime().nice(timeMonth);
const width = parentWidth - GRAPH_PADDING.horizontal;
xScale.domain(graphConfig.dateRange).nice();
xScale.range([0, width]);
const yScale = scaleLinear();
const height = parentHeight - GRAPH_PADDING.vertical;
yScale.domain(graphConfig.valueRange).nice();
yScale.range([height, 0]);
return {
x: xScale, y: yScale, width, height,
};
}
/** Create x and y axes, given the scales and options for tick formatting etc */
function createAxes(scales, graphConfig) {
let xAxis = axisBottom(scales.x)
.tickPadding(5)
.tickFormat(timeFormat('%b %Y'));
xAxis = xAxis.ticks(Math.min(graphConfig.period, MIN_XAXIS_MONTHS));
let yAxis = axisLeft(scales.y)
.ticks(graphConfig.ticksCount)
.tickPadding(8)
.tickSizeInner(-1 * scales.width);
if (graphConfig.tickFormat) {
yAxis = yAxis.tickFormat(graphConfig.tickFormat);
}
return { x: xAxis, y: yAxis };
}
/** Configure the axes for the graph */
function configureAxes(graphConfig) {
const scales = createScales(graphConfig);
const axes = createAxes(scales, graphConfig);
return {
scales,
axes,
};
}
function translateCmd(x, y) {
return `translate(${parseInt(x, 10)},${parseInt(y, 10)})`;
}
/** Draw the graph axes onto the SVG element */
function drawAxes(graphConfig) {
graphConfig.rootElem
.append('g')
.attr('class', 'x axis')
.attr('transform', translateCmd(0, graphConfig.scales.height))
.call(graphConfig.axes.x);
graphConfig.rootElem
.append('g')
.attr('class', 'y axis')
.call(graphConfig.axes.y);
if (_.isNaN(graphConfig.scales.y(0))) {
return;
}
if (graphConfig.symmetricalYAxis) {
graphConfig.rootElem
.append('svg:line')
.attr('class', 'y axis supplemental')
.attr('x1', 0)
.attr('x2', graphConfig.scales.width)
.attr('y1', graphConfig.scales.y(0))
.attr('y2', graphConfig.scales.y(0));
}
}
/** Draw a marker to distinguish a series other than by colour */
function drawPoints(series, index, graphConfig) {
const { scales } = graphConfig;
if (series.length < 2) {
return;
}
const { x: x0, y: y0 } = series[0];
const { y: y1 } = series[1];
const interpolation = interpolateNumber(y0, y1);
// create a point that progressively further from the y-axis
const xDelta = new Date(x0);
const delta = (index * MARKER_OFFSET.mult) + MARKER_OFFSET.constant;
const iDelta = delta / 31; // interpolation requires a number on [0, 1.0]
xDelta.setDate(xDelta.getDate() + delta);
const cssClass = `point v-graph-${index}`;
graphConfig.rootElem
.selectAll(cssClass)
.data([{ x: xDelta, y: interpolation(iDelta) }])
.enter()
.append('path')
.attr('class', cssClass)
.attr('d', (d, i) => symbol().type(SERIES_MARKER[index])(d, i))
.attr('transform', d => translateCmd(scales.x(d.x), scales.y(d.y)));
}
/** Draw an SVG path representing the selected indicator as a line */
function drawLine(series, index, graphConfig) {
const { x, y } = graphConfig.scales;
const ln = line()
.x(d => x(d.x))
.y(d => y(d.y));
graphConfig.rootElem
.append('path')
.datum(series)
.attr('class', `line v-graph-${index}`)
.attr('d', ln);
}
/** Draw the lines or other forms used to portray the data series */
function drawGraphLines(series, index, graphConfig) {
switch (graphConfig.graphType) {
case 'lineAndPoints':
drawPoints(series, index, graphConfig);
drawLine(series, index, graphConfig);
break;
default:
Raven.captureMessage(`Unknown graph type: ${graphConfig.graphType}`);
}
}
const bisectDate = bisector(d => d.x).left;
function formatStatistic(indicator, statistic, value) {
const abbrev = {
all: 'all ',
det: 'det. ',
sem: 's.det. ',
ter: 'terr. ',
fla: 'f/m. ',
}[statistic.slug];
return (abbrev || statistic.label) + formatValue(indicator + statistic, value);
}
function xTrackLabel(statistic, projection, graphConfig, d) {
const series = projection[statistic.slug];
const value = _.find(series, { x: d.x });
return formatStatistic(graphConfig.indicatorId, statistic, value && value.y);
}
/** Track mouse movement and update the overlay */
function onXTrackMouseMove(projection, graphConfig, xTrack) {
const aSeries = _.first(_.values(projection));
if (_.isEmpty(aSeries)) {
return;
}
const { x } = graphConfig.scales;
const x0 = x.invert(mouse(graphConfig.rootElem.node())[0]);
const i = bisectDate(aSeries, x0, 1);
const d0 = aSeries[i - 1];
const d1 = aSeries[i];
const d = (d1 && (x0 - d0.x > d1.x - x0)) ? d1 : d0;
xTrack.attr('transform', translateCmd(x(d.x), -10));
const dateLabel = timeFormat('%b %Y')(d.x);
const labeller = (() => (statistic => xTrackLabel(statistic, projection, graphConfig, d)))();
const label = `${dateLabel}: ${_.map(visibleStatistics(graphConfig), labeller).join(', ')}`;
const labelElem = xTrack.select('text');
const txtLen = labelElem
.text(label)
.node()
.getComputedTextLength();
const maxLeft = graphConfig.scales.width - txtLen;
const delta = maxLeft - x(d.x);
if (delta < 0) {
labelElem.attr('transform', translateCmd(delta, 0));
} else {
labelElem.attr('transform', translateCmd(0, 0));
}
}
/** Prepare the elements necessary to draw the overlay, and set event listeners */
function prepareOverlay(projection, graphConfig) {
const xTrack = graphConfig
.rootElem
.append('g')
.attr('class', 'o-x-track__g')
.style('display', 'none');
xTrack
.append('rect')
.attr('class', 'o-x-track')
.attr('height', graphConfig.scales.height)
.attr('width', 0.5)
.attr('stroke-dasharray', '5,5')
.attr('y', 10);
xTrack
.append('text')
.attr('class', 'o-x-track__title')
.attr('y', 0)
.append('dy', '0.35em');
graphConfig
.rootElem
.append('rect')
.attr('class', 'o-graph-overlay')
.attr('width', graphConfig.scales.width)
.attr('height', graphConfig.scales.height)
.on('mouseover', () => { xTrack.style('display', null); })
.on('mouseout', () => { xTrack.style('display', 'none'); })
.on('mousemove', (() =>
() => { onXTrackMouseMove(projection, graphConfig, xTrack); }
)());
}
/** Generate a warning when there is no data to display */
function warnNoData(graphConfig) {
const label = graphConfig.theme.label.toLocaleLowerCase();
const location = graphConfig.location.labels.en;
graphConfig
.rootElem
.append('text')
.attr('x', 35)
.attr('y', 50)
.text(`Sorry, there is no ${label} data available for ${location}. Please select a different location.`)
.attr('font-size', '15px')
.attr('font-style', 'italic')
.attr('fill', '#303030');
}
export default function drawGraph(projection, options) {
let nPoints = 0;
const graphConfig = Object.assign({}, GRAPH_OPTIONS[options.indicatorId], options);
Object.assign(graphConfig, drawGraphRoot(graphConfig));
graphConfig.valueRange = calculateValueRange(projection, graphConfig);
Object.assign(graphConfig, configureAxes(graphConfig));
drawAxes(graphConfig);
prepareOverlay(projection, graphConfig);
_.each(_.keys(projection), (slug, index) => {
const series = projection[slug];
if (series.length > 0 && isSelectedStatistic(slug, graphConfig)) {
drawGraphLines(series, index, graphConfig);
nPoints += series.length;
}
});
if (nPoints === 0) {
warnNoData(graphConfig);
}
}
| Additional change for #142 - if only one visible point, retain the markers but against the x-axis
| app/javascript/presenters/data-graph.js | Additional change for #142 - if only one visible point, retain the markers but against the x-axis | <ide><path>pp/javascript/presenters/data-graph.js
<ide> /** Draw a marker to distinguish a series other than by colour */
<ide> function drawPoints(series, index, graphConfig) {
<ide> const { scales } = graphConfig;
<del> if (series.length < 2) {
<add> if (series.length < 1) {
<ide> return;
<ide> }
<ide> const { x: x0, y: y0 } = series[0];
<del> const { y: y1 } = series[1];
<add> const { y: y1 } = series.length > 1 ? series[1] : series[0];
<ide> const interpolation = interpolateNumber(y0, y1);
<ide>
<ide> // create a point that progressively further from the y-axis
<ide> const xDelta = new Date(x0);
<ide> const delta = (index * MARKER_OFFSET.mult) + MARKER_OFFSET.constant;
<ide> const iDelta = delta / 31; // interpolation requires a number on [0, 1.0]
<del> xDelta.setDate(xDelta.getDate() + delta);
<add>
<add> if (series.length > 1) {
<add> xDelta.setDate(xDelta.getDate() + delta);
<add> }
<ide>
<ide> const cssClass = `point v-graph-${index}`;
<ide> |
|
JavaScript | mit | 127be786e0e1665a528f26536b593edb0cf8522a | 0 | Ondoher/grubbot,Ondoher/grubbot | fs = require('fs');
var corp = 'corporate.symphony.com';
var corpApi = 'corporate-api.symphony.com';
var nexus = 'nexus.symphony.com';
var nexusApi = 'nexus-api.symphony.com';
var nexus2 = 'nexus2.symphony.com';
var nexus2Api = 'nexus2-api.symphony.com';
nexusApi = 'nexus-dev-ause1-all.symphony.com';
//nexus = 'nexus-dev-ause1-all.symphony.com';
function base64EncodeUrl(str){
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}
var n1CrazyThreadId = base64EncodeUrl('9FR+lyvLNttuARgs7av3D3///rCPekXbdA=='); //nexus
var n2CrazyThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var nexusThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var n2PrivateThreadId = base64EncodeUrl('DxbnV8++z3vny/SIX7NqGX///qPFMGuYdA==');
var corpTestThreadId = base64EncodeUrl('QBsRAH+GVNvyvRsK9AVufX///qOCFrt8dA==');
var corpPAThreadId = base64EncodeUrl('lX1hwfmQ+AK/k/a/BB0y2n///q2+0KfbdA==');
module.exports = {
bots: {
/**/
'1045': {
keyUrl: 'https://' + corpApi + ':8444/keyauth',
sessionUrl: 'https://' + corpApi + ':8444/sessionauth',
agentUrl: 'https://' + corp + ':443/agent',
podUrl: 'https://' + corp + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/grub.bot-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/grub.bot-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: corpPAThreadId,
},
/*
'130' : {
keyUrl: 'https://' + nexus2 + ':8444/keyauth',
sessionUrl: 'https://' + nexus2 + ':8444/sessionauth',
agentUrl: 'https://' + nexus2 + ':443/agent',
podUrl: 'https://' + nexus2 + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: n2PrivateThreadId,
},
/*
'131' : {
keyUrl: 'https://' + nexusApi + ':8444/keyauth',
sessionUrl: 'https://' + nexusApi + ':8444/sessionauth',
agentUrl: 'https://' + nexus + ':443/agent',
podUrl: 'https://' + nexus + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: n1CrazyThreadId,
}
/**/
},
menuFiles: __dirname + '/../../../menus',
}
| bot/src/config/index.js | fs = require('fs');
var corp = 'corporate.symphony.com';
var corpApi = 'corporate-api.symphony.com';
var nexus = 'nexus.symphony.com';
var nexusApi = 'nexus-api.symphony.com';
var nexus2 = 'nexus2.symphony.com';
var nexus2Api = 'nexus2-api.symphony.com';
nexusApi = 'nexus-dev-ause1-all.symphony.com';
//nexus = 'nexus-dev-ause1-all.symphony.com';
function base64EncodeUrl(str){
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}
var n1CrazyThreadId = base64EncodeUrl('9FR+lyvLNttuARgs7av3D3///rCPekXbdA=='); //nexus
var n2CrazyThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var nexusThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var n2PrivateThreadId = base64EncodeUrl('DxbnV8++z3vny/SIX7NqGX///qPFMGuYdA==');
var corpTestThreadId = base64EncodeUrl('QBsRAH+GVNvyvRsK9AVufX///qOCFrt8dA==');
var corpPAThreadId = base64EncodeUrl('lX1hwfmQ+AK/k/a/BB0y2n///q2+0KfbdA==');
module.exports = {
bots: {
/*
'1045': {
keyUrl: 'https://' + corpApi + ':8444/keyauth',
sessionUrl: 'https://' + corpApi + ':8444/sessionauth',
agentUrl: 'https://' + corp + ':443/agent',
podUrl: 'https://' + corp + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/grub.bot-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/grub.bot-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: corpPAThreadId,
},
/**/
'130' : {
keyUrl: 'https://' + nexus2 + ':8444/keyauth',
sessionUrl: 'https://' + nexus2 + ':8444/sessionauth',
agentUrl: 'https://' + nexus2 + ':443/agent',
podUrl: 'https://' + nexus2 + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: n2PrivateThreadId,
},
/*
'131' : {
keyUrl: 'https://' + nexusApi + ':8444/keyauth',
sessionUrl: 'https://' + nexusApi + ':8444/sessionauth',
agentUrl: 'https://' + nexus + ':443/agent',
podUrl: 'https://' + nexus + ':443/pod',
auth: {
cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
passphrase: 'changeit',
},
threadId: n1CrazyThreadId,
}
/**/
},
menuFiles: __dirname + '/../../../menus',
}
| - not configured properly
| bot/src/config/index.js | - not configured properly | <ide><path>ot/src/config/index.js
<ide>
<ide> module.exports = {
<ide> bots: {
<del>/*
<add>/**/
<ide> '1045': {
<ide> keyUrl: 'https://' + corpApi + ':8444/keyauth',
<ide> sessionUrl: 'https://' + corpApi + ':8444/sessionauth',
<ide> },
<ide> threadId: corpPAThreadId,
<ide> },
<del>/**/
<add>/*
<ide> '130' : {
<ide> keyUrl: 'https://' + nexus2 + ':8444/keyauth',
<ide> sessionUrl: 'https://' + nexus2 + ':8444/sessionauth', |
|
JavaScript | mit | ea733435b17b8acc95051f1309c72c97df3d848c | 0 | hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,RJFreund/OpenDSA,RJFreund/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA | (function ($) {
"use strict";
/*global alert: true, ODSA */
$(document).ready(function () {
var initData, bh,
settings = new JSAV.utils.Settings($(".jsavsettings")),
jsav = new JSAV($('.avcontainer'), {settings: settings}),
exercise,
swapIndex, graph, modelGraph;
jsav.recorded();
function init() {
if(graph)
{
graph.clear();
}
graph = jsav.ds.graph({width: 600, height: 600, layout: "manual", directed: false});
initGraph();
graph.layout();
jsav.displayInit();
return graph;
}
function fixState(mGraph) {
}
function model(modeljsav) {
modelGraph = modeljsav.ds.graph({width: 600, height: 600, layout: "manual", directed: false});
initModelGraph();
modelGraph.layout();
modeljsav._undo = [];
modeljsav.displayInit();
modelGraph.nodes()[0].highlight();
modeljsav.stepOption("grade", true);
/*
for(var i=0;i<modelGraph.nodeCount();i++)
{
modeljsav.umsg("Highlighting node "+modelGraph.nodes()[i].value());
modelGraph.nodes()[i].highlight();
modeljsav.stepOption("grade", true);
modeljsav.step();
}
*/
return modelGraph;
}
function initGraph() {
//Nodes of the original graph
var a = graph.addNode("A", {"left": 25, "top": 50});
var b = graph.addNode("B", {"left": 325, "top": 50});
var c = graph.addNode("C", {"left": 145, "top": 75});
var d = graph.addNode("D", {"left": 145, "top": 200});
var e = graph.addNode("E", {"left": 0, "top": 300});
var f = graph.addNode("F", {"left": 325, "top": 250});
//Original graph edges
graph.addEdge(a, c, {"weight": 7});
graph.addEdge(a, e, {"weight": 9});
graph.addEdge(c, b, {"weight": 5});
graph.addEdge(c, d, {"weight": 1});
graph.addEdge(c, f, {"weight": 2});
graph.addEdge(f, b, {"weight": 6});
graph.addEdge(d, f, {"weight": 2});
graph.addEdge(e, f, {"weight": 1});
}
function initModelGraph() {
//Nodes of the original graph
var a = modelGraph.addNode("A", {"left": 25, "top": 50});
var b = modelGraph.addNode("B", {"left": 325, "top": 50});
var c = modelGraph.addNode("C", {"left": 145, "top": 75});
var d = modelGraph.addNode("D", {"left": 145, "top": 200});
var e = modelGraph.addNode("E", {"left": 0, "top": 300});
var f = modelGraph.addNode("F", {"left": 325, "top": 250});
//Original graph edges
modelGraph.addEdge(a, c, {"weight": 7});
modelGraph.addEdge(a, e, {"weight": 9});
modelGraph.addEdge(c, b, {"weight": 5});
modelGraph.addEdge(c, d, {"weight": 1});
modelGraph.addEdge(c, f, {"weight": 2});
modelGraph.addEdge(f, b, {"weight": 6});
modelGraph.addEdge(d, f, {"weight": 2});
modelGraph.addEdge(e, f, {"weight": 1});
}
// Process About button: Pop up a message with an Alert
function about() {
alert("Heapsort Proficiency Exercise\nWritten by Ville Karavirta\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
}
exercise = jsav.exercise(model, init, { css: "background-color" },
{feedback: "continuous",
controls: $('.jsavexercisecontrols'),
fixmode: "fix",
fix: fixState });
exercise.reset();
$(".jsavcontainer").on("click",".jsavgraphnode", function () {
var nodeIndex=$(this).parent(".jsavgraph").find(".jsavgraphnode").index(this);
graph.nodes()[nodeIndex].highlight();
//jsav.step();
exercise.gradeableStep();
});
$("#about").click(about);
});
}(jQuery));
| AV/Development/PrimAVPE.js | (function ($) {
"use strict";
/*global alert: true, ODSA */
$(document).ready(function () {
var initData, bh,
settings = new JSAV.utils.Settings($(".jsavsettings")),
jsav = new JSAV($('.avcontainer'), {settings: settings}),
exercise,
swapIndex, graph, modelGraph;
jsav.recorded();
function init() {
if(graph)
{
graph.clear();
}
graph = jsav.ds.graph({width: 600, height: 600, layout: "manual", directed: false});
initGraph();
graph.layout();
jsav.displayInit();
return graph;
}
function fixState(modelHeap) {
}
function model(modeljsav) {
modelGraph = modeljsav.ds.graph({width: 600, height: 600, layout: "manual", directed: false});
initModelGraph();
modelGraph.layout();
//modeljsav._undo = [];
modeljsav.displayInit();
for(var i=0;i<modelGraph.nodeCount();i++)
{
modeljsav.umsg("Highlighting node "+modelGraph.nodes()[i].value());
modelGraph.nodes()[i].highlight();
modeljsav.stepOption("grade", true);
modeljsav.step();
}
return modelGraph;
}
function initGraph() {
//Nodes of the original graph
var a = graph.addNode("A", {"left": 25, "top": 50});
var b = graph.addNode("B", {"left": 325, "top": 50});
var c = graph.addNode("C", {"left": 145, "top": 75});
var d = graph.addNode("D", {"left": 145, "top": 200});
var e = graph.addNode("E", {"left": 0, "top": 300});
var f = graph.addNode("F", {"left": 325, "top": 250});
//Original graph edges
graph.addEdge(a, c, {"weight": 7});
graph.addEdge(a, e, {"weight": 9});
graph.addEdge(c, b, {"weight": 5});
graph.addEdge(c, d, {"weight": 1});
graph.addEdge(c, f, {"weight": 2});
graph.addEdge(f, b, {"weight": 6});
graph.addEdge(d, f, {"weight": 2});
graph.addEdge(e, f, {"weight": 1});
}
function initModelGraph() {
//Nodes of the original graph
var a = modelGraph.addNode("A", {"left": 25, "top": 50});
var b = modelGraph.addNode("B", {"left": 325, "top": 50});
var c = modelGraph.addNode("C", {"left": 145, "top": 75});
var d = modelGraph.addNode("D", {"left": 145, "top": 200});
var e = modelGraph.addNode("E", {"left": 0, "top": 300});
var f = modelGraph.addNode("F", {"left": 325, "top": 250});
//Original graph edges
modelGraph.addEdge(a, c, {"weight": 7});
modelGraph.addEdge(a, e, {"weight": 9});
modelGraph.addEdge(c, b, {"weight": 5});
modelGraph.addEdge(c, d, {"weight": 1});
modelGraph.addEdge(c, f, {"weight": 2});
modelGraph.addEdge(f, b, {"weight": 6});
modelGraph.addEdge(d, f, {"weight": 2});
modelGraph.addEdge(e, f, {"weight": 1});
}
// Process About button: Pop up a message with an Alert
function about() {
alert("Heapsort Proficiency Exercise\nWritten by Ville Karavirta\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
}
exercise = jsav.exercise(model, init, { css: "background-color" },
{ feedback: "continuous",
controls: $('.jsavexercisecontrols'),
fixmode: "fix",
fix: fixState });
exercise.reset();
$(".jsavcontainer").on("click",".jsavgraphnode", function () {
var nodeIndex=$(this).parent(".jsavgraph").find(".jsavgraphnode").index(this);
graph.nodes()[nodeIndex].highlight();
jsav.step();
exercise.gradeableStep();
});
$("#about").click(about);
});
}(jQuery));
| An oversimplified Toy Graph exercise example
| AV/Development/PrimAVPE.js | An oversimplified Toy Graph exercise example | <ide><path>V/Development/PrimAVPE.js
<ide> return graph;
<ide> }
<ide>
<del> function fixState(modelHeap) {
<add> function fixState(mGraph) {
<ide>
<ide> }
<ide>
<ide> modelGraph = modeljsav.ds.graph({width: 600, height: 600, layout: "manual", directed: false});
<ide> initModelGraph();
<ide> modelGraph.layout();
<del> //modeljsav._undo = [];
<add> modeljsav._undo = [];
<ide> modeljsav.displayInit();
<add> modelGraph.nodes()[0].highlight();
<add> modeljsav.stepOption("grade", true);
<add> /*
<ide> for(var i=0;i<modelGraph.nodeCount();i++)
<ide> {
<ide> modeljsav.umsg("Highlighting node "+modelGraph.nodes()[i].value());
<ide> modeljsav.stepOption("grade", true);
<ide> modeljsav.step();
<ide> }
<add> */
<ide> return modelGraph;
<ide> }
<ide>
<ide> modelGraph.addEdge(e, f, {"weight": 1});
<ide> }
<ide>
<del> // Process About button: Pop up a message with an Alert
<add> // Process About button: Pop up a message with an Alert
<ide> function about() {
<ide> alert("Heapsort Proficiency Exercise\nWritten by Ville Karavirta\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
<ide> }
<ide>
<ide> exercise = jsav.exercise(model, init, { css: "background-color" },
<del> { feedback: "continuous",
<add> {feedback: "continuous",
<ide> controls: $('.jsavexercisecontrols'),
<ide> fixmode: "fix",
<ide> fix: fixState });
<ide> $(".jsavcontainer").on("click",".jsavgraphnode", function () {
<ide> var nodeIndex=$(this).parent(".jsavgraph").find(".jsavgraphnode").index(this);
<ide> graph.nodes()[nodeIndex].highlight();
<del> jsav.step();
<add> //jsav.step();
<ide> exercise.gradeableStep();
<ide> });
<ide> $("#about").click(about); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.