repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/beans/NeuroMotorRootValueVoBean.java
4498
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo.beans; public class NeuroMotorRootValueVoBean extends ims.vo.ValueObjectBean { public NeuroMotorRootValueVoBean() { } public NeuroMotorRootValueVoBean(ims.generalmedical.vo.NeuroMotorRootValueVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.rootvalue = vo.getRootValue() == null ? null : (ims.core.vo.beans.VertebrallevelVoBean)vo.getRootValue().getBean(); this.rightfinding = vo.getRightFinding(); this.leftfinding = vo.getLeftFinding(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.NeuroMotorRootValueVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.rootvalue = vo.getRootValue() == null ? null : (ims.core.vo.beans.VertebrallevelVoBean)vo.getRootValue().getBean(map); this.rightfinding = vo.getRightFinding(); this.leftfinding = vo.getLeftFinding(); } public ims.generalmedical.vo.NeuroMotorRootValueVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.generalmedical.vo.NeuroMotorRootValueVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.NeuroMotorRootValueVo vo = null; if(map != null) vo = (ims.generalmedical.vo.NeuroMotorRootValueVo)map.getValueObject(this); if(vo == null) { vo = new ims.generalmedical.vo.NeuroMotorRootValueVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.core.vo.beans.VertebrallevelVoBean getRootValue() { return this.rootvalue; } public void setRootValue(ims.core.vo.beans.VertebrallevelVoBean value) { this.rootvalue = value; } public Integer getRightFinding() { return this.rightfinding; } public void setRightFinding(Integer value) { this.rightfinding = value; } public Integer getLeftFinding() { return this.leftfinding; } public void setLeftFinding(Integer value) { this.leftfinding = value; } private Integer id; private int version; private ims.core.vo.beans.VertebrallevelVoBean rootvalue; private Integer rightfinding; private Integer leftfinding; }
agpl-3.0
automenta/spimedb
media/src/test/java/spimedb/media/SchemaOrgTest.java
1692
package spimedb.media; import org.junit.Test; import spimedb.SpimeDB; import java.io.IOException; import static org.junit.Assert.assertTrue; /** * tests schema.org import and the type hierarchy creation and inference * ie. equivalent of a mini-RDFS reasoner */ public class SchemaOrgTest { @Test public void test1() throws IOException { SpimeDB db = new SpimeDB(); SchemaOrg.load(db); // r.graph.vertexSet().forEach(v -> { // System.out.println(v); // System.out.println("\t" + r.graph.edgesOf(v)); // }); db.sync(50); assertTrue(db.size() + " has at least 500?" , db.size() > 500); // assertEquals(1, db.graph.outDegreeOf("Action")); // assertTrue(db.graph.inDegreeOf("Action") > 1); // // //System.out.println(db.tags.graph.vertex("Action", false).outVset()); // //System.out.println(db.get("replace")); // // assertEquals(1, db.graph.outDegreeOf("Place")); // assertTrue(db.graph.inDegreeOf("Place") > 1); //TODO: assertTrue(r.tags.isConnected) // System.out.println(r.graph.vertexSet().size() + " " + r.graph.edgeSet().size()); // assertTrue(r.graph.edgeSet().size() > 1000); //AllDirectedPaths a = new AllDirectedPaths(r.graph); // AStarShortestPath a = new AStarShortestPath(r.graph); // GraphPath p1 = a.getShortestPath("Casino", "Place", (x, y) -> 1); // System.out.println(p1); // Object copy = r.graph.clone() // trans = TransitiveClosure.INSTANCE.closeSimpleDirectedGraph(copy); // System.out.println(trans.getClass()); // System.out.println(trans.getClass()); } }
agpl-3.0
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ChunkConditionBar.java
3681
/* * ChunkConditionBar.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text; import org.rstudio.core.client.ColorUtil; import org.rstudio.core.client.js.JsArrayEx; import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkOutputUi; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; public class ChunkConditionBar extends Composite implements EditorThemeListener { private static ChunkConditionBarUiBinder uiBinder = GWT .create(ChunkConditionBarUiBinder.class); interface ChunkConditionBarUiBinder extends UiBinder<Widget, ChunkConditionBar> { } public interface ConditionStyle extends CssResource { String contents(); } public ChunkConditionBar(JsArray<JsArrayEx> conditions, ChunkOutputSize chunkOutputSize) { chunkOutputSize_ = chunkOutputSize; initWidget(uiBinder.createAndBindUi(this)); for (int i = 0; i < conditions.length(); i++) { HorizontalPanel bar; VerticalPanel contents; if (conditions.get(i).getInt(0) == CONDITION_MESSAGE) { bar = messageBar_; contents = messages_; } else if (conditions.get(i).getInt(0) == CONDITION_WARNING) { bar = warningBar_; contents = warnings_; } else { continue; } bar.setVisible(true); Label entry = new Label(conditions.get(i).getString(1)); entry.addStyleName(style.contents()); contents.add(entry); } if (chunkOutputSize_ != ChunkOutputSize.Full) { // limit bar width to plot width getElement().getStyle().setProperty("maxWidth", "" + ChunkOutputUi.MAX_PLOT_WIDTH + "px"); } } @Override public void onEditorThemeChanged(Colors colors) { // create a background color by softening the foreground ColorUtil.RGBColor foreground = ColorUtil.RGBColor.fromCss(colors.foreground); ColorUtil.RGBColor background = new ColorUtil.RGBColor( foreground.red(), foreground.green(), foreground.blue(), 0.075); panel_.getElement().getStyle().setBackgroundColor(background.asRgb()); } @UiField HorizontalPanel messageBar_; @UiField HorizontalPanel warningBar_; @UiField VerticalPanel messages_; @UiField VerticalPanel warnings_; @UiField ConditionStyle style; @UiField VerticalPanel panel_; // symmetric with enum on server public final static int CONDITION_MESSAGE = 0; public final static int CONDITION_WARNING = 1; final ChunkOutputSize chunkOutputSize_; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/PDSBackOfficeItemVo.java
19455
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.vo; /** * Linked to core.admin.PDSBackOfficeItem business object (ID: 1004100073). */ public class PDSBackOfficeItemVo extends ims.core.admin.vo.PDSBackOfficeItemRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public PDSBackOfficeItemVo() { } public PDSBackOfficeItemVo(Integer id, int version) { super(id, version); } public PDSBackOfficeItemVo(ims.core.vo.beans.PDSBackOfficeItemVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.type = bean.getType() == null ? null : ims.core.vo.lookups.PDSBackOfficeType.buildLookup(bean.getType()); this.description = bean.getDescription(); this.source = bean.getSource(); this.priority = bean.getPriority() == null ? null : ims.core.vo.lookups.PDSBackOfficeWorkPriority.buildLookup(bean.getPriority()); this.currentstatus = bean.getCurrentStatus() == null ? null : ims.core.vo.lookups.PDSBackOfficeWorkStatus.buildLookup(bean.getCurrentStatus()); this.statushistory = ims.core.vo.PDSBackOfficeStatusVoCollection.buildFromBeanCollection(bean.getStatusHistory()); this.nhsnumber = bean.getNHSNumber(); this.nhsnumbersuperseded = bean.getNHSNumberSuperseded(); this.outcome = bean.getOutcome() == null ? null : ims.core.vo.lookups.PDSBackOfficeOutcome.buildLookup(bean.getOutcome()); this.updatetype = bean.getUpdateType() == null ? null : ims.core.vo.lookups.PDSUpdateType.buildLookup(bean.getUpdateType()); this.registeryauthoritytype = bean.getRegisteryAuthorityType() == null ? null : ims.core.vo.lookups.PDSRegisteringAuthorityType.buildLookup(bean.getRegisteryAuthorityType()); this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion()); this.notifications = ims.core.vo.NotificationVoCollection.buildFromBeanCollection(bean.getNotifications()); this.systeminformation = bean.getSystemInformation() == null ? null : bean.getSystemInformation().buildSystemInformation(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.beans.PDSBackOfficeItemVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.type = bean.getType() == null ? null : ims.core.vo.lookups.PDSBackOfficeType.buildLookup(bean.getType()); this.description = bean.getDescription(); this.source = bean.getSource(); this.priority = bean.getPriority() == null ? null : ims.core.vo.lookups.PDSBackOfficeWorkPriority.buildLookup(bean.getPriority()); this.currentstatus = bean.getCurrentStatus() == null ? null : ims.core.vo.lookups.PDSBackOfficeWorkStatus.buildLookup(bean.getCurrentStatus()); this.statushistory = ims.core.vo.PDSBackOfficeStatusVoCollection.buildFromBeanCollection(bean.getStatusHistory()); this.nhsnumber = bean.getNHSNumber(); this.nhsnumbersuperseded = bean.getNHSNumberSuperseded(); this.outcome = bean.getOutcome() == null ? null : ims.core.vo.lookups.PDSBackOfficeOutcome.buildLookup(bean.getOutcome()); this.updatetype = bean.getUpdateType() == null ? null : ims.core.vo.lookups.PDSUpdateType.buildLookup(bean.getUpdateType()); this.registeryauthoritytype = bean.getRegisteryAuthorityType() == null ? null : ims.core.vo.lookups.PDSRegisteringAuthorityType.buildLookup(bean.getRegisteryAuthorityType()); this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion()); this.notifications = ims.core.vo.NotificationVoCollection.buildFromBeanCollection(bean.getNotifications()); this.systeminformation = bean.getSystemInformation() == null ? null : bean.getSystemInformation().buildSystemInformation(); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.core.vo.beans.PDSBackOfficeItemVoBean bean = null; if(map != null) bean = (ims.core.vo.beans.PDSBackOfficeItemVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.core.vo.beans.PDSBackOfficeItemVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("TYPE")) return getType(); if(fieldName.equals("DESCRIPTION")) return getDescription(); if(fieldName.equals("SOURCE")) return getSource(); if(fieldName.equals("PRIORITY")) return getPriority(); if(fieldName.equals("CURRENTSTATUS")) return getCurrentStatus(); if(fieldName.equals("STATUSHISTORY")) return getStatusHistory(); if(fieldName.equals("NHSNUMBER")) return getNHSNumber(); if(fieldName.equals("NHSNUMBERSUPERSEDED")) return getNHSNumberSuperseded(); if(fieldName.equals("OUTCOME")) return getOutcome(); if(fieldName.equals("UPDATETYPE")) return getUpdateType(); if(fieldName.equals("REGISTERYAUTHORITYTYPE")) return getRegisteryAuthorityType(); if(fieldName.equals("PATIENT")) return getPatient(); if(fieldName.equals("NOTIFICATIONS")) return getNotifications(); if(fieldName.equals("SYSTEMINFORMATION")) return getSystemInformation(); return super.getFieldValueByFieldName(fieldName); } public boolean getTypeIsNotNull() { return this.type != null; } public ims.core.vo.lookups.PDSBackOfficeType getType() { return this.type; } public void setType(ims.core.vo.lookups.PDSBackOfficeType value) { this.isValidated = false; this.type = value; } public boolean getDescriptionIsNotNull() { return this.description != null; } public String getDescription() { return this.description; } public static int getDescriptionMaxLength() { return 2000; } public void setDescription(String value) { this.isValidated = false; this.description = value; } public boolean getSourceIsNotNull() { return this.source != null; } public String getSource() { return this.source; } public static int getSourceMaxLength() { return 100; } public void setSource(String value) { this.isValidated = false; this.source = value; } public boolean getPriorityIsNotNull() { return this.priority != null; } public ims.core.vo.lookups.PDSBackOfficeWorkPriority getPriority() { return this.priority; } public void setPriority(ims.core.vo.lookups.PDSBackOfficeWorkPriority value) { this.isValidated = false; this.priority = value; } public boolean getCurrentStatusIsNotNull() { return this.currentstatus != null; } public ims.core.vo.lookups.PDSBackOfficeWorkStatus getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.core.vo.lookups.PDSBackOfficeWorkStatus value) { this.isValidated = false; this.currentstatus = value; } public boolean getStatusHistoryIsNotNull() { return this.statushistory != null; } public ims.core.vo.PDSBackOfficeStatusVoCollection getStatusHistory() { return this.statushistory; } public void setStatusHistory(ims.core.vo.PDSBackOfficeStatusVoCollection value) { this.isValidated = false; this.statushistory = value; } public boolean getNHSNumberIsNotNull() { return this.nhsnumber != null; } public String getNHSNumber() { return this.nhsnumber; } public static int getNHSNumberMaxLength() { return 20; } public void setNHSNumber(String value) { this.isValidated = false; this.nhsnumber = value; } public boolean getNHSNumberSupersededIsNotNull() { return this.nhsnumbersuperseded != null; } public String getNHSNumberSuperseded() { return this.nhsnumbersuperseded; } public static int getNHSNumberSupersededMaxLength() { return 20; } public void setNHSNumberSuperseded(String value) { this.isValidated = false; this.nhsnumbersuperseded = value; } public boolean getOutcomeIsNotNull() { return this.outcome != null; } public ims.core.vo.lookups.PDSBackOfficeOutcome getOutcome() { return this.outcome; } public void setOutcome(ims.core.vo.lookups.PDSBackOfficeOutcome value) { this.isValidated = false; this.outcome = value; } public boolean getUpdateTypeIsNotNull() { return this.updatetype != null; } public ims.core.vo.lookups.PDSUpdateType getUpdateType() { return this.updatetype; } public void setUpdateType(ims.core.vo.lookups.PDSUpdateType value) { this.isValidated = false; this.updatetype = value; } public boolean getRegisteryAuthorityTypeIsNotNull() { return this.registeryauthoritytype != null; } public ims.core.vo.lookups.PDSRegisteringAuthorityType getRegisteryAuthorityType() { return this.registeryauthoritytype; } public void setRegisteryAuthorityType(ims.core.vo.lookups.PDSRegisteringAuthorityType value) { this.isValidated = false; this.registeryauthoritytype = value; } public boolean getPatientIsNotNull() { return this.patient != null; } public ims.core.patient.vo.PatientRefVo getPatient() { return this.patient; } public void setPatient(ims.core.patient.vo.PatientRefVo value) { this.isValidated = false; this.patient = value; } public boolean getNotificationsIsNotNull() { return this.notifications != null; } public ims.core.vo.NotificationVoCollection getNotifications() { return this.notifications; } public void setNotifications(ims.core.vo.NotificationVoCollection value) { this.isValidated = false; this.notifications = value; } public boolean getSystemInformationIsNotNull() { return this.systeminformation != null; } public ims.vo.SystemInformation getSystemInformation() { return this.systeminformation; } public void setSystemInformation(ims.vo.SystemInformation value) { this.isValidated = false; this.systeminformation = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } if(this.statushistory != null) { if(!this.statushistory.isValidated()) { this.isBusy = false; return false; } } if(this.notifications != null) { if(!this.notifications.isValidated()) { this.isBusy = false; return false; } } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.description != null) if(this.description.length() > 2000) listOfErrors.add("The length of the field [description] in the value object [ims.core.vo.PDSBackOfficeItemVo] is too big. It should be less or equal to 2000"); if(this.source != null) if(this.source.length() > 100) listOfErrors.add("The length of the field [source] in the value object [ims.core.vo.PDSBackOfficeItemVo] is too big. It should be less or equal to 100"); if(this.statushistory != null) { String[] listOfOtherErrors = this.statushistory.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.nhsnumber != null) if(this.nhsnumber.length() > 20) listOfErrors.add("The length of the field [nhsnumber] in the value object [ims.core.vo.PDSBackOfficeItemVo] is too big. It should be less or equal to 20"); if(this.nhsnumbersuperseded != null) if(this.nhsnumbersuperseded.length() > 20) listOfErrors.add("The length of the field [nhsnumbersuperseded] in the value object [ims.core.vo.PDSBackOfficeItemVo] is too big. It should be less or equal to 20"); if(this.notifications != null) { String[] listOfOtherErrors = this.notifications.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; PDSBackOfficeItemVo clone = new PDSBackOfficeItemVo(this.id, this.version); if(this.type == null) clone.type = null; else clone.type = (ims.core.vo.lookups.PDSBackOfficeType)this.type.clone(); clone.description = this.description; clone.source = this.source; if(this.priority == null) clone.priority = null; else clone.priority = (ims.core.vo.lookups.PDSBackOfficeWorkPriority)this.priority.clone(); if(this.currentstatus == null) clone.currentstatus = null; else clone.currentstatus = (ims.core.vo.lookups.PDSBackOfficeWorkStatus)this.currentstatus.clone(); if(this.statushistory == null) clone.statushistory = null; else clone.statushistory = (ims.core.vo.PDSBackOfficeStatusVoCollection)this.statushistory.clone(); clone.nhsnumber = this.nhsnumber; clone.nhsnumbersuperseded = this.nhsnumbersuperseded; if(this.outcome == null) clone.outcome = null; else clone.outcome = (ims.core.vo.lookups.PDSBackOfficeOutcome)this.outcome.clone(); if(this.updatetype == null) clone.updatetype = null; else clone.updatetype = (ims.core.vo.lookups.PDSUpdateType)this.updatetype.clone(); if(this.registeryauthoritytype == null) clone.registeryauthoritytype = null; else clone.registeryauthoritytype = (ims.core.vo.lookups.PDSRegisteringAuthorityType)this.registeryauthoritytype.clone(); clone.patient = this.patient; if(this.notifications == null) clone.notifications = null; else clone.notifications = (ims.core.vo.NotificationVoCollection)this.notifications.clone(); if(this.systeminformation == null) clone.systeminformation = null; else clone.systeminformation = (ims.vo.SystemInformation)this.systeminformation.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(PDSBackOfficeItemVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A PDSBackOfficeItemVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((PDSBackOfficeItemVo)obj).getBoId() == null) return -1; return this.id.compareTo(((PDSBackOfficeItemVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.type != null) count++; if(this.description != null) count++; if(this.source != null) count++; if(this.priority != null) count++; if(this.currentstatus != null) count++; if(this.statushistory != null) count++; if(this.nhsnumber != null) count++; if(this.nhsnumbersuperseded != null) count++; if(this.outcome != null) count++; if(this.updatetype != null) count++; if(this.registeryauthoritytype != null) count++; if(this.patient != null) count++; if(this.notifications != null) count++; if(this.systeminformation != null) count++; return count; } public int countValueObjectFields() { return 14; } protected ims.core.vo.lookups.PDSBackOfficeType type; protected String description; protected String source; protected ims.core.vo.lookups.PDSBackOfficeWorkPriority priority; protected ims.core.vo.lookups.PDSBackOfficeWorkStatus currentstatus; protected ims.core.vo.PDSBackOfficeStatusVoCollection statushistory; protected String nhsnumber; protected String nhsnumbersuperseded; protected ims.core.vo.lookups.PDSBackOfficeOutcome outcome; protected ims.core.vo.lookups.PDSUpdateType updatetype; protected ims.core.vo.lookups.PDSRegisteringAuthorityType registeryauthoritytype; protected ims.core.patient.vo.PatientRefVo patient; protected ims.core.vo.NotificationVoCollection notifications; protected ims.vo.SystemInformation systeminformation; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/impl/LinkedAppointmentsSummaryImpl.java
3010
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by George Cristian Josan using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. package ims.scheduling.domain.impl; import ims.scheduling.domain.base.impl.BaseLinkedAppointmentsSummaryImpl; import ims.scheduling.domain.objects.Booking_Appointment; import ims.scheduling.vo.Appointment_withLinkedAppointmentsSummaryVo; import ims.scheduling.vo.Booking_AppointmentRefVo; import ims.scheduling.vo.domain.Appointment_withLinkedAppointmentsSummaryVoAssembler; public class LinkedAppointmentsSummaryImpl extends BaseLinkedAppointmentsSummaryImpl { private static final long serialVersionUID = 1L; public Appointment_withLinkedAppointmentsSummaryVo getAppointmentLinkedSummary(Booking_AppointmentRefVo appointment) { if (appointment == null || appointment.getID_Booking_Appointment() == null) return null; return Appointment_withLinkedAppointmentsSummaryVoAssembler.create((Booking_Appointment) getDomainFactory().getDomainObject(Booking_Appointment.class, appointment.getID_Booking_Appointment())); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/themecontrolstest/GenForm.java
138424
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.themecontrolstest; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } public static class lyrMainLayer extends Layer { private static final long serialVersionUID = 1L; public static class tabCombosListsContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class chklistCheckListCheckedListBox extends CheckedListBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.lookups.Specialty value, boolean checked, boolean enabled) { super.control.newItem(new ListItem(value, value.getText(), value.getImage(), value.getTextColor(), checked, enabled)); } public void newRow(ims.core.vo.lookups.Specialty value) { super.control.newItem(new ListItem(value, value.getText(), value.getImage(), value.getTextColor())); } public void newRow(ims.core.vo.lookups.Specialty value, boolean checked) { super.control.newItem(new ListItem(value, value.getText(), value.getImage(), value.getTextColor(), checked, true)); } public ims.core.vo.lookups.SpecialtyCollection getValues() { ListItemCollection checkedItems = super.control.getCheckedItems(); if(checkedItems.size() == 0) return null; ims.core.vo.lookups.SpecialtyCollection items = new ims.core.vo.lookups.SpecialtyCollection(); for(int x = 0; x < checkedItems.size(); x++) { items.add((ims.core.vo.lookups.Specialty)checkedItems.get(x).getValue()); } return items; } public void setValues(ims.core.vo.lookups.SpecialtyCollection values) { if(values == null) super.control.setCheckedItems(null); else { ListItemCollection checkedItems = new ListItemCollection(); for(int x = 0; x < values.size(); x++) { ListItem item = new ListItem(); item.setValue(values.get(x)); checkedItems.add(item); } super.control.setCheckedItems(checkedItems); } } } public static class cmbComboBoxComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.lookups.Specialty value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.lookups.Specialty value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.lookups.Specialty value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.lookups.Specialty value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.lookups.Specialty value) { return super.control.removeRow(value); } public ims.core.vo.lookups.Specialty getValue() { return (ims.core.vo.lookups.Specialty)super.control.getValue(); } public void setValue(ims.core.vo.lookups.Specialty value) { super.control.setValue(value); } } public static class recbrRecordBrowserRecordBrowser extends RecordBrowserBridge { private static final long serialVersionUID = 1L; public void newRow(String value, String text) { super.control.newRow(value, text); } public void newRow(String value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(String value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(String value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public void newRow(int index, String value, String text) { super.control.newRow(index, value, text); } public void newRow(int index, String value, String text, ims.framework.utils.Image image) { super.control.newRow(index, value, text, image); } public void newRow(int index, String value, String text, ims.framework.utils.Color textColor) { super.control.newRow(index, value, text, textColor); } public void newRow(int index, String value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(index, value, text, image, textColor); } public String getValue() { return (String)super.control.getValue(); } public void setValue(String value) { super.control.setValue(value); } } public static class qmbQueryComboBoxComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(String value, String text) { super.control.newRow(value, text); } public void newRow(String value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(String value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(String value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(String value) { return super.control.removeRow(value); } public String getValue() { return (String)super.control.getValue(); } public void setValue(String value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class ansAnswerBoxAnswerBox extends AnswerBoxBridge { private static final long serialVersionUID = 1L; public void clear() { control.clear(); } public java.util.ArrayList getValues() { return control.getValues(); } public void addOption(ims.core.vo.lookups.YesNoUnknown option) { control.addOption(option); } public ims.core.vo.lookups.YesNoUnknown getValue() { return (ims.core.vo.lookups.YesNoUnknown)super.control.getValue(); } public void setValue(ims.core.vo.lookups.YesNoUnknown value) { super.control.setValue(value); } } public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 368, 48, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Answer Box state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 368, 104, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Checklist state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 368, 160, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Combo Box state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 368, 216, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Query Combo state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 368, 272, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Text Box state", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 16, 282, 55, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Textbox:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 16, 250, 85, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Query Combo:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 16, 218, 69, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Combobox:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 16, 72, 60, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper9.getX()), new Integer(anchoringHelper9.getY()), new Integer(anchoringHelper9.getWidth()), new Integer(anchoringHelper9.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Checklist:", new Integer(1), null, new Integer(0)})); // TextBox Controls RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 112, 280, 224, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(0), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // ComboBox Controls RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 112, 216, 224, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_cmbComboBoxTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbComboBoxTemp); cmbComboBoxComboBox cmbComboBox = (cmbComboBoxComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbComboBoxComboBox.class, m_cmbComboBoxTemp); super.addComboBox(cmbComboBox); // RecordBrowser Controls RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 16, 16, 552, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); RecordBrowser m_recbrRecordBrowserTemp = (RecordBrowser)factory.getControl(RecordBrowser.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), new Integer(-1), ControlState.ENABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, null}); addControl(m_recbrRecordBrowserTemp); recbrRecordBrowserRecordBrowser recbrRecordBrowser = (recbrRecordBrowserRecordBrowser)RecordBrowserFlyweightFactory.getInstance().createRecordBrowserBridge(recbrRecordBrowserRecordBrowser.class, m_recbrRecordBrowserTemp); super.addRecordBrowser(recbrRecordBrowser); // Query ComboBox Controls RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 112, 248, 224, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_qmbQueryComboBoxTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.TRUE, new Integer(1), null, Boolean.FALSE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbQueryComboBoxTemp); qmbQueryComboBoxComboBox qmbQueryComboBox = (qmbQueryComboBoxComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbQueryComboBoxComboBox.class, m_qmbQueryComboBoxTemp); super.addComboBox(qmbQueryComboBox); // CheckedListBox Controls RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 112, 72, 224, 124, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); CheckedListBox m_chklistCheckListTemp = (CheckedListBox)factory.getControl(CheckedListBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper14.getX()), new Integer(anchoringHelper14.getY()), new Integer(anchoringHelper14.getWidth()), new Integer(anchoringHelper14.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, null, Boolean.TRUE, null, new Integer(startTabIndex.intValue() + 1), Boolean.FALSE, new Integer(3)}); addControl(m_chklistCheckListTemp); chklistCheckListCheckedListBox chklistCheckList = (chklistCheckListCheckedListBox)CheckedListBoxFlyweightFactory.getInstance().createCheckedListBoxBridge(chklistCheckListCheckedListBox.class, m_chklistCheckListTemp); super.addCheckedListBox(chklistCheckList); // CheckBox Controls RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 472, 72, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper15.getX()), new Integer(anchoringHelper15.getY()), new Integer(anchoringHelper15.getWidth()), new Integer(anchoringHelper15.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 400, 72, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper16.getX()), new Integer(anchoringHelper16.getY()), new Integer(anchoringHelper16.getWidth()), new Integer(anchoringHelper16.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 472, 128, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 400, 128, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 472, 184, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 400, 184, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 472, 240, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 400, 240, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 472, 296, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper24 = new RuntimeAnchoring(designSize, runtimeSize, 400, 296, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1023), new Integer(anchoringHelper24.getX()), new Integer(anchoringHelper24.getY()), new Integer(anchoringHelper24.getWidth()), new Integer(anchoringHelper24.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); // AnswerBox Controls RuntimeAnchoring anchoringHelper25 = new RuntimeAnchoring(designSize, runtimeSize, 16, 48, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); AnswerBox tmpansAnswerBox = (AnswerBox)factory.getControl(AnswerBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1024), new Integer(anchoringHelper25.getX()), new Integer(anchoringHelper25.getY()), new Integer(anchoringHelper25.getWidth()), new Integer(anchoringHelper25.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Answer Box", Boolean.TRUE, Boolean.TRUE, new Integer(10), Boolean.FALSE}); super.addControl(tmpansAnswerBox); ansAnswerBoxAnswerBox ansAnswerBox = (ansAnswerBoxAnswerBox)AnswerBoxBridgeFlyweightFactory.getInstance().createAnswerBoxBridge(ansAnswerBoxAnswerBox.class, tmpansAnswerBox); super.addAnswerBox(ansAnswerBox); } public TextBox txtTextbox() { return (TextBox)super.getControl(9); } public cmbComboBoxComboBox cmbComboBox() { return (cmbComboBoxComboBox)super.getComboBox(0); } public recbrRecordBrowserRecordBrowser recbrRecordBrowser() { return (recbrRecordBrowserRecordBrowser)super.getRecordBrowser(0); } public qmbQueryComboBoxComboBox qmbQueryComboBox() { return (qmbQueryComboBoxComboBox)super.getComboBox(1); } public chklistCheckListCheckedListBox chklistCheckList() { return (chklistCheckListCheckedListBox)super.getCheckedListBox(0); } public CheckBox chkAnswerBoxEnabled() { return (CheckBox)super.getControl(14); } public CheckBox chkAnswerBoxVisible() { return (CheckBox)super.getControl(15); } public CheckBox chkChecklistEnabled() { return (CheckBox)super.getControl(16); } public CheckBox chkChecklistVisible() { return (CheckBox)super.getControl(17); } public CheckBox chkComboBoxEnabled() { return (CheckBox)super.getControl(18); } public CheckBox chkComboBoxVisible() { return (CheckBox)super.getControl(19); } public CheckBox chkQueryComboEnabled() { return (CheckBox)super.getControl(20); } public CheckBox chkQueryComboVisible() { return (CheckBox)super.getControl(21); } public CheckBox chkTextboxEnabled() { return (CheckBox)super.getControl(22); } public CheckBox chkTextboxVisible() { return (CheckBox)super.getControl(23); } public ansAnswerBoxAnswerBox ansAnswerBox() { return (ansAnswerBoxAnswerBox)super.getAnswerBox(0); } } public static class tabDateTimeContainer extends LayerBridge { private static final long serialVersionUID = 1L; public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper26 = new RuntimeAnchoring(designSize, runtimeSize, 368, 184, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1025), new Integer(anchoringHelper26.getX()), new Integer(anchoringHelper26.getY()), new Integer(anchoringHelper26.getWidth()), new Integer(anchoringHelper26.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Time state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper27 = new RuntimeAnchoring(designSize, runtimeSize, 368, 128, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1026), new Integer(anchoringHelper27.getX()), new Integer(anchoringHelper27.getY()), new Integer(anchoringHelper27.getWidth()), new Integer(anchoringHelper27.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Partial Date state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper28 = new RuntimeAnchoring(designSize, runtimeSize, 368, 72, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1027), new Integer(anchoringHelper28.getX()), new Integer(anchoringHelper28.getY()), new Integer(anchoringHelper28.getWidth()), new Integer(anchoringHelper28.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Date Time state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper29 = new RuntimeAnchoring(designSize, runtimeSize, 368, 16, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1028), new Integer(anchoringHelper29.getX()), new Integer(anchoringHelper29.getY()), new Integer(anchoringHelper29.getWidth()), new Integer(anchoringHelper29.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Date state", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper30 = new RuntimeAnchoring(designSize, runtimeSize, 16, 114, 36, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1029), new Integer(anchoringHelper30.getX()), new Integer(anchoringHelper30.getY()), new Integer(anchoringHelper30.getWidth()), new Integer(anchoringHelper30.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Time:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper31 = new RuntimeAnchoring(designSize, runtimeSize, 16, 82, 71, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1030), new Integer(anchoringHelper31.getX()), new Integer(anchoringHelper31.getY()), new Integer(anchoringHelper31.getWidth()), new Integer(anchoringHelper31.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Patial Date:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper32 = new RuntimeAnchoring(designSize, runtimeSize, 16, 50, 66, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1031), new Integer(anchoringHelper32.getX()), new Integer(anchoringHelper32.getY()), new Integer(anchoringHelper32.getWidth()), new Integer(anchoringHelper32.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Date Time:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper33 = new RuntimeAnchoring(designSize, runtimeSize, 16, 18, 35, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1032), new Integer(anchoringHelper33.getX()), new Integer(anchoringHelper33.getY()), new Integer(anchoringHelper33.getWidth()), new Integer(anchoringHelper33.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Date:", new Integer(1), null, new Integer(0)})); // Date Controls RuntimeAnchoring anchoringHelper34 = new RuntimeAnchoring(designSize, runtimeSize, 96, 16, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1033), new Integer(anchoringHelper34.getX()), new Integer(anchoringHelper34.getY()), new Integer(anchoringHelper34.getWidth()), new Integer(anchoringHelper34.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, null, Boolean.TRUE, null, Boolean.FALSE, null})); // Date Time Controls RuntimeAnchoring anchoringHelper35 = new RuntimeAnchoring(designSize, runtimeSize, 96, 48, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(DateTimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1034), new Integer(anchoringHelper35.getX()), new Integer(anchoringHelper35.getY()), new Integer(anchoringHelper35.getWidth()), new Integer(anchoringHelper35.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, null, Boolean.TRUE, null, Boolean.FALSE, null})); // PartialDateBox Controls RuntimeAnchoring anchoringHelper36 = new RuntimeAnchoring(designSize, runtimeSize, 96, 80, 72, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(PartialDateBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1035), new Integer(anchoringHelper36.getX()), new Integer(anchoringHelper36.getY()), new Integer(anchoringHelper36.getWidth()), new Integer(anchoringHelper36.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, null, Boolean.FALSE, Boolean.TRUE})); // CheckBox Controls RuntimeAnchoring anchoringHelper37 = new RuntimeAnchoring(designSize, runtimeSize, 472, 208, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1036), new Integer(anchoringHelper37.getX()), new Integer(anchoringHelper37.getY()), new Integer(anchoringHelper37.getWidth()), new Integer(anchoringHelper37.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper38 = new RuntimeAnchoring(designSize, runtimeSize, 400, 208, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1037), new Integer(anchoringHelper38.getX()), new Integer(anchoringHelper38.getY()), new Integer(anchoringHelper38.getWidth()), new Integer(anchoringHelper38.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper39 = new RuntimeAnchoring(designSize, runtimeSize, 472, 152, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1038), new Integer(anchoringHelper39.getX()), new Integer(anchoringHelper39.getY()), new Integer(anchoringHelper39.getWidth()), new Integer(anchoringHelper39.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper40 = new RuntimeAnchoring(designSize, runtimeSize, 400, 152, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1039), new Integer(anchoringHelper40.getX()), new Integer(anchoringHelper40.getY()), new Integer(anchoringHelper40.getWidth()), new Integer(anchoringHelper40.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper41 = new RuntimeAnchoring(designSize, runtimeSize, 472, 96, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1040), new Integer(anchoringHelper41.getX()), new Integer(anchoringHelper41.getY()), new Integer(anchoringHelper41.getWidth()), new Integer(anchoringHelper41.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper42 = new RuntimeAnchoring(designSize, runtimeSize, 400, 96, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1041), new Integer(anchoringHelper42.getX()), new Integer(anchoringHelper42.getY()), new Integer(anchoringHelper42.getWidth()), new Integer(anchoringHelper42.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper43 = new RuntimeAnchoring(designSize, runtimeSize, 472, 40, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1042), new Integer(anchoringHelper43.getX()), new Integer(anchoringHelper43.getY()), new Integer(anchoringHelper43.getWidth()), new Integer(anchoringHelper43.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper44 = new RuntimeAnchoring(designSize, runtimeSize, 400, 40, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1043), new Integer(anchoringHelper44.getX()), new Integer(anchoringHelper44.getY()), new Integer(anchoringHelper44.getWidth()), new Integer(anchoringHelper44.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); // Time Controls RuntimeAnchoring anchoringHelper45 = new RuntimeAnchoring(designSize, runtimeSize, 96, 112, 200, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(TimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1044), new Integer(anchoringHelper45.getX()), new Integer(anchoringHelper45.getY()), new Integer(anchoringHelper45.getWidth()), new Integer(anchoringHelper45.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.TRUE, null, Boolean.FALSE, ""})); } public DateControl dteDate() { return (DateControl)super.getControl(8); } public DateTimeControl dtimDateTime() { return (DateTimeControl)super.getControl(9); } public PartialDateBox pdtPartialDate() { return (PartialDateBox)super.getControl(10); } public CheckBox chkTimeEnabled() { return (CheckBox)super.getControl(11); } public CheckBox chkTimeVisible() { return (CheckBox)super.getControl(12); } public CheckBox chkPartialDateEnabled() { return (CheckBox)super.getControl(13); } public CheckBox chkPartialDateVisible() { return (CheckBox)super.getControl(14); } public CheckBox chkDateTimeEnabled() { return (CheckBox)super.getControl(15); } public CheckBox chkDateTimeVisible() { return (CheckBox)super.getControl(16); } public CheckBox chkDateEnabled() { return (CheckBox)super.getControl(17); } public CheckBox chkDateVisible() { return (CheckBox)super.getControl(18); } public TimeControl timTime() { return (TimeControl)super.getControl(19); } } public static class tabDecimalsIntegersContainer extends LayerBridge { private static final long serialVersionUID = 1L; public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper46 = new RuntimeAnchoring(designSize, runtimeSize, 368, 184, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1045), new Integer(anchoringHelper46.getX()), new Integer(anchoringHelper46.getY()), new Integer(anchoringHelper46.getWidth()), new Integer(anchoringHelper46.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Int Range Box state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper47 = new RuntimeAnchoring(designSize, runtimeSize, 368, 128, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1046), new Integer(anchoringHelper47.getX()), new Integer(anchoringHelper47.getY()), new Integer(anchoringHelper47.getWidth()), new Integer(anchoringHelper47.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Int Box state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper48 = new RuntimeAnchoring(designSize, runtimeSize, 368, 72, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1047), new Integer(anchoringHelper48.getX()), new Integer(anchoringHelper48.getY()), new Integer(anchoringHelper48.getWidth()), new Integer(anchoringHelper48.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Decimal Range Box state", new Integer(2), ""})); RuntimeAnchoring anchoringHelper49 = new RuntimeAnchoring(designSize, runtimeSize, 368, 16, 200, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1048), new Integer(anchoringHelper49.getX()), new Integer(anchoringHelper49.getY()), new Integer(anchoringHelper49.getWidth()), new Integer(anchoringHelper49.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Decimal Box state", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper50 = new RuntimeAnchoring(designSize, runtimeSize, 16, 130, 90, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1049), new Integer(anchoringHelper50.getX()), new Integer(anchoringHelper50.getY()), new Integer(anchoringHelper50.getWidth()), new Integer(anchoringHelper50.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Int Box Range:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper51 = new RuntimeAnchoring(designSize, runtimeSize, 16, 98, 51, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1050), new Integer(anchoringHelper51.getX()), new Integer(anchoringHelper51.getY()), new Integer(anchoringHelper51.getWidth()), new Integer(anchoringHelper51.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Int Box:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper52 = new RuntimeAnchoring(designSize, runtimeSize, 16, 50, 93, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1051), new Integer(anchoringHelper52.getX()), new Integer(anchoringHelper52.getY()), new Integer(anchoringHelper52.getWidth()), new Integer(anchoringHelper52.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Decimal Range:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper53 = new RuntimeAnchoring(designSize, runtimeSize, 16, 18, 79, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1052), new Integer(anchoringHelper53.getX()), new Integer(anchoringHelper53.getY()), new Integer(anchoringHelper53.getWidth()), new Integer(anchoringHelper53.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Decimal Box:", new Integer(1), null, new Integer(0)})); // CheckBox Controls RuntimeAnchoring anchoringHelper54 = new RuntimeAnchoring(designSize, runtimeSize, 472, 208, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1053), new Integer(anchoringHelper54.getX()), new Integer(anchoringHelper54.getY()), new Integer(anchoringHelper54.getWidth()), new Integer(anchoringHelper54.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper55 = new RuntimeAnchoring(designSize, runtimeSize, 400, 208, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1054), new Integer(anchoringHelper55.getX()), new Integer(anchoringHelper55.getY()), new Integer(anchoringHelper55.getWidth()), new Integer(anchoringHelper55.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper56 = new RuntimeAnchoring(designSize, runtimeSize, 472, 152, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1055), new Integer(anchoringHelper56.getX()), new Integer(anchoringHelper56.getY()), new Integer(anchoringHelper56.getWidth()), new Integer(anchoringHelper56.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper57 = new RuntimeAnchoring(designSize, runtimeSize, 400, 152, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1056), new Integer(anchoringHelper57.getX()), new Integer(anchoringHelper57.getY()), new Integer(anchoringHelper57.getWidth()), new Integer(anchoringHelper57.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper58 = new RuntimeAnchoring(designSize, runtimeSize, 472, 96, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1057), new Integer(anchoringHelper58.getX()), new Integer(anchoringHelper58.getY()), new Integer(anchoringHelper58.getWidth()), new Integer(anchoringHelper58.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper59 = new RuntimeAnchoring(designSize, runtimeSize, 400, 96, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1058), new Integer(anchoringHelper59.getX()), new Integer(anchoringHelper59.getY()), new Integer(anchoringHelper59.getWidth()), new Integer(anchoringHelper59.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper60 = new RuntimeAnchoring(designSize, runtimeSize, 472, 40, 64, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1059), new Integer(anchoringHelper60.getX()), new Integer(anchoringHelper60.getY()), new Integer(anchoringHelper60.getWidth()), new Integer(anchoringHelper60.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper61 = new RuntimeAnchoring(designSize, runtimeSize, 400, 40, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1060), new Integer(anchoringHelper61.getX()), new Integer(anchoringHelper61.getY()), new Integer(anchoringHelper61.getWidth()), new Integer(anchoringHelper61.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"Visible", Boolean.TRUE, null})); // IntBox Controls RuntimeAnchoring anchoringHelper62 = new RuntimeAnchoring(designSize, runtimeSize, 120, 96, 128, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(IntBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1061), new Integer(anchoringHelper62.getX()), new Integer(anchoringHelper62.getY()), new Integer(anchoringHelper62.getWidth()), new Integer(anchoringHelper62.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, null, null, Boolean.FALSE, new Integer(9)})); // IntRangeBox Controls RuntimeAnchoring anchoringHelper63 = new RuntimeAnchoring(designSize, runtimeSize, 120, 128, 128, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(IntRangeBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1062), new Integer(anchoringHelper63.getX()), new Integer(anchoringHelper63.getY()), new Integer(anchoringHelper63.getWidth()), new Integer(anchoringHelper63.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, Boolean.FALSE})); // DecimalBox Controls RuntimeAnchoring anchoringHelper64 = new RuntimeAnchoring(designSize, runtimeSize, 120, 16, 128, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(DecimalBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1063), new Integer(anchoringHelper64.getX()), new Integer(anchoringHelper64.getY()), new Integer(anchoringHelper64.getWidth()), new Integer(anchoringHelper64.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, new Integer(5), new Integer(2), "The decimal value is invalid. A valid value can have up to 3 digits and up to 2 decimals.", null, Boolean.FALSE})); // DecimalRangeBox Controls RuntimeAnchoring anchoringHelper65 = new RuntimeAnchoring(designSize, runtimeSize, 120, 48, 128, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(DecimalRangeBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1064), new Integer(anchoringHelper65.getX()), new Integer(anchoringHelper65.getY()), new Integer(anchoringHelper65.getWidth()), new Integer(anchoringHelper65.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,new Integer(5), new Integer(2), Boolean.FALSE})); } public CheckBox chkintRangeEnabled() { return (CheckBox)super.getControl(8); } public CheckBox chkintRangeVisible() { return (CheckBox)super.getControl(9); } public CheckBox chkIntBoxEnabled() { return (CheckBox)super.getControl(10); } public CheckBox chkIntBoxVisible() { return (CheckBox)super.getControl(11); } public CheckBox chkDecimalRangeEnabled() { return (CheckBox)super.getControl(12); } public CheckBox chkDecimalRangeVisible() { return (CheckBox)super.getControl(13); } public CheckBox chkDecimalEnabled() { return (CheckBox)super.getControl(14); } public CheckBox chkDecimalVisible() { return (CheckBox)super.getControl(15); } public IntBox intIntBox() { return (IntBox)super.getControl(16); } public IntRangeBox irbIntRangeBox() { return (IntRangeBox)super.getControl(17); } public DecimalBox decDecimalBox() { return (DecimalBox)super.getControl(18); } public DecimalRangeBox drbDecimalRangeBox() { return (DecimalRangeBox)super.getControl(19); } } public static class tabGridContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class grdGridRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdGridRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setColSurnameReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isColSurnameReadOnly() { return super.row.isReadOnly(0); } public void showColSurnameOpened() { super.row.showOpened(0); } public String getColSurname() { return (String)super.row.get(0); } public void setColSurname(String value) { super.row.set(0, value); } public void setCellColSurnameTooltip(String value) { super.row.setTooltip(0, value); } public void setColForenameReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean isColForenameReadOnly() { return super.row.isReadOnly(1); } public void showColForenameOpened() { super.row.showOpened(1); } public String getColForename() { return (String)super.row.get(1); } public void setColForename(String value) { super.row.set(1, value); } public void setCellColForenameTooltip(String value) { super.row.setTooltip(1, value); } public void setColDobReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean isColDobReadOnly() { return super.row.isReadOnly(2); } public void showColDobOpened() { super.row.showOpened(2); } public String getColDob() { return (String)super.row.get(2); } public void setColDob(String value) { super.row.set(2, value); } public void setCellColDobTooltip(String value) { super.row.setTooltip(2, value); } public void setColAddressReadOnly(boolean value) { super.row.setReadOnly(3, value); } public boolean isColAddressReadOnly() { return super.row.isReadOnly(3); } public void showColAddressOpened() { super.row.showOpened(3); } public String getColAddress() { return (String)super.row.get(3); } public void setColAddress(String value) { super.row.set(3, value); } public void setCellColAddressTooltip(String value) { super.row.setTooltip(3, value); } public String getValue() { return (String)super.row.getValue(); } public void setValue(String value) { super.row.setValue(value); } } public static class grdGridRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdGridRowCollection(GridRowCollection collection) { super(collection); } public grdGridRow get(int index) { return new grdGridRow(super.collection.get(index)); } public grdGridRow newRow() { return new grdGridRow(super.collection.newRow()); } public grdGridRow newRow(boolean autoSelect) { return new grdGridRow(super.collection.newRow(autoSelect)); } public grdGridRow newRowAt(int index) { return new grdGridRow(super.collection.newRowAt(index)); } public grdGridRow newRowAt(int index, boolean autoSelect) { return new grdGridRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdGridGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } public String[] getValues() { String[] listOfValues = new String[this.getRows().size()]; for(int x = 0; x < this.getRows().size(); x++) { listOfValues[x] = this.getRows().get(x).getValue(); } return listOfValues; } public String getValue() { return (String)super.grid.getValue(); } public void setValue(String value) { super.grid.setValue(value); } public grdGridRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdGridRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdGridRowCollection getRows() { return new grdGridRowCollection(super.grid.getRows()); } public grdGridRow getRowByValue(String value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdGridRow(row); } public void setColSurnameHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getColSurnameHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setColForenameHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getColForenameHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setColDobHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getColDobHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public void setColAddressHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(3, value); } public String getColAddressHeaderTooltip() { return super.grid.getColumnHeaderTooltip(3); } } public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper66 = new RuntimeAnchoring(designSize, runtimeSize, 456, 240, 120, 128, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1065), new Integer(anchoringHelper66.getX()), new Integer(anchoringHelper66.getY()), new Integer(anchoringHelper66.getWidth()), new Integer(anchoringHelper66.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT,"Grid state", new Integer(2), ""})); // CheckBox Controls RuntimeAnchoring anchoringHelper67 = new RuntimeAnchoring(designSize, runtimeSize, 480, 320, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1066), new Integer(anchoringHelper67.getX()), new Integer(anchoringHelper67.getY()), new Integer(anchoringHelper67.getWidth()), new Integer(anchoringHelper67.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"ReadOnly", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper68 = new RuntimeAnchoring(designSize, runtimeSize, 480, 296, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1067), new Integer(anchoringHelper68.getX()), new Integer(anchoringHelper68.getY()), new Integer(anchoringHelper68.getWidth()), new Integer(anchoringHelper68.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper69 = new RuntimeAnchoring(designSize, runtimeSize, 480, 272, 56, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1068), new Integer(anchoringHelper69.getX()), new Integer(anchoringHelper69.getY()), new Integer(anchoringHelper69.getWidth()), new Integer(anchoringHelper69.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Visible", Boolean.TRUE, null})); // Grid Controls RuntimeAnchoring anchoringHelper70 = new RuntimeAnchoring(designSize, runtimeSize, 8, 16, 440, 352, ims.framework.enumerations.ControlAnchoring.ALL); Grid m_grdGridTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1069), new Integer(anchoringHelper70.getX()), new Integer(anchoringHelper70.getY()), new Integer(anchoringHelper70.getWidth()), new Integer(anchoringHelper70.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdGridTemp); grdGridGrid grdGrid = (grdGridGrid)GridFlyweightFactory.getInstance().createGridBridge(grdGridGrid.class, m_grdGridTemp); grdGrid.addStringColumn("Surname", 0, 0, 100, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdGrid.addStringColumn("Forename", 0, 0, 100, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdGrid.addStringColumn("D O B", 0, 0, 100, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdGrid.addStringColumn("Address", 0, 0, 100, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); super.addGrid(grdGrid); // Image Buttons Controls RuntimeAnchoring anchoringHelper71 = new RuntimeAnchoring(designSize, runtimeSize, 520, 16, 48, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1070), new Integer(anchoringHelper71.getX()), new Integer(anchoringHelper71.getY()), new Integer(anchoringHelper71.getWidth()), new Integer(anchoringHelper71.getHeight()), new Integer(-1), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, form_images_local.Core.ClearEnabled24, form_images_local.Core.ClearDisabled24, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper72 = new RuntimeAnchoring(designSize, runtimeSize, 464, 16, 48, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1071), new Integer(anchoringHelper72.getX()), new Integer(anchoringHelper72.getY()), new Integer(anchoringHelper72.getWidth()), new Integer(anchoringHelper72.getHeight()), new Integer(-1), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, form_images_local.Core.FindEnabled24, form_images_local.Core.FindDisabled24, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); } public CheckBox chkGridReadOnly() { return (CheckBox)super.getControl(1); } public CheckBox chkGridEnabled() { return (CheckBox)super.getControl(2); } public CheckBox chkGridVisible() { return (CheckBox)super.getControl(3); } public grdGridGrid grdGrid() { return (grdGridGrid)super.getGrid(0); } public ImageButton imbClear() { return (ImageButton)super.getControl(5); } public ImageButton imbFind() { return (ImageButton)super.getControl(6); } } public static class tabDynamicGridContainer extends LayerBridge { private static final long serialVersionUID = 1L; public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper73 = new RuntimeAnchoring(designSize, runtimeSize, 432, 239, 144, 128, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1072), new Integer(anchoringHelper73.getX()), new Integer(anchoringHelper73.getY()), new Integer(anchoringHelper73.getWidth()), new Integer(anchoringHelper73.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT,"Dynamic Grid state", new Integer(2), ""})); // CheckBox Controls RuntimeAnchoring anchoringHelper74 = new RuntimeAnchoring(designSize, runtimeSize, 464, 319, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1073), new Integer(anchoringHelper74.getX()), new Integer(anchoringHelper74.getY()), new Integer(anchoringHelper74.getWidth()), new Integer(anchoringHelper74.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Read Only", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper75 = new RuntimeAnchoring(designSize, runtimeSize, 464, 295, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1074), new Integer(anchoringHelper75.getX()), new Integer(anchoringHelper75.getY()), new Integer(anchoringHelper75.getWidth()), new Integer(anchoringHelper75.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper76 = new RuntimeAnchoring(designSize, runtimeSize, 464, 271, 56, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1075), new Integer(anchoringHelper76.getX()), new Integer(anchoringHelper76.getY()), new Integer(anchoringHelper76.getWidth()), new Integer(anchoringHelper76.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Visible", Boolean.TRUE, null})); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper77 = new RuntimeAnchoring(designSize, runtimeSize, 8, 16, 416, 352, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1076), new Integer(anchoringHelper77.getX()), new Integer(anchoringHelper77.getY()), new Integer(anchoringHelper77.getWidth()), new Integer(anchoringHelper77.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); // Image Buttons Controls RuntimeAnchoring anchoringHelper78 = new RuntimeAnchoring(designSize, runtimeSize, 520, 16, 48, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1077), new Integer(anchoringHelper78.getX()), new Integer(anchoringHelper78.getY()), new Integer(anchoringHelper78.getWidth()), new Integer(anchoringHelper78.getHeight()), new Integer(startTabIndex.intValue() + 4), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, form_images_local.Core.ClearEnabled24, form_images_local.Core.ClearDisabled24, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper79 = new RuntimeAnchoring(designSize, runtimeSize, 464, 16, 48, 48, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1078), new Integer(anchoringHelper79.getX()), new Integer(anchoringHelper79.getY()), new Integer(anchoringHelper79.getWidth()), new Integer(anchoringHelper79.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, form_images_local.Core.FindEnabled24, form_images_local.Core.FindDisabled24, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); } public CheckBox chkDynamicGridReadOnly() { return (CheckBox)super.getControl(1); } public CheckBox chkDynamicGridEnabled() { return (CheckBox)super.getControl(2); } public CheckBox chkDynamicGrid() { return (CheckBox)super.getControl(3); } public DynamicGrid dyngrdDynGrid() { return (DynamicGrid)super.getControl(4); } public ImageButton imbDynamicClear() { return (ImageButton)super.getControl(5); } public ImageButton imbDynamicFind() { return (ImageButton)super.getControl(6); } } public static class tabTreeContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class GroupExpandTreeRadioButton extends RadioButtonBridge { private static final long serialVersionUID = 1L; protected void setContext(Integer startTabIndex, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize) { if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex "); RuntimeAnchoring anchoringHelper80 = new RuntimeAnchoring(designSize, runtimeSize, 352, 56, 96, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); control.addButton(0, anchoringHelper80.getX(), anchoringHelper80.getY(), anchoringHelper80.getWidth(), "Tree Expanded", -1); RuntimeAnchoring anchoringHelper81 = new RuntimeAnchoring(designSize, runtimeSize, 352, 80, 96, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); control.addButton(1, anchoringHelper81.getX(), anchoringHelper81.getY(), anchoringHelper81.getWidth(), "Tree Collapsed", -1); } public void setText(GroupExpandTreeEnumeration option, String value) { if(option != null && option.id >= 0 && value != null) control.setText(option.id, value); } public GroupExpandTreeEnumeration getValue() { switch (super.control.getValue()) { case -1: return GroupExpandTreeEnumeration.None; case 0: return GroupExpandTreeEnumeration.rdoTreeExpanded; case 1: return GroupExpandTreeEnumeration.rdoTreeCollapsed; } return null; } public void setValue(GroupExpandTreeEnumeration value) { if(value != null) super.control.setValue(value.id); else super.control.setValue(GroupExpandTreeEnumeration.None.id); } public boolean isEnabled(GroupExpandTreeEnumeration option) { return super.control.isEnabled(option.id); } public void setEnabled(GroupExpandTreeEnumeration option, boolean value) { super.control.setEnabled(option.id, value); } public boolean isVisible(GroupExpandTreeEnumeration option) { return super.control.isVisible(option.id); } public void setVisible(GroupExpandTreeEnumeration option, boolean value) { super.control.setVisible(option.id, value); } public void setVisible(boolean value) { super.control.setVisible(value); } public void setEnabled(boolean value) { super.control.setEnabled(value); } } public static class GroupExpandTreeEnumeration implements java.io.Serializable { private static final long serialVersionUID = 1L; public static GroupExpandTreeEnumeration None = new GroupExpandTreeEnumeration(-1); public static GroupExpandTreeEnumeration rdoTreeExpanded = new GroupExpandTreeEnumeration(0); public static GroupExpandTreeEnumeration rdoTreeCollapsed = new GroupExpandTreeEnumeration(1); private GroupExpandTreeEnumeration(int id) { this.id = id; } public boolean equals(Object o) { return this.id == ((GroupExpandTreeEnumeration)o).id; } private int id; } public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate) { super.container.setTabActivatedEvent(delegate); } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Panel Controls RuntimeAnchoring anchoringHelper82 = new RuntimeAnchoring(designSize, runtimeSize, 448, 264, 120, 112, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1079), new Integer(anchoringHelper82.getX()), new Integer(anchoringHelper82.getY()), new Integer(anchoringHelper82.getWidth()), new Integer(anchoringHelper82.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT,"Tree state", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper83 = new RuntimeAnchoring(designSize, runtimeSize, 352, 144, 9, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1080), new Integer(anchoringHelper83.getX()), new Integer(anchoringHelper83.getY()), new Integer(anchoringHelper83.getWidth()), new Integer(anchoringHelper83.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "-", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper84 = new RuntimeAnchoring(designSize, runtimeSize, 352, 120, 69, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1081), new Integer(anchoringHelper84.getX()), new Integer(anchoringHelper84.getY()), new Integer(anchoringHelper84.getWidth()), new Integer(anchoringHelper84.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Tree Value:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper85 = new RuntimeAnchoring(designSize, runtimeSize, 352, 16, 136, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1082), new Integer(anchoringHelper85.getX()), new Integer(anchoringHelper85.getY()), new Integer(anchoringHelper85.getWidth()), new Integer(anchoringHelper85.getHeight()), new Integer(-1), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Populate Tree", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // CheckBox Controls RuntimeAnchoring anchoringHelper86 = new RuntimeAnchoring(designSize, runtimeSize, 472, 344, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1083), new Integer(anchoringHelper86.getX()), new Integer(anchoringHelper86.getY()), new Integer(anchoringHelper86.getWidth()), new Integer(anchoringHelper86.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Selectable", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper87 = new RuntimeAnchoring(designSize, runtimeSize, 472, 320, 72, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1084), new Integer(anchoringHelper87.getX()), new Integer(anchoringHelper87.getY()), new Integer(anchoringHelper87.getWidth()), new Integer(anchoringHelper87.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Enabled", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper88 = new RuntimeAnchoring(designSize, runtimeSize, 472, 296, 56, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1085), new Integer(anchoringHelper88.getX()), new Integer(anchoringHelper88.getY()), new Integer(anchoringHelper88.getWidth()), new Integer(anchoringHelper88.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,"Visible", Boolean.TRUE, null})); // Tree Controls RuntimeAnchoring anchoringHelper89 = new RuntimeAnchoring(designSize, runtimeSize, 16, 16, 320, 360, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT); super.addControl(factory.getControl(TreeView.class, new Object[] { control, new Integer(startControlID.intValue() + 1086), new Integer(anchoringHelper89.getX()), new Integer(anchoringHelper89.getY()), new Integer(anchoringHelper89.getWidth()), new Integer(anchoringHelper89.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT,Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, null, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE})); // RadioButton Controls RadioButton tmpGroupExpandTree = (RadioButton)factory.getControl(RadioButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1087), new Integer(0), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.FALSE}); super.addControl(tmpGroupExpandTree); GroupExpandTreeRadioButton GroupExpandTree = (GroupExpandTreeRadioButton)RadioButtonBridgeFlyweightFactory.getInstance().createRadioButtonBridge(GroupExpandTreeRadioButton.class, tmpGroupExpandTree); GroupExpandTree.setContext(startTabIndex, designSize, runtimeSize); super.addRadioButton(GroupExpandTree); } public Label lblTreeValue() { return (Label)super.getControl(1); } public Button btnPopulateTree() { return (Button)super.getControl(3); } public CheckBox chkTreeSelectable() { return (CheckBox)super.getControl(4); } public CheckBox chkTreeEnabled() { return (CheckBox)super.getControl(5); } public CheckBox chkTreeVisible() { return (CheckBox)super.getControl(6); } public TreeView treTree() { return (TreeView)super.getControl(7); } public GroupExpandTreeRadioButton GroupExpandTree() { return (GroupExpandTreeRadioButton)super.getRadioButton(0); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID "); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); RuntimeAnchoring anchoringHelper90 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabCombosLists = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1088), new Integer(anchoringHelper90.getX()), new Integer(anchoringHelper90.getY()), new Integer(anchoringHelper90.getWidth()), new Integer(anchoringHelper90.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Combox & Lists", new Integer(startControlID.intValue() + 0), new Boolean(true), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabCombosListsContainer m_tabCombosListsContainer = (tabCombosListsContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabCombosListsContainer.class, m_tabCombosLists, factory); super.addContainer(m_tabCombosLists, m_tabCombosListsContainer); ims.framework.utils.SizeInfo m_tabCombosListsDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabCombosListsRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper90.getWidth(), anchoringHelper90.getHeight()); m_tabCombosListsContainer.setContext(form, appForm, m_tabCombosLists, loader, form_images_local, startControlID, m_tabCombosListsDesignSize, m_tabCombosListsRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper91 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabDateTime = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1089), new Integer(anchoringHelper91.getX()), new Integer(anchoringHelper91.getY()), new Integer(anchoringHelper91.getWidth()), new Integer(anchoringHelper91.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Date & Time", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabDateTimeContainer m_tabDateTimeContainer = (tabDateTimeContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabDateTimeContainer.class, m_tabDateTime, factory); super.addContainer(m_tabDateTime, m_tabDateTimeContainer); ims.framework.utils.SizeInfo m_tabDateTimeDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabDateTimeRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper91.getWidth(), anchoringHelper91.getHeight()); m_tabDateTimeContainer.setContext(form, appForm, m_tabDateTime, loader, form_images_local, startControlID, m_tabDateTimeDesignSize, m_tabDateTimeRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper92 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabDecimalsIntegers = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1090), new Integer(anchoringHelper92.getX()), new Integer(anchoringHelper92.getY()), new Integer(anchoringHelper92.getWidth()), new Integer(anchoringHelper92.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Decimals & Integers", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabDecimalsIntegersContainer m_tabDecimalsIntegersContainer = (tabDecimalsIntegersContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabDecimalsIntegersContainer.class, m_tabDecimalsIntegers, factory); super.addContainer(m_tabDecimalsIntegers, m_tabDecimalsIntegersContainer); ims.framework.utils.SizeInfo m_tabDecimalsIntegersDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabDecimalsIntegersRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper92.getWidth(), anchoringHelper92.getHeight()); m_tabDecimalsIntegersContainer.setContext(form, appForm, m_tabDecimalsIntegers, loader, form_images_local, startControlID, m_tabDecimalsIntegersDesignSize, m_tabDecimalsIntegersRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper93 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabGrid = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1091), new Integer(anchoringHelper93.getX()), new Integer(anchoringHelper93.getY()), new Integer(anchoringHelper93.getWidth()), new Integer(anchoringHelper93.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Grid", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabGridContainer m_tabGridContainer = (tabGridContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabGridContainer.class, m_tabGrid, factory); super.addContainer(m_tabGrid, m_tabGridContainer); ims.framework.utils.SizeInfo m_tabGridDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabGridRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper93.getWidth(), anchoringHelper93.getHeight()); m_tabGridContainer.setContext(form, appForm, m_tabGrid, loader, form_images_local, startControlID, m_tabGridDesignSize, m_tabGridRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper94 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabDynamicGrid = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1092), new Integer(anchoringHelper94.getX()), new Integer(anchoringHelper94.getY()), new Integer(anchoringHelper94.getWidth()), new Integer(anchoringHelper94.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Dynamic Grid", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabDynamicGridContainer m_tabDynamicGridContainer = (tabDynamicGridContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabDynamicGridContainer.class, m_tabDynamicGrid, factory); super.addContainer(m_tabDynamicGrid, m_tabDynamicGridContainer); ims.framework.utils.SizeInfo m_tabDynamicGridDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabDynamicGridRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper94.getWidth(), anchoringHelper94.getHeight()); m_tabDynamicGridContainer.setContext(form, appForm, m_tabDynamicGrid, loader, form_images_local, startControlID, m_tabDynamicGridDesignSize, m_tabDynamicGridRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper95 = new RuntimeAnchoring(designSize, runtimeSize, 144, 8, 592, 424, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabTree = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1093), new Integer(anchoringHelper95.getX()), new Integer(anchoringHelper95.getY()), new Integer(anchoringHelper95.getWidth()), new Integer(anchoringHelper95.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Tree", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)}); tabTreeContainer m_tabTreeContainer = (tabTreeContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabTreeContainer.class, m_tabTree, factory); super.addContainer(m_tabTree, m_tabTreeContainer); ims.framework.utils.SizeInfo m_tabTreeDesignSize = new ims.framework.utils.SizeInfo(592, 424); ims.framework.utils.SizeInfo m_tabTreeRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper95.getWidth(), anchoringHelper95.getHeight()); m_tabTreeContainer.setContext(form, appForm, m_tabTree, loader, form_images_local, startControlID, m_tabTreeDesignSize, m_tabTreeRuntimeSize, startTabIndex, skipContextValidation); } public void hide() { tabCombosLists().setVisible(false); tabDateTime().setVisible(false); tabDecimalsIntegers().setVisible(false); tabGrid().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(false); } public void settabCombosListsEnabled(boolean value) { tabCombosLists().setEnabled(value); } public void settabDateTimeEnabled(boolean value) { tabDateTime().setEnabled(value); } public void settabDecimalsIntegersEnabled(boolean value) { tabDecimalsIntegers().setEnabled(value); } public void settabGridEnabled(boolean value) { tabGrid().setEnabled(value); } public void settabDynamicGridEnabled(boolean value) { tabDynamicGrid().setEnabled(value); } public void settabTreeEnabled(boolean value) { tabTree().setEnabled(value); } public void showtabCombosLists() { tabDateTime().setVisible(false); tabDecimalsIntegers().setVisible(false); tabGrid().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(false); tabCombosLists().setVisible(true); } public void showtabDateTime() { tabCombosLists().setVisible(false); tabDecimalsIntegers().setVisible(false); tabGrid().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(false); tabDateTime().setVisible(true); } public void showtabDecimalsIntegers() { tabCombosLists().setVisible(false); tabDateTime().setVisible(false); tabGrid().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(false); tabDecimalsIntegers().setVisible(true); } public void showtabGrid() { tabCombosLists().setVisible(false); tabDateTime().setVisible(false); tabDecimalsIntegers().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(false); tabGrid().setVisible(true); } public void showtabDynamicGrid() { tabCombosLists().setVisible(false); tabDateTime().setVisible(false); tabDecimalsIntegers().setVisible(false); tabGrid().setVisible(false); tabTree().setVisible(false); tabDynamicGrid().setVisible(true); } public void showtabTree() { tabCombosLists().setVisible(false); tabDateTime().setVisible(false); tabDecimalsIntegers().setVisible(false); tabGrid().setVisible(false); tabDynamicGrid().setVisible(false); tabTree().setVisible(true); } public tabCombosListsContainer tabCombosLists() { return (tabCombosListsContainer)super.layers.get(0); } public tabDateTimeContainer tabDateTime() { return (tabDateTimeContainer)super.layers.get(1); } public tabDecimalsIntegersContainer tabDecimalsIntegers() { return (tabDecimalsIntegersContainer)super.layers.get(2); } public tabGridContainer tabGrid() { return (tabGridContainer)super.layers.get(3); } public tabDynamicGridContainer tabDynamicGrid() { return (tabDynamicGridContainer)super.layers.get(4); } public tabTreeContainer tabTree() { return (tabTreeContainer)super.layers.get(5); } } public static class ctn1Container extends ContainerBridge { private static final long serialVersionUID = 1L; protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // CheckBox Controls RuntimeAnchoring anchoringHelper96 = new RuntimeAnchoring(designSize, runtimeSize, 16, 16, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1094), new Integer(anchoringHelper96.getX()), new Integer(anchoringHelper96.getY()), new Integer(anchoringHelper96.getWidth()), new Integer(anchoringHelper96.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Page 1 Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper97 = new RuntimeAnchoring(designSize, runtimeSize, 16, 40, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1095), new Integer(anchoringHelper97.getX()), new Integer(anchoringHelper97.getY()), new Integer(anchoringHelper97.getWidth()), new Integer(anchoringHelper97.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Page 2 Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper98 = new RuntimeAnchoring(designSize, runtimeSize, 16, 64, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1096), new Integer(anchoringHelper98.getX()), new Integer(anchoringHelper98.getY()), new Integer(anchoringHelper98.getWidth()), new Integer(anchoringHelper98.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Page 3 Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper99 = new RuntimeAnchoring(designSize, runtimeSize, 16, 88, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1097), new Integer(anchoringHelper99.getX()), new Integer(anchoringHelper99.getY()), new Integer(anchoringHelper99.getWidth()), new Integer(anchoringHelper99.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Page 4 Visible", Boolean.TRUE, null})); RuntimeAnchoring anchoringHelper100 = new RuntimeAnchoring(designSize, runtimeSize, 16, 112, 88, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1098), new Integer(anchoringHelper100.getX()), new Integer(anchoringHelper100.getY()), new Integer(anchoringHelper100.getWidth()), new Integer(anchoringHelper100.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Page 5 Visible", Boolean.TRUE, null})); } public CheckBox chkPage1Visible() { return (CheckBox)super.getControl(0); } public CheckBox chkPage2Visible() { return (CheckBox)super.getControl(1); } public CheckBox chkPage3Visible() { return (CheckBox)super.getControl(2); } public CheckBox chkPage4Visible() { return (CheckBox)super.getControl(3); } public CheckBox chkPage5Visible() { return (CheckBox)super.getControl(4); } } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(744, 480); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class)); // Layer Clasess lyrMainLayer m_lyrMainLayer = (lyrMainLayer)LayerFlyweightFactory.getInstance().createLayer(lyrMainLayer.class, this, factory); super.addLayer(m_lyrMainLayer); m_lyrMainLayer.setContext(form, appForm, control, loader, this.getImages(), startControlID, designSize, runtimeSize, startTabIndex, skipContextValidation); // Container Clasess RuntimeAnchoring anchoringHelper101 = new RuntimeAnchoring(designSize, runtimeSize, 8, 56, 120, 144, ims.framework.enumerations.ControlAnchoring.TOPLEFT); Container m_ctn1 = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1099), new Integer(anchoringHelper101.getX()), new Integer(anchoringHelper101.getY()), new Integer(anchoringHelper101.getWidth()), new Integer(anchoringHelper101.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, null, new Boolean(false)}); addControl(m_ctn1); ctn1Container ctn1 = (ctn1Container)ContainerBridgeFlyweightFactory.getInstance().createContainerBridge(ctn1Container.class, m_ctn1, factory); ims.framework.utils.SizeInfo m_ctn1DesignSize = new ims.framework.utils.SizeInfo(120, 144); ims.framework.utils.SizeInfo m_ctn1RuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper101.getWidth(), anchoringHelper101.getHeight()); ctn1.setContext(form, appForm, m_ctn1, loader, this.getImages(), startControlID, m_ctn1DesignSize, m_ctn1RuntimeSize, startTabIndex, skipContextValidation); super.addContainer(ctn1); // Label Controls RuntimeAnchoring anchoringHelper102 = new RuntimeAnchoring(designSize, runtimeSize, 208, 448, 12, 22, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1100), new Integer(anchoringHelper102.getX()), new Integer(anchoringHelper102.getY()), new Integer(anchoringHelper102.getWidth()), new Integer(anchoringHelper102.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "-", new Integer(1), null, new Integer(1)})); RuntimeAnchoring anchoringHelper103 = new RuntimeAnchoring(designSize, runtimeSize, 144, 448, 55, 22, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1101), new Integer(anchoringHelper103.getX()), new Integer(anchoringHelper103.getY()), new Integer(anchoringHelper103.getWidth()), new Integer(anchoringHelper103.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Event:", new Integer(1), null, new Integer(1)})); // Button Controls RuntimeAnchoring anchoringHelper104 = new RuntimeAnchoring(designSize, runtimeSize, 8, 440, 96, 32, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1102), new Integer(anchoringHelper104.getX()), new Integer(anchoringHelper104.getY()), new Integer(anchoringHelper104.getWidth()), new Integer(anchoringHelper104.getHeight()), new Integer(startTabIndex.intValue() + 5), ControlState.ENABLED, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper105 = new RuntimeAnchoring(designSize, runtimeSize, 640, 440, 96, 32, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1103), new Integer(anchoringHelper105.getX()), new Integer(anchoringHelper105.getY()), new Integer(anchoringHelper105.getWidth()), new Integer(anchoringHelper105.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // CheckBox Controls RuntimeAnchoring anchoringHelper106 = new RuntimeAnchoring(designSize, runtimeSize, 8, 16, 104, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1104), new Integer(anchoringHelper106.getX()), new Integer(anchoringHelper106.getY()), new Integer(anchoringHelper106.getWidth()), new Integer(anchoringHelper106.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"Layer Visible", Boolean.TRUE, null})); } public Images getImages() { return (Images)super.getImageReferences(); } public lyrMainLayer lyrMain() { return (lyrMainLayer)super.getLayer(0); } public ctn1Container ctn1() { return (ctn1Container)super.getContainer(0); } public Label lblEventValue() { return (Label)super.getControl(7); } public Button btnEdit() { return (Button)super.getControl(9); } public Button btnCancel() { return (Button)super.getControl(10); } public CheckBox chkLayerVisible() { return (CheckBox)super.getControl(11); } public static class Images implements java.io.Serializable { private static final long serialVersionUID = 1L; private final class ImageHelper extends ims.framework.utils.ImagePath { private static final long serialVersionUID = 1L; private ImageHelper(int id, String path, Integer width, Integer height) { super(id, path, width, height); } } private Images() { Core = new CoreImages(); } public final class CoreImages implements java.io.Serializable { private static final long serialVersionUID = 1L; private CoreImages() { FindDisabled24 = new ImageHelper(102172, "Images/Core/FindDisabled_24.png", new Integer(24), new Integer(24)); FindEnabled24 = new ImageHelper(102175, "Images/Core/Find_24.png", new Integer(24), new Integer(24)); ClearDisabled24 = new ImageHelper(102173, "Images/Core/ClearDisabled_24.png", new Integer(24), new Integer(24)); ClearEnabled24 = new ImageHelper(102174, "Images/Core/ClearEnabled_24.png", new Integer(24), new Integer(24)); } public final ims.framework.utils.Image FindDisabled24; public final ims.framework.utils.Image FindEnabled24; public final ims.framework.utils.Image ClearDisabled24; public final ims.framework.utils.Image ClearEnabled24; } public final CoreImages Core; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[144]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DEMENTIABREACHDATETIME", "DementiaBreachDateTime"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DEMENTIAWORKLISTSTATUS", "DementiaWorklistStatus"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MRNSTATUS", "MRNStatus"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-HASSCANNEDCASENOTEFOLDERS", "HasScannedCaseNoteFolders"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISCONFIDENTIAL", "IsConfidential"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFBIRTH", "TimeOfBirth"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-PATIENTCATEGORY", "PatientCategory"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPAENDOSCOPIST", "IsHCPaEndoscopist"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-ID", "ID_NAESReferral"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEREFERRALRECEIVED", "DateReferralReceived"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEOFSURGERY", "DateOfSurgery"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGHOSPITAL", "ReferringHospital"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGDOCTOR", "ReferringDoctor"); fields[71] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRALREASON", "ReferralReason"); fields[72] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-SECONDARYSURGERY", "SecondarySurgery"); fields[73] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-UNDERLYINGREASON", "UnderlyingReason"); fields[74] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-AFFECTEDEYE", "AffectedEye"); fields[75] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANT", "Implant"); fields[76] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANTTYPE", "ImplantType"); fields[77] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-INTERPRETERREQUIRED", "InterpreterRequired"); fields[78] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGE", "Language"); fields[79] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGEIFOTHER", "LanguageIfOther"); fields[80] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERREDBY", "ReferredBy"); fields[81] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_6WEEKKPI", "SixWeekKPI"); fields[82] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_3WEEKKPI", "ThreeWeekKPI"); fields[83] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-PREFERREDCLINIC", "PreferredClinic"); fields[84] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-NOTES", "Notes"); fields[85] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[86] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[87] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[88] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[89] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[90] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[91] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[92] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[93] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[94] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[95] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[96] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-NOTETYPE", "NoteType"); fields[97] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEW", "ForReview"); fields[98] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[99] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ID", "ID_ObservationForm"); fields[100] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-FORMTYPE", "FormType"); fields[101] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DETAILS", "Details"); fields[102] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTART", "DateTimeStart"); fields[103] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTOP", "DateTimeStop"); fields[104] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ISSTOPPED", "IsStopped"); fields[105] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CARECONTEXT", "CareContext"); fields[106] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CLINICALCONTACT", "ClinicalContact"); fields[107] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-ID", "ID_MedicationOverview"); fields[108] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-TYPE", "Type"); fields[109] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-CARECONTEXT", "CareContext"); fields[110] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[111] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[112] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[113] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[114] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[115] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[116] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[117] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[118] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[119] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ID", "ID_Urinalysis"); fields[120] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOABNORMALITYDETECTED", "NoAbnormalityDetected"); fields[121] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-LEUCOCYTES", "Leucocytes"); fields[122] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PROTEIN", "Protein"); fields[123] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BLOOD", "Blood"); fields[124] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-KETONES", "Ketones"); fields[125] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ASCORBICACID", "AscorbicAcid"); fields[126] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-GLUCOSE", "Glucose"); fields[127] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BILIRUBIN", "Bilirubin"); fields[128] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-UROBILINOGEN", "Urobilinogen"); fields[129] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NITRATE", "Nitrate"); fields[130] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PH", "PH"); fields[131] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-SPECIFICGRAVITY", "SpecificGravity"); fields[132] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOSAMPLE", "NoSample"); fields[133] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ISACTIVE", "IsActive"); fields[134] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-CARECONTEXT", "CareContext"); fields[135] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient"); fields[136] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex"); fields[137] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob"); fields[138] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient"); fields[139] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex"); fields[140] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob"); fields[141] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[142] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[143] = new ims.framework.ReportField(this.context, "_cvp_RefMan.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private IReportField[] reportFields = null; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/addressselection/ConfigFlags.java
2705
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH package ims.core.forms.addressselection; import java.io.Serializable; public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable { private static final long serialVersionUID = 1L; public final CAPSCAN_ENABLEDClass CAPSCAN_ENABLED; public ConfigFlags(ims.framework.ConfigFlag configFlags) { super(configFlags); CAPSCAN_ENABLED = new CAPSCAN_ENABLEDClass(configFlags); } public final class CAPSCAN_ENABLEDClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public CAPSCAN_ENABLEDClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public Boolean getValue() { return (Boolean)configFlags.get("CAPSCAN_ENABLED"); } } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/oncology/vo/CancerContactsRefVo.java
4746
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo; /** * Linked to Oncology.CancerContacts business object (ID: 1074100038). */ public class CancerContactsRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public CancerContactsRefVo() { } public CancerContactsRefVo(Integer id, int version) { super(id, version); } public final boolean getID_CancerContactsIsNotNull() { return this.id != null; } public final Integer getID_CancerContacts() { return this.id; } public final void setID_CancerContacts(Integer value) { this.id = value; } public final int getVersion_CancerContacts() { return this.version; } public Object clone() { return new CancerContactsRefVo(this.id, this.version); } public final CancerContactsRefVo toCancerContactsRefVo() { if(this.id == null) return this; return new CancerContactsRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof CancerContactsRefVo)) return false; CancerContactsRefVo compareObj = (CancerContactsRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.oncology.domain.objects.CancerContacts"; } public Class getDomainClass() { return ims.oncology.domain.objects.CancerContacts.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof CancerContactsRefVo)) throw new ClassCastException("A CancerContactsRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((CancerContactsRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((CancerContactsRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_CANCERCONTACTS")) return getID_CancerContacts(); return super.getFieldValueByFieldName(fieldName); } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Correspondence/src/ims/correspondence/forms/correspondenceheadersadminconfiguration/GlobalContext.java
2040
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.correspondence.forms.correspondenceheadersadminconfiguration; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); } }
agpl-3.0
pinae/ctSESAM-android
app/src/androidTest/java/de/pinyto/ctSESAM/PBKDF2Test.java
12880
package de.pinyto.ctSESAM; import junit.framework.TestCase; import java.io.UnsupportedEncodingException; /** * Unit tests for the PBKDF2_HMAC implementation */ public class PBKDF2Test extends TestCase { public void testSha512Hmac () { byte[] key; try { key = "secret".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); key = "secret".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expectedDigest = new byte[] { 0x1B, (byte)0xBA, 0x58, 0x7C, 0x73, 0x0E, (byte)0xED, (byte)0xBA, 0x31, (byte)0xF5, 0x3A, (byte)0xBB, 0x0B, 0x6C, (byte)0xA5, (byte)0x89, (byte)0xE0, (byte)0x9D, (byte)0xE4, (byte)0xE8, (byte)0x94, (byte)0xEE, 0x45, 0x5E, 0x61, 0x40, (byte)0x80, 0x73, (byte)0x99, 0x75, (byte)0x9A, (byte)0xDA, (byte)0xAF, (byte)0xA0, 0x69, (byte)0xEE, (byte)0xC7, (byte)0xC0, 0x16, 0x47, (byte)0xBB, 0x17, 0x3D, (byte)0xCB, 0x17, (byte)0xF5, 0x5D, 0x22, (byte)0xAF, 0x49, (byte)0xA1, (byte)0x80, 0x71, (byte)0xB7, 0x48, (byte)0xC5, (byte)0xC2, (byte)0xED, (byte)0xD7, (byte)0xF7, (byte)0xA8, 0x29, (byte)0xC6, 0x32 }; byte[] digest = PBKDF2.shaHMAC("SHA512", key, message); assertEquals(expectedDigest.length, digest.length); for (int i = 0; i < digest.length; i++) { assertEquals(digest[i], expectedDigest[i]); } } public void testSha512HmacEmptyMessage () { byte[] key; try { key = "secret".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); key = "secret".getBytes(); } byte[] message; try { message = "".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "".getBytes(); } byte[] expectedDigest = new byte[] { (byte)0xB0, (byte)0xE9, 0x65, 0x0C, 0x5F, (byte)0xAF, (byte)0x9C, (byte)0xD8, (byte)0xAE, 0x02, 0x27, 0x66, 0x71, 0x54, 0x54, 0x24, 0x10, 0x45, (byte)0x89, (byte)0xB3, 0x65, 0x67, 0x31, (byte)0xEC, 0x19, 0x3B, 0x25, (byte)0xD0, 0x1B, 0x07, 0x56, 0x1C, 0x27, 0x63, 0x7C, 0x2D, 0x4D, 0x68, 0x38, (byte)0x9D, 0x6C, (byte)0xF5, 0x00, 0x7A, (byte)0x86, 0x32, (byte)0xC2, 0x6E, (byte)0xC8, (byte)0x9B, (byte)0xA8, 0x0A, 0x01, (byte)0xC7, 0x7A, 0x6C, (byte)0xDD, 0x38, (byte)0x9E, (byte)0xC2, (byte)0x8D, (byte)0xB4, 0x39, 0x01 }; byte[] digest = PBKDF2.shaHMAC("SHA512", key, message); assertEquals(expectedDigest.length, digest.length); for (int i = 0; i < digest.length; i++) { assertEquals(digest[i], expectedDigest[i]); } } public void testSha512HmacEmptyKey () { byte[] key; try { key = "".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); key = "".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expectedDigest = new byte[] { 0x08, (byte)0xFC, (byte)0xE5, 0x2F, 0x63, (byte)0x95, (byte)0xD5, (byte)0x9C, 0x2A, 0x3F, (byte)0xB8, (byte)0xAB, (byte)0xB2, (byte)0x81, (byte)0xD7, 0x4A, (byte)0xD6, (byte)0xF1, 0x12, (byte)0xB9, (byte)0xA9, (byte)0xC7, (byte)0x87, (byte)0xBC, (byte)0xEA, 0x29, 0x0D, (byte)0x94, (byte)0xDA, (byte)0xDB, (byte)0xC8, 0x2B, 0x2C, (byte)0xA3, (byte)0xE5, (byte)0xE1, 0x2B, (byte)0xF2, 0x27, 0x7C, 0x7F, (byte)0xED, (byte)0xBB, 0x01, 0x54, (byte)0xD5, 0x49, 0x3E, 0x41, (byte)0xBB, 0x74, 0x59, (byte)0xF6, 0x3C, (byte)0x8E, 0x39, 0x55, 0x4E, (byte)0xA3, 0x65, 0x1B, (byte)0x81, 0x24, (byte)0x92 }; byte[] digest = PBKDF2.shaHMAC("SHA512", key, message); assertEquals(expectedDigest.length, digest.length); for (int i = 0; i < digest.length; i++) { assertEquals(digest[i], expectedDigest[i]); } } public void testSha512 () { byte[] salt; try { salt = "pepper".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "pepper".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expected = new byte[] { 0x26, 0x46, (byte)0xf9, (byte)0xcc, (byte)0xb5, (byte)0x8d, 0x21, 0x40, 0x68, 0x15, (byte)0xba, (byte)0xfc, 0x62, 0x24, 0x57, 0x71, (byte)0xbf, (byte)0x80, (byte)0xaa, (byte)0xa0, (byte)0x80, (byte)0xa6, 0x33, (byte)0xff, 0x1b, (byte)0xdd, 0x66, 0x0e, (byte)0xb4, 0x4f, 0x36, (byte)0x9a, (byte)0x89, (byte)0xda, 0x48, (byte)0xfb, 0x04, 0x1c, 0x55, 0x51, (byte)0xa1, 0x18, (byte)0xde, 0x20, (byte)0xcf, (byte)0xb8, (byte)0xb9, 0x6b, (byte)0x92, (byte)0xe7, (byte)0xa9, (byte)0x94, 0x54, 0x25, (byte)0xba, (byte)0x88, (byte)0x9e, (byte)0x9a, (byte)0xd6, 0x45, 0x61, 0x45, 0x22, (byte)0xeb }; byte[] actual = PBKDF2.hmac("SHA512", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } public void testSha512EmptySalt () { byte[] salt; try { salt = "".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expected = new byte[] { (byte)0xb8, (byte)0xec, 0x13, (byte)0xcf, (byte)0xc9, (byte)0xb9, (byte)0xd4, (byte)0x9c, (byte)0xa1, 0x14, 0x30, 0x18, (byte)0xce, (byte)0x84, 0x13, (byte)0xa9, 0x62, (byte)0xc0, (byte)0x9c, 0x00, 0x63, (byte)0xf3, 0x0a, 0x46, 0x6d, (byte)0xf8, 0x02, (byte)0x89, 0x74, 0x75, (byte)0xc5, 0x7f, 0x26, (byte)0x8d, (byte)0x91, (byte)0xcc, 0x56, (byte)0x8a, (byte)0xc1, (byte)0xb6, (byte)0xa9, (byte)0xf1, (byte)0x9b, 0x1a, 0x0d, (byte)0xb1, 0x0f, 0x30, 0x05, (byte)0x8f, (byte)0xb7, (byte)0xa4, 0x53, (byte)0xb2, 0x67, 0x50, 0x10, (byte)0xef, 0x2b, 0x5f, (byte)0x96, 0x48, 0x7a, (byte)0xd3 }; byte[] actual = PBKDF2.hmac("SHA512", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } public void testSha512EmptyMessage () { byte[] salt; try { salt = "pepper".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "pepper".getBytes(); } byte[] message; try { message = "".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "".getBytes(); } byte[] expected = new byte[] { (byte)0x9d, (byte)0xd3, 0x31, (byte)0xfc, 0x67, 0x42, 0x1e, 0x1d, (byte)0xce, 0x61, (byte)0x9c, (byte)0xbb, (byte)0xb5, 0x17, 0x17, 0x0e, 0x2d, (byte)0xc3, 0x25, 0x49, 0x1d, 0x34, 0x26, 0x42, 0x56, 0x30, (byte)0xc4, (byte)0xc0, 0x1f, (byte)0xd0, (byte)0xec, (byte)0xa8, (byte)0xd8, (byte)0xf5, 0x35, (byte)0xd6, (byte)0xb0, 0x55, 0x5a, 0x2a, (byte)0xa4, 0x3e, (byte)0xfb, (byte)0xc9, 0x14, 0x1e, 0x3d, (byte)0xd7, (byte)0xed, (byte)0xae, (byte)0xf8, (byte)0xb1, 0x27, (byte)0x8a, (byte)0xc3, 0x4e, (byte)0xab, (byte)0xfc, 0x2d, (byte)0xb7, 0x35, (byte)0xd9, (byte)0x92, (byte)0xee }; byte[] actual = PBKDF2.hmac("SHA512", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } public void testSha512LongMessage () { byte[] salt; try { salt = "pepper".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "pepper".getBytes(); } String msgString = "ThisMessageIsLongerThanSixtyFourCharactersWhichLeadsToTheSituation" + "ThatTheMessageHasToBeHashedWhenCalculatingTheHmac"; byte[] message; try { message = msgString.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = msgString.getBytes(); } byte[] expected = new byte[] { (byte)0xef, (byte)0xc8, (byte)0xe7, 0x34, (byte)0xed, 0x5b, 0x56, 0x57, (byte)0xac, 0x22, 0x00, 0x46, 0x75, 0x4b, 0x7d, 0x1d, (byte)0xbe, (byte)0xa0, 0x09, (byte)0x83, (byte)0xf1, 0x32, 0x09, (byte)0xb1, (byte)0xec, 0x1d, 0x0e, 0x41, (byte)0x8e, (byte)0x98, (byte)0x80, 0x7c, (byte)0xba, 0x10, 0x26, (byte)0xd3, (byte)0xed, 0x3f, (byte)0xa2, (byte)0xa0, (byte)0x9d, (byte)0xfa, 0x43, (byte)0xc0, 0x74, 0x44, 0x7b, (byte)0xf4, 0x77, 0x7e, 0x70, (byte)0xe4, (byte)0x99, (byte)0x9d, 0x29, (byte)0xd2, (byte)0xc2, (byte)0xf8, 0x4d, (byte)0xc5, 0x15, 0x02, (byte)0xa1, (byte)0x95 }; byte[] actual = PBKDF2.hmac("SHA512", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } public void testSha384 () { byte[] salt; try { salt = "salt".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "salt".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expected = new byte[] { (byte)0xdc, (byte)0xbe, (byte)0xb0, (byte)0xb9, (byte)0x9a, 0x4c, (byte)0xf4, (byte)0xd1, (byte)0xc9, (byte)0xc1, (byte)0xe8, (byte)0xf6, 0x30, (byte)0xf3, (byte)0xaa, (byte)0x86, 0x37, (byte)0xc8, (byte)0x90, 0x6f, 0x1c, 0x3e, 0x1c, 0x78, (byte)0xfb, 0x4f, 0x46, 0x2b, 0x16, 0x0d, (byte)0xf2, 0x0f, 0x74, 0x35, (byte)0xbd, (byte)0xd6, (byte)0xa9, 0x04, (byte)0xdd, 0x3c, 0x3e, (byte)0xde, 0x7f, (byte)0xf0, 0x4b, (byte)0xc5, 0x3e, (byte)0x90 }; byte[] actual = PBKDF2.hmac("SHA384", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } public void testSha256 () { byte[] salt; try { salt = "salt".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); salt = "salt".getBytes(); } byte[] message; try { message = "message".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); message = "message".getBytes(); } byte[] expected = new byte[] { (byte)0xdb, 0x78, (byte)0xc5, 0x09, 0x14, 0x44, (byte)0x94, 0x0f, (byte)0x96, 0x42, (byte)0xfc, (byte)0xe5, 0x19, 0x09, 0x7e, (byte)0xe7, (byte)0xad, (byte)0xfe, (byte)0xb3, 0x38, (byte)0xfd, 0x69, 0x70, (byte)0x85, 0x51, 0x35, 0x53, (byte)0x90, 0x20, (byte)0xb5, 0x3f, (byte)0xad }; byte[] actual = PBKDF2.hmac("SHA256", message, salt, 3); assertEquals(expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals(expected[i], actual[i]); } } }
agpl-3.0
exercitussolus/yolo
src/main/java/org/elasticsearch/node/internal/InternalNode.java
15475
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.node.internal; import org.elasticsearch.Build; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionModule; import org.elasticsearch.bulk.udp.BulkUdpModule; import org.elasticsearch.bulk.udp.BulkUdpService; import org.elasticsearch.cache.NodeCache; import org.elasticsearch.cache.NodeCacheModule; import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.cache.recycler.CacheRecyclerModule; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClientModule; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterNameModule; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.routing.RoutingService; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.common.StopWatch; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.compress.CompressorFactory; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.inject.Injectors; import org.elasticsearch.common.inject.ModulesBuilder; import org.elasticsearch.common.io.CachedStreams; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsModule; import org.elasticsearch.discovery.Discovery; import org.elasticsearch.discovery.DiscoveryModule; import org.elasticsearch.discovery.DiscoveryService; import org.elasticsearch.env.Environment; import org.elasticsearch.env.EnvironmentModule; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.NodeEnvironmentModule; import org.elasticsearch.gateway.GatewayModule; import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.http.HttpServer; import org.elasticsearch.http.HttpServerModule; import org.elasticsearch.index.search.shape.ShapeModule; import org.elasticsearch.indices.IndicesModule; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.cache.filter.IndicesFilterCache; import org.elasticsearch.indices.cluster.IndicesClusterStateService; import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache; import org.elasticsearch.indices.memory.IndexingMemoryController; import org.elasticsearch.indices.ttl.IndicesTTLService; import org.elasticsearch.monitor.MonitorModule; import org.elasticsearch.monitor.MonitorService; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.node.Node; import org.elasticsearch.percolator.PercolatorModule; import org.elasticsearch.percolator.PercolatorService; import org.elasticsearch.plugins.PluginsModule; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestModule; import org.elasticsearch.river.RiversManager; import org.elasticsearch.river.RiversModule; import org.elasticsearch.script.ScriptModule; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.SearchService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPoolModule; import org.elasticsearch.transport.TransportModule; import org.elasticsearch.transport.TransportService; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * */ public final class InternalNode implements Node { private final Lifecycle lifecycle = new Lifecycle(); private final Injector injector; private final Settings settings; private final Environment environment; private final PluginsService pluginsService; private final Client client; public InternalNode() throws ElasticSearchException { this(ImmutableSettings.Builder.EMPTY_SETTINGS, true); } public InternalNode(Settings pSettings, boolean loadConfigSettings) throws ElasticSearchException { Tuple<Settings, Environment> tuple = InternalSettingsPreparer.prepareSettings(pSettings, loadConfigSettings); Version version = Version.CURRENT; ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name")); logger.info("version[{}], pid[{}], build[{}/{}]", version, JvmInfo.jvmInfo().pid(), Build.CURRENT.hashShort(), Build.CURRENT.timestamp()); logger.info("initializing ..."); if (logger.isDebugEnabled()) { Environment env = tuple.v2(); logger.debug("using home [{}], config [{}], data [{}], logs [{}], work [{}], plugins [{}]", env.homeFile(), env.configFile(), Arrays.toString(env.dataFiles()), env.logsFile(), env.workFile(), env.pluginsFile()); } this.pluginsService = new PluginsService(tuple.v1(), tuple.v2()); this.settings = pluginsService.updatedSettings(); this.environment = tuple.v2(); CompressorFactory.configure(settings); NodeEnvironment nodeEnvironment = new NodeEnvironment(this.settings, this.environment); ModulesBuilder modules = new ModulesBuilder(); modules.add(new Version.Module(version)); modules.add(new CacheRecyclerModule(settings)); modules.add(new PluginsModule(settings, pluginsService)); modules.add(new SettingsModule(settings)); modules.add(new NodeModule(this)); modules.add(new NetworkModule()); modules.add(new NodeCacheModule(settings)); modules.add(new ScriptModule(settings)); modules.add(new EnvironmentModule(environment)); modules.add(new NodeEnvironmentModule(nodeEnvironment)); modules.add(new ClusterNameModule(settings)); modules.add(new ThreadPoolModule(settings)); modules.add(new DiscoveryModule(settings)); modules.add(new ClusterModule(settings)); modules.add(new RestModule(settings)); modules.add(new TransportModule(settings)); if (settings.getAsBoolean("http.enabled", true)) { modules.add(new HttpServerModule(settings)); } modules.add(new RiversModule(settings)); modules.add(new IndicesModule(settings)); modules.add(new SearchModule()); modules.add(new ActionModule(false)); modules.add(new MonitorModule(settings)); modules.add(new GatewayModule(settings)); modules.add(new NodeClientModule()); modules.add(new BulkUdpModule()); modules.add(new ShapeModule()); modules.add(new PercolatorModule()); injector = modules.createInjector(); client = injector.getInstance(Client.class); logger.info("initialized"); } @Override public Settings settings() { return this.settings; } @Override public Client client() { return client; } public Node start() { if (!lifecycle.moveToStarted()) { return this; } ESLogger logger = Loggers.getLogger(Node.class, settings.get("name")); logger.info("starting ..."); // hack around dependency injection problem (for now...) injector.getInstance(Discovery.class).setAllocationService(injector.getInstance(AllocationService.class)); for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) { injector.getInstance(plugin).start(); } injector.getInstance(IndicesService.class).start(); injector.getInstance(IndexingMemoryController.class).start(); injector.getInstance(IndicesClusterStateService.class).start(); injector.getInstance(IndicesTTLService.class).start(); injector.getInstance(RiversManager.class).start(); injector.getInstance(ClusterService.class).start(); injector.getInstance(RoutingService.class).start(); injector.getInstance(SearchService.class).start(); injector.getInstance(MonitorService.class).start(); injector.getInstance(RestController.class).start(); injector.getInstance(TransportService.class).start(); DiscoveryService discoService = injector.getInstance(DiscoveryService.class).start(); // gateway should start after disco, so it can try and recovery from gateway on "start" injector.getInstance(GatewayService.class).start(); if (settings.getAsBoolean("http.enabled", true)) { injector.getInstance(HttpServer.class).start(); } injector.getInstance(BulkUdpService.class).start(); logger.info("started"); return this; } @Override public Node stop() { if (!lifecycle.moveToStopped()) { return this; } ESLogger logger = Loggers.getLogger(Node.class, settings.get("name")); logger.info("stopping ..."); injector.getInstance(BulkUdpService.class).stop(); if (settings.getAsBoolean("http.enabled", true)) { injector.getInstance(HttpServer.class).stop(); } injector.getInstance(RiversManager.class).stop(); // stop any changes happening as a result of cluster state changes injector.getInstance(IndicesClusterStateService.class).stop(); // we close indices first, so operations won't be allowed on it injector.getInstance(IndexingMemoryController.class).stop(); injector.getInstance(IndicesTTLService.class).stop(); injector.getInstance(IndicesService.class).stop(); // sleep a bit to let operations finish with indices service // try { // Thread.sleep(500); // } catch (InterruptedException e) { // // ignore // } injector.getInstance(RoutingService.class).stop(); injector.getInstance(ClusterService.class).stop(); injector.getInstance(DiscoveryService.class).stop(); injector.getInstance(MonitorService.class).stop(); injector.getInstance(GatewayService.class).stop(); injector.getInstance(SearchService.class).stop(); injector.getInstance(RestController.class).stop(); injector.getInstance(TransportService.class).stop(); for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) { injector.getInstance(plugin).stop(); } logger.info("stopped"); return this; } public void close() { if (lifecycle.started()) { stop(); } if (!lifecycle.moveToClosed()) { return; } ESLogger logger = Loggers.getLogger(Node.class, settings.get("name")); logger.info("closing ..."); StopWatch stopWatch = new StopWatch("node_close"); stopWatch.start("bulk.udp"); injector.getInstance(BulkUdpService.class).close(); stopWatch.stop().start("http"); if (settings.getAsBoolean("http.enabled", true)) { injector.getInstance(HttpServer.class).close(); } stopWatch.stop().start("rivers"); injector.getInstance(RiversManager.class).close(); stopWatch.stop().start("client"); injector.getInstance(Client.class).close(); stopWatch.stop().start("indices_cluster"); injector.getInstance(IndicesClusterStateService.class).close(); stopWatch.stop().start("indices"); injector.getInstance(IndicesFilterCache.class).close(); injector.getInstance(IndicesFieldDataCache.class).close(); injector.getInstance(IndexingMemoryController.class).close(); injector.getInstance(IndicesTTLService.class).close(); injector.getInstance(IndicesService.class).close(); stopWatch.stop().start("routing"); injector.getInstance(RoutingService.class).close(); stopWatch.stop().start("cluster"); injector.getInstance(ClusterService.class).close(); stopWatch.stop().start("discovery"); injector.getInstance(DiscoveryService.class).close(); stopWatch.stop().start("monitor"); injector.getInstance(MonitorService.class).close(); stopWatch.stop().start("gateway"); injector.getInstance(GatewayService.class).close(); stopWatch.stop().start("search"); injector.getInstance(SearchService.class).close(); stopWatch.stop().start("rest"); injector.getInstance(RestController.class).close(); stopWatch.stop().start("transport"); injector.getInstance(TransportService.class).close(); stopWatch.stop().start("percolator_service"); injector.getInstance(PercolatorService.class).close(); for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) { stopWatch.stop().start("plugin(" + plugin.getName() + ")"); injector.getInstance(plugin).close(); } stopWatch.stop().start("node_cache"); injector.getInstance(NodeCache.class).close(); stopWatch.stop().start("script"); injector.getInstance(ScriptService.class).close(); stopWatch.stop().start("thread_pool"); injector.getInstance(ThreadPool.class).shutdown(); try { injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore } stopWatch.stop().start("thread_pool_force_shutdown"); try { injector.getInstance(ThreadPool.class).shutdownNow(); } catch (Exception e) { // ignore } stopWatch.stop(); if (logger.isTraceEnabled()) { logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint()); } injector.getInstance(NodeEnvironment.class).close(); injector.getInstance(CacheRecycler.class).close(); Injectors.close(injector); CachedStreams.clear(); logger.info("closed"); } @Override public boolean isClosed() { return lifecycle.closed(); } public Injector injector() { return this.injector; } public static void main(String[] args) throws Exception { final InternalNode node = new InternalNode(); node.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { node.close(); } }); } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Oncology/src/ims/oncology/forms/chemotherapydetails/ConfigFlags.java
2340
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH package ims.oncology.forms.chemotherapydetails; import java.io.Serializable; public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable { private static final long serialVersionUID = 1L; public final STALE_OBJECT_MESSAGEClass STALE_OBJECT_MESSAGE; public ConfigFlags(ims.framework.ConfigFlag configFlags) { super(configFlags); STALE_OBJECT_MESSAGE = new STALE_OBJECT_MESSAGEClass(configFlags); } public final class STALE_OBJECT_MESSAGEClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public STALE_OBJECT_MESSAGEClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public String getValue() { return (String)configFlags.get("STALE_OBJECT_MESSAGE"); } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/entityeventmap/AccessLogic.java
2542
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Mara Iroaie using IMS Development Environment (version 1.80 build 5003.20929) // Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved. package ims.pathways.forms.entityeventmap; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } public boolean isReadOnly() { if(super.isReadOnly()) return true; // TODO: Add your conditions here. return false; } }
agpl-3.0
accesstest3/cfunambol
modules/foundation/foundation-core/src/main/java/com/funambol/foundation/items/dao/PIMContactDAO.java
179451
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2006 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.foundation.items.dao; import java.io.ByteArrayInputStream; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.funambol.common.pim.common.Property; import com.funambol.common.pim.common.TypifiedProperty; import com.funambol.common.pim.contact.*; import com.funambol.framework.server.store.NotFoundException; import com.funambol.framework.tools.DBTools; import com.funambol.server.config.Configuration; import com.funambol.foundation.exception.DAOException; import com.funambol.foundation.items.model.ContactWrapper; import com.funambol.foundation.util.Def; /** * This class implements methods to access PIM contact data in a data store. * * @version $Id$ */ public class PIMContactDAO extends EntityDAO { // --------------------------------------------------------------- Constants private static final String SQL_ORDER_BY_ID = "ORDER BY id"; private static final String SQL_FILTER_BY_CONTACT_TYPE = "WHERE contact = ? AND type = ? "; private static final String SQL_GET_FNBL_PIM_CONTACT = "SELECT id, userid, last_update, status, photo_type, importance, sensitivity, " + "subject, folder, anniversary, first_name, middle_name, " + "last_name, display_name, birthday, body, categories, children, " + "hobbies, initials, languages, nickname, spouse, suffix, title, " + "assistant, company, department, job_title, manager, mileage, " + "office_location, profession, companies, gender " + "FROM fnbl_pim_contact "; private static final String SQL_GET_FNBL_PIM_CONTACT_ID_LIST = "SELECT id FROM fnbl_pim_contact "; private static final String SQL_GET_FNBL_PIM_CONTACT_ID_LIST_BY_USER = SQL_GET_FNBL_PIM_CONTACT_ID_LIST + "WHERE userid = ? " + "AND status <> 'D' "; private static final String SQL_GET_FNBL_PIM_CONTACT_BY_ID_USER = SQL_GET_FNBL_PIM_CONTACT + "WHERE id = ? AND userid = ? "; private static final String SQL_GET_CONTACT_ID_BY_ID_AND_USER_ID = "select id from fnbl_pim_contact where id=? and userid=?"; private static final String SQL_GET_STATUS_BY_ID_USER_TIME = "SELECT status FROM fnbl_pim_contact " + "WHERE id = ? AND userid = ? AND last_update > ? "; private static final String SQL_GET_FNBL_PIM_CONTACT_ITEM_BY_ID = "SELECT type, value FROM fnbl_pim_contact_item WHERE contact = ? " + "ORDER BY type"; private static final String SQL_GET_FNBL_PIM_ADDRESS_BY_ID = "SELECT type, street, city, state, postal_code, country, po_box, " + "extended_address FROM fnbl_pim_address WHERE contact = ? "; private static final String SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM = "SELECT contact FROM fnbl_pim_contact_item " + SQL_FILTER_BY_CONTACT_TYPE; private static final String SQL_SELECT_FROM_FNBL_PIM_ADDRESS = "SELECT contact FROM fnbl_pim_address " + SQL_FILTER_BY_CONTACT_TYPE; private static final String SQL_SELECT_FROM_FNBL_PIM_CONTACT_PHOTO = "SELECT p.contact, p.type, p.photo, p.url FROM fnbl_pim_contact c, " + "fnbl_pim_contact_photo p where c.id = ? and c.userid = ? and " + "c.status != 'D' and c.id = p.contact"; private static final String SQL_GET_CHANGED_CONTACTS_BY_USER_AND_LAST_UPDATE = "select id,status from fnbl_pim_contact where userid=? and " + "last_update>? and last_update<? order by id"; private static final String SQL_INSERT_INTO_FNBL_PIM_CONTACT = "INSERT INTO fnbl_pim_contact " + "(id, userid, last_update, status, photo_type, importance, sensitivity, " + "subject, folder, anniversary, first_name, middle_name, " + "last_name, display_name, birthday, body, categories, children, " + "hobbies, initials, languages, nickname, spouse, suffix, title, " + "assistant, company, department, job_title, manager, mileage, " + "office_location, profession, companies, gender ) " + "VALUES " + "(?, ?, ?, ?, ?, ?, ?, ? , ? , ? , ? , ? , ? , ? , ? , ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; private static final String SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM = "INSERT INTO fnbl_pim_contact_item " + "(contact, type, value) " + "VALUES (?, ?, ?) "; private static final String SQL_INSERT_INTO_FNBL_PIM_ADDRESS = "INSERT INTO fnbl_pim_address " + "(contact, type, street, city, state, postal_code, country, " + "po_box, extended_address) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) "; private static final String SQL_INSERT_INTO_FNBL_PIM_CONTACT_PHOTO = "INSERT INTO fnbl_pim_contact_photo (contact, type, photo, url) VALUES (?,?,?,?)"; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN = "UPDATE fnbl_pim_contact SET "; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_END = " WHERE id = ? AND userid = ? "; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_STATUS = SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN + "status = ?, last_update = ? " + SQL_UPDATE_FNBL_PIM_CONTACT_END; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_PHOTO_TYPE = SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN + "status = ?, last_update = ?, photo_type = ? " + SQL_UPDATE_FNBL_PIM_CONTACT_END; private static final String SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN = "UPDATE fnbl_pim_address SET "; private static final String SQL_UPDATE_FNBL_PIM_ADDRESS_END = " " + SQL_FILTER_BY_CONTACT_TYPE; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_ITEM = "UPDATE fnbl_pim_contact_item SET value = ? " + SQL_FILTER_BY_CONTACT_TYPE; private static final String SQL_UPDATE_FNBL_PIM_CONTACT_PHOTO = "UPDATE fnbl_pim_contact_photo SET type = ?, url = ?, photo = ? where contact = ?"; private static final String SQL_DELETE_FNBL_PIM_CONTACT_ITEM = "DELETE FROM fnbl_pim_contact_item " + SQL_FILTER_BY_CONTACT_TYPE; private static final String SQL_DELETE_CONTACT_BY_ID_USERID = "UPDATE fnbl_pim_contact SET status = 'D', last_update = ? " + "WHERE id = ? AND userid = ? "; private static final String SQL_DELETE_CONTACTS_BY_USERID = "UPDATE fnbl_pim_contact SET status = 'D', last_update = ? " + "WHERE status <> 'D' AND userid = ?"; private static final String SQL_DELETE_FNBL_PIM_CONTACT_PHOTO = "DELETE FROM fnbl_pim_contact_photo WHERE contact = ?"; private static final String SQL_EQUALS_QUESTIONMARK = " = ?"; private static final String SQL_EQUALS_QUESTIONMARK_COMMA = " = ?, "; protected static final String SQL_FIELD_ID = "id"; protected static final String SQL_FIELD_USERID = "userid"; protected static final String SQL_FIELD_LAST_UPDATE = "last_update"; protected static final String SQL_FIELD_STATUS = "status"; protected static final String SQL_FIELD_PHOTO_TYPE = "photo_type"; protected static final String SQL_FIELD_IMPORTANCE = "importance"; protected static final String SQL_FIELD_SENSITIVITY = "sensitivity"; protected static final String SQL_FIELD_SUBJECT = "subject"; protected static final String SQL_FIELD_FOLDER = "folder"; protected static final String SQL_FIELD_ANNIVERSARY = "anniversary"; protected static final String SQL_FIELD_FIRST_NAME = "first_name"; protected static final String SQL_FIELD_MIDDLE_NAME = "middle_name"; protected static final String SQL_FIELD_LAST_NAME = "last_name"; protected static final String SQL_FIELD_DISPLAY_NAME = "display_name"; protected static final String SQL_FIELD_BIRTHDAY = "birthday"; protected static final String SQL_FIELD_BODY = "body"; protected static final String SQL_FIELD_CATEGORIES = "categories"; protected static final String SQL_FIELD_CHILDREN = "children"; protected static final String SQL_FIELD_HOBBIES = "hobbies"; protected static final String SQL_FIELD_GENDER = "gender"; protected static final String SQL_FIELD_INITIALS = "initials"; protected static final String SQL_FIELD_LANGUAGES = "languages"; protected static final String SQL_FIELD_NICKNAME = "nickname"; protected static final String SQL_FIELD_SPOUSE = "spouse"; protected static final String SQL_FIELD_SUFFIX = "suffix"; protected static final String SQL_FIELD_TITLE = "title"; protected static final String SQL_FIELD_ASSISTANT = "assistant"; protected static final String SQL_FIELD_COMPANY = "company"; protected static final String SQL_FIELD_COMPANIES = "companies"; protected static final String SQL_FIELD_DEPARTMENT = "department"; protected static final String SQL_FIELD_JOB_TITLE = "job_title"; protected static final String SQL_FIELD_MANAGER = "manager"; protected static final String SQL_FIELD_MILEAGE = "mileage"; protected static final String SQL_FIELD_OFFICE_LOCATION = "office_location"; protected static final String SQL_FIELD_PROFESSION = "profession"; protected static final String SQL_FIELD_TYPE = "type"; protected static final String SQL_FIELD_VALUE = "value"; protected static final String SQL_FIELD_STREET = "street"; protected static final String SQL_FIELD_CITY = "city"; protected static final String SQL_FIELD_STATE = "state"; protected static final String SQL_FIELD_POSTAL_CODE = "postal_code"; protected static final String SQL_FIELD_COUNTRY = "country"; protected static final String SQL_FIELD_PO_BOX = "po_box"; protected static final String SQL_FIELD_EXTENDED_ADDRESS = "extended_address"; protected static final int SQL_ANNIVERSARY_DIM = 16; protected static final int SQL_ASSISTANT_DIM = 128; protected static final int SQL_BIRTHDAY_DIM = 16; protected static final int SQL_CATEGORIES_DIM = 255; protected static final int SQL_CHILDREN_DIM = 255; protected static final int SQL_CITY_DIM = 64; protected static final int SQL_COMPANY_DIM = 255; protected static final int SQL_COMPANIES_DIM = 255; protected static final int SQL_COUNTRY_DIM = 32; protected static final int SQL_DEPARTMENT_DIM = 255; protected static final int SQL_DISPLAYNAME_DIM = 128; protected static final int SQL_EMAIL_DIM = 255; protected static final int SQL_FIRSTNAME_DIM = 64; protected static final int SQL_FOLDER_DIM = 255; protected static final int SQL_GENDER_DIM = 1; protected static final int SQL_HOBBIES_DIM = 255; protected static final int SQL_INITIALS_DIM = 16; protected static final int SQL_LABEL_DIM = 255; // @todo Enough? protected static final int SQL_LANGUAGES_DIM = 255; protected static final int SQL_LASTNAME_DIM = 64; protected static final int SQL_MANAGER_DIM = 128; protected static final int SQL_MIDDLENAME_DIM = 64; protected static final int SQL_MILEAGE_DIM = 16; protected static final int SQL_NICKNAME_DIM = 64; protected static final int SQL_NOTE_DIM = 4096; protected static final int SQL_OFFICELOCATION_DIM = 64; protected static final int SQL_PHONE_DIM = 255; protected static final int SQL_POSTALCODE_DIM = 16; protected static final int SQL_POSTALOFFICEADDRESS_DIM = 16; protected static final int SQL_EXTENDEDADDRESS_DIM = 255; protected static final int SQL_ROLE_DIM = 64; protected static final int SQL_SALUTATION_DIM = 32; protected static final int SQL_SPOUSE_DIM = 128; protected static final int SQL_STATE_DIM = 64; protected static final int SQL_STREET_DIM = 128; protected static final int SQL_SUBJECT_DIM = 255; protected static final int SQL_SUFFIX_DIM = 32; protected static final int SQL_TITLE_DIM = 128; protected static final int SQL_WEBPAGE_DIM = 255; /** Contact item type cannot be identified */ protected static final int TYPE_UNDEFINED = -1; protected static final int TYPE_ASSISTANT_NUMBER = 13; protected static final String FIELD_ASSISTANT_NUMBER = "AssistantTelephoneNumber"; protected static final int TYPE_BUSINESS_FAX_NUMBER = 11; protected static final String FIELD_BUSINESS_FAX_NUMBER = "BusinessFaxNumber"; protected static final int TYPE_BUSINESS_TELEPHONE_NUMBER = 10; protected static final String FIELD_BUSINESS_TELEPHONE_NUMBER = "BusinessTelephoneNumber"; protected static final int TYPE_CALLBACK_NUMBER = 15; protected static final String FIELD_CALLBACK_NUMBER = "CallbackTelephoneNumber"; protected static final int TYPE_CAR_TELEPHONE_NUMBER = 20; protected static final String FIELD_CAR_TELEPHONE_NUMBER = "CarTelephoneNumber"; protected static final int TYPE_COMPANY_MAIN_TELEPHONE_NUMBER = 12; protected static final String FIELD_COMPANY_MAIN_TELEPHONE_NUMBER = "CompanyMainTelephoneNumber"; protected static final int TYPE_EMAIL_1_ADDRESS = 4; protected static final String FIELD_EMAIL_1_ADDRESS = "Email1Address"; protected static final int TYPE_EMAIL_2_ADDRESS = 16; protected static final String FIELD_EMAIL_2_ADDRESS = "Email2Address"; protected static final int TYPE_HOME_WEB_PAGE = 6; protected static final String FIELD_HOME_WEB_PAGE = "HomeWebPage"; protected static final int TYPE_HOME_TELEPHONE_NUMBER = 1; protected static final String FIELD_HOME_TELEPHONE_NUMBER = "HomeTelephoneNumber"; protected static final int TYPE_HOME_FAX_NUMBER = 2; protected static final String FIELD_HOME_FAX_NUMBER = "HomeFaxNumber"; protected static final int TYPE_MOBILE_TELEPHONE_NUMBER = 3; protected static final String FIELD_MOBILE_TELEPHONE_NUMBER = "MobileTelephoneNumber"; protected static final int TYPE_OTHER_TELEPHONE_NUMBER = 30; protected static final String FIELD_OTHER_TELEPHONE_NUMBER = "OtherTelephoneNumber"; protected static final int TYPE_PAGER_NUMBER = 14; protected static final String FIELD_PAGER_NUMBER = "PagerNumber"; protected static final int TYPE_PRIMARY_TELEPHONE_NUMBER = 21; protected static final String FIELD_PRIMARY_TELEPHONE_NUMBER = "PrimaryTelephoneNumber"; protected static final int TYPE_WEB_PAGE = 5; protected static final String FIELD_WEB_PAGE = "WebPage"; protected static final int TYPE_BUSINESS_WEB_PAGE = 7; protected static final String FIELD_BUSINESS_WEB_PAGE = "BusinessWebPage"; protected static final int TYPE_INSTANT_MESSENGER = 8; protected static final String FIELD_INSTANT_MESSENGER = "IMAddress"; protected static final int TYPE_BUSINESS_LABEL = 17; protected static final String FIELD_BUSINESS_LABEL = "BusinessLabel"; protected static final int TYPE_HOME_LABEL = 18; protected static final String FIELD_HOME_LABEL = "HomeLabel"; protected static final int TYPE_OTHER_LABEL = 19; protected static final String FIELD_OTHER_LABEL = "OtherLabel"; protected static final int TYPE_HOME_2_TELEPHONE_NUMBER = 22; protected static final String FIELD_HOME_2_TELEPHONE_NUMBER = "Home2TelephoneNumber"; protected static final int TYPE_EMAIL_3_ADDRESS = 23; protected static final String FIELD_EMAIL_3_ADDRESS = "Email3Address"; protected static final int TYPE_BUSINESS_2_TELEPHONE_NUMBER = 31; protected static final String FIELD_BUSINESS_2_TELEPHONE_NUMBER = "Business2TelephoneNumber"; protected static final int TYPE_OTHER_FAX_NUMBER = 29; protected static final String FIELD_OTHER_FAX_NUMBER = "OtherFaxNumber"; protected static final int TYPE_TELEX_NUMBER = 27; protected static final String FIELD_TELEX_NUMBER = "TelexNumber"; protected static final int TYPE_RADIO_TELEPHONE_NUMBER = 28; protected static final String FIELD_RADIO_TELEPHONE_NUMBER = "RadioTelephoneNumber"; protected static final String FIELD_JOB_TITLE = "JobTitle"; protected static final String FIELD_NOTE = "Body"; // Address type in fnbl_pim_address table protected static final int ADDRESS_TYPE_HOME = 1; protected static final int ADDRESS_TYPE_WORK = 2; protected static final int ADDRESS_TYPE_OTHER = 3; private static final String UNSET_FIELD_PLACEHOLDER = "<N/A>"; private static final String SQL_GET_POTENTIAL_TWINS = new StringBuilder("SELECT c.id, i.type as item_type, i.value as item_value ") .append("FROM fnbl_pim_contact c LEFT OUTER JOIN fnbl_pim_contact_item i ") .append("ON (c.id = i.contact) WHERE (c.userid = ?) AND ( ") .append("(i.type IS null) OR i.type IN (") //all the contact different phone numbers .append(TYPE_ASSISTANT_NUMBER).append(",") .append(TYPE_BUSINESS_TELEPHONE_NUMBER).append(",") .append(TYPE_BUSINESS_FAX_NUMBER).append(",") .append(TYPE_BUSINESS_2_TELEPHONE_NUMBER).append(",") .append(TYPE_CALLBACK_NUMBER).append(",") .append(TYPE_CAR_TELEPHONE_NUMBER).append(",") .append(TYPE_COMPANY_MAIN_TELEPHONE_NUMBER).append(",") .append(TYPE_HOME_2_TELEPHONE_NUMBER).append(",") .append(TYPE_HOME_FAX_NUMBER).append(",") .append(TYPE_HOME_TELEPHONE_NUMBER).append(",") .append(TYPE_MOBILE_TELEPHONE_NUMBER).append(",") .append(TYPE_OTHER_FAX_NUMBER).append(",") .append(TYPE_OTHER_TELEPHONE_NUMBER).append(",") .append(TYPE_PAGER_NUMBER).append(",") .append(TYPE_PRIMARY_TELEPHONE_NUMBER).append(",") .append(TYPE_RADIO_TELEPHONE_NUMBER).append(",") .append(TYPE_TELEX_NUMBER).append(",") //all the contact different email address .append(TYPE_EMAIL_1_ADDRESS).append(",") .append(TYPE_EMAIL_2_ADDRESS).append(",") .append(TYPE_EMAIL_3_ADDRESS).append(") ) ").toString(); private static final String SQL_UNNAMED_WHERE_CLAUSES = new StringBuilder() .append(" AND ( (c.first_name is null) OR (c.first_name = ?) )") .append(" AND ( (c.last_name is null) OR (c.last_name = ?) )") .append(" AND ( (c.company is null) OR (c.company = ?) )") .append(" AND ( (c.display_name is null) OR (c.display_name = ?) ) ") .toString(); private static final String SQL_STATUS_NOT_D = " AND c.status != 'D' "; // ------------------------------------------------------------ Private data private Map<Long, Map<Integer, String>> unnamedContacts = null; //------------------------------------------------------------- Constructors /** * @param userId the user identifier * @see PIMEntityDAO#PIMEntityDAO(String, String) */ public PIMContactDAO(String userId) { super(userId, Def.ID_COUNTER); if (log.isTraceEnabled()) { log.trace("Created new PIMContactDAO for user ID " + userId); } } //----------------------------------------------------------- Public methods /** * Adds a contact. If necessary, a new ID is generated and set in the * ContactWrapper. * * @param cw as a ContactWrapper object, usually without an ID set. * @throws DAOException * * @see ContactWrapper */ public void addItem(ContactWrapper cw) throws DAOException { if (log.isTraceEnabled()) { log.trace("Storing a contact item..."); } Connection con = null; PreparedStatement ps = null; long id = 0; int type = 0; PersonalDetail personalDetail = null; BusinessDetail businessDetail = null; Address homeAddressBook = null; Address workAddressBook = null; Address otherAddressBook = null; Name name = null; Phone phone = null; Email email = null; WebPage webPage = null; List<WebPage> webPages = new ArrayList<WebPage>(); List<Email> emails = new ArrayList<Email>(); List<Phone> phones = new ArrayList<Phone>(); List<String[]> labels = new ArrayList<String[]>(); String webPageType = null; Short importance = null; Short sensitivity = null; String mileage = null; String subject = null; String folder = null; String anniversary = null; String firstName = null; String middleName = null; String lastName = null; String displayName = null; String birthday = null; String categories = null; String gender = null; String hobbies = null; String initials = null; String languages = null; String nickName = null; String spouse = null; String suffix = null; String assistant = null; String officeLocation = null; String company = null; String companies = null; String department = null; String manager = null; String role = null; String children = null; String salutation = null; String sId = null; Timestamp lastUpdate = cw.getLastUpdate(); if (lastUpdate == null) { lastUpdate = new Timestamp(System.currentTimeMillis()); } try { // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); sId = cw.getId(); if (sId == null) { // ...as it should be sId = getNextID(); cw.setId(sId); } id = Long.parseLong(sId); Contact c = cw.getContact(); personalDetail = c.getPersonalDetail(); businessDetail = c.getBusinessDetail(); name = c.getName(); if (personalDetail != null) { homeAddressBook = personalDetail.getAddress(); otherAddressBook = personalDetail.getOtherAddress(); webPages.addAll(personalDetail.getWebPages()); emails.addAll(personalDetail.getEmails()); phones.addAll(personalDetail.getPhones()); } if (businessDetail != null) { workAddressBook = businessDetail.getAddress(); webPages.addAll(businessDetail.getWebPages()); emails.addAll(businessDetail.getEmails()); phones.addAll(businessDetail.getPhones()); companies = businessDetail.getCompanies(); } importance = c.getImportance(); sensitivity = c.getSensitivity(); mileage = c.getMileage(); subject = c.getSubject(); languages = c.getLanguages(); categories = Property.stringFrom(c.getCategories()); folder = c.getFolder(); if (personalDetail != null) { anniversary = personalDetail.getAnniversary(); birthday = personalDetail.getBirthday(); children = personalDetail.getChildren(); spouse = personalDetail.getSpouse(); hobbies = personalDetail.getHobbies(); gender = personalDetail.getGender(); } if (businessDetail != null) { assistant = businessDetail.getAssistant(); manager = businessDetail.getManager(); officeLocation = businessDetail.getOfficeLocation(); company = Property.stringFrom(businessDetail.getCompany()); department = Property.stringFrom(businessDetail.getDepartment()); role = Property.stringFrom(businessDetail.getRole()); } if (name != null) { firstName = Property.stringFrom(name.getFirstName()); middleName = Property.stringFrom(name.getMiddleName()); lastName = Property.stringFrom(name.getLastName()); displayName = Property.stringFrom(name.getDisplayName()); initials = Property.stringFrom(name.getInitials()); nickName = Property.stringFrom(name.getNickname()); suffix = Property.stringFrom(name.getSuffix()); salutation = Property.stringFrom(name.getSalutation()); } ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT); // // GENERAL // if (log.isTraceEnabled()) { log.trace("Preparing statement with ID " + id); } ps.setLong(1, id); if (log.isTraceEnabled()) { log.trace("Preparing statement with user ID " + userId); } ps.setString(2, userId); ps.setLong(3, lastUpdate.getTime()); ps.setString(4, String.valueOf(Def.PIM_STATE_NEW)); boolean hasPhoto = false; Photo photo = personalDetail.getPhotoObject(); if (photo != null && (photo.getImage() != null || photo.getUrl() != null)) { hasPhoto = true; ps.setShort(5, photo.getImage() != null ? ContactWrapper.PHOTO_IMAGE : ContactWrapper.PHOTO_URL); } else if (photo!= null) { ps.setShort(5, ContactWrapper.EMPTY_PHOTO); } else { ps.setNull(5, Types.SMALLINT); } // // CONTACT DETAILS // if (importance != null) { ps.setShort(6, importance.shortValue()); } else { ps.setNull(6, Types.SMALLINT); } if (sensitivity != null) { ps.setShort(7, sensitivity.shortValue()); } else { ps.setNull(7, Types.SMALLINT); } ps.setString(8, StringUtils.left(subject, SQL_SUBJECT_DIM)); ps.setString(9, StringUtils.left(folder, SQL_FOLDER_DIM)); // // PERSONAL DETAILS // ps.setString(10, StringUtils.left(anniversary, SQL_ANNIVERSARY_DIM)); ps.setString(11, StringUtils.left(firstName, SQL_FIRSTNAME_DIM)); ps.setString(12, StringUtils.left(middleName, SQL_MIDDLENAME_DIM)); ps.setString(13, StringUtils.left(lastName, SQL_LASTNAME_DIM)); ps.setString(14, StringUtils.left(displayName, SQL_DISPLAYNAME_DIM)); ps.setString(15, StringUtils.left(birthday, SQL_BIRTHDAY_DIM)); if (c.getNotes() != null && c.getNotes().size() > 0) { String noteValue = ((Note) c.getNotes().get(0)).getPropertyValueAsString(); ps.setString(16, StringUtils.left(noteValue, SQL_NOTE_DIM)); } else { ps.setString(16, null); } ps.setString(17, StringUtils.left(categories, SQL_CATEGORIES_DIM)); ps.setString(18, StringUtils.left(children, SQL_CHILDREN_DIM)); ps.setString(19, StringUtils.left(hobbies, SQL_HOBBIES_DIM)); ps.setString(20, StringUtils.left(initials, SQL_INITIALS_DIM)); ps.setString(21, StringUtils.left(languages, SQL_LANGUAGES_DIM)); ps.setString(22, StringUtils.left(nickName, SQL_NICKNAME_DIM)); ps.setString(23, StringUtils.left(spouse, SQL_SPOUSE_DIM)); ps.setString(24, StringUtils.left(suffix, SQL_SUFFIX_DIM)); ps.setString(25, StringUtils.left(salutation, SQL_SALUTATION_DIM)); // // BUSINESS DETAILS // ps.setString(26, StringUtils.left(assistant, SQL_ASSISTANT_DIM)); ps.setString(27, StringUtils.left(company, SQL_COMPANY_DIM)); ps.setString(28, StringUtils.left(department, SQL_DEPARTMENT_DIM)); if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) { String titleValue = ((Title) businessDetail.getTitles().get(0)).getPropertyValueAsString(); ps.setString(29, StringUtils.left(titleValue, SQL_TITLE_DIM)); } else { ps.setString(29, null); } ps.setString(30, StringUtils.left(manager, SQL_MANAGER_DIM)); if (mileage != null && mileage.length() > SQL_MILEAGE_DIM) { mileage = mileage.substring(0, SQL_MILEAGE_DIM); } ps.setString(31, StringUtils.left(mileage, SQL_MILEAGE_DIM)); ps.setString(32, StringUtils.left(officeLocation, SQL_OFFICELOCATION_DIM)); ps.setString(33, StringUtils.left(role, SQL_ROLE_DIM)); ps.setString(34, StringUtils.left(companies, SQL_COMPANIES_DIM)); ps.setString(35, StringUtils.left(gender, SQL_GENDER_DIM)); ps.executeUpdate(); DBTools.close(null, ps, null); // // emails // if (!emails.isEmpty()) { ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = emails.size(); i < l; i++) { email = emails.get(i); type = getContactEmailItemTypeFromEmailPropertyType(email.getEmailType()); // Unknown property: saves nothing if (TYPE_UNDEFINED == type) continue; String emailValue = email.getPropertyValueAsString(); if (emailValue != null && emailValue.length() != 0) { if (emailValue.length() > SQL_EMAIL_DIM) { emailValue = emailValue.substring(0, SQL_EMAIL_DIM); } ps.setLong(1, id); ps.setInt(2, type); ps.setString(3, emailValue); ps.executeUpdate(); } } DBTools.close(null, ps, null); } // // phones // if (!phones.isEmpty()) { ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = phones.size(); i < l; i++) { phone = phones.get(i); type = getContactPhoneItemTypeFromPhonePropertyType(phone.getPhoneType()); // Unknown property: saves nothing if (TYPE_UNDEFINED == type) continue; String phoneValue = phone.getPropertyValueAsString(); if (phoneValue != null && phoneValue.length() != 0) { if (phoneValue.length() > SQL_PHONE_DIM) { phoneValue = phoneValue.substring(0, SQL_PHONE_DIM); } ps.setLong(1, id); ps.setInt(2, type); ps.setString(3, phoneValue); ps.executeUpdate(); } } DBTools.close(null, ps, null); } // // webPages // if (!webPages.isEmpty()) { ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = webPages.size(); i < l; i++) { webPage = webPages.get(i); webPageType = webPage.getWebPageType(); if ((FIELD_WEB_PAGE).equals(webPageType)) { type = TYPE_WEB_PAGE; } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) { type = TYPE_HOME_WEB_PAGE; } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) { type = TYPE_BUSINESS_WEB_PAGE; } else { // // Unknown property: saves nothing // continue; } String webPageValue = webPage.getPropertyValueAsString(); if (webPageValue != null && webPageValue.length() != 0) { if (webPageValue.length() > SQL_WEBPAGE_DIM) { webPageValue = webPageValue.substring(0, SQL_WEBPAGE_DIM); } ps.setLong(1, id); ps.setInt(2, type); ps.setString(3, webPageValue); ps.executeUpdate(); } } DBTools.close(null, ps, null); } if (homeAddressBook != null) { String homeStreet = Property.stringFrom(homeAddressBook.getStreet()); String homeCity = Property.stringFrom(homeAddressBook.getCity()); String homePostalCode = Property.stringFrom(homeAddressBook.getPostalCode()); String homeState = Property.stringFrom(homeAddressBook.getState()); String homeCountry = Property.stringFrom(homeAddressBook.getCountry()); String homePostalOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress()); String homeExtendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress()); String homeLabel = Property.stringFrom(homeAddressBook.getLabel()); if (homeLabel != null) { String[] label = {homeLabel, FIELD_HOME_LABEL}; labels.add(label); } String[] homeAddressFields = {homeStreet, homeCity, homePostalCode, homeCountry, homeState, homePostalOfficeAddress, homeExtendedAddress}; if(!hasOnlyEmptyOrNullContent(homeAddressFields)){ ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, id); ps.setInt(2, ADDRESS_TYPE_HOME); ps.setString(3, replaceNewLine( StringUtils.left(homeStreet, SQL_STREET_DIM))); ps.setString(4, StringUtils.left(homeCity, SQL_CITY_DIM)); ps.setString(5, StringUtils.left(homeState, SQL_STATE_DIM)); ps.setString(6, StringUtils.left(homePostalCode, SQL_POSTALCODE_DIM)); ps.setString(7, StringUtils.left(homeCountry, SQL_COUNTRY_DIM)); ps.setString(8, StringUtils.left(homePostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM)); ps.setString(9, StringUtils.left(homeExtendedAddress, SQL_EXTENDEDADDRESS_DIM)); ps.executeUpdate(); DBTools.close(null, ps, null); } } if (otherAddressBook != null) { String otherStreet = Property.stringFrom(otherAddressBook.getStreet()); String otherCity = Property.stringFrom(otherAddressBook.getCity()); String otherPostalCode = Property.stringFrom(otherAddressBook.getPostalCode()); String otherState = Property.stringFrom(otherAddressBook.getState()); String otherCountry = Property.stringFrom(otherAddressBook.getCountry()); String otherPostalOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress()); String otherExtendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress()); String otherLabel = Property.stringFrom(otherAddressBook.getLabel()); if (otherLabel != null) { String[] label = {otherLabel, FIELD_OTHER_LABEL}; labels.add(label); } String[] otherAddressFields = {otherStreet, otherCity, otherPostalCode, otherCountry, otherState, otherPostalOfficeAddress, otherExtendedAddress}; if (!hasOnlyEmptyOrNullContent(otherAddressFields)){ ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, id); ps.setInt(2, ADDRESS_TYPE_OTHER); ps.setString(3, replaceNewLine( StringUtils.left(otherStreet, SQL_STREET_DIM))); ps.setString(4, StringUtils.left(otherCity, SQL_CITY_DIM)); ps.setString(5, StringUtils.left(otherState, SQL_STATE_DIM)); ps.setString(6, StringUtils.left(otherPostalCode, SQL_POSTALCODE_DIM)); ps.setString(7, StringUtils.left(otherCountry, SQL_COUNTRY_DIM)); ps.setString(8, StringUtils.left(otherPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM)); ps.setString(9, StringUtils.left(otherExtendedAddress, SQL_EXTENDEDADDRESS_DIM)); ps.executeUpdate(); DBTools.close(null, ps, null); } } if (workAddressBook != null) { String workStreet = Property.stringFrom(workAddressBook.getStreet()); String workCity = Property.stringFrom(workAddressBook.getCity()); String workPostalCode = Property.stringFrom(workAddressBook.getPostalCode()); String workState = Property.stringFrom(workAddressBook.getState()); String workCountry = Property.stringFrom(workAddressBook.getCountry()); String workPostalOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress()); String workExtendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress()); String workLabel = Property.stringFrom(workAddressBook.getLabel()); if (workLabel != null) { String[] label = {workLabel, FIELD_BUSINESS_LABEL}; labels.add(label); } String[] workAddressFields = {workStreet, workCity, workPostalCode, workCountry, workState, workPostalOfficeAddress, workExtendedAddress}; if (!hasOnlyEmptyOrNullContent(workAddressFields)){ ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, id); ps.setInt(2, ADDRESS_TYPE_WORK); ps.setString(3, replaceNewLine( StringUtils.left(workStreet, SQL_STREET_DIM))); ps.setString(4, StringUtils.left(workCity, SQL_CITY_DIM)); ps.setString(5, StringUtils.left(workState, SQL_STATE_DIM)); ps.setString(6, StringUtils.left(workPostalCode, SQL_POSTALCODE_DIM)); ps.setString(7, StringUtils.left(workCountry, SQL_COUNTRY_DIM)); ps.setString(8, StringUtils.left(workPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM)); ps.setString(9, StringUtils.left(workExtendedAddress, SQL_EXTENDEDADDRESS_DIM)); ps.executeUpdate(); DBTools.close(null, ps, null); } } // // labels // if (!labels.isEmpty()) { ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = labels.size(); i < l; i++) { String[] label = labels.get(i); String labelType = label[1]; if ((FIELD_HOME_LABEL).equals(labelType)) { type = TYPE_HOME_LABEL; } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) { type = TYPE_BUSINESS_LABEL; } else if ((FIELD_OTHER_LABEL).equals(labelType)) { type = TYPE_OTHER_LABEL; } else { // // Unknown property: saves nothing // continue; } String labelValue = label[0]; if (labelValue != null && labelValue.length() != 0) { if (labelValue.length() > SQL_LABEL_DIM) { labelValue = labelValue.substring(0, SQL_LABEL_DIM); } ps.setLong(1, id); ps.setInt(2, type); ps.setString(3, labelValue); ps.executeUpdate(); } } DBTools.close(null, ps, null); } if (hasPhoto) { insertPhoto(con, Long.parseLong(cw.getId()), photo); } } catch (Exception e) { throw new DAOException("Error adding contact.", e); } finally { DBTools.close(con, ps, null); } if(log.isTraceEnabled()) { log.trace("Added item with ID '" + id + "'"); } } /** * Updates a contact. * * @param cw as a ContactWrapper object. If its last update time is null, * then it's set to the current time. * @return the UID of the contact * @throws DAOException * * @see ContactWrapper */ public String updateItem(ContactWrapper cw) throws DAOException { Connection con = null; PreparedStatement ps = null; PreparedStatement ps1 = null; ResultSet rs = null; int type = 0; PersonalDetail personalDetail = null; BusinessDetail businessDetail = null; Address homeAddressBook = null; Address workAddressBook = null; Address otherAddressBook = null; Name name = null; Phone phone = null; Email email = null; WebPage webPage = null; List<WebPage> webPages = new ArrayList<WebPage>(); List<Email> emails = new ArrayList<Email>(); List<Phone> phones = new ArrayList<Phone>(); List<String[]> labels = new ArrayList<String[]>(); String phoneType = null; String webPageType = null; StringBuffer queryUpdateFunPimContact = null; Short importance = null; Short sensitivity = null; String mileage = null; String subject = null; String folder = null; String anniversary = null; String firstName = null; String middleName = null; String lastName = null; String displayName = null; String birthday = null; String note = null; String categories = null; String hobbies = null; String gender = null; String initials = null; String languages = null; String nickName = null; String spouse = null; String suffix = null; String assistant = null; String company = null; String companies = null; String department = null; String jobTitle = null; String manager = null; String city = null; String state = null; String role = null; String children = null; String salutation = null; String officeLocation = null; String street = null; String postalCode = null; String country = null; String postOfficeAddress = null; String extendedAddress = null; String[] addressFields = null; boolean findRecord = false; boolean emptyAddress = false; short photoType = ContactWrapper.EMPTY_PHOTO; boolean photoToRemove = false; boolean photoToSet = false; boolean photoNothingToDo = false; StringBuffer sqlUpdateFunPimAddress = null; try { Timestamp lastUpdate = (cw.getLastUpdate() == null) ? new Timestamp(System.currentTimeMillis()) : cw.getLastUpdate(); // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); Contact c = cw.getContact(); personalDetail = c.getPersonalDetail(); businessDetail = c.getBusinessDetail(); name = c.getName(); importance = c.getImportance(); sensitivity = c.getSensitivity(); mileage = c.getMileage(); subject = c.getSubject(); languages = c.getLanguages(); folder = c.getFolder(); categories = Property.stringFrom(c.getCategories()); if (personalDetail != null) { homeAddressBook = personalDetail.getAddress(); otherAddressBook = personalDetail.getOtherAddress(); anniversary = personalDetail.getAnniversary(); birthday = personalDetail.getBirthday(); children = personalDetail.getChildren(); spouse = personalDetail.getSpouse(); hobbies = personalDetail.getHobbies(); gender = personalDetail.getGender(); webPages.addAll(personalDetail.getWebPages()); emails.addAll(personalDetail.getEmails()); phones.addAll(personalDetail.getPhones()); } if (businessDetail != null) { assistant = businessDetail.getAssistant(); manager = businessDetail.getManager(); workAddressBook = businessDetail.getAddress(); companies = businessDetail.getCompanies(); company = Property.stringFrom(businessDetail.getCompany()); department = Property.stringFrom(businessDetail.getDepartment()); role = Property.stringFrom(businessDetail.getRole()); officeLocation = businessDetail.getOfficeLocation(); webPages.addAll(businessDetail.getWebPages()); emails.addAll(businessDetail.getEmails()); phones.addAll(businessDetail.getPhones()); } if (name != null) { firstName = Property.stringFrom(name.getFirstName()); middleName = Property.stringFrom(name.getMiddleName()); lastName = Property.stringFrom(name.getLastName()); displayName = Property.stringFrom(name.getDisplayName()); initials = Property.stringFrom(name.getInitials()); nickName = Property.stringFrom(name.getNickname()); suffix = Property.stringFrom(name.getSuffix()); salutation = Property.stringFrom(name.getSalutation()); } if (c.getNotes() != null && c.getNotes().size() > 0) { note = ((Note) c.getNotes().get(0)).getPropertyValueAsString(); } else { note = null; } if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) { jobTitle = ((Title) businessDetail.getTitles().get(0)) .getPropertyValueAsString(); } else { jobTitle = null; } queryUpdateFunPimContact = new StringBuffer(); queryUpdateFunPimContact .append(SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN + SQL_FIELD_LAST_UPDATE + SQL_EQUALS_QUESTIONMARK_COMMA); // // Updating photo: // 1. if the contact doesn't have a photo (photo null), // nothing should be done (If there is a photo in the db this will // be kept) // 2. if the contact has a photo (image or url) it must be inserted // in the db // 3. if the photo has a photo but the image and the url are null, // the one in the db must be removed // Photo photo = personalDetail.getPhotoObject(); if (photo == null) { // // nothing to do // photoNothingToDo = true; } else { if (photo.getImage() != null) { photoType = ContactWrapper.PHOTO_IMAGE; photoToSet = true; } else if (photo.getUrl() != null) { photoType = ContactWrapper.PHOTO_URL; photoToSet = true; } else { photoToRemove = true; photoType = ContactWrapper.EMPTY_PHOTO; } queryUpdateFunPimContact.append(SQL_FIELD_PHOTO_TYPE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } if (importance != null) { queryUpdateFunPimContact.append(SQL_FIELD_IMPORTANCE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (sensitivity != null) { queryUpdateFunPimContact.append(SQL_FIELD_SENSITIVITY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (subject != null) { queryUpdateFunPimContact.append(SQL_FIELD_SUBJECT + SQL_EQUALS_QUESTIONMARK_COMMA); } if (folder != null) { queryUpdateFunPimContact.append(SQL_FIELD_FOLDER + SQL_EQUALS_QUESTIONMARK_COMMA); } if (anniversary != null) { queryUpdateFunPimContact.append(SQL_FIELD_ANNIVERSARY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (firstName != null) { queryUpdateFunPimContact.append(SQL_FIELD_FIRST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA); } if (middleName != null) { queryUpdateFunPimContact.append(SQL_FIELD_MIDDLE_NAME + SQL_EQUALS_QUESTIONMARK_COMMA); } if (lastName != null) { queryUpdateFunPimContact.append(SQL_FIELD_LAST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA); } if (displayName != null) { queryUpdateFunPimContact.append(SQL_FIELD_DISPLAY_NAME + SQL_EQUALS_QUESTIONMARK_COMMA); } if (birthday != null) { queryUpdateFunPimContact.append(SQL_FIELD_BIRTHDAY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (note != null) { queryUpdateFunPimContact.append(SQL_FIELD_BODY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (categories != null) { queryUpdateFunPimContact.append(SQL_FIELD_CATEGORIES + SQL_EQUALS_QUESTIONMARK_COMMA); } if (children != null) { queryUpdateFunPimContact.append(SQL_FIELD_CHILDREN + SQL_EQUALS_QUESTIONMARK_COMMA); } if (hobbies != null) { queryUpdateFunPimContact.append(SQL_FIELD_HOBBIES + SQL_EQUALS_QUESTIONMARK_COMMA); } if (initials != null) { queryUpdateFunPimContact.append(SQL_FIELD_INITIALS + SQL_EQUALS_QUESTIONMARK_COMMA); } if (languages != null) { queryUpdateFunPimContact.append(SQL_FIELD_LANGUAGES + SQL_EQUALS_QUESTIONMARK_COMMA); } if (nickName != null) { queryUpdateFunPimContact.append(SQL_FIELD_NICKNAME + SQL_EQUALS_QUESTIONMARK_COMMA); } if (spouse != null) { queryUpdateFunPimContact.append(SQL_FIELD_SPOUSE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (suffix != null) { queryUpdateFunPimContact.append(SQL_FIELD_SUFFIX + SQL_EQUALS_QUESTIONMARK_COMMA); } if (salutation != null) { queryUpdateFunPimContact.append(SQL_FIELD_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (assistant != null) { queryUpdateFunPimContact.append(SQL_FIELD_ASSISTANT + SQL_EQUALS_QUESTIONMARK_COMMA); } if (company != null) { queryUpdateFunPimContact.append(SQL_FIELD_COMPANY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (department != null) { queryUpdateFunPimContact.append(SQL_FIELD_DEPARTMENT + SQL_EQUALS_QUESTIONMARK_COMMA); } if (jobTitle != null) { queryUpdateFunPimContact.append(SQL_FIELD_JOB_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (manager != null) { queryUpdateFunPimContact.append(SQL_FIELD_MANAGER + SQL_EQUALS_QUESTIONMARK_COMMA); } if (mileage != null) { queryUpdateFunPimContact.append(SQL_FIELD_MILEAGE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (officeLocation != null) { queryUpdateFunPimContact.append(SQL_FIELD_OFFICE_LOCATION + SQL_EQUALS_QUESTIONMARK_COMMA); } if (role != null) { queryUpdateFunPimContact.append(SQL_FIELD_PROFESSION + SQL_EQUALS_QUESTIONMARK_COMMA); } if (companies != null) { queryUpdateFunPimContact.append(SQL_FIELD_COMPANIES + SQL_EQUALS_QUESTIONMARK_COMMA); } if (gender != null) { queryUpdateFunPimContact.append(SQL_FIELD_GENDER + SQL_EQUALS_QUESTIONMARK_COMMA); } queryUpdateFunPimContact .append(SQL_FIELD_STATUS + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_CONTACT_END); ps = con.prepareStatement(queryUpdateFunPimContact.toString()); int k = 1; // // GENERAL // ps.setLong(k++, lastUpdate.getTime()); // // PHOTO TYPE // if (!photoNothingToDo) { ps.setShort(k++, photoType); } // // CONTACT DETAILS // if (importance != null) { ps.setShort(k++, importance.shortValue()); } if (sensitivity != null) { ps.setShort(k++, sensitivity.shortValue()); } if (subject != null) { if (subject.length() > SQL_SUBJECT_DIM) { subject = subject.substring(0, SQL_SUBJECT_DIM); } ps.setString(k++, subject); } // // folder // if (folder != null) { if (folder.length() > SQL_FOLDER_DIM) { folder = folder.substring(0, SQL_FOLDER_DIM); } ps.setString(k++, folder); } // // PERSONAL DETAILS // // // anniversary // if (anniversary != null) { if (anniversary.length() > SQL_ANNIVERSARY_DIM) { anniversary = anniversary.substring(0, SQL_ANNIVERSARY_DIM); } ps.setString(k++, anniversary); } // // firstName // if (firstName != null) { if (firstName.length() > SQL_FIRSTNAME_DIM) { firstName = firstName.substring(0, SQL_FIRSTNAME_DIM); } ps.setString(k++, firstName); } // // middleName // if (middleName != null) { if (middleName.length() > SQL_MIDDLENAME_DIM) { middleName = middleName.substring(0, SQL_MIDDLENAME_DIM); } ps.setString(k++, middleName); } // // lastName // if (lastName != null) { if (lastName.length() > SQL_LASTNAME_DIM) { lastName = lastName.substring(0, SQL_LASTNAME_DIM); } ps.setString(k++, lastName); } // // displayName // if (displayName != null) { if (displayName.length() > SQL_DISPLAYNAME_DIM) { displayName = displayName.substring(0, SQL_DISPLAYNAME_DIM); } ps.setString(k++, displayName); } // // birthday // if (birthday != null) { if (birthday.length() > SQL_BIRTHDAY_DIM) { birthday = birthday.substring(0, SQL_BIRTHDAY_DIM); } ps.setString(k++, birthday); } // // note // if (note != null) { if (note.length() > SQL_NOTE_DIM) { note = note.substring(0, SQL_NOTE_DIM); } ps.setString(k++, note); } // // categories // if (categories != null) { if (categories.length() > SQL_CATEGORIES_DIM) { categories = categories.substring(0, SQL_CATEGORIES_DIM); } ps.setString(k++, categories); } // // children // if (children != null) { if (children.length() > SQL_CHILDREN_DIM) { children = children.substring(0, SQL_CHILDREN_DIM); } ps.setString(k++, children); } // // hobbies // if (hobbies != null) { if (hobbies.length() > SQL_HOBBIES_DIM) { hobbies = hobbies.substring(0, SQL_HOBBIES_DIM); } ps.setString(k++, hobbies); } // // initials // if (initials != null) { if (initials.length() > SQL_INITIALS_DIM) { initials = initials.substring(0, SQL_INITIALS_DIM); } ps.setString(k++, initials); } // // languages // if (languages != null) { if (languages.length() > SQL_LANGUAGES_DIM) { languages = initials.substring(0, SQL_LANGUAGES_DIM); } ps.setString(k++, languages); } // // nickName // if (nickName != null) { if (nickName.length() > SQL_NICKNAME_DIM) { nickName = nickName.substring(0, SQL_NICKNAME_DIM); } ps.setString(k++, nickName); } // // spouse // if (spouse != null) { if (spouse.length() > SQL_SPOUSE_DIM) { spouse = spouse.substring(0, SQL_SPOUSE_DIM); } ps.setString(k++, spouse); } // // suffix // if (suffix != null) { if (suffix.length() > SQL_SUFFIX_DIM) { suffix = suffix.substring(0, SQL_SUFFIX_DIM); } ps.setString(k++, suffix); } // // salutation // if (salutation != null) { if (salutation.length() > SQL_SALUTATION_DIM) { salutation = salutation.substring(0, SQL_SALUTATION_DIM); } ps.setString(k++, salutation); } // // assistant // if (assistant != null) { if (assistant.length() > SQL_ASSISTANT_DIM) { assistant = assistant.substring(0, SQL_ASSISTANT_DIM); } ps.setString(k++, assistant); } // // company // if (company != null) { if (company.length() > SQL_COMPANY_DIM) { company = company.substring(0, SQL_COMPANY_DIM); } ps.setString(k++, company); } // // department // if (department != null) { if (department.length() > SQL_DEPARTMENT_DIM) { department = department.substring(0, SQL_DEPARTMENT_DIM); } ps.setString(k++, department); } // // jobTitle // if (jobTitle != null) { if (jobTitle.length() > SQL_TITLE_DIM) { jobTitle = jobTitle.substring(0, SQL_TITLE_DIM); } ps.setString(k++, jobTitle); } // // manager // if (manager != null) { if (manager.length() > SQL_MANAGER_DIM) { manager = manager.substring(0, SQL_MANAGER_DIM); } ps.setString(k++, manager); } // // mileage // if (mileage != null) { if (mileage.length() > SQL_MILEAGE_DIM) { mileage = mileage.substring(0, SQL_MILEAGE_DIM); } ps.setString(k++, mileage); } if (officeLocation != null) { if (officeLocation.length() > SQL_OFFICELOCATION_DIM) { officeLocation = officeLocation.substring(0, SQL_OFFICELOCATION_DIM); } ps.setString(k++, officeLocation); } // // role // if (role != null) { if (role.length() > SQL_ROLE_DIM) { role = role.substring(0, SQL_ROLE_DIM); } ps.setString(k++, role); } // // companies // if (companies != null) { if (companies.length() > SQL_COMPANIES_DIM) { companies = companies.substring(0, SQL_COMPANIES_DIM); } ps.setString(k++, companies); } // // gender // if (gender != null) { if (gender.length() > SQL_GENDER_DIM) { gender = gender.substring(0, SQL_GENDER_DIM); } ps.setString(k++, gender); } // // status // ps.setString(k++, String.valueOf('U')); // // id // ps.setLong(k++, Long.parseLong(cw.getId())); // // userId // ps.setString(k++, userId); ps.executeUpdate(); DBTools.close(null, ps, null); // // emails // if (!emails.isEmpty()) { ps1 = con .prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = emails.size(); i < l; i++) { email = emails.get(i); if ((FIELD_EMAIL_1_ADDRESS).equals(email.getEmailType())) { type = TYPE_EMAIL_1_ADDRESS; } else if ((FIELD_EMAIL_2_ADDRESS).equals(email .getEmailType())) { type = TYPE_EMAIL_2_ADDRESS; } else if ((FIELD_EMAIL_3_ADDRESS).equals(email .getEmailType())) { type = TYPE_EMAIL_3_ADDRESS; } else if ((FIELD_INSTANT_MESSENGER).equals(email .getEmailType())) { type = TYPE_INSTANT_MESSENGER; } else { // // no save unknown property // continue; } ps1.setLong(1, Long.parseLong(cw.getId())); ps1.setInt(2, type); rs = ps1.executeQuery(); findRecord = rs.next(); rs.close(); rs = null; String emailValue = email.getPropertyValueAsString(); emailValue = StringUtils.left(emailValue, SQL_EMAIL_DIM); if (!findRecord) { if (emailValue != null && emailValue.length() != 0) { ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); ps.setString(3, emailValue); ps.executeUpdate(); DBTools.close(null, ps, null); } } else { if (emailValue != null) { ps = con.prepareStatement( SQL_UPDATE_FNBL_PIM_CONTACT_ITEM); ps.setString(1, emailValue); ps.setLong(2, Long.parseLong(cw.getId())); ps.setInt(3, type); } else { ps = con.prepareStatement( SQL_DELETE_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); } ps.executeUpdate(); DBTools.close(null, ps, null); } } DBTools.close(null, ps1, null); } // // phones // if (!phones.isEmpty()) { ps1 = con.prepareStatement( SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = phones.size(); i < l; i++) { phone = phones.get(i); phoneType = phone.getPhoneType(); if ((FIELD_HOME_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_HOME_TELEPHONE_NUMBER; } else if ((FIELD_HOME_2_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_HOME_2_TELEPHONE_NUMBER; } else if ((FIELD_HOME_FAX_NUMBER).equals(phoneType)) { type = TYPE_HOME_FAX_NUMBER; } else if ((FIELD_MOBILE_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_MOBILE_TELEPHONE_NUMBER; } else if ((FIELD_CAR_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_CAR_TELEPHONE_NUMBER; } else if ((FIELD_OTHER_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_OTHER_TELEPHONE_NUMBER; } else if ((FIELD_OTHER_FAX_NUMBER).equals(phoneType)) { type = TYPE_OTHER_FAX_NUMBER; } else if ((FIELD_PRIMARY_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_PRIMARY_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_BUSINESS_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_2_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_BUSINESS_2_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_FAX_NUMBER).equals(phoneType)) { type = TYPE_BUSINESS_FAX_NUMBER; } else if ((FIELD_COMPANY_MAIN_TELEPHONE_NUMBER).equals(phoneType)) { type = TYPE_COMPANY_MAIN_TELEPHONE_NUMBER; } else if ((FIELD_PAGER_NUMBER).equals(phoneType)) { type = TYPE_PAGER_NUMBER; } else if ((FIELD_ASSISTANT_NUMBER).equals(phoneType)) { type = TYPE_ASSISTANT_NUMBER; } else if ((FIELD_CALLBACK_NUMBER).equals(phoneType)) { type = TYPE_CALLBACK_NUMBER; } else { // // Unknown property: saves nothing // continue; } ps1.setLong(1, Long.parseLong(cw.getId())); ps1.setInt(2, type); rs = ps1.executeQuery(); findRecord = rs.next(); String phoneValue = phone.getPropertyValueAsString(); phoneValue = StringUtils.left(phoneValue, SQL_EMAIL_DIM); if (!findRecord) { if (phoneValue != null && phoneValue.length() != 0) { ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); ps.setString(3, phoneValue); ps.executeUpdate(); DBTools.close(null, ps, null); } } else { if (phoneValue != null){ ps = con.prepareStatement( SQL_UPDATE_FNBL_PIM_CONTACT_ITEM); ps.setString(1, phoneValue); ps.setLong(2, Long.parseLong(cw.getId())); ps.setInt(3, type); } else { ps = con.prepareStatement( SQL_DELETE_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); } ps.executeUpdate(); DBTools.close(null, ps, null); } DBTools.close(null, null, rs); } DBTools.close(null, ps1, null); } // // web pages // if (!webPages.isEmpty()) { ps1 = con.prepareStatement( SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = webPages.size(); i < l; i++) { webPage = webPages.get(i); webPageType = webPage.getWebPageType(); if ((FIELD_WEB_PAGE).equals(webPageType)) { type = TYPE_WEB_PAGE; } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) { type = TYPE_HOME_WEB_PAGE; } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) { type = TYPE_BUSINESS_WEB_PAGE; } else { // // Unknown property: saves nothing // continue; } ps1.setLong(1, Long.parseLong(cw.getId())); ps1.setInt(2, type); rs = ps1.executeQuery(); findRecord = rs.next(); String webPageValue = webPage.getPropertyValueAsString(); webPageValue = StringUtils.left(webPageValue, SQL_WEBPAGE_DIM); if (!findRecord) { if (webPageValue != null && webPageValue.length() != 0) { ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); ps.setString(3, webPageValue); ps.executeUpdate(); DBTools.close(null, ps, null); } } else { if (webPageValue != null){ ps = con.prepareStatement( SQL_UPDATE_FNBL_PIM_CONTACT_ITEM); ps.setString(1, webPageValue); ps.setLong(2, Long.parseLong(cw.getId())); ps.setInt(3, type); } else { ps = con.prepareStatement( SQL_DELETE_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); } ps.executeUpdate(); DBTools.close(null, ps, null); } DBTools.close(null, null, rs); } DBTools.close(null, ps1, null); } // // home address // if (homeAddressBook != null) { ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_HOME); rs = ps.executeQuery(); findRecord = rs.next(); DBTools.close(null, ps, rs); street = Property.stringFrom(homeAddressBook.getStreet()); city = Property.stringFrom(homeAddressBook.getCity()); postalCode = Property.stringFrom(homeAddressBook.getPostalCode()); state = Property.stringFrom(homeAddressBook.getState()); country = Property.stringFrom(homeAddressBook.getCountry()); postOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress()); extendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress()); street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM)); city = StringUtils.left(city, SQL_CITY_DIM); state = StringUtils.left(state, SQL_STATE_DIM); postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM); country = StringUtils.left(country, SQL_COUNTRY_DIM); postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM); extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM); String homeLabel = Property.stringFrom(homeAddressBook.getLabel()); if (homeLabel != null) { String[] label = {homeLabel, FIELD_HOME_LABEL}; labels.add(label); } addressFields = new String[] {street, city, postalCode, country, state, postOfficeAddress, extendedAddress}; emptyAddress = hasOnlyNullContent(addressFields); if (!emptyAddress) { if(!findRecord && !hasOnlyEmptyOrNullContent(addressFields)){ ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_HOME); ps.setString(3, street); ps.setString(4, city); ps.setString(5, state); ps.setString(6, postalCode); ps.setString(7, country); ps.setString(8, postOfficeAddress); ps.setString(9, extendedAddress); ps.executeUpdate(); DBTools.close(null, ps, null); } else { sqlUpdateFunPimAddress = new StringBuffer(); sqlUpdateFunPimAddress .append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN); if (street != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA); } if (city != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (state != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postalCode != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (country != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postOfficeAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA); } if (extendedAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA); } sqlUpdateFunPimAddress .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END); ps = con.prepareStatement( sqlUpdateFunPimAddress.toString()); k = 1; if (street != null) { ps.setString(k++, street); } if (city != null) { ps.setString(k++, city); } if (state != null) { ps.setString(k++, state); } if (postalCode != null) { ps.setString(k++, postalCode); } if (country != null) { ps.setString(k++, country); } if (postOfficeAddress != null) { ps.setString(k++, postOfficeAddress); } if (extendedAddress != null) { ps.setString(k++, extendedAddress); } ps.setInt(k++, ADDRESS_TYPE_HOME); ps.setLong(k++, Long.parseLong(cw.getId())); ps.setInt(k++, ADDRESS_TYPE_HOME); ps.executeUpdate(); DBTools.close(null, ps, null); } } } // // other address // if (otherAddressBook != null) { ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_OTHER); rs = ps.executeQuery(); findRecord = rs.next(); DBTools.close(null, ps, rs); street = Property.stringFrom(otherAddressBook.getStreet()); city = Property.stringFrom(otherAddressBook.getCity()); postalCode = Property.stringFrom(otherAddressBook.getPostalCode()); state = Property.stringFrom(otherAddressBook.getState()); country = Property.stringFrom(otherAddressBook.getCountry()); postOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress()); extendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress()); street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM)); city = StringUtils.left(city, SQL_CITY_DIM); state = StringUtils.left(state, SQL_STATE_DIM); postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM); country = StringUtils.left(country, SQL_COUNTRY_DIM); postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM); extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM); addressFields = new String[] {street, city, postalCode, country, state, postOfficeAddress, extendedAddress}; String otherLabel = Property.stringFrom(otherAddressBook.getLabel()); if (otherLabel != null) { String[] label = {otherLabel, FIELD_OTHER_LABEL}; labels.add(label); } emptyAddress = hasOnlyNullContent(addressFields); if (!emptyAddress) { if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)){ ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_OTHER); ps.setString(3, street); ps.setString(4, city); ps.setString(5, state); ps.setString(6, postalCode); ps.setString(7, country); ps.setString(8, postOfficeAddress); ps.setString(9, extendedAddress); ps.executeUpdate(); DBTools.close(null, ps, null); } else { sqlUpdateFunPimAddress = new StringBuffer(); sqlUpdateFunPimAddress .append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN); if (street != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA); } if (city != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (state != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postalCode != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (country != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postOfficeAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA); } if (extendedAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA); } sqlUpdateFunPimAddress .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END); ps = con .prepareStatement( sqlUpdateFunPimAddress.toString()); k = 1; if (street != null) { ps.setString(k++, street); } if (city != null) { ps.setString(k++, city); } if (state != null) { ps.setString(k++, state); } if (postalCode != null) { ps.setString(k++, postalCode); } if (country != null) { ps.setString(k++, country); } if (postOfficeAddress != null) { ps.setString(k++, postOfficeAddress); } if (extendedAddress != null) { ps.setString(k++, extendedAddress); } ps.setInt(k++, ADDRESS_TYPE_OTHER); ps.setLong(k++, Long.parseLong(cw.getId())); ps.setInt(k++, ADDRESS_TYPE_OTHER); ps.executeUpdate(); DBTools.close(null, ps, null); } } } // // work address // if (workAddressBook != null) { ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_WORK); rs = ps.executeQuery(); findRecord = rs.next(); DBTools.close(null, ps, rs); street = Property.stringFrom(workAddressBook.getStreet()); city = Property.stringFrom(workAddressBook.getCity()); postalCode = Property.stringFrom(workAddressBook.getPostalCode()); state = Property.stringFrom(workAddressBook.getState()); country = Property.stringFrom(workAddressBook.getCountry()); postOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress()); extendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress()); street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM)); city = StringUtils.left(city, SQL_CITY_DIM); state = StringUtils.left(state, SQL_STATE_DIM); postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM); country = StringUtils.left(country, SQL_COUNTRY_DIM); postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM); extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM); String workLabel = Property.stringFrom(workAddressBook.getLabel()); if (workLabel != null) { String[] label = {workLabel, FIELD_BUSINESS_LABEL}; labels.add(label); } addressFields = new String[] {street, city, postalCode, country, state, postOfficeAddress, extendedAddress}; emptyAddress = hasOnlyNullContent(addressFields); if (!emptyAddress) { if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)){ ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_ADDRESS); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, ADDRESS_TYPE_WORK); ps.setString(3, street); ps.setString(4, city); ps.setString(5, state); ps.setString(6, postalCode); ps.setString(7, country); ps.setString(8, postOfficeAddress); ps.setString(9, extendedAddress); ps.executeUpdate(); DBTools.close(null, ps, null); } else { sqlUpdateFunPimAddress = new StringBuffer(); sqlUpdateFunPimAddress .append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN); if (street != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA); } if (city != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (state != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postalCode != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA); } if (country != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA); } if (postOfficeAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA); } if (extendedAddress != null) { sqlUpdateFunPimAddress.append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA); } sqlUpdateFunPimAddress .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END); ps = con.prepareStatement( sqlUpdateFunPimAddress.toString()); k = 1; if (street != null) { ps.setString(k++, street); } if (city != null) { ps.setString(k++, city); } if (state != null) { ps.setString(k++, state); } if (postalCode != null) { ps.setString(k++, postalCode); } if (country != null) { ps.setString(k++, country); } if (postOfficeAddress != null) { ps.setString(k++, postOfficeAddress); } if (extendedAddress != null) { ps.setString(k++, extendedAddress); } ps.setInt(k++, ADDRESS_TYPE_WORK); ps.setLong(k++, Long.parseLong(cw.getId())); ps.setInt(k++, ADDRESS_TYPE_WORK); ps.executeUpdate(); DBTools.close(null, ps, null); } } } // // labels // if (!labels.isEmpty()) { ps1 = con.prepareStatement( SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM); for (int i = 0, l = labels.size(); i < l; i++) { String[] label = labels.get(i); String labelType = label[1]; if ((FIELD_HOME_LABEL).equals(labelType)) { type = TYPE_HOME_LABEL; } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) { type = TYPE_BUSINESS_LABEL; } else if ((FIELD_OTHER_LABEL).equals(labelType)) { type = TYPE_OTHER_LABEL; } else { // // Unknown property: saves nothing // continue; } ps1.setLong(1, Long.parseLong(cw.getId())); ps1.setInt(2, type); rs = ps1.executeQuery(); findRecord = rs.next(); String labelValue = StringUtils.left(label[0], SQL_LABEL_DIM); if (!findRecord) { if (labelValue != null && labelValue.length() != 0) { ps = con.prepareStatement( SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); ps.setString(3, labelValue); ps.executeUpdate(); DBTools.close(null, ps, null); } } else { if (labelValue != null){ ps = con.prepareStatement( SQL_UPDATE_FNBL_PIM_CONTACT_ITEM); ps.setString(1, labelValue); ps.setLong(2, Long.parseLong(cw.getId())); ps.setInt(3, type); } else { ps = con.prepareStatement( SQL_DELETE_FNBL_PIM_CONTACT_ITEM); ps.setLong(1, Long.parseLong(cw.getId())); ps.setInt(2, type); } ps.executeUpdate(); DBTools.close(null, ps, null); } DBTools.close(null, null, rs); } DBTools.close(null, ps1, null); } if (photoToSet) { setPhoto(con, Long.parseLong(cw.getId()), photo); } else if (photoToRemove) { deletePhoto(con, Long.parseLong(cw.getId())); } } catch (Exception e) { throw new DAOException("Error updating contact.", e); } finally { DBTools.close(con, ps, rs); } return cw.getId(); } /** * Removes a contact, provided it has the same userId as this DAO. * The deletion is soft (reversible). * * @param contact whence the UID and the last update Date are extracted * @throws DAOException */ public void removeItem(ContactWrapper contact) throws DAOException { removeItem(contact.getId(), null); } /** * Gets the contact with given UID, provided it has the same userId as this * DAO without retrieve its photo * * @param uid corresponds to the id field in the fnbl_pim_contact table * @throws DAOException * @return the contact as a ContactWrapper object. */ public ContactWrapper getItem(String uid) throws DAOException { return getItem(uid, false); } /** * Gets the contact with given UID, provided it has the same userId as this * DAO. The contact photo will be provide if <code>withPhoto</code> is true, * otherwise the contact is retrived without photo * * @param uid corresponds to the id field in the fnbl_pim_contact table * @param withPhoto should the contact contain its photo ? * @throws DAOException * @return the contact as a ContactWrapper object. */ public ContactWrapper getItem(String uid, boolean withPhoto) throws DAOException { if (log.isTraceEnabled()) { log.trace("Retrieving contact '" + uid + "'"); } Connection con = null; PreparedStatement ps = null; ResultSet rs = null; ContactWrapper c; Long id = Long.parseLong(uid); try { // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); con.setReadOnly(true); ps = con.prepareStatement(SQL_GET_FNBL_PIM_CONTACT_BY_ID_USER); ps.setLong(1, id); ps.setString(2, userId); rs = ps.executeQuery(); c = createContact(uid, rs); DBTools.close(null, ps, rs); ps = con.prepareStatement(SQL_GET_FNBL_PIM_CONTACT_ITEM_BY_ID); ps.setLong(1, id); rs = ps.executeQuery(); try { addPIMContactItems(c, rs); } catch (SQLException sqle) { throw new SQLException("Error while adding extra PIM contact " + "information. " + sqle.getMessage(), sqle.getSQLState()); } DBTools.close(null, ps, rs); ps = con.prepareStatement(SQL_GET_FNBL_PIM_ADDRESS_BY_ID); ps.setLong(1, id); rs = ps.executeQuery(); try { addPIMAddresses(c, rs); } catch (SQLException sqle) { throw new SQLException("Error while adding PIM address " + "information. " + sqle, sqle.getSQLState()); } if (withPhoto) { //if the photo type is null, there is nothing to do if (c.getPhotoType() != null) { if (ContactWrapper.PHOTO_IMAGE.equals(c.getPhotoType()) || ContactWrapper.PHOTO_URL.equals(c.getPhotoType())) { Photo photo = getPhoto(con, id); c.getContact().getPersonalDetail().setPhotoObject(photo); } else if (ContactWrapper.EMPTY_PHOTO.equals(c.getPhotoType())) { c.getContact().getPersonalDetail().setPhotoObject(new Photo(null, null, null)); } } } } catch (Exception e) { throw new DAOException("Error retrieving contact.", e); } finally { DBTools.close(con, ps, rs); } return c; } /** * Retrieves the UID list of the contacts considered to be "twins" of a * given contact. * * @param c the Contact object representing the contact whose twins * need to be found. * @return a List of UIDs (as String objects) that may be empty but not null * @throws DAOException if an error occurs */ public List<String> getTwinItems(Contact c) throws DAOException { if (log.isTraceEnabled()) { log.trace("Retrieving twin items for the given contact..."); } List<String> twins = new ArrayList<String>(); Map<Long, Map<Integer, String>> twinsFound = new HashMap<Long, Map<Integer, String>>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; if(!isTwinSearchAppliableOn(c)) { if (log.isTraceEnabled()) { log.trace("Item with no email addresses, company name, first, " + "last and display names: twin search skipped."); } return twins; } try { String firstName = c.getName().getFirstName().getPropertyValueAsString(); String lastName = c.getName().getLastName().getPropertyValueAsString(); String displayName = c.getName().getDisplayName().getPropertyValueAsString(); String companyName = null; if (c.getBusinessDetail().getCompany() != null) { companyName = c.getBusinessDetail() .getCompany().getPropertyValueAsString(); } firstName = StringUtils.left(firstName, SQL_FIRSTNAME_DIM); lastName = StringUtils.left(lastName, SQL_LASTNAME_DIM); displayName = StringUtils.left(displayName, SQL_DISPLAYNAME_DIM); companyName = StringUtils.left(companyName, SQL_COMPANY_DIM); firstName = normalizeField(firstName); lastName = normalizeField(lastName); displayName = normalizeField(displayName); companyName = normalizeField(companyName); StringBuilder query = new StringBuilder(SQL_GET_POTENTIAL_TWINS); List<String> params = new ArrayList<String>(); // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); con.setReadOnly(true); // // If Funambol is not in the debug mode is not possible to print the // contact because it contains sensitive data. // if (Configuration.getConfiguration().isDebugMode()) { if (log.isTraceEnabled()) { StringBuilder sb = new StringBuilder(100); sb.append("Looking for items having: ") .append("\n> first name : '").append(toPrintableString(firstName)).append('\'') .append("\n> last name : '").append(toPrintableString(lastName)).append('\'') .append("\n> display name : '").append(toPrintableString(displayName)).append('\'') .append("\n> company name : '").append(toPrintableString(companyName)).append('\''); log.trace(sb.toString()); } } boolean isUnnamedContact = StringUtils.isEmpty(firstName) && StringUtils.isEmpty(lastName) && StringUtils.isEmpty(displayName) && StringUtils.isEmpty(companyName); if (isUnnamedContact) { if (unnamedContacts == null) { query.append(SQL_UNNAMED_WHERE_CLAUSES); query.append(SQL_STATUS_NOT_D); query.append(SQL_ORDER_BY_ID); params.add(userId); params.add(firstName); params.add(lastName); params.add(companyName); params.add(displayName); ps = con.prepareStatement(query.toString()); int cont = 1; for (String param : params) { ps.setString(cont++, param); } rs = ps.executeQuery(); //slipts query result in a better organized data structure //-contact id // -item type, item value // -item type, item value // -... //-contact id // -... unnamedContacts = getTwinsItemsFromRecordset(rs); if (log.isTraceEnabled()) { log.trace("Found '"+unnamedContacts.size()+ "' potential twin unnamed contacts with ids '"+ unnamedContacts.keySet().toString()+"'"); } DBTools.close(null, null, rs); } // returns only the twin items twinsFound = retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, unnamedContacts, isUnnamedContact); } else { params.add(userId); query.append(" AND ("); if ("".equals(firstName)) { query.append(" (c.first_name is null) OR "); } query.append(" (lower(c.first_name) = ?) "); params.add(firstName.toLowerCase()); query.append(" )"); query.append(" AND ("); if ("".equals(lastName)) { query.append(" (c.last_name is null) OR "); } query.append(" (lower(c.last_name) = ?) "); params.add(lastName.toLowerCase()); query.append(" )"); // // Only if the first name and last name are empty, // the company is used in the research of twin items. // if ("".equals(firstName) && "".equals(lastName)) { query.append(" AND ("); if ("".equals(companyName)) { query.append(" (c.company is null) OR "); } query.append(" (lower(c.company) = ?) "); params.add(companyName.toLowerCase()); query.append(" )"); // // Only if the first name, last name and company are empty, // the display name is used in the research of twin items. // if ("".equals(companyName)) { query.append(" AND ("); if ("".equals(displayName)) { query.append(" (c.display_name is null) OR "); } query.append(" (lower(c.display_name) = ?) "); params.add(displayName.toLowerCase()); query.append(" ) "); } } query.append(SQL_STATUS_NOT_D); query.append(SQL_ORDER_BY_ID); ps = con.prepareStatement(query.toString()); int cont = 1; for (String param : params) { ps.setString(cont++, param); } rs = ps.executeQuery(); //slipts query result in a better organized data structure //-contact id // -item type, item value // -item type, item value // -... //-contact id // -... Map<Long, Map<Integer, String>> twinsInfo = getTwinsItemsFromRecordset(rs); if (log.isTraceEnabled()) { log.trace("Found '"+twinsInfo.size()+ "' potential twin contacts with ids '"+ twinsInfo.keySet().toString()+"'"); } DBTools.close(null, null, rs); //returns only the twin items twinsFound= retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, twinsInfo, isUnnamedContact); } for (Long twinId : twinsFound.keySet()) { if (log.isTraceEnabled()) { log.trace("Found twin '" + twinId + "'"); } twins.add(Long.toString(twinId)); } } catch (Exception e) { throw new DAOException("Error retrieving contact twin items", e); } finally { DBTools.close(con, ps, rs); } return twins; } /** * Sets the contact identified with the given id with the given photo. * Moreover, the contact will be marked as updated. * <br/> * If the contact has already a photo, that will be updated with the new one. * <br/> * If the given photo is null, the one in the db (if there is) will be removed. * * @param id contact id * @param photo the photo to set * @throws com.funambol.foundation.exception.DAOException if an error occurs */ public void setContactPhoto(Long id, Photo photo) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); setContactPhoto(conn, id, photo); } catch (Exception ex) { throw new DAOException("Error setting photo", ex); } finally { DBTools.close(conn, null, null); } } /** * Sets the contact identified with the given id with the given photo using * the given connection. * Moroever, the contact will be marked as updated. * <br/> * If the contact has already a photo, that will be updated with the new one. * <br/> * If the given photo is null, the one in the db (if there is) will be removed. * * @param conn the connection to use * @param id contact id * @param photo the photo to set * @throws com.funambol.foundation.exception.DAOException if an error occurs */ public void setContactPhoto(Connection conn, Long id, Photo photo) throws DAOException { if (photo != null) { if (photo.getUrl() == null && photo.getImage() == null) { deleteContactPhoto(conn, id); setPhotoType(conn, id, ContactWrapper.EMPTY_PHOTO ); } } else { deleteContactPhoto(conn, id); setPhotoType(conn, id, ContactWrapper.EMPTY_PHOTO ); } if (!updatePhoto(conn, id, photo)) { insertPhoto(conn, id, photo); } setPhotoType(conn, id, photo); } /** * Returns the photo of the contact identified by the given id or null if * not found. * @param id the contact id * @return the photo * @throws com.funambol.foundation.exception.DAOException if an error occurs */ public Photo getPhoto(Long id) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); conn.setReadOnly(true); return getPhoto(conn, id); } catch (Exception ex) { throw new DAOException("Error retrieving photo with id: " + id, ex); } finally { DBTools.close(conn, null, null); } } /** * Returns the photo with the given id using the given connection. * <p>Note that the connection is not closed at the end of the method * @param con the connection to use * @param id the if * @return the photo, or null if not found * @throws DAOException if an error occurs */ public Photo getPhoto(Connection con, Long id) throws DAOException { Photo photo = null; PreparedStatement stmt = null; ResultSet rs = null; try { stmt = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_CONTACT_PHOTO); stmt.setLong(1, id); stmt.setString(2, userId); rs = stmt.executeQuery(); while (rs.next()) { photo = new Photo(); photo.setType(rs.getString(2)); photo.setImage(rs.getBytes(3)); photo.setUrl(rs.getString(4)); } } catch (Exception e) { throw new DAOException("Error retrieving photo with id: " + id, e); } finally { DBTools.close(null, stmt, rs); } return photo; } /** * Deletes the photo for the contact with the given id * @param contactId the contac id * @return true if the photo has been removed * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ public boolean deleteContactPhoto(Long contactId) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); return deleteContactPhoto(conn, contactId); } catch (Exception ex) { throw new DAOException("Error removing photo for contact: '" + contactId + "'", ex); } finally { DBTools.close(conn, null, null); } } /** * Deletes the photo for the contact with the given id using the given connection * @param con the connection to use * @param contactId the contac id * @return true if the photo has been removed * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ public boolean deleteContactPhoto(Connection con, Long contactId) throws DAOException { boolean photoDeleted = deletePhoto(con, contactId); setPhotoType(con, contactId, (Short)null); return photoDeleted; } /** * This method allows to understand if is possible to run the twin search * on the given contact. * Fields used in the twin search are: * - firstName * - lastName * - displayName * - companyName * - at least one email address * - at least one phone number * * @param contact the contact we want to check * * @return true if at least one field used for twin search contains * meaningful data, false otherwise */ public boolean isTwinSearchAppliableOn(Contact contact) { if(contact==null) return false; boolean hasAtLeastOneValidEmail = hasAtLeastOneNonEmptyProperty( contact.getPersonalDetail().getEmails(), contact.getBusinessDetail().getEmails()); boolean hasAtLeastOneValidPhone = hasAtLeastOneNonEmptyProperty( contact.getPersonalDetail().getPhones(), contact.getBusinessDetail().getPhones()); String firstName = contact.getName().getFirstName().getPropertyValueAsString(); String lastName = contact.getName().getLastName().getPropertyValueAsString(); String displayName = contact.getName().getDisplayName().getPropertyValueAsString(); String companyName = null; if (contact.getBusinessDetail().getCompany() != null) { companyName = contact.getBusinessDetail() .getCompany().getPropertyValueAsString(); } firstName = normalizeField(firstName); lastName = normalizeField(lastName); displayName = normalizeField(displayName); companyName = normalizeField(companyName); return (firstName.length() > 0 || lastName.length() > 0 || companyName.length() > 0 || displayName.length() > 0 || hasAtLeastOneValidEmail || hasAtLeastOneValidPhone ); } // ------------------------------------------------------- Protected methods /** * Sets the given photo for the contact identified by the given id. * BTW, the contact is not updated. To update the contact use setContactPhoto(...) * @param id the contact id * @param photo the photo to set * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void setPhoto(Long id, Photo photo) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); setPhoto(conn, id, photo); } catch (Exception ex) { throw new DAOException("Error setting photo", ex); } finally { DBTools.close(conn, null, null); } } /** * Sets the given photo for the contact identified by the given id. * BTW, the contact is not updated. To update the contact use setContactPhoto(...) * @param conn the connection to use * @param id the contact id * @param photo the photo to set * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void setPhoto(Connection conn, Long id, Photo photo) throws DAOException { if (!updatePhoto(conn, id, photo)) { insertPhoto(conn, id, photo); } } /** * Adds the given photo for the contact identified by the given id. Also the * contact is updated accordlying. * @param contactId the contact id * @param photo the photo to add * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void addContactPhoto(Long contactId, Photo photo) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); insertPhoto(conn, contactId, photo); setPhotoType(conn, contactId, photo); } catch (Exception ex) { throw new DAOException("Error storing photo", ex); } finally { DBTools.close(conn, null, null); } } /** * Adds the given photo for the contact identified by the given id using the * given connection. Also the contact is updated accordlying. * @param con the connection to use * @param contactId the contact id * @param photo the photo to add * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void addContactPhoto(Connection con, Long contactId, Photo photo) throws DAOException { insertPhoto(con, contactId, photo); setPhotoType(con, contactId, photo); } /** * Updates the given photo for the contact identified by the given id. * Also the contact is updated accordlying. * @param contactId the contact id * @param photo the photo to add * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void updateContactPhoto(Long contactId, Photo photo) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); updateContactPhoto(conn, contactId, photo); } catch (Exception ex) { throw new DAOException("Error updating photo", ex); } finally { DBTools.close(conn, null, null); } } /** * Updates the given photo for the contact identified by the given id using * the given connection. * Also the contact is updated accordlying. * @param con the connection to use * @param contactId the contact id * @param photo the photo to add * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void updateContactPhoto(Connection con, Long contactId, Photo photo) throws DAOException { updatePhoto(con, contactId, photo); setPhotoType(con, contactId, photo); } /** * Deletes the photo identified by the given id. The contact is NOT update. * Use deleteContactPhoto to update also the contact. * @param id the photo id * @return true if the photo is deleted, false * @throws com.funambol.foundation.exception.DAOException */ protected boolean deletePhoto(Long id) throws DAOException { Connection conn = null; try { conn = getUserDataSource().getRoutedConnection(userId); return deletePhoto(conn, id); } catch (Exception ex) { throw new DAOException("Error deleting photo with id: '" + id + "'", ex); } finally { DBTools.close(conn, null, null); } } /** * Deletes the photo identified by the given id. The contact is NOT update. * Use deleteContactPhoto to update also the contact. * @param con the connection to use * @param id the photo id * @return true if the photo is deleted, false * @throws com.funambol.foundation.exception.DAOException */ protected boolean deletePhoto(Connection con, Long id) throws DAOException { if (!verifyPermission(con, id)) { throw new DAOException("Contact '" + id + " is not a contact of the user '" + userId + "'"); } PreparedStatement stmt = null; int numDeletedRows = 0; try { stmt = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_PHOTO); stmt.setLong(1, id); numDeletedRows = stmt.executeUpdate(); } catch (SQLException ex) { throw new DAOException("Error deleting photo with id: '" + id + "'", ex); } finally { DBTools.close(null, stmt, null); } return (numDeletedRows == 1); } /** * Updates the property 'photoType' of the contact with the given id to the * given value according to the given photo. If the photo is null, ContactWrapper.NO_PHOTO * is set; if the photo is not null and the photo contains an image, ContactWrapper.PHOTO_TYPE_IMAGE * is set; if the photo is not null and the photo contains an url, ContactWrapper.PHOTO_TYPE_URL * is set; otherwise ContactWrapper.NO_PHOTO is set * <br/> * The contact is moreover marked as UPDATED and its last_update is updated * @param con the connection to use * @param contactId the contact to update * @param photo the photo * @return the number of the updated rows * @throws DAOException if an error occurs */ protected int setPhotoType(Connection con, Long contactId, Photo photo) throws DAOException { if (photo != null) { if (photo.getImage() != null) { return setPhotoType(con, contactId, ContactWrapper.PHOTO_IMAGE); } else if (photo.getUrl() != null) { return setPhotoType(con, contactId, ContactWrapper.PHOTO_URL); } else { return setPhotoType(con, contactId, ContactWrapper.EMPTY_PHOTO); } } return setPhotoType(con, contactId, (Short)null); } /** * Updates the given photo for the contact identified by the given id using * the given connection. * Note the contact is NOT updated accordlying. Use updateContactPhoto to * update also the contact. * @param con the connection to use * @param id the contact id * @param photo the photo to update * @return true if the photo has been updated, false * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected boolean updatePhoto(Connection con, Long id, Photo photo) throws DAOException { if (!verifyPermission(con, id)) { throw new DAOException("Contact '" + id + " is not a contact of the user '" + userId + "'"); } PreparedStatement stmt = null; byte[] image = null; String type = null; String url = null; if (photo != null) { image = photo.getImage(); type = photo.getType(); url = photo.getUrl(); } int numUpdatedRows = 0; try { stmt = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_PHOTO); if (type == null) { stmt.setNull(1, Types.VARCHAR); } else { stmt.setString(1, type); } if (url == null) { stmt.setNull(2, Types.VARCHAR); } else { stmt.setString(2, url); } if (image == null) { stmt.setNull(3, Types.BINARY); } else { stmt.setBinaryStream(3, new ByteArrayInputStream(image), image.length); } stmt.setLong(4, id); numUpdatedRows = stmt.executeUpdate(); } catch (SQLException ex) { throw new DAOException("Error updating photo", ex); } finally { DBTools.close(null, stmt, null); } return (numUpdatedRows == 1); } /** * Changes the contact status with the given parameters * @param con the connection to use * @param contactId the contact id * @param status the status to set * @return true if the contact has been updated, false otherwise * @throws com.funambol.foundation.exception.DAOException */ protected boolean changeContactStatus(Connection con, Long contactId, char status) throws DAOException { PreparedStatement stmt = null; int numUpdatedRows = 0; try { stmt = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_STATUS); stmt.setString(1, String.valueOf(status)); stmt.setLong(2, System.currentTimeMillis()); stmt.setLong(3, contactId); stmt.setString(4, userId); numUpdatedRows = stmt.executeUpdate(); } catch (SQLException ex) { throw new DAOException("Error changing status of contact '" + contactId + "' to '" + status + "'", ex); } finally { DBTools.close(null, stmt, null); } return (numUpdatedRows == 1); } /** * Inserts the photo identified by the given id. The contact is NOT update. * Use deleteContactPhoto to update also the contact. * @param con the connection to use * @param contactId the photo id * @param photo the Photo to insert * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ protected void insertPhoto(Connection con, Long contactId, Photo photo) throws DAOException { if (!verifyPermission(con, contactId)) { throw new DAOException("Contact '" + contactId + " is not a contact of the user '" + userId + "'"); } PreparedStatement stmt = null; if (photo == null) { return ; } byte[] image = photo.getImage(); try { stmt = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_PHOTO); stmt.setLong(1, contactId); if (photo.getType() == null) { stmt.setNull(2, Types.VARCHAR); } else { stmt.setString(2, photo.getType()); } if (image == null) { stmt.setNull(3, Types.BINARY); } else { stmt.setBinaryStream(3, new ByteArrayInputStream(image), image.length); } if (photo.getUrl() == null) { stmt.setNull(4, Types.VARCHAR); } else { stmt.setString(4, photo.getUrl()); } stmt.execute(); } catch (SQLException ex) { throw new DAOException("Error storing photo", ex); } finally { DBTools.close(null, stmt, null); } } //---------------------------------------------------------- Private methods /** * Creates a ContactWrapper object from a ResultSet. Only the basic data are * set. * * @param wrapperId the UID of the wrapper object to be returned * @param rs the result of the execution of a proper SQL SELECT statement on * the fnbl_pim_contact table, with the cursor before its first row * @return a newly created ContactWrapper initialized with the fields in the * result set * @throws java.sql.SQLException * @throws NotFoundException */ private static ContactWrapper createContact(String wrapperId, ResultSet rs) throws SQLException, NotFoundException { if (!rs.next()) { throw new NotFoundException("No contact found."); } ResultSetMetaData rsmd = rs.getMetaData(); ContactWrapper cw = null; Note note = null; Title title = null; String column = null; String userId = rs.getString(SQL_FIELD_USERID); Contact c = new Contact(); cw = new ContactWrapper(wrapperId, userId, c); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; ++i) { column = rsmd.getColumnName(i); // // General // if (SQL_FIELD_ID.equalsIgnoreCase(column)) { // Does nothing: field already set at construction time } else if (SQL_FIELD_LAST_UPDATE.equalsIgnoreCase(column)) { cw.setLastUpdate(new Timestamp(rs.getLong(i))); } else if (SQL_FIELD_USERID.equalsIgnoreCase(column)) { // Does nothing: field already set at construction time } else if (SQL_FIELD_STATUS.equalsIgnoreCase(column)) { cw.setStatus(rs.getString(i).charAt(0)); } else if (SQL_FIELD_PHOTO_TYPE.equalsIgnoreCase(column)) { short phType = rs.getShort(i); if (!rs.wasNull()) { cw.setPhotoType(Short.valueOf(phType)); } // // contact details // } else if (SQL_FIELD_IMPORTANCE.equalsIgnoreCase(column)) { short importance = rs.getShort(i); if (!rs.wasNull()) { c.setImportance(Short.valueOf(importance)); } } else if (SQL_FIELD_SENSITIVITY.equalsIgnoreCase(column)) { short sensitivity = rs.getShort(i); if (!rs.wasNull()) { c.setSensitivity(Short.valueOf(sensitivity)); } } else if (SQL_FIELD_SUBJECT.equalsIgnoreCase(column)) { c.setSubject(rs.getString(i)); } else if (SQL_FIELD_FOLDER.equalsIgnoreCase(column)) { c.setFolder(rs.getString(i)); // // Personal details // } else if (SQL_FIELD_ANNIVERSARY.equalsIgnoreCase(column)) { c.getPersonalDetail().setAnniversary(rs.getString(i)); } else if (SQL_FIELD_FIRST_NAME.equalsIgnoreCase(column)) { c.getName().getFirstName().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_MIDDLE_NAME.equalsIgnoreCase(column)) { c.getName().getMiddleName().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_LAST_NAME.equalsIgnoreCase(column)) { c.getName().getLastName().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_DISPLAY_NAME.equalsIgnoreCase(column)) { c.getName().getDisplayName().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_BIRTHDAY.equalsIgnoreCase(column)) { c.getPersonalDetail().setBirthday(rs.getString(i)); } else if (SQL_FIELD_BODY.equalsIgnoreCase(column)) { String noteStr = rs.getString(i); if (noteStr != null) { note = new Note(); note.setNoteType(FIELD_NOTE); note.setPropertyValue(noteStr); c.addNote(note); } } else if (SQL_FIELD_CATEGORIES.equalsIgnoreCase(column)) { c.getCategories().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_CHILDREN.equalsIgnoreCase(column)) { c.getPersonalDetail().setChildren(rs.getString(i)); } else if (SQL_FIELD_HOBBIES.equalsIgnoreCase(column)) { c.getPersonalDetail().setHobbies(rs.getString(i)); } else if (SQL_FIELD_GENDER.equalsIgnoreCase(column)) { c.getPersonalDetail().setGender(rs.getString(i)); } else if (SQL_FIELD_INITIALS.equalsIgnoreCase(column)) { c.getName().getInitials().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_LANGUAGES.equalsIgnoreCase(column)) { c.setLanguages(rs.getString(i)); } else if (SQL_FIELD_NICKNAME.equalsIgnoreCase(column)) { c.getName().getNickname().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_SPOUSE.equalsIgnoreCase(column)) { c.getPersonalDetail().setSpouse(rs.getString(i)); } else if (SQL_FIELD_SUFFIX.equalsIgnoreCase(column)) { c.getName().getSuffix().setPropertyValue(rs.getString(i)); } else if (SQL_FIELD_TITLE.equalsIgnoreCase(column)) { c.getName().getSalutation().setPropertyValue(rs.getString(i)); // // Business details // } else if (SQL_FIELD_ASSISTANT.equalsIgnoreCase(column)) { c.getBusinessDetail().setAssistant(rs.getString(i)); } else if (SQL_FIELD_COMPANY.equalsIgnoreCase(column)) { c.getBusinessDetail().getCompany().setPropertyValue( rs.getString(i)); } else if (SQL_FIELD_COMPANIES.equalsIgnoreCase(column)) { c.getBusinessDetail().setCompanies(rs.getString(i)); } else if (SQL_FIELD_DEPARTMENT.equalsIgnoreCase(column)) { c.getBusinessDetail().getDepartment().setPropertyValue( rs.getString(i)); } else if (SQL_FIELD_JOB_TITLE.equalsIgnoreCase(column)) { String titleStr = null; titleStr = rs.getString(i); if (titleStr != null) { title = new Title(); title.setTitleType(FIELD_JOB_TITLE); title.setPropertyValue(titleStr); c.getBusinessDetail().addTitle(title); } } else if (SQL_FIELD_MANAGER.equalsIgnoreCase(column)) { c.getBusinessDetail().setManager(rs.getString(i)); } else if (SQL_FIELD_MILEAGE.equalsIgnoreCase(column)) { c.setMileage(rs.getString(i)); } else if (SQL_FIELD_OFFICE_LOCATION.equalsIgnoreCase(column)) { c.getBusinessDetail().setOfficeLocation(rs.getString(i)); } else if (SQL_FIELD_PROFESSION.equalsIgnoreCase(column)) { c.getBusinessDetail().getRole().setPropertyValue( rs.getString(i)); } else { throw new SQLException("Unhandled column: " + column); } } return cw; } /** * Attaches the address(es) to a contact on the basis of a ResultSet. * * @param cw the contact (as a ContactWrapper) still lacking address * information * @param rs the result of the execution of a proper SQL SELECT statement on * the fnbl_pim_address table, with the cursor before its first * row * @return the ContactWrapper object with address information attached * @throws java.sql.SQLException */ private static ContactWrapper addPIMAddresses(ContactWrapper cw, ResultSet rs) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); Contact c = cw.getContact(); int type = 0; String street = null; String city = null; String state = null; String postalCode = null; String country = null; String poBox = null; String extendedAddress = null; String column = null; int columnCount = 0; while (rs.next()) { columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; ++i) { column = rsmd.getColumnName(i); if (SQL_FIELD_TYPE.equalsIgnoreCase(column)) { type = rs.getInt(i); } else if (SQL_FIELD_STREET.equalsIgnoreCase(column)) { street = rs.getString(i); } else if (SQL_FIELD_CITY.equalsIgnoreCase(column)) { city = rs.getString(i); } else if (SQL_FIELD_STATE.equalsIgnoreCase(column)) { state = rs.getString(i); } else if (SQL_FIELD_POSTAL_CODE.equalsIgnoreCase(column)) { postalCode = rs.getString(i); } else if (SQL_FIELD_COUNTRY.equalsIgnoreCase(column)) { country = rs.getString(i); } else if (SQL_FIELD_PO_BOX.equalsIgnoreCase(column)) { poBox = rs.getString(i); } else if (SQL_FIELD_EXTENDED_ADDRESS.equalsIgnoreCase(column)) { extendedAddress = rs.getString(i); } else { throw new SQLException("Unhandled column: " + column); } } switch (type) { case ADDRESS_TYPE_HOME: c.getPersonalDetail().getAddress().getStreet() .setPropertyValue(street); c.getPersonalDetail().getAddress().getCity() .setPropertyValue(city); c.getPersonalDetail().getAddress().getState() .setPropertyValue(state); c.getPersonalDetail().getAddress().getPostalCode() .setPropertyValue(postalCode); c.getPersonalDetail().getAddress().getCountry() .setPropertyValue(country); c.getPersonalDetail().getAddress().getPostOfficeAddress() .setPropertyValue(poBox); c.getPersonalDetail().getAddress().getExtendedAddress() .setPropertyValue(extendedAddress); break; case ADDRESS_TYPE_OTHER: c.getPersonalDetail().getOtherAddress().getStreet() .setPropertyValue(street); c.getPersonalDetail().getOtherAddress().getCity() .setPropertyValue(city); c.getPersonalDetail().getOtherAddress().getState() .setPropertyValue(state); c.getPersonalDetail().getOtherAddress().getPostalCode() .setPropertyValue(postalCode); c.getPersonalDetail().getOtherAddress().getCountry() .setPropertyValue(country); c.getPersonalDetail().getOtherAddress() .getPostOfficeAddress().setPropertyValue(poBox); c.getPersonalDetail().getOtherAddress().getExtendedAddress() .setPropertyValue(extendedAddress); break; case ADDRESS_TYPE_WORK: c.getBusinessDetail().getAddress().getStreet() .setPropertyValue(street); c.getBusinessDetail().getAddress().getCity() .setPropertyValue(city); c.getBusinessDetail().getAddress().getState() .setPropertyValue(state); c.getBusinessDetail().getAddress().getPostalCode() .setPropertyValue(postalCode); c.getBusinessDetail().getAddress().getCountry() .setPropertyValue(country); c.getBusinessDetail().getAddress().getPostOfficeAddress() .setPropertyValue(poBox); c.getBusinessDetail().getAddress().getExtendedAddress() .setPropertyValue(extendedAddress); break; default: break; } } return cw; } /** * Attaches extra information to a contact on the basis of a ResultSet. * * @param cw the contact still lacking extra information * @param rs the result of the execution of a proper SQL SELECT statement on * the fnbl_pim_contact_item table, with the cursor before its * first row * @return the ContactWrapper object with extra information attached * @throws java.sql.SQLException */ private static ContactWrapper addPIMContactItems(ContactWrapper cw, ResultSet rs) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); Contact c = cw.getContact(); int type = 0; String value = null; int columnCount = 0; String column = null; Phone phone; Email email; WebPage webPage; while (rs.next()) { columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; ++i) { column = rsmd.getColumnName(i); if (SQL_FIELD_TYPE.equalsIgnoreCase(column)) { type = rs.getInt(i); } else if (SQL_FIELD_VALUE.equalsIgnoreCase(column)) { value = rs.getString(i); } else { throw new SQLException("Unhandled column: " + column); } } switch (type) { case TYPE_HOME_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_HOME_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_HOME_FAX_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_HOME_FAX_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_MOBILE_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_MOBILE_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_EMAIL_1_ADDRESS: email = new Email(); email.setEmailType(FIELD_EMAIL_1_ADDRESS); email.setPropertyValue(value); c.getPersonalDetail().addEmail(email); break; case TYPE_WEB_PAGE: webPage = new WebPage(); webPage.setWebPageType(FIELD_WEB_PAGE); webPage.setPropertyValue(value); c.getPersonalDetail().addWebPage(webPage); break; case TYPE_BUSINESS_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_BUSINESS_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_BUSINESS_FAX_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_BUSINESS_FAX_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_COMPANY_MAIN_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_COMPANY_MAIN_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_ASSISTANT_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_ASSISTANT_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_PAGER_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_PAGER_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_CALLBACK_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_CALLBACK_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_EMAIL_2_ADDRESS: email = new Email(); email.setEmailType(FIELD_EMAIL_2_ADDRESS); email.setPropertyValue(value); c.getPersonalDetail().addEmail(email); break; case TYPE_EMAIL_3_ADDRESS: email = new Email(); email.setEmailType(FIELD_EMAIL_3_ADDRESS); email.setPropertyValue(value); c.getBusinessDetail().addEmail(email); break; case TYPE_HOME_WEB_PAGE: webPage = new WebPage(); webPage.setWebPageType(FIELD_HOME_WEB_PAGE); webPage.setPropertyValue(value); c.getPersonalDetail().addWebPage(webPage); break; case TYPE_CAR_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_CAR_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_PRIMARY_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_PRIMARY_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_HOME_2_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_HOME_2_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_BUSINESS_2_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_BUSINESS_2_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_BUSINESS_WEB_PAGE: webPage = new WebPage(); webPage.setWebPageType(FIELD_BUSINESS_WEB_PAGE); webPage.setPropertyValue(value); c.getBusinessDetail().addWebPage(webPage); break; case TYPE_INSTANT_MESSENGER: email = new Email(); email.setEmailType(FIELD_INSTANT_MESSENGER); email.setPropertyValue(value); c.getPersonalDetail().addEmail(email); break; case TYPE_BUSINESS_LABEL: c.getBusinessDetail().getAddress().getLabel() .setPropertyValue(value); break; case TYPE_OTHER_LABEL: c.getPersonalDetail().getOtherAddress().getLabel() .setPropertyValue(value); break; case TYPE_HOME_LABEL: c.getPersonalDetail().getAddress().getLabel() .setPropertyValue(value); break; case TYPE_OTHER_FAX_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_OTHER_FAX_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_OTHER_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_OTHER_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; case TYPE_TELEX_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_TELEX_NUMBER); phone.setPropertyValue(value); c.getBusinessDetail().addPhone(phone); break; case TYPE_RADIO_TELEPHONE_NUMBER: phone = new Phone(); phone.setPhoneType(FIELD_RADIO_TELEPHONE_NUMBER); phone.setPropertyValue(value); c.getPersonalDetail().addPhone(phone); break; default: break; } } return cw; } /** * Checks whether an array of String objects has some non-white content. * * @param strings could also be null * @return false only if the array contains at least a non-null string * having some content different from white spaces */ private static boolean hasOnlyEmptyOrNullContent(String[] strings) { if (strings == null) { return true; } for (int i = 0; i < strings.length; i++) { if (strings[i] != null && strings[i].length() > 0) { return false; } } return true; } /** * Checks whether an array of String objects has some non-null content. * * @param strings could also be null * @return false only if the array contains at least a string not being null */ private static boolean hasOnlyNullContent(String[] strings) { if (strings == null) { return true; } for (int i = 0; i < strings.length; i++) { if (strings[i] != null) { return false; } } return true; } /** * Strips away new line characters from a string. * * @param string a String object, possibly made of several lines of text * @return the modified string, having all new line characters replaced by * white spaces. */ private static String replaceNewLine(String string) { if (string != null) { char[] nl = { 10 }; String newLine = new String(nl); string = string.replaceAll(newLine, " "); } return string; } /** * Updates the property 'photoType' of the contact with the given id to the * given value using the given connection. * <br/> * The contact is moreover marked as UPDATED and its last_update is updated * @param con the connection to use * @param contactId the contact to update * @param photoType the type of the photo * @return the number of the updated rows * @throws DAOException if an error occurs */ private int setPhotoType(Connection con, Long contactId, Short photoType) throws DAOException { if (!ContactWrapper.EMPTY_PHOTO.equals(photoType) && !ContactWrapper.PHOTO_IMAGE.equals(photoType) && !ContactWrapper.PHOTO_URL.equals(photoType) && photoType != null) { throw new IllegalArgumentException(photoType + " is not a valid photoType"); } PreparedStatement stmt = null; int numUpdatedRows = 0; try { stmt = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_PHOTO_TYPE); stmt.setString(1, String.valueOf(Def.PIM_STATE_UPDATED)); stmt.setLong (2, System.currentTimeMillis()); if (photoType != null) { stmt.setShort(3, photoType); } else { stmt.setNull(3, Types.SMALLINT); } stmt.setLong (4, contactId); stmt.setString(5, userId); numUpdatedRows = stmt.executeUpdate(); } catch (SQLException ex) { throw new DAOException("Error updating '" + contactId + "'", ex); } finally { DBTools.close(null, stmt, null); } return numUpdatedRows; } /** * Verify if the contact identified by the given id is associated to the user * used to create the dao * @param con the connection to use * @param contactId the contact id * @return true if the contact is associated to the user used to create the * dao, false otherwise * @throws com.funambol.foundation.exception.DAOException if an error * occurs */ private boolean verifyPermission(Connection con, Long contactId) throws DAOException { PreparedStatement stmt = null; ResultSet rs = null; boolean contactFound = false; try { stmt = con.prepareStatement(SQL_GET_CONTACT_ID_BY_ID_AND_USER_ID); stmt.setLong(1, contactId); stmt.setString(2, userId); rs = stmt.executeQuery(); while (rs.next()) { contactFound = true; } } catch (Exception e) { throw new DAOException("Error checking contact '" + contactId + "'", e); } finally { DBTools.close(null, stmt, rs); } return contactFound; } /** * * * @param fieldValue the value of the field to normalize * * @return the normalized field, the field itself if it's not null */ private String normalizeField(String fieldValue) { if (fieldValue == null || ("null".equals(fieldValue))) { return ""; } return fieldValue; } /** * * @param fieldValue the string we want to log * * @return a log printable representation of the given string */ private String toPrintableString(String fieldValue) { return (fieldValue!=null && fieldValue.length()>0)? fieldValue: UNSET_FIELD_PLACEHOLDER; } /** * Return the query to use to retrieve all the Items belonging to a user * @return */ @Override protected String getAllItemsQuery() { return SQL_GET_FNBL_PIM_CONTACT_ID_LIST_BY_USER + SQL_ORDER_BY_ID; } /** * Return the query string to use to remove the Item belonging to a user * @return the query string to use to remove the Item belonging to a user */ @Override protected String getRemoveItemQuery() { return SQL_DELETE_CONTACT_BY_ID_USERID; } /** * Return the query string to use to remove the all Items belonging to a user * @return the query string to use to remove the all Items belonging to a user */ @Override protected String getRemoveAllItemsQuery() { return SQL_DELETE_CONTACTS_BY_USERID; } /** * Return the query string to use to retrieve the status of an Items * belonging to a user * @return the query string to use to retrieve the status of an Items * belonging to a user */ @Override protected String getItemStateQuery() { return SQL_GET_STATUS_BY_ID_USER_TIME; } @Override protected String getChangedItemsQuery() { return SQL_GET_CHANGED_CONTACTS_BY_USER_AND_LAST_UPDATE; } /** * Read data from twin query and put it inside a Map. * First map has the contact id as Key and a map of contact items as their values. * Second map has the item type as Key and the item value as Value. * * @param rs the ResultSet to check * @return the map of potential twins */ private Map<Long, Map<Integer, String>> getTwinsItemsFromRecordset(ResultSet rs) throws Exception { long oldTwinId = -1; long twinId; int itemType; String itemValue; Map<Integer, String> twinValues = null; Map<Long, Map<Integer, String>> values = new HashMap<Long, Map<Integer, String>>(); while(rs.next()) { twinId = rs.getLong(1); // The id is the first if (twinId != oldTwinId) { //new contact id oldTwinId = twinId; twinValues = new HashMap<Integer, String>(); //add new contact record values.put(twinId, twinValues); } //add new item type and value to the map of contact items itemType = rs.getByte(2); itemValue = rs.getString(3); twinValues.put(itemType, itemValue); } return values; } /** * Analyzes raw list of twins for a contact and returns only the items that * satisfies the condition on emails and phone numbers. * * @param contact the contact to check twins * @param twinsInfo the information about potential twins to check * @param isUnnamedContact true id the contact is unnamed, false otherwise * @return a Map of twin items */ private Map<Long, Map<Integer, String>> retrievePotentialTwinsComparingEmailsAndPhoneNumbers( Contact contact, Map<Long, Map<Integer, String>> twinsInfo, boolean isUnnamedContact) { Map<Long, Map<Integer, String>> twinsFound = new HashMap<Long, Map<Integer, String>>(); if (twinsInfo.isEmpty()) return twinsFound; //get emails from contact List<Email> contactEmails = getContactPropertiesRemovingNullOrEmptyValues( contact.getPersonalDetail().getEmails(), contact.getBusinessDetail().getEmails()); List<Email> contactEmailsAux = new ArrayList<Email>(); for (Email index : contactEmails) { index.setPropertyValue(StringUtils.left(index.getPropertyValueAsString(),SQL_EMAIL_DIM)); contactEmailsAux.add(index); } contactEmails = contactEmailsAux; //get phone numbers from contact List<Phone> contactPhones = getContactPropertiesRemovingNullOrEmptyValues( contact.getPersonalDetail().getPhones(), contact.getBusinessDetail().getPhones()); for (Long twinId: twinsInfo.keySet()) { Map<Integer, String> twinValues = twinsInfo.get(twinId); //get emails for the potential twin Map <Integer, String> twinEmails = getPropertiesWithValidValues( twinValues, TYPE_EMAIL_1_ADDRESS, TYPE_EMAIL_2_ADDRESS, TYPE_EMAIL_3_ADDRESS); //get phone numbers for the potential twin Map <Integer, String> twinPhones = getPropertiesWithValidValues( twinValues, TYPE_ASSISTANT_NUMBER, TYPE_BUSINESS_2_TELEPHONE_NUMBER, TYPE_BUSINESS_FAX_NUMBER, TYPE_BUSINESS_TELEPHONE_NUMBER, TYPE_CALLBACK_NUMBER, TYPE_CAR_TELEPHONE_NUMBER, TYPE_COMPANY_MAIN_TELEPHONE_NUMBER, TYPE_HOME_2_TELEPHONE_NUMBER, TYPE_HOME_FAX_NUMBER, TYPE_HOME_TELEPHONE_NUMBER, TYPE_MOBILE_TELEPHONE_NUMBER, TYPE_OTHER_FAX_NUMBER, TYPE_OTHER_TELEPHONE_NUMBER, TYPE_PAGER_NUMBER, TYPE_PRIMARY_TELEPHONE_NUMBER, TYPE_RADIO_TELEPHONE_NUMBER, TYPE_TELEX_NUMBER); boolean areTwins = false; //manages the conditions that make the potential twins true twins //(inclusion cases) if (!isUnnamedContact) { //case //- if both contact and twins haven't email addresses and phone // numbers, they must be considered twins if (!areTwins) { areTwins = contactEmails.isEmpty() && contactPhones.isEmpty() && twinEmails.isEmpty() && twinPhones.isEmpty(); } //case //- if the contact contains no fields other than name // (first/last/display/company) and the twin contains name // plus other fields (or viceversa), they must be considered // twins if (!areTwins) { areTwins = contactOrTwinHasNoFieldsWhileTheOtherHas( contactEmails, contactPhones, twinEmails, twinPhones); } } //case //- If they contain at least one identical email address in any // of the address fields if (!areTwins) { areTwins = haveContactAndTwinEmailsInCommon(contactEmails, twinEmails); } //case //- If they contain at least one identical phone number in any of // the phone number fields if (!areTwins) { areTwins = haveContactAndTwinPhoneNumbersInCommon(contactPhones, twinPhones); } //manages the conditions that make the true twins not twins anymore //(exclusion cases) //manage the case //- If the contacts don't have different phone numbers/email // addresses/ in the same corresponding field (e.g. 2 different // phone numbers in the same HOME phone # fields of the contacts) if (areTwins) { areTwins = haveContactAndTwinSameEmailsInSamePosition(contactEmails, twinEmails); } if (areTwins) { areTwins = haveContactAndTwinSamePhonesInSamePosition(contactPhones, twinPhones); } if (areTwins){ twinsFound.put(twinId, twinValues); } } return twinsFound; } /** * Checks if contact and potential twin have emails in common. * * @param contactEmails the list of contact's emails * @param twinEmails the map of twin's emails * * @return <b>true</b> if contact and twin have at least one email address * in common, <b>false</b> otherwise */ private boolean haveContactAndTwinEmailsInCommon( List<Email> contactEmails, Map<Integer, String> twinEmails) { //no emails to process if (contactEmails.isEmpty() || twinEmails.isEmpty()) return false; //aggregate the two email lists List<String> emailsSummary = aggregateEmailAddressesRemovingDuplicates( contactEmails, twinEmails); // checks if contact and twin do not share emails or if they share, and // if the total number of emails are greater than 3 (prevent data loss) if (emailsSummary.size() < (contactEmails.size() + twinEmails.size()) && emailsSummary.size() <= 3) { return true; } else { return false; } } /** * Checks if contact and potential twin have phone numbers in common. * * @param contactPhones the list of contact's phone numbers * @param twinPhones the map of twin's phone numbers * * @return <b>true</b> if contact and twin have at least one phone numbers * in common, <b>false</b> otherwise */ private boolean haveContactAndTwinPhoneNumbersInCommon( List<Phone> contactPhones, Map<Integer, String> twinPhones) { //no phone number to process if (contactPhones.isEmpty() || twinPhones.isEmpty()) return false; for (Phone phone:contactPhones) { String contactPhone = phone.getPropertyValueAsString(); if (twinPhones.containsValue(contactPhone)) { return true; } } return false; } /** * Creates a list that contains all the emails starting from contact and * twin lists, but without duplicate elements. * The comparison is case insensitive. * * @param contactEmails the list of contact's emails * @param twinEmails the map of twin's emails * @return a List of emails */ private List<String> aggregateEmailAddressesRemovingDuplicates( List<Email> contactEmails, Map<Integer, String> twinEmails) { List<String> finalList = new ArrayList<String>(); for (Email email:contactEmails) { finalList.add(email.getPropertyValueAsString()); } for (String twinEmail:twinEmails.values()) { boolean foundEmail = false; //find if new twin email is a duplicate of an already existing email for (Email contactEmail:contactEmails) { if (twinEmail.equalsIgnoreCase(contactEmail.getPropertyValueAsString())) { foundEmail = true; break; } } //if it isn't, then add it to the list if (!foundEmail) finalList.add(twinEmail); } return finalList; } /** * Retrieves the map of property that have a not null and not empty value * for the given value types. * * @param values the list of property values to check * @param valueTypes the property types to consider * @return the list of property values with a valid value. */ private Map<Integer, String> getPropertiesWithValidValues( Map<Integer, String> values, int... valueTypes) { Map<Integer, String> result = new HashMap<Integer, String>(); for (int type : valueTypes) { String value = values.get(type); if (StringUtils.isNotEmpty(value)) { result.put(type, value); } } return result; } /** * Retrieves only the list of contact properties that have a value. * The properties with a null or empty value is discarded. * * @param contactPropertiesLists the list of contact properies to check * @return the list of contact's properties with a valid value. */ private List getContactPropertiesRemovingNullOrEmptyValues( List... contactPropertiesLists) { List<TypifiedProperty> result = new ArrayList(); for (List<TypifiedProperty> propertiesList : contactPropertiesLists) { for (TypifiedProperty property : propertiesList) { if (StringUtils.isNotEmpty(property.getPropertyValueAsString())) { result.add(property); } } } return result; } /** * Verifies that if * - the contact contains no fields other than name, and the twin contains * the same name plus emails and/or phone numbers, they can be considered * twins * - the twin contains no fields other than name, and the contact contains * the same name plus emails and/or phone numbers, they can be considered * twins * * @param contactEmails the list of contact emails * @param contactPhones the list of contact phone numbers * @param twinEmails the map of the twin's emails * @param twinPhones the map of the twin's phone numbers * @return true if the conditions are satisfied */ private boolean contactOrTwinHasNoFieldsWhileTheOtherHas( List<Email> contactEmails, List<Phone> contactPhones, Map<Integer, String> twinEmails, Map<Integer, String> twinPhones) { boolean contactHasEmails = false; boolean contactHasPhones = false; boolean twinHasEmails = false; boolean twinHasPhones = false; if (twinEmails != null) twinHasEmails = !twinEmails.isEmpty(); if (twinPhones != null) twinHasPhones = !twinPhones.isEmpty(); if (contactEmails != null) contactHasEmails = !contactEmails.isEmpty(); if (contactPhones != null) contactHasPhones = !contactPhones.isEmpty(); return ( (twinHasEmails || twinHasPhones) && !(contactHasEmails || contactHasPhones) ) || ( (contactHasEmails || contactHasPhones) && !(twinHasEmails || twinHasPhones) ); } /** * Verify that contact and twin have same emails in the same positions. * * @param contactEmails the list of contact's emails * @param twinEmails the map of twin's emails * @return true if contact and twin have same emails in the same positions */ private boolean haveContactAndTwinSameEmailsInSamePosition( List<Email> contactEmails, Map<Integer, String> twinEmails) { for (Email email : contactEmails) { int type = getContactEmailItemTypeFromEmailPropertyType(email.getPropertyType()); if (TYPE_UNDEFINED == type) continue; //get emails String emailContactValue = email.getPropertyValueAsString(); String emailTwinValue = twinEmails.get(type); if (StringUtils.isNotEmpty(emailTwinValue)) { if (!emailContactValue.equalsIgnoreCase(emailTwinValue)) return false; } } return true; } /** * Verify that contact and twin have same phones in the same positions. * * @param contactPhones the list of contact's phones * @param twinPhones the map of twin's phones * @return true if contact and twin have same phones in the same positions */ private boolean haveContactAndTwinSamePhonesInSamePosition( List<Phone> contactPhones, Map<Integer, String> twinPhones) { for (Phone phone : contactPhones) { int type = getContactPhoneItemTypeFromPhonePropertyType(phone.getPropertyType()); if (TYPE_UNDEFINED == type) continue; //get emails String phoneContactValue = phone.getPropertyValueAsString(); String phoneTwinValue = twinPhones.get(type); //check them if (StringUtils.isNotEmpty(phoneTwinValue)) { if (!phoneContactValue.equalsIgnoreCase(phoneTwinValue)) return false; } } return true; } /** * Verify if the list of {@link TypifiedProperty} contains at least a valid * property value. * * @param listsOfProperties the list of properties to check * @return true if the list contains at least a value */ private boolean hasAtLeastOneNonEmptyProperty(List... listsOfProperties) { if (null == listsOfProperties) return false; for (List propertiesList : listsOfProperties) { if (null == propertiesList) continue; //analyze the single list of properties for(Object rawProperty : propertiesList) { if (rawProperty == null) continue; TypifiedProperty prop = (TypifiedProperty) rawProperty; String value = prop.getPropertyValueAsString(); //the property has a non empty value if (!StringUtils.isEmpty(normalizeField(value))) return true; } } return false; } /** * Returns the identifier of the given email description type. * * @param emailPropertyType the description of the email type * @return the identifier of the email type */ private int getContactEmailItemTypeFromEmailPropertyType(String emailPropertyType) { int itemType = TYPE_UNDEFINED; if ((FIELD_EMAIL_1_ADDRESS).equals(emailPropertyType)) { itemType = TYPE_EMAIL_1_ADDRESS; } else if ((FIELD_EMAIL_2_ADDRESS).equals(emailPropertyType)) { itemType = TYPE_EMAIL_2_ADDRESS; } else if ((FIELD_EMAIL_3_ADDRESS).equals(emailPropertyType)) { itemType = TYPE_EMAIL_3_ADDRESS; } else if ((FIELD_INSTANT_MESSENGER).equals(emailPropertyType)) { itemType = TYPE_INSTANT_MESSENGER; } return itemType; } /** * Returns the identifier of the given phone description type. * * @param phonePropertyType the description of the phone type * @return the identifier of the phone type */ private int getContactPhoneItemTypeFromPhonePropertyType(String phonePropertyType) { int itemType = TYPE_UNDEFINED; if ((FIELD_HOME_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_HOME_TELEPHONE_NUMBER; } else if ((FIELD_HOME_2_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_HOME_2_TELEPHONE_NUMBER; } else if ((FIELD_HOME_FAX_NUMBER).equals(phonePropertyType)) { itemType = TYPE_HOME_FAX_NUMBER; } else if ((FIELD_MOBILE_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_MOBILE_TELEPHONE_NUMBER; } else if ((FIELD_CAR_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_CAR_TELEPHONE_NUMBER; } else if ((FIELD_OTHER_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_OTHER_TELEPHONE_NUMBER; } else if ((FIELD_OTHER_FAX_NUMBER).equals(phonePropertyType)) { itemType = TYPE_OTHER_FAX_NUMBER; } else if ((FIELD_PRIMARY_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_PRIMARY_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_BUSINESS_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_2_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_BUSINESS_2_TELEPHONE_NUMBER; } else if ((FIELD_BUSINESS_FAX_NUMBER).equals(phonePropertyType)) { itemType = TYPE_BUSINESS_FAX_NUMBER; } else if ((FIELD_COMPANY_MAIN_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_COMPANY_MAIN_TELEPHONE_NUMBER; } else if ((FIELD_PAGER_NUMBER).equals(phonePropertyType)) { itemType = TYPE_PAGER_NUMBER; } else if ((FIELD_ASSISTANT_NUMBER).equals(phonePropertyType)) { itemType = TYPE_ASSISTANT_NUMBER; } else if ((FIELD_CALLBACK_NUMBER).equals(phonePropertyType)) { itemType = TYPE_CALLBACK_NUMBER; } else if ((FIELD_TELEX_NUMBER).equals(phonePropertyType)) { itemType = TYPE_TELEX_NUMBER; } else if ((FIELD_RADIO_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_RADIO_TELEPHONE_NUMBER; } else if ((FIELD_TELEX_NUMBER).equals(phonePropertyType)) { itemType = TYPE_TELEX_NUMBER; } else if ((FIELD_RADIO_TELEPHONE_NUMBER).equals(phonePropertyType)) { itemType = TYPE_RADIO_TELEPHONE_NUMBER; } return itemType; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/scheduling/vo/beans/SessionEmergencyTheatreVoBean.java
8365
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.scheduling.vo.beans; public class SessionEmergencyTheatreVoBean extends ims.vo.ValueObjectBean { public SessionEmergencyTheatreVoBean() { } public SessionEmergencyTheatreVoBean(ims.scheduling.vo.SessionEmergencyTheatreVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.sessiondate = vo.getSessionDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getSessionDate().getBean(); this.schlocation = vo.getSchLocation() == null ? null : (ims.core.vo.beans.LocationMinVoBean)vo.getSchLocation().getBean(); this.listowners = vo.getListOwners() == null ? null : vo.getListOwners().getBeanCollection(); this.theatreproceduresremaining = vo.getTheatreProceduresRemaining() == null ? null : (ims.scheduling.vo.beans.TheatreProceduresRemainingTimeVoBean)vo.getTheatreProceduresRemaining().getBean(); this.listtype = vo.getListType() == null ? null : (ims.vo.LookupInstanceBean)vo.getListType().getBean(); this.sessioncomment = vo.getSessionComment(); this.endtm = vo.getEndTm() == null ? null : (ims.framework.utils.beans.TimeBean)vo.getEndTm().getBean(); this.noofappointments = vo.getNoOfAppointments(); this.parentchildslots = vo.getParentChildSlots() == null ? null : vo.getParentChildSlots().getBeanCollection(); this.theatretype = vo.getTheatreType() == null ? null : (ims.vo.LookupInstanceBean)vo.getTheatreType().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.scheduling.vo.SessionEmergencyTheatreVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.sessiondate = vo.getSessionDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getSessionDate().getBean(); this.schlocation = vo.getSchLocation() == null ? null : (ims.core.vo.beans.LocationMinVoBean)vo.getSchLocation().getBean(map); this.listowners = vo.getListOwners() == null ? null : vo.getListOwners().getBeanCollection(); this.theatreproceduresremaining = vo.getTheatreProceduresRemaining() == null ? null : (ims.scheduling.vo.beans.TheatreProceduresRemainingTimeVoBean)vo.getTheatreProceduresRemaining().getBean(map); this.listtype = vo.getListType() == null ? null : (ims.vo.LookupInstanceBean)vo.getListType().getBean(); this.sessioncomment = vo.getSessionComment(); this.endtm = vo.getEndTm() == null ? null : (ims.framework.utils.beans.TimeBean)vo.getEndTm().getBean(); this.noofappointments = vo.getNoOfAppointments(); this.parentchildslots = vo.getParentChildSlots() == null ? null : vo.getParentChildSlots().getBeanCollection(); this.theatretype = vo.getTheatreType() == null ? null : (ims.vo.LookupInstanceBean)vo.getTheatreType().getBean(); } public ims.scheduling.vo.SessionEmergencyTheatreVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.scheduling.vo.SessionEmergencyTheatreVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.scheduling.vo.SessionEmergencyTheatreVo vo = null; if(map != null) vo = (ims.scheduling.vo.SessionEmergencyTheatreVo)map.getValueObject(this); if(vo == null) { vo = new ims.scheduling.vo.SessionEmergencyTheatreVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getSessionDate() { return this.sessiondate; } public void setSessionDate(ims.framework.utils.beans.DateBean value) { this.sessiondate = value; } public ims.core.vo.beans.LocationMinVoBean getSchLocation() { return this.schlocation; } public void setSchLocation(ims.core.vo.beans.LocationMinVoBean value) { this.schlocation = value; } public ims.scheduling.vo.beans.SessionListOwnerLiteVoBean[] getListOwners() { return this.listowners; } public void setListOwners(ims.scheduling.vo.beans.SessionListOwnerLiteVoBean[] value) { this.listowners = value; } public ims.scheduling.vo.beans.TheatreProceduresRemainingTimeVoBean getTheatreProceduresRemaining() { return this.theatreproceduresremaining; } public void setTheatreProceduresRemaining(ims.scheduling.vo.beans.TheatreProceduresRemainingTimeVoBean value) { this.theatreproceduresremaining = value; } public ims.vo.LookupInstanceBean getListType() { return this.listtype; } public void setListType(ims.vo.LookupInstanceBean value) { this.listtype = value; } public String getSessionComment() { return this.sessioncomment; } public void setSessionComment(String value) { this.sessioncomment = value; } public ims.framework.utils.beans.TimeBean getEndTm() { return this.endtm; } public void setEndTm(ims.framework.utils.beans.TimeBean value) { this.endtm = value; } public Integer getNoOfAppointments() { return this.noofappointments; } public void setNoOfAppointments(Integer value) { this.noofappointments = value; } public ims.scheduling.vo.beans.SessionParentChildSlotDurationVoBean[] getParentChildSlots() { return this.parentchildslots; } public void setParentChildSlots(ims.scheduling.vo.beans.SessionParentChildSlotDurationVoBean[] value) { this.parentchildslots = value; } public ims.vo.LookupInstanceBean getTheatreType() { return this.theatretype; } public void setTheatreType(ims.vo.LookupInstanceBean value) { this.theatretype = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean sessiondate; private ims.core.vo.beans.LocationMinVoBean schlocation; private ims.scheduling.vo.beans.SessionListOwnerLiteVoBean[] listowners; private ims.scheduling.vo.beans.TheatreProceduresRemainingTimeVoBean theatreproceduresremaining; private ims.vo.LookupInstanceBean listtype; private String sessioncomment; private ims.framework.utils.beans.TimeBean endtm; private Integer noofappointments; private ims.scheduling.vo.beans.SessionParentChildSlotDurationVoBean[] parentchildslots; private ims.vo.LookupInstanceBean theatretype; }
agpl-3.0
deerwalk/voltdb
tests/test_apps/live-rejoin-consistency/src/liverejoinconsistency/procedures/MPUpdateRep.java
2042
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * 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 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. */ // // Initializes the database, pushing the list of contestants and documenting domain data (Area codes and States). // package liverejoinconsistency.procedures; import org.voltdb.ProcInfo; import org.voltdb.SQLStmt; import org.voltdb.VoltProcedure; import org.voltdb.VoltTable; import java.util.Random; @ProcInfo ( singlePartition = false ) public class MPUpdateRep extends VoltProcedure { public final SQLStmt sql3 = new SQLStmt("UPDATE counters_rep set counter=counter*2;"); public final SQLStmt sql4 = new SQLStmt("UPDATE counters_rep set counter=counter/2;"); Random rand = new Random(); public long run() { switch(rand.nextInt(2)) { case 0: voltQueueSQL(sql3); break; case 1: voltQueueSQL(sql4); break; } VoltTable result[] = voltExecuteSQL(true); return 0; } }
agpl-3.0
calogera/DataHubSystem
core/src/main/java/fr/gael/dhus/api/stub/StubSavedSearchController.java
5825
package fr.gael.dhus.api.stub; import java.security.Principal; import java.util.HashMap; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.SchedulerException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import fr.gael.dhus.database.object.Search; import fr.gael.dhus.database.object.User; import fr.gael.dhus.service.exception.UserNotExistingException; import fr.gael.dhus.spring.context.ApplicationContextProvider; @RestController public class StubSavedSearchController { private static Log logger = LogFactory .getLog(StubSavedSearchController.class); @RequestMapping(value = "/stub/users/{userid}/searches", method = RequestMethod.POST) public void storeUserSearch(final Principal principal, @PathVariable(value = "userid") final String userid, @RequestParam(value = "complete", defaultValue = "") final String complete) { final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); final User u = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); if (u == null) { throw new UserNotExistingException(); } logger.info("complete search " + complete); userService.storeUserSearch(u.getId(), complete, "", new HashMap<String, String>(), complete); } @RequestMapping(value = "/stub/users/{userid}/searches", method = RequestMethod.GET) public List<Search> getUserSearches(final Principal principal, @PathVariable(value = "userid") final String userid, @RequestParam(value = "offset", defaultValue = "") final int offset, @RequestParam(value = "count", defaultValue = "") final int count) { List<Search> searches = null; final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); final User u = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); if (u == null) { throw new UserNotExistingException(); } logger.info(" ***** parameters ***** "); logger.info(" ***** offset ***** " + offset); logger.info(" ***** count ***** " + count); searches = userService.scrollSearchesOfUser(u.getId(), offset, count); try { userService.getNextScheduleSearch(); } catch (final SchedulerException e) { logger.error("Error scheduling next search" + e.getMessage()); e.printStackTrace(); } return searches; } @RequestMapping(value = "/stub/users/{userid}/searches/count", method = RequestMethod.GET) public int getUserSearchesCount(final Principal principal, @PathVariable(value = "userid") final String userid) { int count = 0; final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); final User u = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); if (u == null) { throw new UserNotExistingException(); } count = userService.countUserSearches(u.getId()); return count; } @RequestMapping(value = "/stub/users/{userid}/searches", method = RequestMethod.DELETE) public void clearSavedSearches(final Principal principal, @PathVariable(value = "userid") final String userid) { final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); final User u = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); if (u == null) { throw new UserNotExistingException(); } userService.clearSavedSearches(u.getId()); } @RequestMapping(value = "/stub/users/{userid}/searches/{searchid}", method = RequestMethod.DELETE) public void removeUserSearch(final Principal principal, @PathVariable(value = "userid") final String userid, @PathVariable(value = "searchid") final String searchid, @RequestParam(value = "id", defaultValue = "") final long id) { final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); final User u = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); if (u == null) { throw new UserNotExistingException(); } userService.removeUserSearch(u.getId(), id); } @RequestMapping(value = "/stub/users/{userid}/searches/{searchid}", method = RequestMethod.POST) public void updateUserSearchNotification(@PathVariable(value = "userid") final String userid, @PathVariable(value = "searchid") final String searchid, @RequestParam(value = "id", defaultValue = "") final long id, @RequestParam(value = "notify", defaultValue = "") final boolean notify) { final fr.gael.dhus.service.UserService userService = ApplicationContextProvider .getBean(fr.gael.dhus.service.UserService.class); userService.activateUserSearchNotification(id, notify); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/lookuptree/Handlers.java
18142
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.lookuptree; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode, ims.framework.interfaces.IClearInfo { abstract protected void bindgrdMappingsExtSystemLookup(); abstract protected void onFormModeChanged(); abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkSystemTypesValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkUserTypesValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkFormsClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnSearchClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkActiveOnlyValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnUpdTypeClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnNewTypeClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnCancelTypeClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnSaveTypeClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onQmbImageValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onQmbImageTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnInstCancelClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnInstSaveClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdMappingsGridButtonClicked(int column, GenForm.lyr1Layer.InstanceContainer.grdMappingsRow row) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdMappingsSelectionChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnFormFilterClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdFormsSelectionChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnSetDefaultClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdFormLookupsSelectionChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onTreTypesTreeViewNodeDropped(ims.framework.controls.TreeNode node, ims.framework.controls.TreeNode previousParentNode) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onTreTypesTreeViewSelectionCleared() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onTreTypesTreeViewSelectionChanged(ims.framework.controls.TreeNode node) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormModeChangedEvent(new FormModeChanged() { private static final long serialVersionUID = 1L; public void handle() { onFormModeChanged(); } }); this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { bindLookups(); onFormOpen(); } }); this.form.setFormDialogClosedEvent(new FormDialogClosed() { private static final long serialVersionUID = 1L; public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onFormDialogClosed(formName, result); } }); this.form.chkSystemTypes().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkSystemTypesValueChanged(); } }); this.form.chkUserTypes().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkUserTypesValueChanged(); } }); this.form.lnkForms().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkFormsClick(); } }); this.form.btnSearch().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnSearchClick(); } }); this.form.chkActiveOnly().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkActiveOnlyValueChanged(); } }); this.form.lyr1().Type().btnUpdType().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnUpdTypeClick(); } }); this.form.lyr1().Type().btnNewType().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnNewTypeClick(); } }); this.form.lyr1().Type().btnCancelType().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnCancelTypeClick(); } }); this.form.lyr1().Type().btnSaveType().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnSaveTypeClick(); } }); this.form.lyr1().Instance().btnNew().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnNewClick(); } }); this.form.lyr1().Instance().qmbImage().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onQmbImageValueChanged(); } }); this.form.lyr1().Instance().qmbImage().setSearchEvent(new ComboBoxSearch() { private static final long serialVersionUID = 1L; public void handle(String value) throws ims.framework.exceptions.PresentationLogicException { onQmbImageTextSubmited(value); } }); this.form.lyr1().Instance().btnInstCancel().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnInstCancelClick(); } }); this.form.lyr1().Instance().btnInstSave().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnInstSaveClick(); } }); this.form.lyr1().Instance().grdMappings().setGridButtonClickedEvent(new GridButtonClicked() { private static final long serialVersionUID = 1L; public void handle(int column, ims.framework.controls.GridRow row) throws ims.framework.exceptions.PresentationLogicException { onGrdMappingsGridButtonClicked(column, new GenForm.lyr1Layer.InstanceContainer.grdMappingsRow(row)); } }); this.form.lyr1().Instance().grdMappings().setSelectionChangedEvent(new GridSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onGrdMappingsSelectionChanged(); } }); this.form.lyr1().Forms().btnFormFilter().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnFormFilterClick(); } }); this.form.lyr1().Forms().grdForms().setSelectionChangedEvent(new GridSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onGrdFormsSelectionChanged(); } }); this.form.lyr1().Forms().btnSetDefault().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnSetDefaultClick(); } }); this.form.lyr1().Forms().grdFormLookups().setSelectionChangedEvent(new GridSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onGrdFormLookupsSelectionChanged(); } }); this.form.treTypes().setTreeViewNodeDroppedEvent(new TreeViewNodeDropped() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.TreeNode node, ims.framework.controls.TreeNode previousParentNode) throws ims.framework.exceptions.PresentationLogicException { onTreTypesTreeViewNodeDropped(node, previousParentNode); } }); this.form.treTypes().setTreeViewSelectionClearedEvent(new TreeViewSelectionCleared() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onTreTypesTreeViewSelectionCleared(); } }); this.form.treTypes().setTreeViewSelectionChangedEvent(new TreeViewSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.TreeNode node) throws ims.framework.exceptions.PresentationLogicException { onTreTypesTreeViewSelectionChanged(node); } }); this.form.getContextMenus().getMappingGridAddItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.MappingGrid.Add, sender); } }); this.form.getContextMenus().getMappingGridDeleteItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.MappingGrid.Delete, sender); } }); this.form.getContextMenus().getLookupAdminAddItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Add, sender); } }); this.form.getContextMenus().getLookupAdminUpdateItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Update, sender); } }); this.form.getContextMenus().getLookupAdminEditItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Edit, sender); } }); this.form.getContextMenus().getLookupAdminDeactivateItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Deactivate, sender); } }); this.form.getContextMenus().getLookupAdminSortItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Sort, sender); } }); this.form.getContextMenus().getLookupAdminSaveItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Save, sender); } }); this.form.getContextMenus().getLookupAdminViewItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.View, sender); } }); this.form.getContextMenus().getLookupAdminExpandItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Expand, sender); } }); this.form.getContextMenus().getLookupAdminCollapseItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.Collapse, sender); } }); this.form.getContextMenus().getLookupAdminRefreshCacheItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LookupAdmin.RefreshCache, sender); } }); } protected void bindLookups() { bindgrdMappingsExtSystemLookup(); } protected void rebindAllLookups() { bindgrdMappingsExtSystemLookup(); } protected void defaultAllLookupValues() { } public void free() { this.engine = null; this.form = null; } public abstract void clearContextInformation(); protected ims.framework.UIEngine engine; protected GenForm form; }
agpl-3.0
auroreallibe/Silverpeas-Core
core-services/mylinks/src/test/java/org/silverpeas/core/mylinks/service/DefaultMyLinksServiceTest.java
4336
package org.silverpeas.core.mylinks.service; import org.silverpeas.core.mylinks.dao.LinkDAO; import org.silverpeas.core.mylinks.model.LinkDetail; import org.apache.commons.lang3.tuple.Pair; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.silverpeas.core.test.rule.CommonAPI4Test; import org.silverpeas.core.test.rule.MockByReflectionRule; import org.silverpeas.core.persistence.jdbc.ConnectionPool; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import static org.apache.commons.lang3.tuple.Pair.of; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class DefaultMyLinksServiceTest { @Rule public CommonAPI4Test commonAPI4Test = new CommonAPI4Test(); @Rule public MockByReflectionRule reflectionRule = new MockByReflectionRule(); private DefaultMyLinksService service; private LinkDAO dao; @Before public void setup() throws Exception { service = spy(new DefaultMyLinksService()); commonAPI4Test.injectIntoMockedBeanContainer(mock(ConnectionPool.class)); dao = reflectionRule.mockField(LinkDAO.class, LinkDAO.class, "linkDAO"); } @Test @SuppressWarnings("unchecked") public void createLinkAndVerifyIdIsSet() throws Exception { when(dao.createLink(any(Connection.class), any(LinkDetail.class))) .thenAnswer(new Answer<Integer>() { @Override public Integer answer(final InvocationOnMock invocation) throws Throwable { return 38; } }); LinkDetail linkToAdd = new LinkDetail(); service.createLink(linkToAdd); assertThat(linkToAdd.getLinkId(), is(38)); } @Test @SuppressWarnings("unchecked") public void getAllLinksByUserWithoutPositions() throws Exception { List<LinkDetail> links = initLinkPositions(null, null, null, null, null); when(dao.getAllLinksByUser(any(Connection.class), anyString())).thenReturn(links); assertThat(extractLinkIdPositions(links), contains(of(10, 0), of(11, 0), of(12, 0), of(13, 0), of(14, 0))); links = service.getAllLinksByUser(""); assertThat(extractLinkIdPositions(links), contains(of(14, 0), of(13, 0), of(12, 0), of(11, 0), of(10, 0))); } @Test @SuppressWarnings("unchecked") public void getAllLinksByUserWithPositions() throws Exception { List<LinkDetail> links = initLinkPositions(5, 0, 2, 1, 3); doReturn(links).when(dao).getAllLinksByUser(any(Connection.class), anyString()); assertThat(extractLinkIdPositions(links), contains(of(10, 5), of(11, 0), of(12, 2), of(13, 1), of(14, 3))); links = service.getAllLinksByUser(""); assertThat(extractLinkIdPositions(links), contains(of(11, 0), of(13, 1), of(12, 2), of(14, 3), of(10, 5))); } @Test @SuppressWarnings("unchecked") public void getAllLinksByUserWithAndWithoutPositions() throws Exception { List<LinkDetail> links = initLinkPositions(null, 0, null, 1, 3); doReturn(links).when(dao).getAllLinksByUser(any(Connection.class), anyString()); assertThat(extractLinkIdPositions(links), contains(of(10, 0), of(11, 0), of(12, 0), of(13, 1), of(14, 3))); links = service.getAllLinksByUser(""); assertThat(extractLinkIdPositions(links), contains(of(12, 0), of(10, 0), of(11, 0), of(13, 1), of(14, 3))); } /* METHOD TOOLS */ private List<LinkDetail> initLinkPositions(Integer... positions) { List<LinkDetail> links = new ArrayList<LinkDetail>(); for (Integer position : positions) { LinkDetail link = new LinkDetail(); link.setLinkId(links.size() + 10); if (position != null) { link.setPosition(position); link.setHasPosition(true); } links.add(link); } return links; } private List<Pair<Integer, Integer>> extractLinkIdPositions(List<LinkDetail> links) { List<Pair<Integer, Integer>> linkIdPositions = new ArrayList<Pair<Integer, Integer>>(); for (LinkDetail link : links) { linkIdPositions.add(of(link.getLinkId(), link.getPosition())); } return linkIdPositions; } }
agpl-3.0
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/documentation/src/main/docbook/userGuide/en-US/chapters/fetching/extras/Employee.java
393
@Entity public class Employee { @Id private Long id; @NaturalId private String userid; @Column( name="pswd" ) @ColumnTransformer( read="decrypt(pswd)" write="encrypt(?)" ) private String password; private int accessLevel; @ManyToOne( fetch=LAZY ) @JoinColumn private Department department; @ManyToMany(mappedBy="employees") @JoinColumn private Set<Project> projects; ... }
lgpl-2.1
SensorsINI/jaer
src/net/sf/jaer/event/PolarityEventInterface.java
542
package net.sf.jaer.event; import net.sf.jaer.event.PolarityEvent.Polarity; /** Additional interface of PolarityEvent * @author tobi */ public interface PolarityEventInterface extends BasicEventInterface { /** * @return the polarity */ public Polarity getPolarity(); /** Returns +1 if polarity is On or -1 if polarity is Off. * * @return +1 from On event, -1 from Off event. */ int getPolaritySignum(); /** * @param polarity the polarity to set */ void setPolarity(Polarity polarity); }
lgpl-2.1
SuperUnitato/UnLonely
build/tmp/recompileMc/sources/net/minecraft/block/BlockTallGrass.java
7340
package net.minecraft.block; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IStringSerializable; import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockTallGrass extends BlockBush implements IGrowable, net.minecraftforge.common.IShearable { public static final PropertyEnum<BlockTallGrass.EnumType> TYPE = PropertyEnum.<BlockTallGrass.EnumType>create("type", BlockTallGrass.EnumType.class); protected static final AxisAlignedBB TALL_GRASS_AABB = new AxisAlignedBB(0.09999999403953552D, 0.0D, 0.09999999403953552D, 0.8999999761581421D, 0.800000011920929D, 0.8999999761581421D); protected BlockTallGrass() { super(Material.VINE); this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return TALL_GRASS_AABB; } public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state) { return super.canBlockStay(worldIn, pos, state); } /** * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) */ public boolean isReplaceable(IBlockAccess worldIn, BlockPos pos) { return true; } /** * Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState state, Random rand, int fortune) { return null; } /** * Get the quantity dropped based on the given fortune level */ public int quantityDroppedWithBonus(int fortune, Random random) { return 1 + random.nextInt(fortune * 2 + 1); } public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, ItemStack stack) { if (!worldIn.isRemote && stack.getItem() == Items.SHEARS) { player.addStat(StatList.getBlockStats(this)); spawnAsEntity(worldIn, pos, new ItemStack(Blocks.TALLGRASS, 1, ((BlockTallGrass.EnumType)state.getValue(TYPE)).getMeta())); } else { super.harvestBlock(worldIn, player, pos, state, te, stack); } } public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(this, 1, state.getBlock().getMetaFromState(state)); } /** * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) */ @SideOnly(Side.CLIENT) public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list) { for (int i = 1; i < 3; ++i) { list.add(new ItemStack(itemIn, 1, i)); } } /** * Whether this IGrowable can grow */ public boolean canGrow(World worldIn, BlockPos pos, IBlockState state, boolean isClient) { return state.getValue(TYPE) != BlockTallGrass.EnumType.DEAD_BUSH; } public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state) { return true; } public void grow(World worldIn, Random rand, BlockPos pos, IBlockState state) { BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.GRASS; if (state.getValue(TYPE) == BlockTallGrass.EnumType.FERN) { blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.FERN; } if (Blocks.DOUBLE_PLANT.canPlaceBlockAt(worldIn, pos)) { Blocks.DOUBLE_PLANT.placeAt(worldIn, pos, blockdoubleplant$enumplanttype, 2); } } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(TYPE, BlockTallGrass.EnumType.byMetadata(meta)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { return ((BlockTallGrass.EnumType)state.getValue(TYPE)).getMeta(); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] {TYPE}); } /** * Get the OffsetType for this Block. Determines if the model is rendered slightly offset. */ public Block.EnumOffsetType getOffsetType() { return Block.EnumOffsetType.XYZ; } public static enum EnumType implements IStringSerializable { DEAD_BUSH(0, "dead_bush"), GRASS(1, "tall_grass"), FERN(2, "fern"); private static final BlockTallGrass.EnumType[] META_LOOKUP = new BlockTallGrass.EnumType[values().length]; private final int meta; private final String name; private EnumType(int meta, String name) { this.meta = meta; this.name = name; } public int getMeta() { return this.meta; } public String toString() { return this.name; } public static BlockTallGrass.EnumType byMetadata(int meta) { if (meta < 0 || meta >= META_LOOKUP.length) { meta = 0; } return META_LOOKUP[meta]; } public String getName() { return this.name; } static { for (BlockTallGrass.EnumType blocktallgrass$enumtype : values()) { META_LOOKUP[blocktallgrass$enumtype.getMeta()] = blocktallgrass$enumtype; } } } @Override public boolean isShearable(ItemStack item, IBlockAccess world, BlockPos pos){ return true; } @Override public NonNullList<ItemStack> onSheared(ItemStack item, IBlockAccess world, BlockPos pos, int fortune) { return NonNullList.withSize(1, new ItemStack(Blocks.TALLGRASS, 1, ((BlockTallGrass.EnumType)world.getBlockState(pos).getValue(TYPE)).getMeta())); } @Override public NonNullList<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { if (RANDOM.nextInt(8) != 0) return NonNullList.create(); ItemStack seed = net.minecraftforge.common.ForgeHooks.getGrassSeed(RANDOM, fortune); if (!seed.isEmpty()) return NonNullList.withSize(1, seed); else return NonNullList.create(); } }
lgpl-2.1
ggiudetti/opencms-core
src/org/opencms/loader/CmsJspLoader.java
75848
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, 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.loader; import org.opencms.configuration.CmsParameterConfiguration; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.file.history.CmsHistoryResourceHandler; import org.opencms.flex.CmsFlexCache; import org.opencms.flex.CmsFlexController; import org.opencms.flex.CmsFlexRequest; import org.opencms.flex.CmsFlexResponse; import org.opencms.gwt.shared.CmsGwtConstants; import org.opencms.i18n.CmsEncoder; import org.opencms.i18n.CmsMessageContainer; import org.opencms.jsp.CmsJspTagEnableAde; import org.opencms.jsp.jsonpart.CmsJsonPartFilter; import org.opencms.jsp.util.CmsJspLinkMacroResolver; import org.opencms.jsp.util.CmsJspStandardContextBean; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.monitor.CmsMemoryMonitor; import org.opencms.relations.CmsRelation; import org.opencms.relations.CmsRelationFilter; import org.opencms.relations.CmsRelationType; import org.opencms.staticexport.CmsLinkManager; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsRequestUtil; import org.opencms.util.CmsStringUtil; import org.opencms.util.I_CmsRegexSubstitution; import org.opencms.workplace.CmsWorkplaceManager; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.SocketException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import com.google.common.base.Splitter; /** * The JSP loader which enables the execution of JSP in OpenCms.<p> * * Parameters supported by this loader:<dl> * * <dt>jsp.repository</dt><dd> * (Optional) This is the root directory in the "real" file system where generated JSPs are stored. * The default is the web application path, e.g. in Tomcat if your web application is * names "opencms" it would be <code>${TOMCAT_HOME}/webapps/opencms/</code>. * The <code>jsp.folder</code> (see below) is added to this path. * Usually the <code>jsp.repository</code> is not changed. * </dd> * * <dt>jsp.folder</dt><dd> * (Optional) A path relative to the <code>jsp.repository</code> path where the * JSPs generated by OpenCms are stored. The default is to store the generated JSP in * <code>/WEB-INF/jsp/</code>. * This works well in Tomcat 4, and the JSPs are * not accessible directly from the outside this way, only through the OpenCms servlet. * <i>Please note:</i> Some servlet environments (e.g. BEA Weblogic) do not permit * JSPs to be stored under <code>/WEB-INF</code>. For environments like these, * set the path to some place where JSPs can be accessed, e.g. <code>/jsp/</code> only. * </dd> * * <dt>jsp.errorpage.committed</dt><dd> * (Optional) This parameter controls behavior of JSP error pages * i.e. <code>&lt;% page errorPage="..." %&gt;</code>. If you find that these don't work * in your servlet environment, you should try to change the value here. * The default <code>true</code> has been tested with Tomcat 4.1 and 5.0. * Older versions of Tomcat like 4.0 require a setting of <code>false</code>.</dd> * </dl> * * @since 6.0.0 * * @see I_CmsResourceLoader */ public class CmsJspLoader implements I_CmsResourceLoader, I_CmsFlexCacheEnabledLoader, I_CmsEventListener { /** Property value for "cache" that indicates that the FlexCache should be bypassed. */ public static final String CACHE_PROPERTY_BYPASS = "bypass"; /** Property value for "cache" that indicates that the output should be streamed. */ public static final String CACHE_PROPERTY_STREAM = "stream"; /** Default jsp folder constant. */ public static final String DEFAULT_JSP_FOLDER = "/WEB-INF/jsp/"; /** Special JSP directive tag start (<code>%&gt;</code>). */ public static final String DIRECTIVE_END = "%>"; /** Special JSP directive tag start (<code>&lt;%&#0040;</code>). */ public static final String DIRECTIVE_START = "<%@"; /** Extension for JSP managed by OpenCms (<code>.jsp</code>). */ public static final String JSP_EXTENSION = ".jsp"; /** Cache max age parameter name. */ public static final String PARAM_CLIENT_CACHE_MAXAGE = "client.cache.maxage"; /** Jsp cache size parameter name. */ public static final String PARAM_JSP_CACHE_SIZE = "jsp.cache.size"; /** Error page committed parameter name. */ public static final String PARAM_JSP_ERRORPAGE_COMMITTED = "jsp.errorpage.committed"; /** Jsp folder parameter name. */ public static final String PARAM_JSP_FOLDER = "jsp.folder"; /** Jsp repository parameter name. */ public static final String PARAM_JSP_REPOSITORY = "jsp.repository"; /** The id of this loader. */ public static final int RESOURCE_LOADER_ID = 6; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsJspLoader.class); /** The maximum age for delivered contents in the clients cache. */ private static long m_clientCacheMaxAge; /** Read write locks for jsp files. */ private static Map<String, ReentrantReadWriteLock> m_fileLocks = CmsMemoryMonitor.createLRUCacheMap(10000); /** The directory to store the generated JSP pages in (absolute path). */ private static String m_jspRepository; /** The directory to store the generated JSP pages in (relative path in web application). */ private static String m_jspWebAppRepository; /** The CmsFlexCache used to store generated cache entries in. */ private CmsFlexCache m_cache; /** The resource loader configuration. */ private CmsParameterConfiguration m_configuration; /** Flag to indicate if error pages are marked as "committed". */ private boolean m_errorPagesAreNotCommitted; /** The offline JSPs. */ private Map<String, Boolean> m_offlineJsps; /** The online JSPs. */ private Map<String, Boolean> m_onlineJsps; /** A map from taglib names to their URIs. */ private Map<String, String> m_taglibs = new HashMap<String, String>(); /** Lock used to prevent JSP repository from being accessed while it is purged. The read lock is needed for accessing the JSP repository, the write lock is needed for purging it. */ private ReentrantReadWriteLock m_purgeLock = new ReentrantReadWriteLock(true); /** * The constructor of the class is empty, the initial instance will be * created by the resource manager upon startup of OpenCms.<p> * * @see org.opencms.loader.CmsResourceManager */ public CmsJspLoader() { m_configuration = new CmsParameterConfiguration(); OpenCms.addCmsEventListener( this, new int[] {EVENT_CLEAR_CACHES, EVENT_CLEAR_OFFLINE_CACHES, EVENT_CLEAR_ONLINE_CACHES}); m_fileLocks = CmsMemoryMonitor.createLRUCacheMap(10000); initCaches(1000); } /** * @see org.opencms.configuration.I_CmsConfigurationParameterHandler#addConfigurationParameter(java.lang.String, java.lang.String) */ public void addConfigurationParameter(String paramName, String paramValue) { m_configuration.add(paramName, paramValue); if (paramName.startsWith("taglib.")) { m_taglibs.put(paramName.replaceFirst("^taglib\\.", ""), paramValue.trim()); } } /** * @see org.opencms.main.I_CmsEventListener#cmsEvent(org.opencms.main.CmsEvent) */ public void cmsEvent(CmsEvent event) { switch (event.getType()) { case EVENT_CLEAR_CACHES: m_offlineJsps.clear(); m_onlineJsps.clear(); return; case EVENT_CLEAR_OFFLINE_CACHES: m_offlineJsps.clear(); return; case EVENT_CLEAR_ONLINE_CACHES: m_onlineJsps.clear(); return; default: // do nothing } } /** * Destroy this ResourceLoder, this is a NOOP so far. */ public void destroy() { // NOOP } /** * @see org.opencms.loader.I_CmsResourceLoader#dump(org.opencms.file.CmsObject, org.opencms.file.CmsResource, java.lang.String, java.util.Locale, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public byte[] dump( CmsObject cms, CmsResource file, String element, Locale locale, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // get the current Flex controller CmsFlexController controller = CmsFlexController.getController(req); CmsFlexController oldController = null; if (controller != null) { // for dumping we must create an new "top level" controller, save the old one to be restored later oldController = controller; } byte[] result = null; try { // now create a new, temporary Flex controller controller = getController(cms, file, req, res, false, false); if (element != null) { // add the element parameter to the included request String[] value = new String[] {element}; Map<String, String[]> parameters = Collections.singletonMap( I_CmsResourceLoader.PARAMETER_ELEMENT, value); controller.getCurrentRequest().addParameterMap(parameters); } controller.getCurrentRequest().addAttributeMap(CmsRequestUtil.getAtrributeMap(req)); // dispatch to the JSP result = dispatchJsp(controller); // remove temporary controller CmsFlexController.removeController(req); } finally { if ((oldController != null) && (controller != null)) { // update "date last modified" oldController.updateDates(controller.getDateLastModified(), controller.getDateExpires()); // reset saved controller CmsFlexController.setController(req, oldController); } } return result; } /** * @see org.opencms.loader.I_CmsResourceLoader#export(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public byte[] export(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // get the Flex controller CmsFlexController controller = getController(cms, resource, req, res, false, true); // dispatch to the JSP byte[] result = dispatchJsp(controller); // remove the controller from the request CmsFlexController.removeController(req); // return the contents return result; } /** * @see org.opencms.configuration.I_CmsConfigurationParameterHandler#getConfiguration() */ public CmsParameterConfiguration getConfiguration() { // return the configuration in an immutable form return m_configuration; } /** * Returns the absolute path in the "real" file system for the JSP repository * toplevel directory.<p> * * @return The full path to the JSP repository */ public String getJspRepository() { return m_jspRepository; } /** * @see org.opencms.loader.I_CmsResourceLoader#getLoaderId() */ public int getLoaderId() { return RESOURCE_LOADER_ID; } /** * Returns a set of root paths of files that are including the given resource using the 'link.strong' macro.<p> * * @param cms the current cms context * @param resource the resource to check * @param referencingPaths the set of already referencing paths, also return parameter * * @throws CmsException if something goes wrong */ public void getReferencingStrongLinks(CmsObject cms, CmsResource resource, Set<String> referencingPaths) throws CmsException { CmsRelationFilter filter = CmsRelationFilter.SOURCES.filterType(CmsRelationType.JSP_STRONG); Iterator<CmsRelation> it = cms.getRelationsForResource(resource, filter).iterator(); while (it.hasNext()) { CmsRelation relation = it.next(); try { CmsResource source = relation.getSource(cms, CmsResourceFilter.DEFAULT); // check if file was already included if (referencingPaths.contains(source.getRootPath())) { // no need to include this file more than once continue; } referencingPaths.add(source.getRootPath()); getReferencingStrongLinks(cms, source, referencingPaths); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } } } /** * Return a String describing the ResourceLoader, * which is (localized to the system default locale) * <code>"The OpenCms default resource loader for JSP"</code>.<p> * * @return a describing String for the ResourceLoader */ public String getResourceLoaderInfo() { return Messages.get().getBundle().key(Messages.GUI_LOADER_JSP_DEFAULT_DESC_0); } /** * @see org.opencms.configuration.I_CmsConfigurationParameterHandler#initConfiguration() */ public void initConfiguration() { m_jspRepository = m_configuration.get(PARAM_JSP_REPOSITORY); if (m_jspRepository == null) { m_jspRepository = OpenCms.getSystemInfo().getWebApplicationRfsPath(); } m_jspWebAppRepository = m_configuration.getString(PARAM_JSP_FOLDER, DEFAULT_JSP_FOLDER); if (!m_jspWebAppRepository.endsWith("/")) { m_jspWebAppRepository += "/"; } m_jspRepository = CmsFileUtil.normalizePath(m_jspRepository + m_jspWebAppRepository); String maxAge = m_configuration.get(PARAM_CLIENT_CACHE_MAXAGE); if (maxAge == null) { m_clientCacheMaxAge = -1; } else { m_clientCacheMaxAge = Long.parseLong(maxAge); } // get the "error pages are committed or not" flag from the configuration m_errorPagesAreNotCommitted = m_configuration.getBoolean(PARAM_JSP_ERRORPAGE_COMMITTED, true); int cacheSize = m_configuration.getInteger(PARAM_JSP_CACHE_SIZE, -1); if (cacheSize > 0) { initCaches(cacheSize); } // output setup information if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JSP_REPOSITORY_ABS_PATH_1, m_jspRepository)); CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WEBAPP_PATH_1, m_jspWebAppRepository)); CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_JSP_REPOSITORY_ERR_PAGE_COMMOTED_1, Boolean.valueOf(m_errorPagesAreNotCommitted))); if (m_clientCacheMaxAge > 0) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_CLIENT_CACHE_MAX_AGE_1, maxAge)); } if (cacheSize > 0) { CmsLog.INIT.info( Messages.get().getBundle().key(Messages.INIT_JSP_CACHE_SIZE_1, String.valueOf(cacheSize))); } CmsLog.INIT.info( Messages.get().getBundle().key(Messages.INIT_LOADER_INITIALIZED_1, this.getClass().getName())); } } /** * @see org.opencms.loader.I_CmsResourceLoader#isStaticExportEnabled() */ public boolean isStaticExportEnabled() { return true; } /** * @see org.opencms.loader.I_CmsResourceLoader#isStaticExportProcessable() */ public boolean isStaticExportProcessable() { return true; } /** * @see org.opencms.loader.I_CmsResourceLoader#isUsableForTemplates() */ public boolean isUsableForTemplates() { return true; } /** * @see org.opencms.loader.I_CmsResourceLoader#isUsingUriWhenLoadingTemplate() */ public boolean isUsingUriWhenLoadingTemplate() { return false; } /** * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void load(CmsObject cms, CmsResource file, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, CmsException { CmsRequestContext context = cms.getRequestContext(); // If we load template jsp or template-element jsp (xml contents or xml pages) don't show source (2nd test) if ((CmsHistoryResourceHandler.isHistoryRequest(req)) && (context.getUri().equals(context.removeSiteRoot(file.getRootPath())))) { showSource(cms, file, req, res); } else { // load and process the JSP boolean streaming = false; boolean bypass = false; // read "cache" property for requested VFS resource to check for special "stream" and "bypass" values String cacheProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CACHE, true).getValue(); if (cacheProperty != null) { cacheProperty = cacheProperty.trim(); if (CACHE_PROPERTY_STREAM.equals(cacheProperty)) { streaming = true; } else if (CACHE_PROPERTY_BYPASS.equals(cacheProperty)) { streaming = true; bypass = true; } } // For now, disable flex caching when the __json parameter is used if (CmsJsonPartFilter.isJsonRequest(req)) { streaming = true; bypass = true; } // get the Flex controller CmsFlexController controller = getController(cms, file, req, res, streaming, true); Lock lock = m_purgeLock.readLock(); try { lock.lock(); if (bypass || controller.isForwardMode()) { // initialize the standard contex bean to be available for all requests CmsJspStandardContextBean.getInstance(controller.getCurrentRequest()); // once in forward mode, always in forward mode (for this request) controller.setForwardMode(true); // bypass Flex cache for this page, update the JSP first if necessary String target = updateJsp(file, controller, new HashSet<String>()); // dispatch to external JSP req.getRequestDispatcher(target).forward(controller.getCurrentRequest(), res); } else { // Flex cache not bypassed, dispatch to internal JSP dispatchJsp(controller); } } finally { lock.unlock(); } // remove the controller from the request if not forwarding if (!controller.isForwardMode()) { CmsFlexController.removeController(req); } } } /** * Replaces taglib attributes in page directives with taglib directives.<p> * * @param content the JSP source text * * @return the transformed JSP text */ @Deprecated public String processTaglibAttributes(String content) { // matches a whole page directive final Pattern directivePattern = Pattern.compile("(?sm)<%@\\s*page.*?%>"); // matches a taglibs attribute and captures its values final Pattern taglibPattern = Pattern.compile("(?sm)taglibs\\s*=\\s*\"(.*?)\""); final Pattern commaPattern = Pattern.compile("(?sm)\\s*,\\s*"); final Set<String> taglibs = new LinkedHashSet<String>(); // we insert the marker after the first page directive final String marker = ":::TAGLIBS:::"; I_CmsRegexSubstitution directiveSub = new I_CmsRegexSubstitution() { private boolean m_first = true; public String substituteMatch(String string, Matcher matcher) { String match = string.substring(matcher.start(), matcher.end()); I_CmsRegexSubstitution taglibSub = new I_CmsRegexSubstitution() { public String substituteMatch(String string1, Matcher matcher1) { // values of the taglibs attribute String match1 = string1.substring(matcher1.start(1), matcher1.end(1)); for (String taglibKey : Splitter.on(commaPattern).split(match1)) { taglibs.add(taglibKey); } return ""; } }; String result = CmsStringUtil.substitute(taglibPattern, match, taglibSub); if (m_first) { result += marker; m_first = false; } return result; } }; String substituted = CmsStringUtil.substitute(directivePattern, content, directiveSub); // insert taglib inclusion substituted = substituted.replaceAll(marker, generateTaglibInclusions(taglibs)); // remove empty page directives substituted = substituted.replaceAll("(?sm)<%@\\s*page\\s*%>", ""); return substituted; } /** * Removes the given resources from the cache.<p> * * @param rootPaths the set of root paths to remove * @param online if online or offline */ public void removeFromCache(Set<String> rootPaths, boolean online) { Map<String, Boolean> cache; if (online) { cache = m_onlineJsps; } else { cache = m_offlineJsps; } Iterator<String> itRemove = rootPaths.iterator(); while (itRemove.hasNext()) { String rootPath = itRemove.next(); cache.remove(rootPath); } } /** * Removes a JSP from an offline project from the RFS.<p> * * @param resource the offline JSP resource to remove from the RFS * * @throws CmsLoaderException if accessing the loader fails */ public void removeOfflineJspFromRepository(CmsResource resource) throws CmsLoaderException { String jspName = getJspRfsPath(resource, false); Set<String> pathSet = new HashSet<String>(); pathSet.add(resource.getRootPath()); ReentrantReadWriteLock lock = getFileLock(jspName); lock.writeLock().lock(); try { removeFromCache(pathSet, false); File jspFile = new File(jspName); jspFile.delete(); } finally { lock.writeLock().unlock(); } } /** * @see org.opencms.loader.I_CmsResourceLoader#service(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ public void service(CmsObject cms, CmsResource resource, ServletRequest req, ServletResponse res) throws ServletException, IOException, CmsLoaderException { Lock lock = m_purgeLock.readLock(); try { lock.lock(); CmsFlexController controller = CmsFlexController.getController(req); // get JSP target name on "real" file system String target = updateJsp(resource, controller, new HashSet<String>(8)); // important: Indicate that all output must be buffered controller.getCurrentResponse().setOnlyBuffering(true); // initialize the standard contex bean to be available for all requests CmsJspStandardContextBean.getInstance(controller.getCurrentRequest()); // dispatch to external file controller.getCurrentRequest().getRequestDispatcherToExternal(cms.getSitePath(resource), target).include( req, res); } finally { lock.unlock(); } } /** * @see org.opencms.loader.I_CmsFlexCacheEnabledLoader#setFlexCache(org.opencms.flex.CmsFlexCache) */ public void setFlexCache(CmsFlexCache cache) { m_cache = cache; // output setup information if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ADD_FLEX_CACHE_0)); } } /** * Triggers an asynchronous purge of the JSP repository.<p> * * @param afterPurgeAction the action to execute after purging */ public void triggerPurge(final Runnable afterPurgeAction) { OpenCms.getExecutor().execute(new Runnable() { @SuppressWarnings("synthetic-access") public void run() { WriteLock lock = m_purgeLock.writeLock(); try { lock.lock(); doPurge(afterPurgeAction); } catch (Exception e) { LOG.error("Error while purging jsp repository: " + e.getLocalizedMessage(), e); } finally { lock.unlock(); } } }); } /** * Updates a JSP page in the "real" file system in case the VFS resource has changed.<p> * * Also processes the <code>&lt;%@ cms %&gt;</code> tags before the JSP is written to the real FS. * Also recursively updates all files that are referenced by a <code>&lt;%@ cms %&gt;</code> tag * on this page to make sure the file actually exists in the real FS. * All <code>&lt;%@ include %&gt;</code> tags are parsed and the name in the tag is translated * from the OpenCms VFS path to the path in the real FS. * The same is done for filenames in <code>&lt;%@ page errorPage=... %&gt;</code> tags.<p> * * @param resource the requested JSP file resource in the VFS * @param controller the controller for the JSP integration * @param updatedFiles a Set containing all JSP pages that have been already updated * * @return the file name of the updated JSP in the "real" FS * * @throws ServletException might be thrown in the process of including the JSP * @throws IOException might be thrown in the process of including the JSP * @throws CmsLoaderException if the resource type can not be read */ public String updateJsp(CmsResource resource, CmsFlexController controller, Set<String> updatedFiles) throws IOException, ServletException, CmsLoaderException { String jspVfsName = resource.getRootPath(); String extension; boolean isHardInclude; int loaderId = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getLoaderId(); if ((loaderId == CmsJspLoader.RESOURCE_LOADER_ID) && (!jspVfsName.endsWith(JSP_EXTENSION))) { // this is a true JSP resource that does not end with ".jsp" extension = JSP_EXTENSION; isHardInclude = false; } else { // not a JSP resource or already ends with ".jsp" extension = ""; // if this is a JSP we don't treat it as hard include isHardInclude = (loaderId != CmsJspLoader.RESOURCE_LOADER_ID); } String jspTargetName = CmsFileUtil.getRepositoryName( m_jspWebAppRepository, jspVfsName + extension, controller.getCurrentRequest().isOnline()); // check if page was already updated if (updatedFiles.contains(jspTargetName)) { // no need to write the already included file to the real FS more then once return jspTargetName; } String jspPath = CmsFileUtil.getRepositoryName( m_jspRepository, jspVfsName + extension, controller.getCurrentRequest().isOnline()); File d = new File(jspPath).getParentFile(); if ((d == null) || (d.exists() && !(d.isDirectory() && d.canRead()))) { CmsMessageContainer message = Messages.get().container(Messages.LOG_ACCESS_DENIED_1, jspPath); LOG.error(message.key()); // can not continue throw new ServletException(message.key()); } if (!d.exists()) { // create directory structure d.mkdirs(); } ReentrantReadWriteLock readWriteLock = getFileLock(jspVfsName); try { // get a read lock for this jsp readWriteLock.readLock().lock(); File jspFile = new File(jspPath); // check if the JSP must be updated boolean mustUpdate = false; long jspModificationDate = 0; if (!jspFile.exists()) { // file does not exist in real FS mustUpdate = true; // make sure the parent folder exists File folder = jspFile.getParentFile(); if (!folder.exists()) { boolean success = folder.mkdirs(); if (!success) { LOG.error( org.opencms.db.Messages.get().getBundle().key( org.opencms.db.Messages.LOG_CREATE_FOLDER_FAILED_1, folder.getAbsolutePath())); } } } else { jspModificationDate = jspFile.lastModified(); if (jspModificationDate < resource.getDateLastModified()) { // file in real FS is older then file in VFS mustUpdate = true; } else if (controller.getCurrentRequest().isDoRecompile()) { // recompile is forced with parameter mustUpdate = true; } else { // check if update is needed if (controller.getCurrentRequest().isOnline()) { mustUpdate = !m_onlineJsps.containsKey(jspVfsName); } else { mustUpdate = !m_offlineJsps.containsKey(jspVfsName); } // check strong links only if update is needed if (mustUpdate) { // update strong link dependencies mustUpdate = updateStrongLinks(resource, controller, updatedFiles); } } } if (mustUpdate) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_WRITING_JSP_1, jspTargetName)); } // jsp needs updating, acquire a write lock readWriteLock.readLock().unlock(); readWriteLock.writeLock().lock(); try { // check again if updating is still necessary as this might have happened while waiting for the write lock if (!jspFile.exists() || (jspModificationDate == jspFile.lastModified())) { updatedFiles.add(jspTargetName); byte[] contents; String encoding; try { CmsObject cms = controller.getCmsObject(); contents = cms.readFile(resource).getContents(); // check the "content-encoding" property for the JSP, use system default if not found on path encoding = cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(); if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); } else { encoding = CmsEncoder.lookupEncoding(encoding.trim(), encoding); } } catch (CmsException e) { controller.setThrowable(e, jspVfsName); throw new ServletException( Messages.get().getBundle().key(Messages.ERR_LOADER_JSP_ACCESS_1, jspVfsName), e); } try { // parse the JSP and modify OpenCms critical directives contents = parseJsp(contents, encoding, controller, updatedFiles, isHardInclude); if (LOG.isInfoEnabled()) { // check for existing file and display some debug info LOG.info( Messages.get().getBundle().key( Messages.LOG_JSP_PERMCHECK_4, new Object[] { jspFile.getAbsolutePath(), Boolean.valueOf(jspFile.exists()), Boolean.valueOf(jspFile.isFile()), Boolean.valueOf(jspFile.canWrite())})); } // write the parsed JSP content to the real FS synchronized (CmsJspLoader.class) { // this must be done only one file at a time FileOutputStream fs = new FileOutputStream(jspFile); fs.write(contents); fs.close(); // we set the modification date to (approximately) that of the VFS resource. This is needed because in the Online project, the old version of a JSP // may be generated in the RFS JSP repository *after* the JSP has been changed, but *before* it has been published, which would lead // to it not being updated after the changed JSP is published. // Note: the RFS may only support second precision for the last modification date jspFile.setLastModified((1 + (resource.getDateLastModified() / 1000)) * 1000); } if (controller.getCurrentRequest().isOnline()) { m_onlineJsps.put(jspVfsName, Boolean.TRUE); } else { m_offlineJsps.put(jspVfsName, Boolean.TRUE); } if (LOG.isInfoEnabled()) { LOG.info( Messages.get().getBundle().key( Messages.LOG_UPDATED_JSP_2, jspTargetName, jspVfsName)); } } catch (FileNotFoundException e) { throw new ServletException( Messages.get().getBundle().key(Messages.ERR_LOADER_JSP_WRITE_1, jspFile.getName()), e); } } } finally { readWriteLock.readLock().lock(); readWriteLock.writeLock().unlock(); } } // update "last modified" and "expires" date on controller controller.updateDates(jspFile.lastModified(), CmsResource.DATE_EXPIRED_DEFAULT); } finally { //m_processingFiles.remove(jspVfsName); readWriteLock.readLock().unlock(); } return jspTargetName; } /** * Updates the internal jsp repository when the servlet container * tries to compile a jsp file that may not exist.<p> * * @param servletPath the servlet path, just to avoid unneeded recursive calls * @param request the current request */ public void updateJspFromRequest(String servletPath, CmsFlexRequest request) { // assemble the RFS name of the requested jsp String jspUri = servletPath; String pathInfo = request.getPathInfo(); if (pathInfo != null) { jspUri += pathInfo; } // check the file name if ((jspUri == null) || !jspUri.startsWith(m_jspWebAppRepository)) { // nothing to do, this kind of request are handled by the CmsJspLoader#service method return; } // remove prefixes jspUri = jspUri.substring(m_jspWebAppRepository.length()); if (jspUri.startsWith(CmsFlexCache.REPOSITORY_ONLINE)) { jspUri = jspUri.substring(CmsFlexCache.REPOSITORY_ONLINE.length()); } else if (jspUri.startsWith(CmsFlexCache.REPOSITORY_OFFLINE)) { jspUri = jspUri.substring(CmsFlexCache.REPOSITORY_OFFLINE.length()); } else { // this is not an OpenCms jsp file return; } // read the resource from OpenCms CmsFlexController controller = CmsFlexController.getController(request); try { CmsResource includeResource; try { // first try to read the resource assuming no additional jsp extension was needed includeResource = readJspResource(controller, jspUri); } catch (CmsVfsResourceNotFoundException e) { // try removing the additional jsp extension if (jspUri.endsWith(JSP_EXTENSION)) { jspUri = jspUri.substring(0, jspUri.length() - JSP_EXTENSION.length()); } includeResource = readJspResource(controller, jspUri); } // make sure the jsp referenced file is generated updateJsp(includeResource, controller, new HashSet<String>(8)); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getLocalizedMessage(), e); } } } /** * Dispatches the current request to the OpenCms internal JSP.<p> * * @param controller the current controller * * @return the content of the processed JSP * * @throws ServletException if inclusion does not work * @throws IOException if inclusion does not work */ protected byte[] dispatchJsp(CmsFlexController controller) throws ServletException, IOException { // get request / response wrappers CmsFlexRequest f_req = controller.getCurrentRequest(); CmsFlexResponse f_res = controller.getCurrentResponse(); try { f_req.getRequestDispatcher(controller.getCmsObject().getSitePath(controller.getCmsResource())).include( f_req, f_res); } catch (SocketException e) { // uncritical, might happen if client (browser) does not wait until end of page delivery LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e); } byte[] result = null; HttpServletResponse res = controller.getTopResponse(); if (!controller.isStreaming() && !f_res.isSuspended()) { try { // if a JSP error page was triggered the response will be already committed here if (!res.isCommitted() || m_errorPagesAreNotCommitted) { // check if the current request was done by a workplace user boolean isWorkplaceUser = CmsWorkplaceManager.isWorkplaceUser(f_req); // check if the content was modified since the last request if (controller.isTop() && !isWorkplaceUser && CmsFlexController.isNotModifiedSince(f_req, controller.getDateLastModified())) { if (f_req.getParameterMap().size() == 0) { // only use "expires" header on pages that have no parameters, // otherwise some browsers (e.g. IE 6) will not even try to request // updated versions of the page CmsFlexController.setDateExpiresHeader( res, controller.getDateExpires(), m_clientCacheMaxAge); } res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return null; } // get the result byte array result = f_res.getWriterBytes(); HttpServletRequest req = controller.getTopRequest(); if (req.getHeader(CmsRequestUtil.HEADER_OPENCMS_EXPORT) != null) { // this is a non "on-demand" static export request, don't write to the response stream req.setAttribute( CmsRequestUtil.HEADER_OPENCMS_EXPORT, new Long(controller.getDateLastModified())); } else if (controller.isTop()) { // process headers and write output if this is the "top" request/response res.setContentLength(result.length); // check for preset error code Integer errorCode = (Integer)req.getAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE); if (errorCode == null) { // set last modified / no cache headers only if this is not an error page if (isWorkplaceUser) { res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis()); CmsRequestUtil.setNoCacheHeaders(res); } else { // set date last modified header CmsFlexController.setDateLastModifiedHeader(res, controller.getDateLastModified()); if ((f_req.getParameterMap().size() == 0) && (controller.getDateLastModified() > -1)) { // only use "expires" header on pages that have no parameters // and that are cachable (i.e. 'date last modified' is set) // otherwise some browsers (e.g. IE 6) will not even try to request // updated versions of the page CmsFlexController.setDateExpiresHeader( res, controller.getDateExpires(), m_clientCacheMaxAge); } } // set response status to "200 - OK" (required for static export "on-demand") res.setStatus(HttpServletResponse.SC_OK); } else { // set previously saved error code res.setStatus(errorCode.intValue()); } // process the headers CmsFlexResponse.processHeaders(f_res.getHeaders(), res); res.getOutputStream().write(result); res.getOutputStream().flush(); } } } catch (IllegalStateException e) { // uncritical, might happen if JSP error page was used LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e); } catch (SocketException e) { // uncritical, might happen if client (browser) does not wait until end of page delivery LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e); } } return result; } /** * Purges the JSP repository.<p< * * @param afterPurgeAction the action to execute after purging */ protected void doPurge(Runnable afterPurgeAction) { if (LOG.isInfoEnabled()) { LOG.info( org.opencms.flex.Messages.get().getBundle().key( org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0)); } File d; d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator); CmsFileUtil.purgeDirectory(d); d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator); CmsFileUtil.purgeDirectory(d); if (afterPurgeAction != null) { afterPurgeAction.run(); } if (LOG.isInfoEnabled()) { LOG.info( org.opencms.flex.Messages.get().getBundle().key( org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0)); } } /** * Generates the taglib directives for a collection of taglib identifiers.<p> * * @param taglibs the taglib identifiers * * @return a string containing taglib directives */ protected String generateTaglibInclusions(Collection<String> taglibs) { StringBuffer buffer = new StringBuffer(); for (String taglib : taglibs) { String uri = m_taglibs.get(taglib); if (uri != null) { buffer.append("<%@ taglib prefix=\"" + taglib + "\" uri=\"" + uri + "\" %>"); } } return buffer.toString(); } /** * Delivers a Flex controller, either by creating a new one, or by re-using an existing one.<p> * * @param cms the initial CmsObject to wrap in the controller * @param resource the resource requested * @param req the current request * @param res the current response * @param streaming indicates if the response is streaming * @param top indicates if the response is the top response * * @return a Flex controller */ protected CmsFlexController getController( CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res, boolean streaming, boolean top) { CmsFlexController controller = null; if (top) { // only check for existing controller if this is the "top" request/response controller = CmsFlexController.getController(req); } if (controller == null) { // create new request / response wrappers if (!cms.getRequestContext().getCurrentProject().isOnlineProject() && (CmsHistoryResourceHandler.isHistoryRequest(req) || CmsJspTagEnableAde.isDirectEditDisabled(req))) { cms.getRequestContext().setAttribute(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT, Boolean.TRUE); } controller = new CmsFlexController(cms, resource, m_cache, req, res, streaming, top); CmsFlexController.setController(req, controller); CmsFlexRequest f_req = new CmsFlexRequest(req, controller); CmsFlexResponse f_res = new CmsFlexResponse(res, controller, streaming, true); controller.push(f_req, f_res); } else if (controller.isForwardMode()) { // reset CmsObject (because of URI) if in forward mode controller = new CmsFlexController(cms, controller); CmsFlexController.setController(req, controller); } return controller; } /** * Initializes the caches.<p> * * @param cacheSize the cache size */ protected void initCaches(int cacheSize) { m_offlineJsps = CmsMemoryMonitor.createLRUCacheMap(cacheSize); m_onlineJsps = CmsMemoryMonitor.createLRUCacheMap(cacheSize); } /** * Parses the JSP and modifies OpenCms critical directive information.<p> * * @param byteContent the original JSP content * @param encoding the encoding to use for the JSP * @param controller the controller for the JSP integration * @param updatedFiles a Set containing all JSP pages that have been already updated * @param isHardInclude indicated if this page is actually a "hard" include with <code>&lt;%@ include file="..." &gt;</code> * * @return the modified JSP content */ protected byte[] parseJsp( byte[] byteContent, String encoding, CmsFlexController controller, Set<String> updatedFiles, boolean isHardInclude) { String content; // make sure encoding is set correctly try { content = new String(byteContent, encoding); } catch (UnsupportedEncodingException e) { // encoding property is not set correctly LOG.error( Messages.get().getBundle().key( Messages.LOG_UNSUPPORTED_ENC_1, controller.getCurrentRequest().getElementUri()), e); try { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); content = new String(byteContent, encoding); } catch (UnsupportedEncodingException e2) { // should not happen since default encoding is always a valid encoding (checked during system startup) content = new String(byteContent); } } // parse for special %(link:...) macros content = parseJspLinkMacros(content, controller); // parse for special <%@cms file="..." %> tag content = parseJspCmsTag(content, controller, updatedFiles); // parse for included files in tags content = parseJspIncludes(content, controller, updatedFiles); // parse for <%@page pageEncoding="..." %> tag content = parseJspEncoding(content, encoding, isHardInclude); // Processes magic taglib attributes in page directives content = processTaglibAttributes(content); // convert the result to bytes and return it try { return content.getBytes(encoding); } catch (UnsupportedEncodingException e) { // should not happen since encoding was already checked return content.getBytes(); } } /** * Parses the JSP content for the special <code>&lt;%cms file="..." %&gt;</code> tag.<p> * * @param content the JSP content to parse * @param controller the current JSP controller * @param updatedFiles a set of already updated jsp files * * @return the parsed JSP content */ protected String parseJspCmsTag(String content, CmsFlexController controller, Set<String> updatedFiles) { // check if a JSP directive occurs in the file int i1 = content.indexOf(DIRECTIVE_START); if (i1 < 0) { // no directive occurs return content; } StringBuffer buf = new StringBuffer(content.length()); int p0 = 0, i2 = 0, slen = DIRECTIVE_START.length(), elen = DIRECTIVE_END.length(); while (i1 >= 0) { // parse the file and replace JSP filename references i2 = content.indexOf(DIRECTIVE_END, i1 + slen); if (i2 < 0) { // wrong syntax (missing end directive) - let the JSP compiler produce the error message return content; } else if (i2 > i1) { String directive = content.substring(i1 + slen, i2); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_DETECTED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; while (directive.charAt(t1) == ' ') { t1++; } String argument = null; if (directive.startsWith("cms", t1)) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_X_DIRECTIVE_DETECTED_1, "cms")); } t2 = directive.indexOf("file", t1 + 3); t5 = 4; } if (t2 > 0) { String sub = directive.substring(t2 + t5); char c1 = sub.charAt(t3); while ((c1 == ' ') || (c1 == '=') || (c1 == '"')) { c1 = sub.charAt(++t3); } t4 = t3; while (c1 != '"') { c1 = sub.charAt(++t4); } if (t4 > t3) { argument = sub.substring(t3, t4); } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_DIRECTIVE_ARG_1, argument)); } } if (argument != null) { // try to update the referenced file String jspname = updateJsp(argument, controller, updatedFiles); if (jspname != null) { directive = jspname; if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_CHANGED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } } // cms directive was found buf.append(content.substring(p0, i1)); buf.append(directive); p0 = i2 + elen; i1 = content.indexOf(DIRECTIVE_START, p0); } else { // cms directive was not found buf.append(content.substring(p0, i1 + slen)); buf.append(directive); p0 = i2; i1 = content.indexOf(DIRECTIVE_START, p0); } } } if (i2 > 0) { // the content of the JSP was changed buf.append(content.substring(p0, content.length())); content = buf.toString(); } return content; } /** * Parses the JSP content for the <code>&lt;%page pageEncoding="..." %&gt;</code> tag * and ensures that the JSP page encoding is set according to the OpenCms * "content-encoding" property value of the JSP.<p> * * @param content the JSP content to parse * @param encoding the encoding to use for the JSP * @param isHardInclude indicated if this page is actually a "hard" include with <code>&lt;%@ include file="..." &gt;</code> * * @return the parsed JSP content */ protected String parseJspEncoding(String content, String encoding, boolean isHardInclude) { // check if a JSP directive occurs in the file int i1 = content.indexOf(DIRECTIVE_START); if (i1 < 0) { // no directive occurs if (isHardInclude) { return content; } } StringBuffer buf = new StringBuffer(content.length() + 64); int p0 = 0, i2 = 0, slen = DIRECTIVE_START.length(); boolean found = false; if (i1 < 0) { // no directive found at all, append content to buffer buf.append(content); } while (i1 >= 0) { // parse the file and set/replace page encoding i2 = content.indexOf(DIRECTIVE_END, i1 + slen); if (i2 < 0) { // wrong syntax (missing end directive) - let the JSP compiler produce the error message return content; } else if (i2 > i1) { String directive = content.substring(i1 + slen, i2); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_DETECTED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; while (directive.charAt(t1) == ' ') { t1++; } String argument = null; if (directive.startsWith("page", t1)) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_X_DIRECTIVE_DETECTED_1, "page")); } t2 = directive.indexOf("pageEncoding", t1 + 4); t5 = 12; if (t2 > 0) { found = true; } } if (t2 > 0) { String sub = directive.substring(t2 + t5); char c1 = sub.charAt(t3); while ((c1 == ' ') || (c1 == '=') || (c1 == '"')) { c1 = sub.charAt(++t3); } t4 = t3; while (c1 != '"') { c1 = sub.charAt(++t4); } if (t4 > t3) { argument = sub.substring(t3, t4); } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_DIRECTIVE_ARG_1, argument)); } } if (argument != null) { // a pageEncoding setting was found, changes have to be made String pre = directive.substring(0, t2 + t3 + t5); String suf = directive.substring(t2 + t3 + t5 + argument.length()); // change the encoding directive = pre + encoding + suf; if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_CHANGED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } } buf.append(content.substring(p0, i1 + slen)); buf.append(directive); p0 = i2; i1 = content.indexOf(DIRECTIVE_START, p0); } } if (i2 > 0) { // the content of the JSP was changed buf.append(content.substring(p0, content.length())); } if (found) { content = buf.toString(); } else if (!isHardInclude) { // encoding setting was not found // if this is not a "hard" include then add the encoding to the top of the page // checking for the hard include is important to prevent errors with // multiple page encoding settings if a template is composed from several hard included elements // this is an issue in Tomcat 4.x but not 5.x StringBuffer buf2 = new StringBuffer(buf.length() + 32); buf2.append("<%@ page pageEncoding=\""); buf2.append(encoding); buf2.append("\" %>"); buf2.append(buf); content = buf2.toString(); } return content; } /** * Parses the JSP content for includes and replaces all OpenCms VFS * path information with information for the real FS.<p> * * @param content the JSP content to parse * @param controller the current JSP controller * @param updatedFiles a set of already updated files * * @return the parsed JSP content */ protected String parseJspIncludes(String content, CmsFlexController controller, Set<String> updatedFiles) { // check if a JSP directive occurs in the file int i1 = content.indexOf(DIRECTIVE_START); if (i1 < 0) { // no directive occurs return content; } StringBuffer buf = new StringBuffer(content.length()); int p0 = 0, i2 = 0, slen = DIRECTIVE_START.length(); while (i1 >= 0) { // parse the file and replace JSP filename references i2 = content.indexOf(DIRECTIVE_END, i1 + slen); if (i2 < 0) { // wrong syntax (missing end directive) - let the JSP compiler produce the error message return content; } else if (i2 > i1) { String directive = content.substring(i1 + slen, i2); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_DETECTED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; while (directive.charAt(t1) == ' ') { t1++; } String argument = null; if (directive.startsWith("include", t1)) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_X_DIRECTIVE_DETECTED_1, "include")); } t2 = directive.indexOf("file", t1 + 7); t5 = 6; } else if (directive.startsWith("page", t1)) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_X_DIRECTIVE_DETECTED_1, "page")); } t2 = directive.indexOf("errorPage", t1 + 4); t5 = 11; } if (t2 > 0) { String sub = directive.substring(t2 + t5); char c1 = sub.charAt(t3); while ((c1 == ' ') || (c1 == '=') || (c1 == '"')) { c1 = sub.charAt(++t3); } t4 = t3; while (c1 != '"') { c1 = sub.charAt(++t4); } if (t4 > t3) { argument = sub.substring(t3, t4); } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_DIRECTIVE_ARG_1, argument)); } } if (argument != null) { // a file was found, changes have to be made String pre = directive.substring(0, t2 + t3 + t5); String suf = directive.substring(t2 + t3 + t5 + argument.length()); // now try to update the referenced file String jspname = updateJsp(argument, controller, updatedFiles); if (jspname != null) { // only change something in case no error had occurred directive = pre + jspname + suf; if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_DIRECTIVE_CHANGED_3, DIRECTIVE_START, directive, DIRECTIVE_END)); } } } buf.append(content.substring(p0, i1 + slen)); buf.append(directive); p0 = i2; i1 = content.indexOf(DIRECTIVE_START, p0); } } if (i2 > 0) { // the content of the JSP was changed buf.append(content.substring(p0, content.length())); content = buf.toString(); } return content; } /** * Parses all jsp link macros, and replace them by the right target path.<p> * * @param content the content to parse * @param controller the request controller * * @return the parsed content */ protected String parseJspLinkMacros(String content, CmsFlexController controller) { CmsJspLinkMacroResolver macroResolver = new CmsJspLinkMacroResolver(controller.getCmsObject(), null, true); return macroResolver.resolveMacros(content); } /** * Returns the jsp resource identified by the given name, using the controllers cms context.<p> * * @param controller the flex controller * @param jspName the name of the jsp * * @return an OpenCms resource * * @throws CmsException if something goes wrong */ protected CmsResource readJspResource(CmsFlexController controller, String jspName) throws CmsException { // create an OpenCms user context that operates in the root site CmsObject cms = OpenCms.initCmsObject(controller.getCmsObject()); // we only need to change the site, but not the project, // since the request has already the right project set cms.getRequestContext().setSiteRoot(""); // try to read the resource return cms.readResource(jspName); } /** * Delivers the plain uninterpreted resource with escaped XML.<p> * * This is intended for viewing historical versions.<p> * * @param cms the initialized CmsObject which provides user permissions * @param file the requested OpenCms VFS resource * @param req the servlet request * @param res the servlet response * * @throws IOException might be thrown by the servlet environment * @throws CmsException in case of errors accessing OpenCms functions */ protected void showSource(CmsObject cms, CmsResource file, HttpServletRequest req, HttpServletResponse res) throws CmsException, IOException { CmsResource historyResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (historyResource == null) { historyResource = file; } CmsFile historyFile = cms.readFile(historyResource); String content = new String(historyFile.getContents()); // change the content-type header so that browsers show plain text res.setContentLength(content.length()); res.setContentType("text/plain"); Writer out = res.getWriter(); out.write(content); out.close(); } /** * Updates a JSP page in the "real" file system in case the VFS resource has changed based on the resource name.<p> * * Generates a resource based on the provided name and calls {@link #updateJsp(CmsResource, CmsFlexController, Set)}.<p> * * @param vfsName the name of the JSP file resource in the VFS * @param controller the controller for the JSP integration * @param updatedFiles a Set containing all JSP pages that have been already updated * * @return the file name of the updated JSP in the "real" FS */ protected String updateJsp(String vfsName, CmsFlexController controller, Set<String> updatedFiles) { String jspVfsName = CmsLinkManager.getAbsoluteUri(vfsName, controller.getCurrentRequest().getElementRootPath()); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_UPDATE_JSP_1, jspVfsName)); } String jspRfsName; try { CmsResource includeResource; try { // first try a root path includeResource = readJspResource(controller, jspVfsName); } catch (CmsVfsResourceNotFoundException e) { // if fails, try a site relative path includeResource = readJspResource( controller, controller.getCmsObject().getRequestContext().addSiteRoot(jspVfsName)); } // make sure the jsp referenced file is generated jspRfsName = updateJsp(includeResource, controller, updatedFiles); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_NAME_REAL_FS_1, jspRfsName)); } } catch (Exception e) { jspRfsName = null; if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_UPDATE_1, jspVfsName), e); } } return jspRfsName; } /** * Updates all jsp files that include the given jsp file using the 'link.strong' macro.<p> * * @param resource the current updated jsp file * @param controller the controller for the jsp integration * @param updatedFiles the already updated files * * @return <code>true</code> if the given JSP file should be updated due to dirty included files * * @throws ServletException might be thrown in the process of including the JSP * @throws IOException might be thrown in the process of including the JSP * @throws CmsLoaderException if the resource type can not be read */ protected boolean updateStrongLinks(CmsResource resource, CmsFlexController controller, Set<String> updatedFiles) throws CmsLoaderException, IOException, ServletException { int numberOfUpdates = updatedFiles.size(); CmsObject cms = controller.getCmsObject(); CmsRelationFilter filter = CmsRelationFilter.TARGETS.filterType(CmsRelationType.JSP_STRONG); Iterator<CmsRelation> it; try { it = cms.getRelationsForResource(resource, filter).iterator(); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } return false; } while (it.hasNext()) { CmsRelation relation = it.next(); CmsResource target = null; try { target = relation.getTarget(cms, CmsResourceFilter.DEFAULT); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } continue; } // prevent recursive update when including the same file if (resource.equals(target)) { continue; } // update the target updateJsp(target, controller, updatedFiles); } // the current jsp file should be updated only if one of the included jsp has been updated return numberOfUpdates < updatedFiles.size(); } /** * Returns the read-write-lock for the given jsp vfs name.<p> * * @param jspVfsName the jsp vfs name * * @return the read-write-lock */ private ReentrantReadWriteLock getFileLock(String jspVfsName) { ReentrantReadWriteLock lock = m_fileLocks.get(jspVfsName); if (lock == null) { synchronized (m_fileLocks) { if (!m_fileLocks.containsKey(jspVfsName)) { m_fileLocks.put(jspVfsName, new ReentrantReadWriteLock(true)); } lock = m_fileLocks.get(jspVfsName); } } return lock; } /** * Returns the RFS path for a JSP resource.<p> * * This does not check whether there actually exists a file at the returned path. * * @param resource the JSP resource * @param online true if the path for the online project should be returned * * @return the RFS path for the JSP * * @throws CmsLoaderException if accessing the resource loader fails */ private String getJspRfsPath(CmsResource resource, boolean online) throws CmsLoaderException { String jspVfsName = resource.getRootPath(); String extension; int loaderId = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getLoaderId(); if ((loaderId == CmsJspLoader.RESOURCE_LOADER_ID) && (!jspVfsName.endsWith(JSP_EXTENSION))) { // this is a true JSP resource that does not end with ".jsp" extension = JSP_EXTENSION; } else { // not a JSP resource or already ends with ".jsp" extension = ""; } String jspPath = CmsFileUtil.getRepositoryName(m_jspRepository, jspVfsName + extension, online); return jspPath; } }
lgpl-2.1
OpenNMS/jrobin
src/main/java/org/jrobin/data/SDef.java
1964
/******************************************************************************* * Copyright (c) 2001-2005 Sasa Markovic and Ciaran Treanor. * Copyright (c) 2011 The OpenNMS Group, Inc. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ package org.jrobin.data; import org.jrobin.core.RrdException; class SDef extends Source { private String defName; private String consolFun; private double value; SDef(String name, String defName, String consolFun) { super(name); this.defName = defName; this.consolFun = consolFun; } String getDefName() { return defName; } String getConsolFun() { return consolFun; } void setValue(double value) { this.value = value; int count = getTimestamps().length; double[] values = new double[count]; for (int i = 0; i < count; i++) { values[i] = value; } setValues(values); } Aggregates getAggregates(long tStart, long tEnd) throws RrdException { Aggregates agg = new Aggregates(); agg.first = agg.last = agg.min = agg.max = agg.average = value; agg.total = value * (tEnd - tStart); return agg; } double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { return value; } }
lgpl-2.1
ethaneldridge/vassal
src/org/litesoft/p2pchat/PendingPeerManager.java
6831
package org.litesoft.p2pchat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; // Copyright Status: // // All Software available from LiteSoft.org (including this file) is // hereby released into the public domain. // // It is free! As in, you may use it freely in both commercial and // non-commercial applications, bundle it with your software // distribution, include it on a CD-ROM, list the source code in a book, // mirror the documentation at your own web site, or use it in any other // way you see fit. // // NO Warranty! // // All software is provided "as is". // // There is ABSOLUTELY NO WARRANTY OF ANY KIND: not for the design, fitness // (for a particular purpose), level of errors (or lack thereof), or // applicability of this software. The entire risk as to the quality // and performance of this software is with you. Should this software // prove defective, you assume the cost of all necessary servicing, repair // or correction. // // In no event unless required by applicable law or agreed to in writing // will any party who created or may modify and/or redistribute this // software, be liable to you for damages, including any general, // special, incidental or consequential damages arising out of the use or // inability to use this software (including but not limited to loss of // data or data being rendered inaccurate or losses sustained by you or // third parties or a failure of this software to operate with any // other programs), even if such holder or other party has been advised // of the possibility of such damages. // // NOTE: Should you discover a bug, have a recogmendation for a change, wish // to submit modifications, or wish to add new classes/functionality, // please email them to: // // changes@litesoft.org // /** * @author Devin Smith and George Smith * @version 0.4 04/06/13 Add finish() to cleanly stop the PPM thread * @version 0.3 02/02/02 Added IllegalArgument.ifNull for all public params that may not be null * @version 0.2 01/28/02 Refactored and Added Licence * @version 0.1 12/27/01 Initial Version */ public class PendingPeerManager extends Thread implements NewPeersSupport { private UserDialog zUserDialog; private PendingPeerLinkedList zPendingPeers = new PendingPeerLinkedList(); private PendingPeersSupport zPendingPeersSupport = null; private int maxRetries = 3; private boolean finish = false; public PendingPeerManager(UserDialog pUserDialog) { IllegalArgument.ifNull("UserDialog", zUserDialog = pUserDialog); zUserDialog.setPendingPeerManager(this); } public void start(PendingPeersSupport pPendingPeersSupport) { IllegalArgument.ifNull("PendingPeersSupport", zPendingPeersSupport = pPendingPeersSupport); start(); } public void addNewPeer(PeerInfo pInfo) { IllegalArgument.ifNull("Info", pInfo); zPendingPeers.add(null, pInfo); } public void addNewPeer(Socket pSocket) { IllegalArgument.ifNull("Socket", pSocket); InetAddress theirAddress = pSocket.getInetAddress(); String theirName = theirAddress.getHostName(); String theirIP = theirAddress.getHostAddress(); String name = theirIP.equals(theirName) ? null : "(Host: " + theirName + ")"; zPendingPeers.add(pSocket, new PeerInfo(name, theirIP)); } public void addNewPeer(PeerInfo info, PeerReader reader, PeerWriter writer) { zPendingPeersSupport.addActivePeer(info, reader, writer); } public void run() { while (true) { final PendingPeerNode next = zPendingPeers.next(); if (finish) { return; } Runnable runnable = new Runnable() { public void run() { handleNewPeerClient(next); } }; new Thread(runnable).start(); } } public void finish() { finish = true; interrupt(); } private void handleNewPeerClient(PendingPeerNode pPendingPeerNode) { PeerInfo peerInfo = pPendingPeerNode.getPeerInfo(); if (zPendingPeersSupport.isAlreadyConnected(peerInfo)) { return; } if ("true".equals(System.getProperty("debug"))) { System.err.println("Attempting to contact " + peerInfo.format()); } Socket socket = pPendingPeerNode.getSocket(); if (socket == null) { try { socket = getPeerClientSocketFromAddresses(peerInfo); } catch (IOException e) { if ("true".equals(System.getProperty("debug"))) { System.err.println("Failed to establish connection to " + peerInfo.format() + ": " + e.getMessage()); } // If we're under the maximum number of retries, send this peer to the end of the queue if (peerInfo.incrementFailureCount() <= maxRetries) { zPendingPeers.add(socket, peerInfo); } else { if ("true".equals(System.getProperty("debug"))) { System.err.println("Maximum retries reached for " + peerInfo.format()); } peerInfo.setFailureReason(e); zUserDialog.showConnectFailed(peerInfo); } return; } } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); } catch (IOException e) { zUserDialog.showStreamsFailed(peerInfo); try { socket.close(); } catch (IOException ignore) { } return; } zPendingPeersSupport.addActivePeer(peerInfo, inputStream, outputStream); zUserDialog.showConnect(peerInfo); } private Socket getPeerClientSocketFromAddresses(PeerInfo pPeerInfo) throws IOException { String pPeerAddresses = pPeerInfo.getAddresses(); int peerPort = pPeerInfo.getPort(); for (int i; -1 != (i = pPeerAddresses.indexOf(',')); pPeerAddresses = pPeerAddresses.substring(i + 1)) { try { return getPeerClientSocket(pPeerAddresses.substring(0, i), peerPort); } catch (IOException e) { if ("true".equals(System.getProperty("debug"))) { System.err.println("Failed to establish connection to " + pPeerAddresses.substring(0, i) + ":" + peerPort + ". " + e.getMessage()); } } } return getPeerClientSocket(pPeerAddresses, peerPort); } private Socket getPeerClientSocket(String pPeerAddress, int pPeerPort) throws IOException { Socket retval = new Socket(pPeerAddress, pPeerPort); if ("true".equals(System.getProperty("debug"))) { System.err.println("Established connection to " + pPeerAddress + ":" + pPeerPort); } return retval; } public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } public void setSocketConnectTimeout(long socketConnectTimeout) { } }
lgpl-2.1
codeaudit/openccg
src/opennlp/ccg/hylo/graph/LFGraphFactory.java
6697
////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2012 Scott Martin // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// package opennlp.ccg.hylo.graph; import static opennlp.ccg.hylo.HyloHelper.isAttrPred; import static opennlp.ccg.hylo.HyloHelper.isElementaryPredication; import static opennlp.ccg.hylo.HyloHelper.isLexPred; import static opennlp.ccg.hylo.HyloHelper.isRelPred; import java.util.List; import java.util.Map; import opennlp.ccg.hylo.Diamond; import opennlp.ccg.hylo.Flattener; import opennlp.ccg.hylo.HyloHelper; import opennlp.ccg.hylo.Nominal; import opennlp.ccg.hylo.Proposition; import opennlp.ccg.hylo.SatOp; import opennlp.ccg.realize.Realizer; import opennlp.ccg.synsem.LF; import org.jdom.Element; import org.jdom.input.DOMBuilder; /** * Factory class for creating LF graphs based on {@link LF}s and XML elements * that represent them. Graph factories cannot be instantiated, however, their * methods for building LF graphs are statically accessible. * * @author <a href="http://www.ling.ohio-state.edu/~scott/">Scott Martin</a> * @see LFGraph * @see LFGraphFactory#newGraphFrom(LF) */ public class LFGraphFactory { /** * An instance of {@link DefaultLFEdgeFactory}. */ public static final LFEdgeFactory DEFAULT_EDGE_FACTORY = new DefaultLFEdgeFactory(); static final DOMBuilder DOM_BUILDER = new DOMBuilder(); static final Flattener FLATTENER = new Flattener(); private LFGraphFactory() { // can't instantiate } /** * Builds a new LF graph based on the representation provided in the specified w3c XML element. * @param lfElement The XML element with root element tagged <tt>lf</tt>. * @return The value of {@link #newGraphFrom(Element)} after using a {@link DOMBuilder} to create a * jdom document. * * @see #newGraphFrom(Element) */ public static LFGraph newGraphFrom(org.w3c.dom.Element lfElement) { return newGraphFrom(DOM_BUILDER.build(lfElement)); } /** * Creates a new LF graph from the corresponding representation contained in the specified * jdom XML element. * @param lfElement The jdom element containing the representation of the LF. * @return An LF graph build from an {@link LF} object obtained by calling * {@link Realizer#getLfFromElt(Element)}. * * @see LFGraphFactory#newGraphFrom(LF) */ public static LFGraph newGraphFrom(Element lfElement) { return newGraphFrom(Realizer.getLfFromElt(lfElement)); } /** * Creates a new LF graph based on the specified LF object. The LF object is first flattened, and then * its LF ancestry structure is obtained by calling {@link Flattener#getHighestParentMap()}. * <p> * This method makes two passes over the list of {@link SatOp}s obtained by flattening the specified LF. * The first pass adds vertices to the graph for every lexical predication, as determined by calling * {@link HyloHelper#isLexPred(LF)} on the {@linkplain SatOp#getNominal() SatOp's nominal} and * {@linkplain SatOp#getArg() proposition argument}. * <p> * The second pass proceeds by cases, depending on the nature of the SatOp in question: * <dl> * <dt>Lexical predications</dt> * <dd>cause the new LF graph to be updated with the corresponding LF ancestry, as determined by * {@link Flattener#getHighestParentMap()}.</dd> * <dt>Relation predications</dt> * <dd>cause a new {@link LFEdge} to be added to the LF graph based on the * {@linkplain SatOp#getArg() SatOp's argument} and {@linkplain Diamond#getMode() the argument's * mode}.</dd> * <dt>Attribute-value predications</dt> * <dd>cause the vertex corresponding to the {@linkplain SatOp#getNominal() SatOp's nominal} to have * attributes {@linkplain LFVertex#setAttribute(opennlp.ccg.hylo.Mode, Proposition) added} based on * the {@linkplain SatOp#getArg() SatOp's argument}.</dd> * </dl> * where the nature of the SatOp in question is determined using {@link HyloHelper#isLexPred(LF)}, * {@link HyloHelper#isRelPred(LF)}, and {@link HyloHelper#isAttrPred(LF)}. * * @param lf The LF object to build an LF graph for. * @return A new LF graph whose vertices represent the nominals in the LF's flattened representation and * whose edges represent its relation predications. * @throws IllegalArgumentException If <tt>lf</tt> is <tt>null</tt>. */ public static LFGraph newGraphFrom(LF lf) { if(lf == null) { throw new IllegalArgumentException("lf is null"); } LFGraph g = new LFGraph(DEFAULT_EDGE_FACTORY); Flattener f = new Flattener(); List<SatOp> satOps = f.flatten(lf); Map<Nominal,Nominal> ancestorMap = f.getHighestParentMap(); for(SatOp so : satOps) { // first pass adds vertices if(isLexPred(so)) { g.addVertex(new LFVertex(so.getNominal(), (Proposition)so.getArg())); } } for(SatOp so : satOps) { // second pass adds edges and attributes, sets highest parent (if any) if(isElementaryPredication(so)) { Nominal soNom = so.getNominal(); LFVertex source = g.findVertexByNominal(soNom); // check if node is not yet added (not a lex. pred.) if(source == null) { source = new LFVertex(soNom); g.addVertex(source); } if(isLexPred(so)) { Nominal parent = ancestorMap.get(source.nominal); if(parent != null) { g.highestAncestorMap.put(source, g.findVertexByNominal(parent)); } } else if(isRelPred(so)) { Diamond d = (Diamond)so.getArg(); Nominal dArg = (Nominal)d.getArg(); LFVertex target = g.findVertexByNominal(dArg); if(target == null) { target = new LFVertex(dArg); g.addVertex(target); } g.addLabeledEdge(source, target, LFEdgeLabel.forMode(d.getMode())); } else if(isAttrPred(so)) { Diamond d = (Diamond)so.getArg(); source.addAttribute(d.getMode(), (Proposition)d.getArg()); } } } return g; } }
lgpl-2.1
lucene-gosen/lucene-gosen
src/main/java/org/apache/lucene/analysis/gosen/tokenAttributes/PartOfSpeechAttribute.java
1149
/* * 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.lucene.analysis.gosen.tokenAttributes; import net.java.sen.dictionary.Morpheme; import org.apache.lucene.util.Attribute; /** * Attribute for {@link Morpheme#getPartOfSpeech()}. */ public interface PartOfSpeechAttribute extends Attribute { public String getPartOfSpeech(); public void setMorpheme(Morpheme morpheme); }
lgpl-2.1
Sable/polyglot
src/polyglot/ext/jl/ast/Lit_c.java
845
package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; import java.util.List; /** * <code>Lit</code> represents any Java literal. */ public abstract class Lit_c extends Expr_c implements Lit { public Lit_c(Position pos) { super(pos); } /** Get the precedence of the expression. */ public Precedence precedence() { return Precedence.LITERAL; } /** * Return the first (sub)term performed when evaluating this * term. */ public Term entry() { return this; } /** * Visit this term in evaluation order. */ public List acceptCFG(CFGBuilder v, List succs) { return succs; } public boolean isConstant() { return true; } public abstract Object constantValue(); }
lgpl-2.1
pixlepix/MineChem
src/main/java/buildcraft/api/core/Position.java
3373
/** * Copyright (c) SpaceToad, 2011 * http://www.mod-buildcraft.com * * BuildCraft is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.api.core; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.ForgeDirection; public class Position { public double x, y, z; public ForgeDirection orientation; public Position(double ci, double cj, double ck) { x = ci; y = cj; z = ck; orientation = ForgeDirection.UNKNOWN; } public Position(double ci, double cj, double ck, ForgeDirection corientation) { x = ci; y = cj; z = ck; orientation = corientation; } public Position(Position p) { x = p.x; y = p.y; z = p.z; orientation = p.orientation; } public Position(NBTTagCompound nbttagcompound) { x = nbttagcompound.getDouble("i"); y = nbttagcompound.getDouble("j"); z = nbttagcompound.getDouble("k"); orientation = ForgeDirection.UNKNOWN; } public Position(TileEntity tile) { x = tile.xCoord; y = tile.yCoord; z = tile.zCoord; } public void moveRight(double step) { switch (orientation) { case SOUTH: x = x - step; break; case NORTH: x = x + step; break; case EAST: z = z + step; break; case WEST: z = z - step; break; default: } } public void moveLeft(double step) { moveRight(-step); } public void moveForwards(double step) { switch (orientation) { case UP: y = y + step; break; case DOWN: y = y - step; break; case SOUTH: z = z + step; break; case NORTH: z = z - step; break; case EAST: x = x + step; break; case WEST: x = x - step; break; default: } } public void moveBackwards(double step) { moveForwards(-step); } public void moveUp(double step) { switch (orientation) { case SOUTH: case NORTH: case EAST: case WEST: y = y + step; break; default: } } public void moveDown(double step) { moveUp(-step); } public void writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setDouble("i", x); nbttagcompound.setDouble("j", y); nbttagcompound.setDouble("k", z); } @Override public String toString() { return "{" + x + ", " + y + ", " + z + "}"; } public Position min(Position p) { return new Position(p.x > x ? x : p.x, p.y > y ? y : p.y, p.z > z ? z : p.z); } public Position max(Position p) { return new Position(p.x < x ? x : p.x, p.y < y ? y : p.y, p.z < z ? z : p.z); } }
lgpl-2.1
xwiki-labs/sankoreorg
xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/plugin/charts/params/NumberFormatChartParam.java
3562
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.plugin.charts.params; import java.text.NumberFormat; import java.util.Locale; import java.util.Map; import com.xpn.xwiki.plugin.charts.exceptions.InvalidArgumentException; import com.xpn.xwiki.plugin.charts.exceptions.MissingArgumentException; import com.xpn.xwiki.plugin.charts.exceptions.ParamException; public class NumberFormatChartParam extends LocaleChartParam { public static final String TYPE = "type"; public static final String GENERAL = "general"; public static final String NUMBER = "number"; public static final String INTEGER = "integer"; public static final String CURRENCY = "currency"; public static final String PERCENT = "percent"; public NumberFormatChartParam(String name) { super(name); } public NumberFormatChartParam(String name, boolean optional) { super(name, optional); } @Override public Class getType() { return NumberFormat.class; } @Override public Object convert(String value) throws ParamException { Map map = parseMap(value); String type = getStringArg(map, TYPE); Locale locale; try { locale = (Locale) super.convert(value); } catch (MissingArgumentException e) { locale = null; } if (type.equals(GENERAL)) { if (locale != null) { return NumberFormat.getInstance(locale); } else { return NumberFormat.getInstance(); } } else if (type.equals(NUMBER)) { if (locale != null) { return NumberFormat.getNumberInstance(locale); } else { return NumberFormat.getNumberInstance(); } } else if (type.equals(INTEGER)) { if (locale != null) { return NumberFormat.getIntegerInstance(locale); } else { return NumberFormat.getIntegerInstance(); } } else if (type.equals(CURRENCY)) { if (locale != null) { return NumberFormat.getCurrencyInstance(locale); } else { return NumberFormat.getCurrencyInstance(); } } else if (type.equals(PERCENT)) { if (locale != null) { return NumberFormat.getPercentInstance(locale); } else { return NumberFormat.getPercentInstance(); } } else { throw new InvalidArgumentException("Invalid value for parameter " + getName() + ": Unexpected value for type argument: " + type); } } }
lgpl-2.1
MrRiegel/Kind-of-Magic
src/main/java/mrriegel/rwl/item/ItemFlyer.java
1916
package mrriegel.rwl.item; import mrriegel.rwl.init.ModItems; import mrriegel.rwl.inventory.InventoryTaliBag; import mrriegel.rwl.reference.Reference; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class ItemFlyer extends ItemTalisman { public ItemFlyer() { super(); this.setUnlocalizedName(Reference.MOD_ID + ":" + "flyer"); this.setTextureName(Reference.MOD_ID + ":" + "flyer"); } @Override public void perform(EntityPlayer player) { player.capabilities.allowFlying = true; } @SubscribeEvent public void anti(LivingUpdateEvent event) { if (event.entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.entity; int contains = -1; for (int i = 0; i < player.inventory.mainInventory.length; i++) { if (player.inventory.mainInventory[i] == null) continue; if (player.inventory.mainInventory[i].getItem().equals( ModItems.tbag)) { contains = i; break; } } boolean anti = false; if (contains != -1) { ItemStack bag = player.inventory.mainInventory[contains]; for (int i = 0; i < 6; i++) { try { ItemStack invStack = ItemStack.loadItemStackFromNBT(bag .getTagCompound() .getTagList(InventoryTaliBag.tagName, bag.getTagCompound().getId()) .getCompoundTagAt(i)); if (invStack == null) continue; if (invStack.getItem().equals(ModItems.flyer)) { anti = true; break; } } catch (NullPointerException e) { } } } if ((!anti && !player.capabilities.isCreativeMode) || !TaliBag.validCount(player)) { player.capabilities.allowFlying = false; if (player.capabilities.isFlying) player.capabilities.isFlying = false; } } } }
lgpl-2.1
Qingbao/PasswdManagerAndroid
src/noconflict/org/bouncycastle/asn1/DERExternalParser.java
1117
package noconflict.org.bouncycastle.asn1; import java.io.IOException; public class DERExternalParser implements DEREncodable, InMemoryRepresentable { private ASN1StreamParser _parser; /** * */ public DERExternalParser(ASN1StreamParser parser) { this._parser = parser; } public DEREncodable readObject() throws IOException { return _parser.readObject(); } public DERObject getLoadedObject() throws IOException { try { return new DERExternal(_parser.readVector()); } catch (IllegalArgumentException e) { throw new ASN1Exception(e.getMessage(), e); } } public DERObject getDERObject() { try { return getLoadedObject(); } catch (IOException ioe) { throw new ASN1ParsingException("unable to get DER object", ioe); } catch (IllegalArgumentException ioe) { throw new ASN1ParsingException("unable to get DER object", ioe); } } }
lgpl-2.1
pbondoer/xwiki-platform
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/user/impl/xwiki/AppServerTrustedAuthServiceImpl.java
2659
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.user.impl.xwiki; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.user.api.XWikiUser; /** * Implements an authentication mechanism which is trusting the App Server authentication. If it fails it falls back to * the standard XWiki authentication. * * @version $Id$ */ public class AppServerTrustedAuthServiceImpl extends XWikiAuthServiceImpl { private static final Logger LOGGER = LoggerFactory.getLogger(AppServerTrustedAuthServiceImpl.class); @Override public XWikiUser checkAuth(XWikiContext context) throws XWikiException { String user = context.getRequest().getRemoteUser(); if ((user == null) || user.equals("")) { return super.checkAuth(context); } else { LOGGER.debug("Launching create user for [{}]", user); createUser(user, context); LOGGER.debug("Create user done for [{}]", user); user = "XWiki." + user; } context.setUser(user); return new XWikiUser(user); } /** * We cannot authenticate locally since we need to trust the app server for authentication. */ @Override public XWikiUser checkAuth(String username, String password, String rememberme, XWikiContext context) throws XWikiException { String user = context.getRequest().getRemoteUser(); if ((user == null) || user.equals("")) { return super.checkAuth(username, password, rememberme, context); } else { createUser(user, context); user = "XWiki." + user; } context.setUser(user); return new XWikiUser(user); } }
lgpl-2.1
IlyaAI/xacml4j
xacml-core/src/main/java/org/xacml4j/v30/spi/pip/XacmlContentResolverDescriptor.java
1189
package org.xacml4j.v30.spi.pip; /* * #%L * Xacml4J Core Engine Implementation * %% * Copyright (C) 2009 - 2014 Xacml4J.org * %% * This program 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface XacmlContentResolverDescriptor { String id(); String name(); String category(); int cacheTTL() default 0; }
lgpl-3.0
jspresso/jspresso-ce
model/src/main/java/org/jspresso/framework/model/descriptor/basic/EFetchType.java
1121
/* * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved. * * This file is part of the Jspresso framework. * * Jspresso 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 3 of the License, or * (at your option) any later version. * * Jspresso 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 Jspresso. If not, see <http://www.gnu.org/licenses/>. */ package org.jspresso.framework.model.descriptor.basic; /** * Relationship fetch policy. * * @author Vincent Vandenschrick */ public enum EFetchType { /** * {@code JOIN} fetch type. */ JOIN, /** * {@code SELECT} fetch type. */ SELECT, /** * {@code SUBSELECT} fetch type. */ SUBSELECT }
lgpl-3.0
guyue123/ly
ly-luoying-desktop/src/name/huliqing/ly/object/game/story/AbstractTaskStep.java
1716
/* * LuoYing is a program used to make 3D RPG game. * Copyright (c) 2014-2016 Huliqing <31703299@qq.com> * * This file is part of LuoYing. * * LuoYing 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 3 of the License, or * (at your option) any later version. * * LuoYing 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 LuoYing. If not, see <http://www.gnu.org/licenses/>. */ package name.huliqing.ly.object.game.story; /** * 简单的游戏任务逻辑 * @author huliqing */ public abstract class AbstractTaskStep implements TaskStep{ protected boolean started; public AbstractTaskStep() {} @Override public final void start(TaskStep previous) { doInit(previous); started = true; } @Override public void update(float tpf) { if (!started) return; doLogic(tpf); } @Override public void cleanup() { started = false; } /** * 初始化任务 * @param previous 前一个任务,部分任务可能需要前一个任务的信息。 */ protected abstract void doInit(TaskStep previous); /** * 执行任务逻辑 * @param tpf */ protected abstract void doLogic(float tpf); }
lgpl-3.0
ambrinchaudhary/com-liferay-adaptive-media
adaptive-media-image-impl/src/test/java/com/liferay/adaptive/media/image/internal/handler/PathInterpreterTest.java
4983
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * 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. */ package com.liferay.adaptive.media.image.internal.handler; import com.liferay.adaptive.media.exception.AMRuntimeException; import com.liferay.adaptive.media.image.configuration.AMImageConfigurationEntry; import com.liferay.adaptive.media.image.configuration.AMImageConfigurationHelper; import com.liferay.adaptive.media.image.internal.configuration.AMImageConfigurationHelperImpl; import com.liferay.adaptive.media.image.internal.util.Tuple; import com.liferay.document.library.kernel.service.DLAppService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.repository.model.FileVersion; import com.liferay.portal.kernel.util.StringUtil; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * @author Adolfo Pérez */ public class PathInterpreterTest { @Before public void setUp() { _pathInterpreter.setDLAppService(_dlAppService); _pathInterpreter.setAMImageConfigurationHelper( _amImageConfigurationHelper); } @Test public void testFileEntryPath() throws Exception { Mockito.when( _dlAppService.getFileEntry(Mockito.anyLong()) ).thenReturn( _fileEntry ); Mockito.when( _fileEntry.getFileVersion() ).thenReturn( _fileVersion ); Mockito.when( _amImageConfigurationHelper.getAMImageConfigurationEntry( Mockito.anyLong(), Mockito.eq("x")) ).thenReturn( Optional.of(_amImageConfigurationEntry) ); _pathInterpreter.interpretPath("/image/0/x/foo.jpg"); Mockito.verify( _dlAppService ).getFileEntry( 0 ); Mockito.verify( _fileVersion ).getCompanyId(); Mockito.verify( _amImageConfigurationEntry ).getProperties(); Mockito.verify( _amImageConfigurationEntry ).getUUID(); } @Test(expected = AMRuntimeException.class) public void testFileEntryPathDLAppFailure() throws Exception { Mockito.when( _dlAppService.getFileEntry(0) ).thenThrow( PortalException.class ); _pathInterpreter.interpretPath("/image/0/x/foo.jpg"); } @Test(expected = AMRuntimeException.class) public void testFileEntryPathGetFileVersionFailure() throws Exception { Mockito.when( _dlAppService.getFileEntry(0) ).thenReturn( _fileEntry ); Mockito.when( _fileEntry.getFileVersion() ).thenThrow( PortalException.class ); _pathInterpreter.interpretPath("/image/0/x/foo.jpg"); } @Test public void testFileVersionPath() throws Exception { Mockito.when( _dlAppService.getFileVersion(1) ).thenReturn( _fileVersion ); Mockito.when( _amImageConfigurationHelper.getAMImageConfigurationEntry( Mockito.anyLong(), Mockito.eq("x")) ).thenReturn( Optional.of(_amImageConfigurationEntry) ); _pathInterpreter.interpretPath("/image/0/1/x/foo.jpg"); Mockito.verify( _dlAppService ).getFileEntry( 0 ); Mockito.verify( _dlAppService ).getFileVersion( 1 ); Mockito.verify( _fileVersion ).getCompanyId(); Mockito.verify( _amImageConfigurationEntry ).getProperties(); Mockito.verify( _amImageConfigurationEntry ).getUUID(); } @Test(expected = AMRuntimeException.class) public void testFileVersionPathDLAppFailure() throws Exception { Mockito.when( _dlAppService.getFileVersion(1) ).thenThrow( PortalException.class ); _pathInterpreter.interpretPath("/image/0/1/x/foo.jpg"); } @Test public void testNonMatchingPathInfo() { Optional<Tuple<FileVersion, Map<String, String>>> resultOptional = _pathInterpreter.interpretPath("/" + StringUtil.randomString()); Assert.assertFalse(resultOptional.isPresent()); } @Test(expected = IllegalArgumentException.class) public void testNullPathInfoFails() { _pathInterpreter.interpretPath(null); } private final AMImageConfigurationEntry _amImageConfigurationEntry = Mockito.mock(AMImageConfigurationEntry.class); private final AMImageConfigurationHelper _amImageConfigurationHelper = Mockito.mock(AMImageConfigurationHelperImpl.class); private final DLAppService _dlAppService = Mockito.mock(DLAppService.class); private final FileEntry _fileEntry = Mockito.mock(FileEntry.class); private final FileVersion _fileVersion = Mockito.mock(FileVersion.class); private final PathInterpreter _pathInterpreter = new PathInterpreter(); }
lgpl-3.0
Albloutant/Galacticraft
dependencies/codechicken/lib/render/ColourMultiplier.java
861
package codechicken.lib.render; import net.minecraft.client.renderer.Tessellator; import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourRGBA; import codechicken.lib.vec.Vector3; public class ColourMultiplier implements IVertexModifier { public Colour colour; public ColourMultiplier(Colour colour) { this.colour = colour; } public ColourMultiplier(int colour) { this(new ColourRGBA(colour)); } @Override public void applyModifiers(CCModel m, Tessellator tess, Vector3 vec, UV uv, Vector3 normal, int i) { if(CCRenderState.useModelColours() && m != null && m.colours != null) CCRenderState.vertexColour(new ColourRGBA(m.colours[i]).multiply(colour).rgba()); } @Override public boolean needsNormals() { return false; } }
lgpl-3.0
OldShatterhand77/Portofino
portofino-admin/src/main/java/com/manydesigns/portofino/modules/AdminModule.java
7238
/* * Copyright (C) 2005-2015 ManyDesigns srl. All rights reserved. * http://www.manydesigns.com/ * * This 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 3 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.manydesigns.portofino.modules; import com.manydesigns.portofino.actions.admin.SettingsAction; import com.manydesigns.portofino.actions.admin.appwizard.ApplicationWizard; import com.manydesigns.portofino.actions.admin.database.ConnectionProvidersAction; import com.manydesigns.portofino.actions.admin.database.ReloadModelAction; import com.manydesigns.portofino.actions.admin.database.TablesAction; import com.manydesigns.portofino.actions.admin.groovy.GroovyAdminAction; import com.manydesigns.portofino.actions.admin.mail.MailSettingsAction; import com.manydesigns.portofino.actions.admin.modules.ModulesAction; import com.manydesigns.portofino.actions.admin.info.InfoAction; import com.manydesigns.portofino.actions.admin.page.RootChildrenAction; import com.manydesigns.portofino.actions.admin.page.RootPermissionsAction; import com.manydesigns.portofino.actions.admin.servletcontext.ServletContextAction; import com.manydesigns.portofino.di.Inject; import com.manydesigns.portofino.menu.MenuBuilder; import com.manydesigns.portofino.menu.SimpleMenuAppender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; /* * @author Paolo Predonzani - paolo.predonzani@manydesigns.com * @author Angelo Lupo - angelo.lupo@manydesigns.com * @author Giampiero Granatella - giampiero.granatella@manydesigns.com * @author Alessio Stalla - alessio.stalla@manydesigns.com */ public class AdminModule implements Module { public static final String copyright = "Copyright (c) 2005-2015, ManyDesigns srl"; public final static String ADMIN_MENU = "com.manydesigns.portofino.menu.Menu.admin"; //************************************************************************** // Fields //************************************************************************** @Inject(BaseModule.SERVLET_CONTEXT) public ServletContext servletContext; protected ModuleStatus status = ModuleStatus.CREATED; //************************************************************************** // Logging //************************************************************************** public static final Logger logger = LoggerFactory.getLogger(AdminModule.class); @Override public String getModuleVersion() { return ModuleRegistry.getPortofinoVersion(); } @Override public int getMigrationVersion() { return 1; } @Override public double getPriority() { return 30; } @Override public String getId() { return "admin"; } @Override public String getName() { return "Admin"; } @Override public int install() { return 1; } @Override public void init() { logger.debug("Installing standard menu builders"); MenuBuilder adminMenu = new MenuBuilder(); SimpleMenuAppender group; SimpleMenuAppender link; //General configuration group = SimpleMenuAppender.group("info", null, "info", 1.0); adminMenu.menuAppenders.add(group); link = SimpleMenuAppender.link( "info", "info", null, "info", InfoAction.URL_BINDING, 1.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "info", "modules", null, "modules", ModulesAction.URL_BINDING, 2.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "info", "servlet-context", null, "servlet.context", ServletContextAction.URL_BINDING, 3.0); adminMenu.menuAppenders.add(link); //General configuration group = SimpleMenuAppender.group("configuration", null, "configuration", 2.0); adminMenu.menuAppenders.add(group); link = SimpleMenuAppender.link( "configuration", "settings", null, "settings", SettingsAction.URL_BINDING, 1.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "configuration", "topLevelPages", null, "top.level.pages", RootChildrenAction.URL_BINDING, 2.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "configuration", "groovy", null, "groovy", GroovyAdminAction.URL_BINDING, 3.0); adminMenu.menuAppenders.add(link); //Security group = SimpleMenuAppender.group("security", null, "security", 3.0); adminMenu.menuAppenders.add(group); link = SimpleMenuAppender.link( "security", "rootPermissions", null, "root.permissions", RootPermissionsAction.URL_BINDING, 1.0); adminMenu.menuAppenders.add(link); //Database & modeling group = SimpleMenuAppender.group("dataModeling", null, "data.modeling", 4.0); adminMenu.menuAppenders.add(group); link = SimpleMenuAppender.link( "dataModeling", "wizard", null, "wizard", ApplicationWizard.URL_BINDING, 1.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "dataModeling", "connectionProviders", null, "connection.providers", ConnectionProvidersAction.URL_BINDING, 2.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "dataModeling", "tables", null, "tables", TablesAction.BASE_ACTION_PATH, 3.0); adminMenu.menuAppenders.add(link); link = SimpleMenuAppender.link( "dataModeling", "reloadModel", null, "reload.model", ReloadModelAction.URL_BINDING, 4.0); adminMenu.menuAppenders.add(link); //Mail group = SimpleMenuAppender.group("mail", null, "mail", 5.0); adminMenu.menuAppenders.add(group); link = SimpleMenuAppender.link( "mail", "Mail", null, "mail", MailSettingsAction.URL_BINDING, 1.0); adminMenu.menuAppenders.add(link); servletContext.setAttribute(ADMIN_MENU, adminMenu); status = ModuleStatus.ACTIVE; } @Override public void start() { status = ModuleStatus.STARTED; } @Override public void stop() { status = ModuleStatus.STOPPED; } @Override public void destroy() { status = ModuleStatus.DESTROYED; } @Override public ModuleStatus getStatus() { return status; } }
lgpl-3.0
davidmc24/restwars
service/src/main/java/restwars/service/points/PointsService.java
1009
package restwars.service.points; import restwars.model.player.Player; import restwars.model.points.PlayerWithPoints; import restwars.model.points.Points; import java.util.List; import java.util.Optional; /** * Service for points. */ public interface PointsService { /** * Calculates the points for all players. */ void calculatePointsForAllPlayers(); /** * Returns the current points for the given player. * * @param player Player. * @return Points. */ Optional<Points> getPointsForPlayer(Player player); /** * Returns the points history for the given player. * * @param player Player. * @param max Maximum number of points. * @return Points history. */ List<Points> getPointsHistoryForPlayer(Player player, int max); /** * Fetches the player ranking. * * @param max Maximum number of points. * @return Player ranking. */ List<PlayerWithPoints> fetchPlayerRanking(int max); }
lgpl-3.0
neilcsmith-net/gst1-java-core
src/org/freedesktop/gstreamer/MiniObject.java
4746
/* * Copyright (c) 2019 Neil C Smith * Copyright (c) 2016 Christophe Lafolet * Copyright (c) 2014 Tom Greenwood <tgreenwood@cafex.com> * Copyright (c) 2009 Levente Farkas * Copyright (c) 2007 Wayne Meissner * * This file is part of gstreamer-java. * * This code is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3 only, as * published by the Free Software Foundation. * * This code 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 * version 3 for more details. * * You should have received a copy of the GNU Lesser General Public License * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package org.freedesktop.gstreamer; import org.freedesktop.gstreamer.lowlevel.GstMiniObjectAPI.MiniObjectStruct; import org.freedesktop.gstreamer.glib.RefCountedObject; import org.freedesktop.gstreamer.lowlevel.GPointer; import static org.freedesktop.gstreamer.lowlevel.GstMiniObjectAPI.GSTMINIOBJECT_API; import org.freedesktop.gstreamer.lowlevel.GstMiniObjectPtr; /** * Lightweight base class for the GStreamer object hierarchy * <p> * See upstream documentation at * <a href="https://gstreamer.freedesktop.org/data/doc/gstreamer/stable/gstreamer/html/gstreamer-GstMiniObject.html" * >https://gstreamer.freedesktop.org/data/doc/gstreamer/stable/gstreamer/html/gstreamer-GstMiniObject.html</a> * <p> * MiniObject is a simple structure that can be used to implement refcounted * types. */ public abstract class MiniObject extends RefCountedObject { /** * Creates a new instance of MiniObject */ protected MiniObject(Initializer init) { this(new Handle(init.ptr.as(GstMiniObjectPtr.class, GstMiniObjectPtr::new), init.ownsHandle), init.needRef); } protected MiniObject(Handle handle, boolean needRef) { super(handle, needRef); } /** * If mini_object has the LOCKABLE flag set, check if the current EXCLUSIVE * lock on object is the only one, this means that changes to the object * will not be visible to any other object. * * <p> * </p>If the LOCKABLE flag is not set, check if the refcount of mini_object * is exactly 1, meaning that no other reference exists to the object and * that the object is therefore writable. * * <p> * </p>Modification of a mini-object should only be done after verifying * that it is writable. * * @return true if the object is writable. */ public boolean isWritable() { return GSTMINIOBJECT_API.gst_mini_object_is_writable(this); } /** * Makes a writable instance of this MiniObject. * <p> * The result is cast to <tt>subclass</tt>. * * @return a writable version (possibly a duplicate) of this MiniObject. */ protected <T extends MiniObject> T makeWritable() { MiniObject result = GSTMINIOBJECT_API.gst_mini_object_make_writable(this); if (result == null) { throw new NullPointerException("Could not make " + this.getClass().getSimpleName() + " writable"); } return (T) result; } /** * Create a new MiniObject as a copy of the this instance. * * @return the new MiniObject. */ public <T extends MiniObject> T copy() { MiniObject result = GSTMINIOBJECT_API.gst_mini_object_copy(this); if (result == null) { throw new NullPointerException("Could not make a copy of " + this.getClass().getSimpleName()); } return (T) result; } public int getRefCount() { final MiniObjectStruct struct = new MiniObjectStruct(getRawPointer()); return (Integer) struct.readField("refcount"); } protected static class Handle extends RefCountedObject.Handle { public Handle(GstMiniObjectPtr ptr, boolean ownsHandle) { super(ptr, ownsHandle); } @Override protected void disposeNativeHandle(GPointer ptr) { GSTMINIOBJECT_API.gst_mini_object_unref( ptr.as(GstMiniObjectPtr.class, GstMiniObjectPtr::new)); } @Override protected void ref() { GSTMINIOBJECT_API.gst_mini_object_ref(getPointer()); } @Override protected void unref() { GSTMINIOBJECT_API.gst_mini_object_unref(getPointer()); } @Override protected GstMiniObjectPtr getPointer() { return (GstMiniObjectPtr) super.getPointer(); } } }
lgpl-3.0
Razz0991/PeculiarItems
src/au/com/mineauz/peculiaritems/commands/CreateModifierCommand.java
3492
package au.com.mineauz.peculiaritems.commands; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.google.common.collect.Lists; import au.com.mineauz.peculiaritems.PeculiarItemsPlugin; import au.com.addstar.monolith.lookup.Lookup; import au.com.addstar.monolith.lookup.MaterialDefinition; import au.com.mineauz.peculiaritems.PCRUtils; import au.com.mineauz.peculiaritems.PeculiarItem; import au.com.mineauz.peculiaritems.PeculiarModifier; import au.com.mineauz.peculiaritems.peculiarstats.PeculiarStat; public class CreateModifierCommand implements ICommand { @Override public String getName() { return "createmodifier"; } @Override public String[] getAliases() { return new String[] {"crmod", "createmod", "cmod"}; } @Override public boolean canBeConsole() { return false; } @Override public boolean canBeCommandBlock() { return false; } @Override public String[] getUsage() { return new String[] {"<Material> <Stat>", "<Material> random", "HAND <Stat>", "HAND random"}; } @Override public List<String> onTabComplete(CommandSender sender, String[] args) { if (args.length == 2) { List<String> values = Lists.newArrayList(); for (PeculiarStat stat : PeculiarItemsPlugin.getPlugin().getStats().getAllStats()) { values.add(stat.getName().toLowerCase()); } values.add("random"); return PCRUtils.tabCompleteMatch(values, args[1]); } return null; } @Override public boolean onCommand(CommandSender sender, String[] args) { if (args.length < 2) { return false; } PeculiarItemsPlugin plugin = PeculiarItemsPlugin.getPlugin(); Player player = (Player)sender; // Get the target item ItemStack target; boolean isHand = false; if (args[0].equals("HAND")) { target = player.getInventory().getItemInMainHand(); isHand = true; if (target == null || target.getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "You are not holding an item"); return true; } } else { // Parse a material MaterialDefinition def = Lookup.findItemByName(args[0]); if (def == null) { Material type = Material.getMaterial(args[0]); if (type == null) { player.sendMessage(ChatColor.RED + "Unknown material " + args[0]); return true; } target = new ItemStack(type, 1); } else { target = def.asItemStack(1); } } // Make sure its not a peculiar item if (new PeculiarItem(target).isPeculiar()) { player.sendMessage(ChatColor.RED + "You cannot turn this item in a modifier"); return true; } // Determine the stat to add PeculiarStat stat; if (args[1].equalsIgnoreCase("random")) { stat = plugin.getStats().getRandomStat(); } else { stat = plugin.getStats().loadStat(args[1]); if (stat == null) { player.sendMessage(ChatColor.RED + "No stat by the name " + args[1]); return true; } } PeculiarModifier modifier = new PeculiarModifier(target); modifier.addStat(stat); if (isHand) { player.sendMessage(ChatColor.GREEN + "This item is now a peculiar modifier"); player.getInventory().setItemInMainHand(modifier.getItemStack()); } else { player.sendMessage(ChatColor.GREEN + "Given you a peculiar modifier"); player.getInventory().addItem(modifier.getItemStack()); } player.updateInventory(); return true; } }
lgpl-3.0
iantmoore/substeps-framework
core/src/test/java/com/technophobia/substeps/runner/syntax/SyntaxBuilderTest.java
5345
/* * Copyright Technophobia Ltd 2012 * * This file is part of Substeps. * * Substeps 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 3 of the License, or * (at your option) any later version. * * Substeps 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 Substeps. If not, see <http://www.gnu.org/licenses/>. */ package com.technophobia.substeps.runner.syntax; import com.technophobia.substeps.model.ParentStep; import com.technophobia.substeps.model.Step; import com.technophobia.substeps.model.StepImplementation; import com.technophobia.substeps.model.Syntax; import com.technophobia.substeps.model.exception.DuplicatePatternException; import com.technophobia.substeps.model.exception.DuplicateStepImplementationException; import com.technophobia.substeps.stepimplementations.DuplicateStepImplementations; import com.technophobia.substeps.stepimplementations.MockStepImplementations; import com.technophobia.substeps.stepimplementations.MockStepImplementationsContainer; import com.technophobia.substeps.steps.TestStepImplementations; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; /** * @author imoore */ public class SyntaxBuilderTest { @Test(expected = DuplicatePatternException.class) public void testDuplicateDefinitionsThrowError() { final List<Class<?>> stepImplsList = new ArrayList<Class<?>>(); stepImplsList.add(TestStepImplementations.class); final List<Class<?>> stepImpls = new ArrayList<Class<?>>(); stepImpls.add(MockStepImplementations.class); SyntaxBuilder.buildSyntax(stepImpls, new File("./target/test-classes/substeps/duplicates.substeps")); } @Test(expected = DuplicateStepImplementationException.class) public void testDuplicateStepImplementaionsThrowError() { final List<Class<?>> stepImplsList = new ArrayList<Class<?>>(); stepImplsList.add(TestStepImplementations.class); final List<Class<?>> stepImpls = new ArrayList<Class<?>>(); stepImpls.add(DuplicateStepImplementations.class); SyntaxBuilder.buildSyntax(stepImpls, new File("./target/test-classes/substeps/simple.substeps")); } @Test public void testSyntaxBuilder() { final List<Class<?>> stepImpls = new ArrayList<Class<?>>(); stepImpls.add(MockStepImplementations.class); checkSyntaxBuilderWithStepImpls(stepImpls); } @Test public void testSyntaxBuilderWithDeferringStepImplementations() { final List<Class<?>> stepImpls = new ArrayList<Class<?>>(); stepImpls.add(MockStepImplementationsContainer.class); checkSyntaxBuilderWithStepImpls(stepImpls); } private void checkSyntaxBuilderWithStepImpls(final List<Class<?>> stepImpls) { final Syntax syntax = SyntaxBuilder.buildSyntax(stepImpls, new File( "./target/test-classes/substeps/allFeatures.substeps")); final List<StepImplementation> stepImplementations = syntax.getStepImplementations(); Assert.assertFalse("expecting some step impls", stepImplementations.isEmpty()); System.out.println("\nStep implementations\n"); for (final StepImplementation impl : stepImplementations) { System.out.println(impl.getKeyword() + " " + impl.getValue() + " : " + impl.getImplementedIn().getSimpleName() + "." + impl.getMethod().getName()); } final List<ParentStep> sortedList = syntax.getSortedRootSubSteps(); System.out.println("\n\n\nSubSteps\n"); for (final ParentStep parent : sortedList) { final StringBuilder buf = new StringBuilder(); buf.append("Parent: " + parent.getParent().getLine() + " in: " + parent.getSubStepFile()); for (final Step substep : parent.getSteps()) { buf.append("\n\t").append(substep.getLine()); } System.out.println(buf.toString()); } } @Test public void testSingleWordSubStepDefinition() { final Step parent = new Step("ASingleWord", true, new File("./target/test-classes/substeps/bugs.substeps"), 23, 11); Assert.assertNotNull(parent.getPattern()); final List<Class<?>> stepImplsList = new ArrayList<Class<?>>(); stepImplsList.add(MockStepImplementations.class); // final List<Class<?>> stepImpls = new ArrayList<Class<?>>(); // stepImpls.add(DuplicateStepImplementations.class); final Syntax syntax = SyntaxBuilder.buildSyntax(stepImplsList, new File( "./target/test-classes/substeps/bugs.substeps")); final List<ParentStep> substeps = syntax.getSubStepsMap().get("AnotherSingleWord"); Assert.assertNotNull(substeps); Assert.assertThat(substeps.size(), is(1)); } }
lgpl-3.0
TPPIDev/Modpack-Tweaks
src/main/java/modpacktweaks/util/TxtParser.java
6401
package modpacktweaks.util; import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; import modpacktweaks.ModpackTweaks; import modpacktweaks.command.CommandMT; import modpacktweaks.config.ConfigurationHandler; /** * Beware all ye who enter here, for the sake of your sanity, turn back */ public class TxtParser { /** The useable lines (not commented) from the file last processed by parseFileMain **/ private static ArrayList<String> useableLines = new ArrayList<String>(); /** * Parses a file, taking into account all comments, line-skips, and pagination/formatting * @param file * @return an array of pages */ public static ArrayList<String> parseFileMain(InputStream file) { ArrayList<String> bookText = new ArrayList<String>(); useableLines.clear(); if (file == null) return new ArrayList<String>(); Scanner scanner; scanner = new Scanner(file); String nextPage = ""; while (scanner.hasNextLine()) { String temp = scanner.nextLine(); // If the line is a comment if (temp.length() == 0 || temp.startsWith("**")) { // If the line is possibly a line-skip comment if (temp.startsWith("***")) { boolean validSkip = true; for (int i = 3; i < temp.length(); i++) if (!isANumber(temp.charAt(i))) { validSkip = false; break; } // Skip the requested amount of lines by parsing the number // after the asterisks if (validSkip) { for (int i = 0; i <= Integer.parseInt(temp.substring(3, temp.length())); i++) { scanner.nextLine(); } } else ModpackTweaks.logger.error("ModpackTweaks - Invalid line-skip in changelog. This may not work as intended"); } // Finally, do not add this to the page continue; } // If this line is a page break if (temp.equals("~~~")) { bookText.add(nextPage); nextPage = ""; } else { useableLines.add(temp); // If there is a line break if (temp.charAt(temp.length() - 1) == '~') { temp = temp.substring(0, temp.length() - 1); temp += "\n"; if (nextPage.length() + temp.length() > 240 && nextPage.length() != 0 && temp.length() != 0) { bookText.add(nextPage); nextPage = temp; temp = ""; } else nextPage += temp; } // In the end just concatenate to the page else { if (nextPage.length() + temp.length() > 240 && nextPage.length() != 0 && temp.length() != 0 && ConfigurationHandler.forcePageBreaks) { bookText.add(nextPage); nextPage = temp; temp = ""; } else nextPage += temp + " "; } } } if (nextPage.length() > 1) bookText.add(nextPage); scanner.close(); return bookText; } /** * @param charAt * @return If this char is a number */ private static boolean isANumber(char charAt) { for (int i = 0; i < 10; i++) { try { if (Integer.parseInt(String.valueOf(charAt)) == i) return true; } catch (Exception e) { // Do Nothing } } return false; } /** * Parses a file, identically to ParseFileMain, but takes into account mod names, searching for the >< identifier. * @param file * @param modName * @return an array of pages, only containing the lines of info about the passed in modname */ public static ArrayList<String> parseFileMods(InputStream file, String modName) { ArrayList<String> bookText = new ArrayList<String>(); Scanner scanner = new Scanner(file); String nextPage = ""; while (scanner.hasNextLine()) { String temp = scanner.nextLine(); if (temp.startsWith(">") && temp.contains("<")) { String test = temp.substring(1, temp.length() - 1); if (test.contains(modName)) break; } } while (scanner.hasNextLine()) { String temp = scanner.nextLine(); if (temp.startsWith(">") && temp.contains("<")) break; // If the line is a comment if (temp.length() == 0 || temp.startsWith("**")) { // If the line is possibly a line-skip comment if (temp.startsWith("***")) { boolean validSkip = true; for (int i = 3; i < temp.length(); i++) if (!isANumber(temp.charAt(i))) { validSkip = false; break; } // Skip the requested amount of lines by parsing the number // after the asterisks if (validSkip) { for (int i = 0; i <= Integer.parseInt(temp.substring(3, temp.length())); i++) { scanner.nextLine(); } } else ModpackTweaks.logger.info("ModpackTweaks - Invalid line-skip in changelog. This may not work as intended"); } // Finally, do not add this to the page continue; } // If this line is a page break if (temp.equals("~~~")) { bookText.add(nextPage); nextPage = ""; } else { // If there is a line break if (temp.charAt(temp.length() - 1) == '~') { temp = temp.substring(0, temp.length() - 1); temp += "\n"; if (nextPage.length() + temp.length() > 240 && nextPage.length() != 0 && temp.length() != 0 && ConfigurationHandler.forcePageBreaks) { bookText.add(nextPage); nextPage = temp; temp = ""; } else nextPage += temp; } // In the end just concatenate to the page else { if (nextPage.length() + temp.length() > 240 && nextPage.length() != 0 && temp.length() != 0) { bookText.add(nextPage); nextPage = temp; temp = ""; } else nextPage += temp + " "; } } } if (nextPage.length() > 1) bookText.add(nextPage); scanner.close(); return bookText; } /** * Gets mod names from the file * @param file * @return an array of Strings, the names of mods that are described in the file, evidenced by the >< identifier */ public static ArrayList<String> getSupportedMods(InputStream file) { ArrayList<String> mods = new ArrayList<String>(); Scanner scanner; scanner = new Scanner(file); parseFileMain(file); for (String s : useableLines) { if (s.startsWith(">") && s.contains("<")) { String[] nameThatHasBeenSplit = s.substring(1, s.indexOf('<')).split(", "); CommandMT.addProperNameMapping(nameThatHasBeenSplit[0], nameThatHasBeenSplit[1]); mods.add(nameThatHasBeenSplit[0]); } } scanner.close(); return mods; } }
lgpl-3.0
christianhujer/japi
historic2/src/prj/net/sf/japi/progs/jeduca/jtest/io/XMLUtils.java
1584
/* * Copyright (C) 2009 Christian Hujer * * 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/>. */ package net.sf.japi.progs.jeduca.jtest.io; import org.xml.sax.ext.DefaultHandler2; /** Class for XML Utilities like EntityResolvers, ErrorHandlers and stuff like that. * @author <a href="mailto:cher@riedquat.de">Christian Hujer</a> * @since 0.1 */ public final class XMLUtils { /** Singleton instance. */ private static final XMLUtils INSTANCE = new XMLUtils(); /** Singleton constructor. */ private XMLUtils() { } /** Get an instance of XMLUtils. * @return instance of XMLUtils */ public static XMLUtils getInstance() { return INSTANCE; } /** Quiet error handler. */ private final DefaultHandler2 quietHandler = new DefaultHandler2(); /** Get the quiet error handler. * @return The quiet error handler. */ public DefaultHandler2 getQuietHandler() { return quietHandler; } } // class XMLUtils
lgpl-3.0
haisamido/SFDaaS
src/org/apache/commons/math/optimization/GoalType.java
1172
/* * 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.commons.math.optimization; import java.io.Serializable; /** * Goal type for an optimization problem. * @version $Revision: 811685 $ $Date: 2009-09-05 19:36:48 +0200 (sam. 05 sept. 2009) $ * @since 2.0 */ public enum GoalType implements Serializable { /** Maximization goal. */ MAXIMIZE, /** Minimization goal. */ MINIMIZE }
lgpl-3.0
HATB0T/RuneCraftery
forge/mcp/src/minecraft/net/minecraft/client/gui/mco/GuiScreenBackupRestoreTask.java
2050
package net.minecraft.client.gui.mco; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.TaskLongRunning; import net.minecraft.client.mco.Backup; import net.minecraft.client.mco.ExceptionMcoService; import net.minecraft.client.mco.McoClient; import net.minecraft.client.resources.I18n; @SideOnly(Side.CLIENT) class GuiScreenBackupRestoreTask extends TaskLongRunning { /** The backup being restored */ private final Backup theBackup; /** The screen running this task */ final GuiScreenBackup theBackupScreen; private GuiScreenBackupRestoreTask(GuiScreenBackup par1GuiScreenBackup, Backup par2Backup) { this.theBackupScreen = par1GuiScreenBackup; this.theBackup = par2Backup; } public void run() { this.setMessage(I18n.getString("mco.backup.restoring")); try { McoClient mcoclient = new McoClient(this.getMinecraft().getSession()); mcoclient.func_111235_c(GuiScreenBackup.func_110367_b(this.theBackupScreen), this.theBackup.field_110727_a); try { Thread.sleep(1000L); } catch (InterruptedException interruptedexception) { Thread.currentThread().interrupt(); } this.getMinecraft().displayGuiScreen(GuiScreenBackup.func_130031_d(this.theBackupScreen)); } catch (ExceptionMcoService exceptionmcoservice) { GuiScreenBackup.func_130035_e(this.theBackupScreen).getLogAgent().logSevere(exceptionmcoservice.toString()); this.setFailedMessage(exceptionmcoservice.toString()); } catch (Exception exception) { this.setFailedMessage(exception.getLocalizedMessage()); } } GuiScreenBackupRestoreTask(GuiScreenBackup par1GuiScreenBackup, Backup par2Backup, GuiScreenBackupDownloadThread par3GuiScreenBackupDownloadThread) { this(par1GuiScreenBackup, par2Backup); } }
lgpl-3.0
bartcharbon/molgenis
molgenis-js/src/test/java/org/molgenis/js/JsMagmaScriptEvaluatorTest.java
33409
package org.molgenis.js; import static com.google.common.collect.Lists.newArrayList; import static java.lang.Double.valueOf; import static java.lang.Long.MAX_VALUE; import static java.time.Instant.now; import static java.time.ZoneOffset.UTC; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.molgenis.data.meta.AttributeType.BOOL; import static org.molgenis.data.meta.AttributeType.CATEGORICAL; import static org.molgenis.data.meta.AttributeType.DATE; import static org.molgenis.data.meta.AttributeType.DATE_TIME; import static org.molgenis.data.meta.AttributeType.DECIMAL; import static org.molgenis.data.meta.AttributeType.INT; import static org.molgenis.data.meta.AttributeType.LONG; import static org.molgenis.data.meta.AttributeType.MREF; import static org.molgenis.data.meta.AttributeType.STRING; import com.google.common.base.Stopwatch; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.time.Instant; import java.time.LocalDate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.script.ScriptException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.molgenis.data.Entity; import org.molgenis.data.meta.model.Attribute; import org.molgenis.data.meta.model.EntityType; import org.molgenis.data.support.DynamicEntity; import org.molgenis.js.magma.JsMagmaScriptEvaluator; import org.molgenis.js.nashorn.NashornScriptEngine; class JsMagmaScriptEvaluatorTest { private static EntityType personWeightEntityType; private static EntityType personHeightEntityType; private static EntityType personWeightAndHeightEntityType; private static EntityType personBirthDateMeta; private static EntityType personAgeEntityType; private static EntityType personGenderEntityType; private static EntityType personTraitEntityType; private static EntityType personSmokingEntityType; private static EntityType personLastUpdatedEntityType; private static EntityType personLongEntityType; // Reference tables private static EntityType genderEntityType; private static EntityType traitEntityType; private static JsMagmaScriptEvaluator jsMagmaScriptEvaluator; @BeforeAll static void beforeClass() throws ScriptException, IOException { Attribute idAttribute = mock(Attribute.class); when(idAttribute.getName()).thenReturn("id"); when(idAttribute.getDataType()).thenReturn(STRING); Attribute weightAttr = when(mock(Attribute.class).getName()).thenReturn("weight").getMock(); when(weightAttr.getDataType()).thenReturn(INT); personWeightEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personWeightEntityType.getIdAttribute()).thenReturn(idAttribute); when(personWeightEntityType.getAttribute("weight")).thenReturn(weightAttr); when(personWeightEntityType.getAtomicAttributes()).thenReturn(singletonList(weightAttr)); Attribute heightAttr = when(mock(Attribute.class).getName()).thenReturn("height").getMock(); when(heightAttr.getDataType()).thenReturn(INT); personHeightEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personHeightEntityType.getIdAttribute()).thenReturn(idAttribute); when(personHeightEntityType.getAttribute("height")).thenReturn(heightAttr); when(personHeightEntityType.getAtomicAttributes()).thenReturn(singletonList(heightAttr)); personWeightAndHeightEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personWeightAndHeightEntityType.getIdAttribute()).thenReturn(idAttribute); when(personWeightAndHeightEntityType.getAttribute("weight")).thenReturn(weightAttr); when(personWeightAndHeightEntityType.getAttribute("height")).thenReturn(heightAttr); when(personWeightAndHeightEntityType.getAtomicAttributes()) .thenReturn(asList(weightAttr, heightAttr)); Attribute birthDateAttr = when(mock(Attribute.class).getName()).thenReturn("birthdate").getMock(); when(birthDateAttr.getDataType()).thenReturn(DATE); personBirthDateMeta = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personBirthDateMeta.getIdAttribute()).thenReturn(idAttribute); when(personBirthDateMeta.getAttribute("birthdate")).thenReturn(birthDateAttr); when(personBirthDateMeta.getAtomicAttributes()).thenReturn(singletonList(birthDateAttr)); Attribute ageAttr = when(mock(Attribute.class).getName()).thenReturn("age").getMock(); when(ageAttr.getDataType()).thenReturn(INT); personAgeEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personAgeEntityType.getIdAttribute()).thenReturn(idAttribute); when(personAgeEntityType.getAttribute("age")).thenReturn(ageAttr); when(personAgeEntityType.getAtomicAttributes()).thenReturn(singletonList(ageAttr)); Attribute genderAttr = when(mock(Attribute.class).getName()).thenReturn("gender").getMock(); when(genderAttr.getDataType()).thenReturn(CATEGORICAL); personGenderEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personGenderEntityType.getIdAttribute()).thenReturn(idAttribute); when(personGenderEntityType.getAttribute("gender")).thenReturn(genderAttr); when(personGenderEntityType.getAtomicAttributes()).thenReturn(singletonList(genderAttr)); Attribute labelAttr = when(mock(Attribute.class).getName()).thenReturn("label").getMock(); when(labelAttr.getDataType()).thenReturn(STRING); genderEntityType = when(mock(EntityType.class).getId()).thenReturn("gender").getMock(); when(genderEntityType.getIdAttribute()).thenReturn(idAttribute); when(genderEntityType.getAttribute("id")).thenReturn(idAttribute); when(genderEntityType.getAttribute("label")).thenReturn(labelAttr); when(genderEntityType.getAtomicAttributes()).thenReturn(newArrayList(idAttribute, labelAttr)); Attribute traitAttr = when(mock(Attribute.class).getName()).thenReturn("trait").getMock(); when(traitAttr.getDataType()).thenReturn(MREF); personTraitEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personTraitEntityType.getIdAttribute()).thenReturn(idAttribute); when(personTraitEntityType.getAttribute("id")).thenReturn(idAttribute); when(personTraitEntityType.getAttribute("trait")).thenReturn(traitAttr); when(personTraitEntityType.getAtomicAttributes()) .thenReturn(newArrayList(idAttribute, traitAttr)); Attribute nameAttr = when(mock(Attribute.class).getName()).thenReturn("name").getMock(); when(nameAttr.getDataType()).thenReturn(STRING); traitEntityType = when(mock(EntityType.class).getId()).thenReturn("trait").getMock(); when(traitEntityType.getIdAttribute()).thenReturn(idAttribute); when(traitEntityType.getAttribute("id")).thenReturn(idAttribute); when(traitEntityType.getAttribute("name")).thenReturn(nameAttr); when(traitEntityType.getAtomicAttributes()).thenReturn(newArrayList(idAttribute, nameAttr)); Attribute smokingAttr = when(mock(Attribute.class).getName()).thenReturn("smoking").getMock(); when(smokingAttr.getDataType()).thenReturn(BOOL); personSmokingEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personSmokingEntityType.getIdAttribute()).thenReturn(idAttribute); when(personSmokingEntityType.getAttribute("id")).thenReturn(idAttribute); when(personSmokingEntityType.getAttribute("smoking")).thenReturn(smokingAttr); when(personSmokingEntityType.getAtomicAttributes()) .thenReturn(newArrayList(idAttribute, smokingAttr)); Attribute lastUpdateAttr = when(mock(Attribute.class).getName()).thenReturn("lastUpdate").getMock(); when(lastUpdateAttr.getDataType()).thenReturn(DATE_TIME); personLastUpdatedEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personLastUpdatedEntityType.getIdAttribute()).thenReturn(idAttribute); when(personLastUpdatedEntityType.getAttribute("id")).thenReturn(idAttribute); when(personLastUpdatedEntityType.getAttribute("lastUpdate")).thenReturn(lastUpdateAttr); when(personLastUpdatedEntityType.getAtomicAttributes()) .thenReturn(newArrayList(idAttribute, lastUpdateAttr)); Attribute longAttr = when(mock(Attribute.class).getName()).thenReturn("long").getMock(); when(longAttr.getDataType()).thenReturn(LONG); personLongEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(personLongEntityType.getIdAttribute()).thenReturn(idAttribute); when(personLongEntityType.getAttribute("id")).thenReturn(idAttribute); when(personLongEntityType.getAttribute("long")).thenReturn(longAttr); when(personLongEntityType.getAtomicAttributes()) .thenReturn(newArrayList(idAttribute, longAttr)); jsMagmaScriptEvaluator = new JsMagmaScriptEvaluator(new NashornScriptEngine()); } @SuppressWarnings("UnnecessaryBoxing") @Test void testValueForDateTime() { Entity person = new DynamicEntity(personLastUpdatedEntityType); Instant lastUpdate = Instant.now(); person.set("lastUpdate", lastUpdate); Object result = jsMagmaScriptEvaluator.eval("$('lastUpdate').value()", person, 1); assertEquals(valueOf(lastUpdate.toEpochMilli()), result); } @Test void testValueForBool() { Entity person = new DynamicEntity(personSmokingEntityType); person.set("smoking", true); Object result = jsMagmaScriptEvaluator.eval("$('smoking').value()", person, 1); assertEquals(true, result); } @SuppressWarnings("UnnecessaryBoxing") @Test void testValueForLong() { Entity person = new DynamicEntity(personLongEntityType); person.set("long", Long.MAX_VALUE); Object result = jsMagmaScriptEvaluator.eval("$('long').value()", person, 1); assertEquals(valueOf(MAX_VALUE), result); } @Test void testValueForXrefDefaultDepth() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "1"); gender.set("label", "male"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object result = jsMagmaScriptEvaluator.eval("$('gender').attr('label').value()", person); assertNull(result); } @Test void testValueForNestedXrefDefaultDepth() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "1"); gender.set("label", "male"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object scriptExceptionObj = jsMagmaScriptEvaluator.eval("$('gender').attr('xref').attr('label').value()", person); assertEquals( "org.molgenis.script.core.ScriptException: TypeError: Cannot read property \"label\" from undefined", scriptExceptionObj.toString()); } @Test void testValueForMref() { Entity trait = new DynamicEntity(traitEntityType); trait.set("id", "1"); trait.set("name", "Hello"); Entity person = new DynamicEntity(personTraitEntityType); person.set("id", "1"); person.set("trait", singletonList(trait)); Object result = jsMagmaScriptEvaluator.eval("$('trait').value()", person, 3); assertEquals(singletonList("1"), result); } @Test void testValueForMrefWithComplexAlgorithm() { Entity trait = new DynamicEntity(traitEntityType); trait.set("id", "1"); trait.set("name", "Hello"); Entity person = new DynamicEntity(personTraitEntityType); person.set("id", "1"); person.set("trait", singletonList(trait)); Object result = jsMagmaScriptEvaluator.eval( "var result = [];$('trait').map(function (entity) {result.push(entity.attr('name').value())});result", person, 3); assertEquals(singletonList("Hello"), result); } @Test void testValueForMrefWithSimplifiedAlgorithm() { Entity trait = new DynamicEntity(traitEntityType); trait.set("id", "1"); trait.set("name", "Hello"); Entity person = new DynamicEntity(personTraitEntityType); person.set("id", "1"); person.set("trait", singletonList(trait)); Object result = jsMagmaScriptEvaluator.eval( "$('trait').map(function (entity) {return entity.attr('name').value()}).value()", person, 3); assertEquals(singletonList("Hello"), result); } @Test void test$() { Entity person = new DynamicEntity(personWeightEntityType); person.set("weight", 82); Object weight = jsMagmaScriptEvaluator.eval("$('weight').value()", person, 3); assertEquals(82, weight); } @Test void testEvalDefaultDepth$() { Entity person = new DynamicEntity(personWeightEntityType); person.set("weight", 82); Object weight = jsMagmaScriptEvaluator.eval("$('weight').value()", person); assertEquals(82, weight); } @Test void testUnitConversion() { Entity person = new DynamicEntity(personWeightEntityType); person.set("weight", 82); Object weight = jsMagmaScriptEvaluator.eval( "$('weight').unit('kg').toUnit('poundmass').value()", person, 3); assertEquals(180.7790549915996, weight); } @Test void testAttrValue() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "1"); gender.set("label", "male"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object weight = jsMagmaScriptEvaluator.eval("$('gender').attr('label').value()", person, 3); assertEquals("male", weight); } @Test void testCompareIdValue() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "1"); gender.set("label", "male"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object weight = jsMagmaScriptEvaluator.eval("$('gender').value() === '1'", person, 3); assertEquals(true, weight); } @Test void mapSimple() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "m"); gender.set("label", "Male"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object result = jsMagmaScriptEvaluator.eval("$('gender').map({'m':'Male'}).value()", person, 3); assertEquals("Male", result); } @Test void mapDefault() { Entity gender = new DynamicEntity(genderEntityType); gender.set("id", "f"); gender.set("label", "Female"); Entity person = new DynamicEntity(personGenderEntityType); person.set("gender", gender); Object result = jsMagmaScriptEvaluator.eval("$('gender').map({'m':'Male'}, 'Female').value()", person, 3); assertEquals("Female", result); } @Test void mapNull() { Object result = jsMagmaScriptEvaluator.eval( "$('gender').map({'20':'2'}, 'B2', 'B3').value()", new DynamicEntity(personGenderEntityType), 3); assertEquals("B3", result); } @Test void testAverageValueOfMultipleNumericAttributes() { Attribute idAttribute = mock(Attribute.class); when(idAttribute.getName()).thenReturn("id"); when(idAttribute.getDataType()).thenReturn(STRING); Attribute sbp1Attr = when(mock(Attribute.class).getName()).thenReturn("SBP_1").getMock(); when(sbp1Attr.getDataType()).thenReturn(DECIMAL); Attribute sbp2Attr = when(mock(Attribute.class).getName()).thenReturn("SBP_2").getMock(); when(sbp2Attr.getDataType()).thenReturn(DECIMAL); EntityType sbpPersonEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(sbpPersonEntityType.getIdAttribute()).thenReturn(idAttribute); when(sbpPersonEntityType.getAttribute("SBP_1")).thenReturn(sbp1Attr); when(sbpPersonEntityType.getAttribute("SBP_2")).thenReturn(sbp2Attr); when(sbpPersonEntityType.getAtomicAttributes()).thenReturn(asList(sbp1Attr, sbp2Attr)); Entity entity0 = new DynamicEntity(sbpPersonEntityType); entity0.set("SBP_1", 120d); entity0.set("SBP_2", 124d); Entity entity1 = new DynamicEntity(sbpPersonEntityType); entity1.set("SBP_1", 120d); Entity entity2 = new DynamicEntity(sbpPersonEntityType); String script = "var counter = 0;\nvar SUM=newValue(0);\nif(!$('SBP_1').isNull().value()){\n\tSUM.plus($('SBP_1').value());\n\tcounter++;\n}\nif(!$('SBP_2').isNull().value()){\n\tSUM.plus($('SBP_2').value());\n\tcounter++;\n}\nif(counter !== 0){\n\tSUM.div(counter);\nSUM.value();\n}\nelse{\n\tnull;\n}"; Object result1 = jsMagmaScriptEvaluator.eval(script, entity0, 3); assertEquals(122, result1); Object result2 = jsMagmaScriptEvaluator.eval(script, entity1, 3); assertEquals(120, result2); Object result3 = jsMagmaScriptEvaluator.eval(script, entity2, 3); assertNull(result3); } @Test void testGroup() { Entity entity1 = new DynamicEntity(personAgeEntityType); entity1.set("age", 29); Object result1 = jsMagmaScriptEvaluator.eval("$('age').group([18, 35, 56]).value();", entity1, 3); assertEquals("18-35", result1); Entity entity2 = new DynamicEntity(personAgeEntityType); entity2.set("age", 999); Object result2 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56], [888, 999]).value();", entity2, 3); assertEquals(999, result2); Entity entity3 = new DynamicEntity(personAgeEntityType); entity3.set("age", 47); Object result3 = jsMagmaScriptEvaluator.eval("$('age').group([18, 35, 56]).value();", entity3, 3); assertEquals("35-56", result3); } @Test void testGroupNull() { Entity entity4 = new DynamicEntity(personAgeEntityType); entity4.set("age", 47); Object result4 = jsMagmaScriptEvaluator.eval("$('age').group().value();", entity4, 3); assertNull(result4); Object result5 = jsMagmaScriptEvaluator.eval("$('age').group([56, 18, 35]).value();", entity4, 3); assertNull(result5); Object result6 = jsMagmaScriptEvaluator.eval( "$('age').group([56, 18, 35], null,'123456').value();", entity4, 3); assertEquals("123456", result6); } @Test void testGroupConstantValue() { Entity entity4 = new DynamicEntity(personAgeEntityType); entity4.set("age", 47); Object result4 = jsMagmaScriptEvaluator.eval( "var age_variable=new newValue(45);age_variable.group([18, 35, 56]).value();", entity4, 3); assertEquals("35-56", result4); } @Test void combineGroupMapFunctions() { Entity entity1 = new DynamicEntity(personAgeEntityType); entity1.set("age", 29); Object result1 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56]).map({'-18':'0','18-35':'1','35-56':'2','56+':'3'}).value();", entity1, 3); assertEquals("1", result1); Entity entity2 = new DynamicEntity(personAgeEntityType); entity2.set("age", 17); Object result2 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56]).map({'-18':'0','18-35':'1','35-56':'2','56+':'3'}).value();", entity2, 3); assertEquals("0", result2); Entity entity3 = new DynamicEntity(personAgeEntityType); entity3.set("age", 40); Object result3 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56]).map({'-18':'0','18-35':'1','35-56':'2','56+':'3'}).value();", entity3, 3); assertEquals("2", result3); Entity entity4 = new DynamicEntity(personAgeEntityType); entity4.set("age", 70); Object result4 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56]).map({'-18':'0','18-35':'1','35-56':'2','56+':'3'}).value();", entity4, 3); assertEquals("3", result4); Entity entity5 = new DynamicEntity(personAgeEntityType); entity5.set("age", 999); Object result5 = jsMagmaScriptEvaluator.eval( "$('age').group([18, 35, 56], [999]).map({'-18':0,'18-35':1,'35-56':2,'56+':3,'999':'9'}).value();", entity5, 3); assertEquals("9", result5); } @Test void combinePlusGroupMapFunctions() { Attribute idAttribute = mock(Attribute.class); when(idAttribute.getName()).thenReturn("id"); when(idAttribute.getDataType()).thenReturn(STRING); Attribute food59Attr = when(mock(Attribute.class).getName()).thenReturn("FOOD59A1").getMock(); when(food59Attr.getDataType()).thenReturn(INT); Attribute food60Attr = when(mock(Attribute.class).getName()).thenReturn("FOOD60A1").getMock(); when(food60Attr.getDataType()).thenReturn(INT); EntityType foodPersonEntityType = when(mock(EntityType.class).getId()).thenReturn("person").getMock(); when(foodPersonEntityType.getIdAttribute()).thenReturn(idAttribute); when(foodPersonEntityType.getAttribute("FOOD59A1")).thenReturn(food59Attr); when(foodPersonEntityType.getAttribute("FOOD60A1")).thenReturn(food60Attr); when(foodPersonEntityType.getAtomicAttributes()).thenReturn(asList(food59Attr, food60Attr)); Entity entity0 = new DynamicEntity(foodPersonEntityType); entity0.set("FOOD59A1", 7); entity0.set("FOOD60A1", 6); Object result1 = jsMagmaScriptEvaluator.eval( "var SUM_WEIGHT = new newValue(0);SUM_WEIGHT.plus($('FOOD59A1').map({\"1\":0,\"2\":0.2,\"3\":0.6,\"4\":1,\"5\":2.5,\"6\":4.5,\"7\":6.5}, null, null).value());SUM_WEIGHT.plus($('FOOD60A1').map({\"1\":0,\"2\":0.2,\"3\":0.6,\"4\":1,\"5\":2.5,\"6\":4.5,\"7\":6.5}, null, null).value());SUM_WEIGHT.group([0,1,2,6,7]).map({\"0-1\":\"4\",\"1-2\":\"3\",\"2-6\":\"2\",\"6-7\":\"1\", \"7+\" : \"1\"},null,null).value();", entity0, 3); assertEquals("1", result1); } @Test void testPlusValue() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 180); Object result = jsMagmaScriptEvaluator.eval("$('height').plus(100).value()", entity0, 3); assertEquals(280, result); } @Test void testPlusObject() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 180); Object result1 = jsMagmaScriptEvaluator.eval("$('height').plus(new newValue(100)).value()", entity0, 3); assertEquals(280, result1); } @Test void testPlusNullValue() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 180); Object result1 = jsMagmaScriptEvaluator.eval("$('height').plus(null).value()", entity0, 3); assertEquals(180, result1); } @Test void testTimes() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 2); Object result = jsMagmaScriptEvaluator.eval("$('height').times(100).value()", entity0, 3); assertEquals(200, result); } @Test void div() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 200); Object result = jsMagmaScriptEvaluator.eval("$('height').div(100).value()", entity0, 3); assertEquals(2, result); } @Test void pow() { Entity entity0 = new DynamicEntity(personHeightEntityType); entity0.set("height", 20); Object result = jsMagmaScriptEvaluator.eval("$('height').pow(2).value()", entity0, 3); assertEquals(400, result); } @Test void testBmi() { Entity person = new DynamicEntity(personWeightAndHeightEntityType); person.set("weight", 82); person.set("height", 189); Object bmi = jsMagmaScriptEvaluator.eval( "$('weight').div($('height').div(100).pow(2)).value()", person, 3); DecimalFormat df = new DecimalFormat("#.####", new DecimalFormatSymbols(Locale.ENGLISH)); assertEquals(df.format(82.0 / (1.89 * 1.89)), df.format(bmi)); } @Test void testGlucose() { Attribute idAttribute = mock(Attribute.class); when(idAttribute.getName()).thenReturn("id"); when(idAttribute.getDataType()).thenReturn(STRING); Attribute gluc1Attr = when(mock(Attribute.class).getName()).thenReturn("GLUC_1").getMock(); when(gluc1Attr.getDataType()).thenReturn(DECIMAL); EntityType personGlucoseMeta = when(mock(EntityType.class).getId()).thenReturn("glucose").getMock(); when(personGlucoseMeta.getIdAttribute()).thenReturn(idAttribute); when(personGlucoseMeta.getAttribute("GLUC_1")).thenReturn(gluc1Attr); when(personGlucoseMeta.getAtomicAttributes()).thenReturn(singletonList(gluc1Attr)); Entity glucose = new DynamicEntity(personGlucoseMeta); glucose.set("GLUC_1", 4.1); Object bmi = jsMagmaScriptEvaluator.eval("$('GLUC_1').div(100).value()", glucose, 3); DecimalFormat df = new DecimalFormat("#.####", new DecimalFormatSymbols(Locale.ENGLISH)); assertEquals(df.format(4.1 / 100), df.format(bmi)); } @Test void age() { Entity person = new DynamicEntity(personBirthDateMeta); person.set("birthdate", now().atOffset(UTC).toLocalDate()); Object result = jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person); assertEquals(0, result); } @Test void evalList() { Entity person = new DynamicEntity(personWeightAndHeightEntityType); person.set("weight", 80); person.set("height", 20); Collection<Object> result = jsMagmaScriptEvaluator.eval( Arrays.asList("$('weight').value()", "$('height').pow(2).value()"), person); assertEquals(asList(80, 400), result); } @Disabled @Test void testPerformance() { Entity person = new DynamicEntity(personBirthDateMeta); person.set("birthdate", now().atOffset(UTC).toLocalDate()); jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person); Stopwatch sw = Stopwatch.createStarted(); jsMagmaScriptEvaluator.eval(Collections.nCopies(10000, "$('birthdate').age().value()"), person); System.out.println(sw.elapsed(TimeUnit.MILLISECONDS) + " millis passed evalList"); sw.reset().start(); for (int i = 0; i < 10000; i++) { jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person); } System.out.println( sw.elapsed(TimeUnit.MILLISECONDS) + " millis passed recreating bindings for each evaluation"); } @Test void testNull() { Entity person0 = new DynamicEntity(personBirthDateMeta); person0.set("birthdate", LocalDate.now()); String script = "$('birthdate').age().value() < 18 || $('birthdate').value() != null"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(true, result); Entity person1 = new DynamicEntity(personBirthDateMeta); person1.set("birthdate", null); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(false, result); } @Test void testEq() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", 100); String script = "$('weight').eq(100).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(true, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(false, result); } @Test void testIsValidJson() { Entity person = new DynamicEntity(personWeightEntityType); Collection<Object> result = jsMagmaScriptEvaluator.eval( Arrays.asList( "newValue('{\"foo\":3}').isValidJson().value()", "newValue('{foo:3}').isValidJson().value()"), person); assertEquals(asList(true, false), result); } @Test void testIsNull() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').isNull().value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(true, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(false, result); } @Test void testNot() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').isNull().not().value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(true, result); } @Test void testOr() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').eq(99).or($('weight').eq(100)).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(true, result); Entity person2 = new DynamicEntity(personWeightEntityType); person2.set("weight", 100); result = jsMagmaScriptEvaluator.eval(script, person2, 3); assertEquals(true, result); Entity person3 = new DynamicEntity(personWeightEntityType); person3.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person3, 3); assertEquals(true, result); } @Test void testGt() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').gt(100).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(false, result); Entity person2 = new DynamicEntity(personWeightEntityType); person2.set("weight", 100); result = jsMagmaScriptEvaluator.eval(script, person2, 3); assertEquals(false, result); Entity person3 = new DynamicEntity(personWeightEntityType); person3.set("weight", 101); result = jsMagmaScriptEvaluator.eval(script, person3, 3); assertEquals(true, result); } @Test void testLt() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').lt(100).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(true, result); Entity person2 = new DynamicEntity(personWeightEntityType); person2.set("weight", 100); result = jsMagmaScriptEvaluator.eval(script, person2, 3); assertEquals(false, result); Entity person3 = new DynamicEntity(personWeightEntityType); person3.set("weight", 101); result = jsMagmaScriptEvaluator.eval(script, person3, 3); assertEquals(false, result); } @Test void testGe() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').ge(100).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(false, result); Entity person2 = new DynamicEntity(personWeightEntityType); person2.set("weight", 100); result = jsMagmaScriptEvaluator.eval(script, person2, 3); assertEquals(true, result); Entity person3 = new DynamicEntity(personWeightEntityType); person3.set("weight", 101); result = jsMagmaScriptEvaluator.eval(script, person3, 3); assertEquals(true, result); } @Test void testLe() { Entity person0 = new DynamicEntity(personWeightEntityType); person0.set("weight", null); String script = "$('weight').le(100).value()"; Object result = jsMagmaScriptEvaluator.eval(script, person0, 3); assertEquals(false, result); Entity person1 = new DynamicEntity(personWeightEntityType); person1.set("weight", 99); result = jsMagmaScriptEvaluator.eval(script, person1, 3); assertEquals(true, result); Entity person2 = new DynamicEntity(personWeightEntityType); person2.set("weight", 100); result = jsMagmaScriptEvaluator.eval(script, person2, 3); assertEquals(true, result); Entity person3 = new DynamicEntity(personWeightEntityType); person3.set("weight", 101); result = jsMagmaScriptEvaluator.eval(script, person3, 3); assertEquals(false, result); } }
lgpl-3.0
datacleaner/DataCleaner
components/reference-data/src/test/java/org/datacleaner/beans/transform/SynonymLookupTransformerTest.java
9325
/** * DataCleaner (community edition) * Copyright (C) 2014 Free Software Foundation, Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.beans.transform; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.List; import org.datacleaner.configuration.DataCleanerConfiguration; import org.datacleaner.configuration.DataCleanerConfigurationImpl; import org.datacleaner.data.MockInputColumn; import org.datacleaner.data.MockInputRow; import org.datacleaner.reference.SynonymCatalog; import org.datacleaner.reference.TextFileSynonymCatalog; import org.junit.Test; public class SynonymLookupTransformerTest { private final DataCleanerConfiguration configuration = new DataCleanerConfigurationImpl(); private final SynonymCatalog sc = new TextFileSynonymCatalog("my synonyms", "src/test/resources/synonym-countries.txt", true, "UTF8"); @Test public void testCaseInsensitiveMathingOnEveryToken() throws Exception { final SynonymCatalog sc = new TextFileSynonymCatalog("my synonyms", "src/test/resources/synonym-countries.txt", false, "UTF8"); final MockInputColumn<String> col = new MockInputColumn<>("my col", String.class); final SynonymLookupTransformer transformer = new SynonymLookupTransformer(col, sc, true, configuration); transformer.replaceInlinedSynonyms = true; transformer.init(); assertEquals("Hello DNK DNK DNK!", transformer.transform(new MockInputRow().put(col, "Hello denmark dnk dk!"))[0]); assertEquals("DNK", transformer.transform(new MockInputRow().put(col, "dk"))[0]); assertEquals("Hello GBR DNK GBR.", transformer.transform(new MockInputRow().put(col, "Hello United KINGDOM danmark uk."))[0]); transformer.close(); } @Test public void testCaseInsensitiveMathingOnCompleteExpression() throws Exception { final SynonymCatalog sc = new TextFileSynonymCatalog("my synonyms", "src/test/resources/synonym-countries.txt", false, "UTF8"); final MockInputColumn<String> col = new MockInputColumn<>("my col", String.class); final SynonymLookupTransformer transformer = new SynonymLookupTransformer(col, sc, true, configuration); transformer.replaceInlinedSynonyms = false; transformer.init(); assertEquals("Hello denmark dnk dk!", transformer.transform(new MockInputRow().put(col, "Hello denmark dnk dk!"))[0]); assertNull(transformer.transform(new MockInputRow().put(col, "Hello denmark dnk dk!"))[1]); assertNull(transformer.transform(new MockInputRow().put(col, "Hello denmark dnk dk!"))[2]); assertEquals("DNK", transformer.transform(new MockInputRow().put(col, "dk"))[0]); assertEquals("dk", transformer.transform(new MockInputRow().put(col, "dk"))[1]); assertEquals("DNK", transformer.transform(new MockInputRow().put(col, "dk"))[2]); assertEquals("Hello United KINGDOM danmark uk.", transformer.transform(new MockInputRow().put(col, "Hello United KINGDOM danmark uk."))[0]); assertNull(transformer.transform(new MockInputRow().put(col, "Hello United KINGDOM danmark uk."))[1]); assertNull(transformer.transform(new MockInputRow().put(col, "Hello United KINGDOM danmark uk."))[2]); transformer.close(); } @Test public void testTransformWithCompleteInput() throws Exception { final MockInputColumn<String> col = new MockInputColumn<>("my col", String.class); // with retain original value SynonymLookupTransformer transformer = new SynonymLookupTransformer(col, sc, true, configuration); transformer.replaceInlinedSynonyms = false; assertEquals(3, transformer.getOutputColumns().getColumnCount()); assertEquals("my col (synonyms replaced)", transformer.getOutputColumns().getColumnName(0)); transformer.init(); assertEquals("hello", transformer.transform(new MockInputRow().put(col, "hello"))[0]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[0]); assertEquals("I come from Albania!", transformer.transform(new MockInputRow().put(col, "I come from Albania!"))[0]); transformer.close(); // without retain original value transformer = new SynonymLookupTransformer(col, sc, false, configuration); transformer.replaceInlinedSynonyms = false; assertEquals(3, transformer.getOutputColumns().getColumnCount()); assertEquals("my col (synonyms replaced)", transformer.getOutputColumns().getColumnName(0)); assertEquals("my col (synonyms found)", transformer.getOutputColumns().getColumnName(1)); assertEquals("my col (master terms found)", transformer.getOutputColumns().getColumnName(2)); transformer.init(); assertNull(transformer.transform(new MockInputRow().put(col, "hello"))[0]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[0]); assertEquals("Albania", transformer.transform(new MockInputRow().put(col, "Albania"))[1]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[2]); assertNull(transformer.transform(new MockInputRow().put(col, "foo"))[0]); assertNull(transformer.transform(new MockInputRow().put(col, "foo"))[1]); assertNull(transformer.transform(new MockInputRow().put(col, "foo"))[2]); transformer.close(); } @Test public void testTransformWithEveryToken() throws Exception { final MockInputColumn<String> col = new MockInputColumn<>("my col", String.class); // with retain original value SynonymLookupTransformer transformer = new SynonymLookupTransformer(col, sc, true, configuration); transformer.replaceInlinedSynonyms = true; transformer.replacedSynonymsType = SynonymLookupTransformer.ReplacedSynonymsType.LIST; transformer.init(); assertEquals(3, transformer.getOutputColumns().getColumnCount()); assertEquals("my col (synonyms replaced)", transformer.getOutputColumns().getColumnName(0)); assertEquals("my col (synonyms found)", transformer.getOutputColumns().getColumnName(1)); assertEquals("my col (master terms found)", transformer.getOutputColumns().getColumnName(2)); assertEquals("hello", transformer.transform(new MockInputRow().put(col, "hello"))[0]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[0]); assertEquals("I come from ALB!", transformer.transform(new MockInputRow().put(col, "I come from ALB!"))[0]); assertEquals("I come from GBR!", transformer.transform(new MockInputRow().put(col, "I come from Britain!"))[0]); assertEquals("I come from GBR!", transformer.transform(new MockInputRow().put(col, "I come from Great Britain!"))[0]); final Object[] result = transformer.transform(new MockInputRow().put(col, "I come from Great Great Britain Albania!")); assertEquals("I come from Great GBR ALB!", result[0]); @SuppressWarnings("unchecked") final List<String> synonyms = (List<String>) result[1]; @SuppressWarnings("unchecked") final List<String> masterTerms = (List<String>) result[2]; assertEquals("Great Britain", synonyms.get(0)); assertEquals("Albania", synonyms.get(1)); assertEquals("GBR", masterTerms.get(0)); assertEquals("ALB", masterTerms.get(1)); transformer.close(); // without retain original value transformer = new SynonymLookupTransformer(col, sc, false, configuration); transformer.replaceInlinedSynonyms = false; transformer.init(); assertEquals(3, transformer.getOutputColumns().getColumnCount()); assertEquals("my col (synonyms replaced)", transformer.getOutputColumns().getColumnName(0)); assertNull(transformer.transform(new MockInputRow().put(col, "hello"))[0]); assertNull(transformer.transform(new MockInputRow().put(col, "hello"))[1]); assertNull(transformer.transform(new MockInputRow().put(col, "hello"))[2]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[0]); assertEquals("Albania", transformer.transform(new MockInputRow().put(col, "Albania"))[1]); assertEquals("ALB", transformer.transform(new MockInputRow().put(col, "Albania"))[2]); transformer.close(); } }
lgpl-3.0
nightscape/JMathLib
src/jmathlib/toolbox/jmathlib/matrix/not.java
2331
package jmathlib.toolbox.jmathlib.matrix; import jmathlib.core.tokens.numbertokens.DoubleNumberToken; import jmathlib.core.tokens.Token; import jmathlib.core.tokens.OperandToken; import jmathlib.core.tokens.LogicalToken; import jmathlib.core.functions.ExternalFunction; import jmathlib.core.interpreter.GlobalValues; /**An external function for computing NOT a matrix */ public class not extends ExternalFunction { /**return a matrix * @param operands[0] = matrix * @return matrix function NOT of each element */ public OperandToken evaluate(Token[] operands, GlobalValues globals) { // two operands (e.g. not(A) ) if (getNArgIn(operands) != 1) throwMathLibException("not: number of arguments != 1"); if (operands[0] instanceof DoubleNumberToken) { DoubleNumberToken num = (DoubleNumberToken)operands[0]; int n = num.getNumberOfElements(); boolean[] values = new boolean[n]; for (int i=0; i<n ; i++) { if (num.getValueIm(i)!=0.0) throwMathLibException("not: only works on REAL numbers"); if (num.getValueRe(i) != 0.0) { values[i] = false; } else { values[i] = true; } } return new LogicalToken(num.getSize(), values); } else if (operands[0] instanceof LogicalToken) { LogicalToken l = (LogicalToken)operands[0]; int n = l.getNumberOfElements(); boolean[] ret = new boolean[n]; for (int i=0; i<n; i++) { ret[i] = !l.getValue(i); } return new LogicalToken(l.getSize(), ret); } else { throwMathLibException("not: works on numbers and logical only"); return null; } } // end eval } /* @GROUP matrix @SYNTAX answer = not(matrix) @DOC Returns the boolean NOT of all the elements of a matrix. @NOTES @EXAMPLES <programlisting> not([false, true]) = [true, false] not([1,1;1,1]) = [0,0;0,0] not([0,1,2]) = [1,0,0] </programlisting> @SEE and, or, xor */
lgpl-3.0
EasysoftCompany/LPTI3
calculadora+cosasraras/src/java/BD/cDatos.java
3546
/* * Copyright (C) 2014 Easysoft Company * * 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package BD; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * * @author Ger */ public class cDatos { private String usrBD; private String passBD; private String urlBD; private String driverClassName; private Connection conn = null; private Statement estancia; public cDatos(String usuarioBD, String passwordBD, String url, String driverClassName) { this.usrBD = usuarioBD; this.passBD = passwordBD; this.urlBD = url; this.driverClassName = driverClassName; } public cDatos() { //poner los datos apropiados this.usrBD = "root"; this.passBD = ""; this.urlBD = "jdbc:mysql://127.0.0.1:3306/bd_220115";//Si Somos huevones le cambiamos la BD xD this.driverClassName = "com.mysql.jdbc.Driver"; } //metodos para establecer los valores de conexion a la BD public void setUsuarioBD(String usuario) throws SQLException { this.usrBD = usuario; } public void setPassBD(String pass) { this.passBD = pass; } public void setUrlBD(String url) { this.urlBD = url; } public void setConn(Connection conn) { this.conn = conn; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } //Conexion a la BD public void conectar() throws SQLException { try { Class.forName(this.driverClassName).newInstance(); this.conn = DriverManager.getConnection(this.urlBD, this.usrBD, this.passBD); } catch (Exception err) { System.out.println("Error " + err.getMessage()); } } //Cerrar la conexion de BD public void cierraConexion() throws SQLException { this.conn.close(); } //Metodos para ejecutar sentencias SQL public ResultSet consulta(String consulta) throws SQLException { this.estancia = (Statement) conn.createStatement(); return this.estancia.executeQuery(consulta); } public void actualizar(String actualiza) throws SQLException { this.estancia = (Statement) conn.createStatement(); estancia.executeUpdate(actualiza); } public ResultSet borrar(String borra) throws SQLException { Statement st = (Statement) this.conn.createStatement(); return (ResultSet) st.executeQuery(borra); } public int insertar(String inserta) throws SQLException { Statement st = (Statement) this.conn.createStatement(); return st.executeUpdate(inserta); } }
unlicense
Pieterjaninfo/PP
src/pp/block6/cc/func/TypeKind.java
217
package pp.block6.cc.func; /** Pascal data type kind. */ public enum TypeKind { /** Integer base type. */ INT, /** Boolean base type. */ BOOL, /** Function type. */ FUNC, /** Array compound type. */ ARRAY; }
unlicense
nmsorgeslabs/anxova
anxova/src/main/java/org/nms/anxova/parse/IElementParser.java
344
package org.nms.anxova.parse; import java.util.List; import org.nms.anxova.process.beans.IElement; public interface IElementParser { /** * Parses a list of elements. * * @param elements List of elements * @return List of elements parsed */ @SuppressWarnings("rawtypes") public List<IElement> parse(IElement...elements); }
unlicense
aol/cyclops-react
cyclops/src/test/java/cyclops/data/basetests/HeadAndTail.java
2585
package cyclops.data.basetests; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Supplier; import cyclops.control.Eval; import cyclops.control.Maybe; import cyclops.reactive.ReactiveSeq; import cyclops.function.Memoize; import lombok.AllArgsConstructor; /** * A class that represents a lazily constructed Head and Tail from a non-scalar data type * * @author johnmcclean * * @param <T> Data type of elements in this Head and Tail */ @AllArgsConstructor public class HeadAndTail<T> { private final Supplier<T> head; private final Supplier<ReactiveSeq<T>> tail; private final Supplier<Boolean> isHead; public static <T> HeadAndTail<T> headAndTail(Iterable<T> it){ return new HeadAndTail<>(it.iterator()); } /** * Construct a HeadAndTail from an Iterator * * @param it Iterator to construct head and tail from */ public HeadAndTail(final Iterator<T> it) { isHead = Memoize.memoizeSupplier(() -> it.hasNext()); head = Memoize.memoizeSupplier(() -> { if (isHead.get()) return it.next(); throw new NoSuchElementException(); }); tail = Memoize.memoizeSupplier(() -> { if (isHead.get()) head.get(); else return ReactiveSeq.empty(); return ReactiveSeq.fromIterator(it); }); } /** * @return true if the head is present */ public boolean isHeadPresent() { return isHead.get(); } /** * @return Head (first) value, will throw an exception if the head is not present */ public T head() { return head.get(); } /** * @return Optional.zero if the head is not present, otherwise an Optional containing the head */ public Optional<T> headOptional() { return isHeadPresent() ? Optional.of(head()) : Optional.empty(); } /** * @return Maybe.none if the head is not present, otherwise a Maybe.some containing the first value */ public Maybe<T> headMaybe() { return isHeadPresent() ? Maybe.fromEval(Eval.later(head)) : Maybe.nothing(); } /** * @return A Stream containing the Head if present */ public ReactiveSeq<T> headStream() { return isHeadPresent() ? ReactiveSeq.of(head) .map(Supplier::get) : ReactiveSeq.empty(); } /** * @return The tail */ public ReactiveSeq<T> tail() { return tail.get(); } }
apache-2.0
intalio/axis2
modules/metadata/test/org/apache/axis2/jaxws/description/builder/DescriptionBuilderTests.java
13838
/* * 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.axis2.jaxws.description.builder; import junit.framework.TestCase; import org.apache.axis2.jaxws.description.EndpointDescription; import javax.jws.WebParam.Mode; import javax.jws.WebService; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Directly test the Description classes built via annotations without a WSDL file. These tests * focus on combinations of the following: - A generic service (no annotations) - A generated * service (annotations) - An SEI */ public class DescriptionBuilderTests extends TestCase { /* * ======================================================================== * ServiceDescription Tests * ======================================================================== */ public void testCreateWebServiceAnnot() { String name = "EchoServiceAnnotated"; String targetNamespace = "http://description.jaxws.axis2.apache.org/"; String serviceName = "EchoServiceName"; String wsdlLocation = "http://EchoService/wsdl"; String endpointInterface = "EchoServiceEndpointInterface"; String portName = "EchoServiceAnnotatedPort"; WebServiceAnnot webServiceAnnotImpl1 = WebServiceAnnot.createWebServiceAnnotImpl(); WebServiceAnnot webServiceAnnotImpl2 = WebServiceAnnot.createWebServiceAnnotImpl(name, targetNamespace, serviceName, wsdlLocation, endpointInterface, portName); DescriptionBuilderComposite descriptionBuilderComposite = new DescriptionBuilderComposite(); descriptionBuilderComposite.setWebServiceAnnot(webServiceAnnotImpl2); WebService webServiceAnnotImpl3 = descriptionBuilderComposite.getWebServiceAnnot(); assertNotNull("WebService name not set", webServiceAnnotImpl3.name()); assertNotNull("WebService targetNamespace not set", webServiceAnnotImpl3.targetNamespace()); assertNotNull("WebService serviceName not set", webServiceAnnotImpl3.serviceName()); assertNotNull("WebService wsdlLocation not set", webServiceAnnotImpl3.wsdlLocation()); assertNotNull("WebService endpointInterface not set", webServiceAnnotImpl3.endpointInterface()); System.out.println("WebService name:" + webServiceAnnotImpl3.name()); } public void testCreateWebServiceProviderAnnot() { String name = "EchoServiceAnnotated"; String targetNamespace = "http://description.jaxws.axis2.apache.org/"; String serviceName = "EchoServiceName"; String wsdlLocation = "http://EchoService/wsdl"; String endpointInterface = "EchoServiceEndpointInterface"; String portName = "EchoServiceAnnotatedPort"; WebServiceProviderAnnot webServiceProviderAnnot = WebServiceProviderAnnot.createWebServiceAnnotImpl(); webServiceProviderAnnot.setPortName(portName); webServiceProviderAnnot.setServiceName(serviceName); webServiceProviderAnnot.setTargetNamespace(targetNamespace); webServiceProviderAnnot.setWsdlLocation(wsdlLocation); DescriptionBuilderComposite descriptionBuilderComposite = new DescriptionBuilderComposite(); descriptionBuilderComposite.setWebServiceProviderAnnot(webServiceProviderAnnot); javax.xml.ws.WebServiceProvider webServiceProviderAnnot3 = descriptionBuilderComposite.getWebServiceProviderAnnot(); assertEquals("WebServiceProvider port name not set properly", webServiceProviderAnnot3.portName(), portName); assertEquals("WebServiceProvider targetNamespace not set properly", webServiceProviderAnnot3.targetNamespace(), targetNamespace); assertEquals("WebServiceProvider serviceName not set properly", webServiceProviderAnnot3.serviceName(), serviceName); assertEquals("WebServiceProvider wsdlLocation not set properly", webServiceProviderAnnot3.wsdlLocation(), wsdlLocation); System.out.println("WebService name:" + webServiceProviderAnnot3.portName()); } public void testCreateWebMethodAnnot() { String operationName = "echoStringMethod"; String action = "urn:EchoStringMethod"; boolean exclude = true; WebMethodAnnot webMethodAnnot = WebMethodAnnot.createWebMethodAnnotImpl(); webMethodAnnot.setOperationName(operationName); webMethodAnnot.setAction(action); webMethodAnnot.setExclude(exclude); DescriptionBuilderComposite dbc = new DescriptionBuilderComposite(); MethodDescriptionComposite mdc = new MethodDescriptionComposite(); mdc.setWebMethodAnnot(webMethodAnnot); mdc.setMethodName(operationName); dbc.addMethodDescriptionComposite(mdc); WebMethodAnnot webMethodAnnot3 = dbc.getMethodDescriptionComposite(operationName, 1).getWebMethodAnnot(); assertEquals("WebMethod operation name not set properly", webMethodAnnot3.operationName(), operationName); assertEquals("WebMethod action not set properly", webMethodAnnot3.action(), action); assertEquals("WebMethod exclude flag not set properly", webMethodAnnot3.exclude(), exclude); } public void testCreateWebParamAnnot() { String name = "arg0"; String partName = "sku"; String targetNamespace = "http://description.jaxws.axis2.apache.org/"; Mode mode = Mode.IN; boolean header = true; WebParamAnnot webParamAnnot = WebParamAnnot.createWebParamAnnotImpl(); webParamAnnot.setName(name); webParamAnnot.setPartName(partName); webParamAnnot.setMode(mode); webParamAnnot.setTargetNamespace(targetNamespace); webParamAnnot.setHeader(header); DescriptionBuilderComposite dbc = new DescriptionBuilderComposite(); ParameterDescriptionComposite pdc = new ParameterDescriptionComposite(); pdc.setWebParamAnnot(webParamAnnot); pdc.setParameterType("int"); MethodDescriptionComposite mdc = new MethodDescriptionComposite(); mdc.setMethodName("TestMethod1"); try { //First test adds this pdc out of bounds mdc.addParameterDescriptionComposite(pdc, 1); } catch (IndexOutOfBoundsException e) { // Expected flow } catch (Exception e) { fail("Caught unexpected exception" + e); } try { //Now, add it at the proper position mdc.addParameterDescriptionComposite(pdc, 0); } catch (IndexOutOfBoundsException e) { // Expected flow } catch (Exception e) { fail("Caught unexpected exception" + e); } dbc.addMethodDescriptionComposite(mdc); WebParamAnnot webParamAnnot3 = dbc.getMethodDescriptionComposite("TestMethod1", 1) .getParameterDescriptionComposite(0).getWebParamAnnot(); assertEquals("WebMethod name not set properly", webParamAnnot3.name(), name); assertEquals("WebMethod PartName not set properly", webParamAnnot3.partName(), partName); assertEquals("WebMethod Mode flag not set properly", webParamAnnot3.mode(), mode); assertEquals("WebMethod Target Namespace not set properly", webParamAnnot3.targetNamespace(), targetNamespace); assertEquals("WebMethod Header not set properly", webParamAnnot3.header(), header); assertEquals("Unable to convert string to parameterTypeClass", pdc.getParameterTypeClass().getName(), "int"); } public void testGenericAnnotationInstancesAndProcessor() { TestProcessor annotationProcessor = new TestProcessor(); annotationProcessor.setAnnotationInstanceClassName(CustomAnnotation.class.getName()); DescriptionBuilderComposite dbc = new DescriptionBuilderComposite(); dbc.addCustomAnnotationProcessor(annotationProcessor); Map<String, CustomAnnotationProcessor> processors = dbc.getCustomAnnotationProcessors(); assertNotNull(processors); assertNotNull(processors.values()); assertEquals(processors.values().size(), 1); CustomAnnotationProcessor instance = processors.get(CustomAnnotation.class.getName()); assertNotNull(instance); assertEquals(instance.getClass().getName(), TestProcessor.class.getName()); assertEquals(instance.getAnnotationInstanceClassName(), CustomAnnotation.class.getName()); CustomAnnotation annotation = new CustomAnnotation(); annotation.setAnnotationClassName(Custom.class.getName()); annotation.setTarget(ElementType.TYPE); annotation.addParameterData("name", annotation.getClass().getSimpleName()); dbc.addCustomAnnotationInstance(annotation); List<CustomAnnotationInstance> gaiList = dbc.getCustomAnnotationInstances(); assertNotNull(gaiList); assertEquals(1, gaiList.size()); CustomAnnotationInstance gai = gaiList.get(0); assertNotNull(gai); assertEquals(gai.getClass().getName(), CustomAnnotation.class.getName()); assertEquals(gai.getAnnotationClassName(), Custom.class.getName()); assertEquals(gai.getTarget(), ElementType.TYPE); assertEquals(gai.getParameterData("name"), gai.getClass().getSimpleName()); IllegalArgumentException ex = null; try { gai.getParameterData("unknown"); } catch(IllegalArgumentException iae) { ex = iae; } assertNotNull(ex); try { gai.addParameterData("unknown", null); } catch(IllegalArgumentException iae) { ex = iae; } assertNotNull(ex); } class TestProcessor implements CustomAnnotationProcessor { private String annotationInstanceClassName; public String getAnnotationInstanceClassName() { return annotationInstanceClassName; } public void setAnnotationInstanceClassName(String annotationInstanceClassName) { this.annotationInstanceClassName = annotationInstanceClassName; } public void processTypeLevelAnnotation(EndpointDescription ed, CustomAnnotationInstance annotation) { // do nothing, testing purproses only } } class CustomAnnotation implements CustomAnnotationInstance { private Map<String, Object> dataMap = new HashMap<String, Object>(); private ElementType elementType; List<String> knownParamNames; private String annotationClassName; CustomAnnotation(List<String> knownParamNames) { this.knownParamNames = knownParamNames; } CustomAnnotation() { knownParamNames = new ArrayList<String>(); knownParamNames.add("name"); } public void setAnnotationClassName(String annotationClassName) { this.annotationClassName = annotationClassName; } public String getAnnotationClassName() { return annotationClassName; } public void addParameterData(String paramName, Object value) throws IllegalArgumentException { checkParamName(paramName); dataMap.put(paramName, value); } public Object getParameterData(String paramName) throws IllegalArgumentException { checkParamName(paramName); return dataMap.get(paramName); } public void setTarget(ElementType elementType) { this.elementType = elementType; } public ElementType getTarget() { return elementType; } private void checkParamName(String paramName) throws IllegalArgumentException { if(knownParamNames != null && !knownParamNames.isEmpty() && !knownParamNames.contains(paramName)) { throw new IllegalArgumentException("The parameter " + paramName + " is an unknown parameter for the CustomAnnotation type."); } } } @interface Custom { String name() default ""; } @WebService @Custom class AnnotatedService { public String echo(String echoString) { return echoString; } } }
apache-2.0
gracefullife/gerrit
gerrit-server/src/main/java/com/google/gerrit/server/project/ListChildProjects.java
3718
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.project; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.project.ProjectJson.ProjectInfo; import com.google.inject.Inject; import org.kohsuke.args4j.Option; import java.util.List; import java.util.Map; public class ListChildProjects implements RestReadView<ProjectResource> { @Option(name = "--recursive", usage = "to list child projects recursively") private boolean recursive; private final ProjectCache projectCache; private final AllProjectsName allProjects; private final ProjectJson json; private final ProjectNode.Factory projectNodeFactory; @Inject ListChildProjects(ProjectCache projectCache, AllProjectsName allProjects, ProjectJson json, ProjectNode.Factory projectNodeFactory) { this.projectCache = projectCache; this.allProjects = allProjects; this.json = json; this.projectNodeFactory = projectNodeFactory; } @Override public List<ProjectInfo> apply(ProjectResource rsrc) { if (recursive) { return getChildProjectsRecursively(rsrc.getNameKey(), rsrc.getControl().getCurrentUser()); } else { return getDirectChildProjects(rsrc.getNameKey()); } } private List<ProjectInfo> getDirectChildProjects(Project.NameKey parent) { List<ProjectInfo> childProjects = Lists.newArrayList(); for (Project.NameKey projectName : projectCache.all()) { ProjectState e = projectCache.get(projectName); if (e == null) { // If we can't get it from the cache, pretend it's not present. continue; } if (parent.equals(e.getProject().getParent(allProjects))) { childProjects.add(json.format(e.getProject())); } } return childProjects; } private List<ProjectInfo> getChildProjectsRecursively(Project.NameKey parent, CurrentUser user) { Map<Project.NameKey, ProjectNode> projects = Maps.newHashMap(); for (Project.NameKey name : projectCache.all()) { ProjectState p = projectCache.get(name); if (p == null) { // If we can't get it from the cache, pretend it's not present. continue; } projects.put(name, projectNodeFactory.create(p.getProject(), p.controlFor(user).isVisible())); } for (ProjectNode key : projects.values()) { ProjectNode node = projects.get(key.getParentName()); if (node != null) { node.addChild(key); } } return getChildProjectsRecursively(projects.get(parent)); } private List<ProjectInfo> getChildProjectsRecursively(ProjectNode p) { List<ProjectInfo> allChildren = Lists.newArrayList(); for (ProjectNode c : p.getChildren()) { if (c.isVisible()) { allChildren.add(json.format(c.getProject())); allChildren.addAll(getChildProjectsRecursively(c)); } } return allChildren; } }
apache-2.0
zogwei/zeus3
schedule/src/main/java/com/taobao/zeus/jobs/sub/conf/OnlineConf.java
729
package com.taobao.zeus.jobs.sub.conf; import org.apache.hadoop.conf.Configuration; import com.taobao.zeus.log.Global; public class OnlineConf extends Configuration{ public OnlineConf(){ set("hadoop.job.ugi", "tbresys,cug-tbauction,cug-tbdp,cug-tbptd-dev,cug-verticalmarket,cug-tbdataapplication,cug-taobao-sns,cug-mercury,#resys123"); set("mapred.job.queue.name","cug-tbdataapplication"); set("proxy.hosts","172.24.160.65:1080"); set("hadoop.rpc.socket.factory.class.default","com.taobao.cmp.proxy.HadoopProxy"); set("fs.default.name",Global.getConfig("fs.default.name")); set("mapred.job.tracker",Global.getConfig("mapred.job.tracker")); set("mapred.working.dir",Global.getConfig("mapred.working.dir")); } }
apache-2.0
jivesoftware/miru
miru-stumptown-plugins/src/main/java/com/jivesoftware/os/miru/stumptown/plugins/StumptownEndpoints.java
3529
package com.jivesoftware.os.miru.stumptown.plugins; import com.jivesoftware.os.miru.api.activity.MiruPartitionId; import com.jivesoftware.os.miru.plugin.partition.MiruPartitionUnavailableException; import com.jivesoftware.os.miru.plugin.solution.MiruPartitionResponse; import com.jivesoftware.os.miru.plugin.solution.MiruRequest; import com.jivesoftware.os.miru.plugin.solution.MiruRequestAndReport; import com.jivesoftware.os.miru.plugin.solution.MiruResponse; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import com.jivesoftware.os.routing.bird.shared.ResponseHelper; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static com.jivesoftware.os.miru.stumptown.plugins.StumptownConstants.CUSTOM_QUERY_ENDPOINT; import static com.jivesoftware.os.miru.stumptown.plugins.StumptownConstants.STUMPTOWN_PREFIX; @Singleton @Path(STUMPTOWN_PREFIX) public class StumptownEndpoints { private static final MetricLogger log = MetricLoggerFactory.getLogger(); private final StumptownInjectable injectable; private final ResponseHelper responseHelper = ResponseHelper.INSTANCE; public StumptownEndpoints( @Context StumptownInjectable injectable) { this.injectable = injectable; } @POST @Path(CUSTOM_QUERY_ENDPOINT) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response scoreStumptowning(MiruRequest<StumptownQuery> request) { try { long t = System.currentTimeMillis(); MiruResponse<StumptownAnswer> response = injectable.score(request); if (response.answer != null && response.answer.waveforms != null) { log.info("scoreStumptowning: " + response.answer.waveforms.size() + " in " + (System.currentTimeMillis() - t) + " ms"); } return responseHelper.jsonResponse(response); } catch (MiruPartitionUnavailableException | InterruptedException e) { return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Unavailable " + e.getMessage()).build(); } catch (Exception e) { log.error("Failed to score trending.", e); return Response.serverError().build(); } } @POST @Path(CUSTOM_QUERY_ENDPOINT + "/{partitionId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response scoreStumptowning(@PathParam("partitionId") int id, MiruRequestAndReport<StumptownQuery, StumptownReport> requestAndReport) { MiruPartitionId partitionId = MiruPartitionId.of(id); try { MiruPartitionResponse<StumptownAnswer> result = injectable.score(partitionId, requestAndReport); return responseHelper.jsonResponse(result != null ? result : new MiruPartitionResponse<>(StumptownAnswer.EMPTY_RESULTS, null)); } catch (MiruPartitionUnavailableException | InterruptedException e) { return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Unavailable " + e.getMessage()).build(); } catch (Exception e) { log.error("Failed to score trending for partition: " + partitionId.getId(), e); return Response.serverError().build(); } } }
apache-2.0
xiwc/tms
src/main/java/com/lhjz/portal/util/ZipUtil.java
5905
package com.lhjz.portal.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; /** * ZIP文件压缩和解压(要使用apache ant.jar以处理中文乱码) * * @creation 2014年4月12日 下午7:15:00 * @modification 2014年4月12日 下午7:15:00 * @company * @author xiweicheng * @version 1.0 * */ public class ZipUtil { /** * 压缩文件file成zip文件zipFile * * @param file * 要压缩的文件 * @param zipFile * 压缩文件存放地方 * @throws Exception */ public static void zip(File file, File zipFile) throws Exception { ZipOutputStream output = null; try { output = new ZipOutputStream(new FileOutputStream(zipFile)); // 顶层目录开始 zipFile(output, file, ""); } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (output != null) { output.flush(); output.close(); } } } /** * 压缩文件为zip格式 * * @param output * ZipOutputStream对象 * @param file * 要压缩的文件或文件夹 * @param basePath * 条目根目录 * @throws IOException */ private static void zipFile(ZipOutputStream output, File file, String basePath) throws IOException { FileInputStream input = null; try { // 文件为目录 if (file.isDirectory()) { // 得到当前目录里面的文件列表 File list[] = file.listFiles(); basePath = basePath + (basePath.length() == 0 ? "" : "/") + file.getName(); // 循环递归压缩每个文件 for (File f : list) { zipFile(output, f, basePath); } } else { // 压缩文件 basePath = (basePath.length() == 0 ? "" : basePath + "/") + file.getName(); // System.out.println(basePath); output.putNextEntry(new ZipEntry(basePath)); input = new FileInputStream(file); int readLen = 0; byte[] buffer = new byte[1024 * 8]; while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) { output.write(buffer, 0, readLen); } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (input != null) { input.close(); } } } /** * 解压zip文件 * * @param zipFilePath * zip文件绝对路径 * @param unzipDirectory * 解压到的目录 * @throws Exception */ public static void unzip(String zipFilePath, String unzipDirectory) throws Exception { // 定义输入输出流对象 InputStream input = null; OutputStream output = null; ZipFile zipFile = null; try { // 创建文件对象 File file = new File(zipFilePath); // 创建zip文件对象 zipFile = new ZipFile(file); // 创建本zip文件解压目录 String name = file.getName().substring(0, file.getName().lastIndexOf(".")); File unzipFile = new File(unzipDirectory + "/" + name); if (unzipFile.exists()) { unzipFile.delete(); } unzipFile.mkdir(); // 得到zip文件条目枚举对象 Enumeration<?> zipEnum = zipFile.entries(); // 定义对象 ZipEntry entry = null; String entryName = null, path = null; String names[] = null; int length; // 循环读取条目 while (zipEnum.hasMoreElements()) { // 得到当前条目 entry = (ZipEntry) zipEnum.nextElement(); entryName = new String(entry.getName()); // 用/分隔条目名称 names = entryName.split("\\/"); length = names.length; path = unzipFile.getAbsolutePath(); for (int v = 0; v < length; v++) { if (v < length - 1) { // 最后一个目录之前的目录 FileUtils.forceMkdir(new File(path += "/" + names[v] + "/")); } else { // 最后一个 if (entryName.endsWith("/")) { // 为目录,则创建文件夹 FileUtils.forceMkdir(new File(unzipFile.getAbsolutePath() + "/" + entryName)); } else { // 为文件,则输出到文件 input = zipFile.getInputStream(entry); output = new FileOutputStream(new File(unzipFile.getAbsolutePath() + "/" + entryName)); byte[] buffer = new byte[1024 * 8]; int readLen = 0; while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) { output.write(buffer, 0, readLen); } } } } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (input != null) { input.close(); } if (output != null) { output.flush(); output.close(); } if (zipFile != null) { zipFile.close(); } } } /** * 压缩多个文件. * * @author xiweicheng * @creation 2014年4月12日 下午7:43:12 * @modification 2014年4月12日 下午7:43:12 * @param file * @param filePaths */ public static void zip(File zipFile, String[] filePaths) { ZipOutputStream output = null; try { output = new ZipOutputStream(new FileOutputStream(zipFile)); FileInputStream input = null; try { // 文件为目录 for (String filePath : filePaths) { output.putNextEntry(new ZipEntry(new File(filePath).getName())); input = new FileInputStream(filePath); int readLen = 0; byte[] buffer = new byte[1024 * 8]; while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) { output.write(buffer, 0, readLen); } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (input != null) { input.close(); } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (output != null) { try { output.flush(); output.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
apache-2.0
jamesagnew/hapi-fhir
hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/config/TestDstu3Config.java
6256
package ca.uhn.fhir.jpa.config; import ca.uhn.fhir.jpa.dao.BaseJpaTest; import ca.uhn.fhir.jpa.subscription.match.deliver.email.EmailSenderImpl; import ca.uhn.fhir.jpa.subscription.match.deliver.email.IEmailSender; import ca.uhn.fhir.jpa.util.CircularQueueCaptureQueriesListener; import ca.uhn.fhir.jpa.util.CurrentThreadCaptureQueriesListener; import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.rest.server.mail.IMailSvc; import ca.uhn.fhir.rest.server.mail.MailConfig; import ca.uhn.fhir.rest.server.mail.MailSvc; import ca.uhn.fhir.validation.ResultSeverityEnum; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import ca.uhn.fhir.jpa.model.dialect.HapiFhirH2Dialect; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.sql.Connection; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.fail; @Configuration @Import(TestJPAConfig.class) @EnableTransactionManagement() public class TestDstu3Config extends BaseJavaConfigDstu3 { static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TestDstu3Config.class); private Exception myLastStackTrace; @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { return new CircularQueueCaptureQueriesListener(); } @Bean public BasicDataSource basicDataSource() { BasicDataSource retVal = new BasicDataSource() { @Override public Connection getConnection() { ConnectionWrapper retVal; try { retVal = new ConnectionWrapper(super.getConnection()); } catch (Exception e) { ourLog.error("Exceeded maximum wait for connection", e); logGetConnectionStackTrace(); // if ("true".equals(System.getStringProperty("ci"))) { fail("Exceeded maximum wait for connection: " + e); // } // System.exit(1); retVal = null; } try { throw new Exception(); } catch (Exception e) { myLastStackTrace = e; } return retVal; } private void logGetConnectionStackTrace() { StringBuilder b = new StringBuilder(); b.append("Last connection request stack trace:"); for (StackTraceElement next : myLastStackTrace.getStackTrace()) { b.append("\n "); b.append(next.getClassName()); b.append("."); b.append(next.getMethodName()); b.append("("); b.append(next.getFileName()); b.append(":"); b.append(next.getLineNumber()); b.append(")"); } ourLog.info(b.toString()); } }; retVal.setDriver(new org.h2.Driver()); retVal.setUrl("jdbc:h2:mem:testdb_dstu3"); retVal.setMaxWaitMillis(10000); retVal.setUsername(""); retVal.setPassword(""); /* * We use a randomized number of maximum threads in order to try * and catch any potential deadlocks caused by database connection * starvation */ int maxThreads = (int) (Math.random() * 6.0) + 1; if ("true".equals(System.getProperty("single_db_connection"))) { maxThreads = 1; } retVal.setMaxTotal(maxThreads); return retVal; } @Bean @Primary() public DataSource dataSource() { DataSource dataSource = ProxyDataSourceBuilder .create(basicDataSource()) // .logQueryBySlf4j(SLF4JLogLevel.INFO, "SQL") .logSlowQueryBySlf4j(1000, TimeUnit.MILLISECONDS) .afterQuery(captureQueriesListener()) .afterQuery(new CurrentThreadCaptureQueriesListener()) .countQuery() .build(); return dataSource; } @Bean public IEmailSender emailSender() { final MailConfig mailConfig = new MailConfig().setSmtpHostname("localhost").setSmtpPort(3025); final IMailSvc mailSvc = new MailSvc(mailConfig); return new EmailSenderImpl(mailSvc); } @Override @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory) { LocalContainerEntityManagerFactoryBean retVal = super.entityManagerFactory(theConfigurableListableBeanFactory); retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu3"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); return retVal; } private Properties jpaProperties() { Properties extraProperties = new Properties(); extraProperties.put("hibernate.jdbc.batch_size", "50"); extraProperties.put("hibernate.format_sql", "false"); extraProperties.put("hibernate.show_sql", "false"); extraProperties.put("hibernate.hbm2ddl.auto", "update"); extraProperties.put("hibernate.dialect", HapiFhirH2Dialect.class.getName()); boolean enableLucene = myEnv.getProperty(BaseJpaTest.CONFIG_ENABLE_LUCENE, Boolean.TYPE, BaseJpaTest.CONFIG_ENABLE_LUCENE_DEFAULT_VALUE); Map<String, String> hibernateSearchProperties = BaseJpaTest.buildHibernateSearchProperties(enableLucene); extraProperties.putAll(hibernateSearchProperties); return extraProperties; } /** * Bean which validates incoming requests */ @Bean @Lazy public RequestValidatingInterceptor requestValidatingInterceptor() { RequestValidatingInterceptor requestValidator = new RequestValidatingInterceptor(); requestValidator.setFailOnSeverity(ResultSeverityEnum.ERROR); requestValidator.setAddResponseHeaderOnSeverity(null); requestValidator.setAddResponseOutcomeHeaderOnSeverity(ResultSeverityEnum.INFORMATION); requestValidator.addValidatorModule(instanceValidator()); return requestValidator; } /** * This lets the "@Value" fields reference properties from the properties file */ @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
apache-2.0
XinyueZ/AcClient
app/src/main/java/thereisnospon/acclient/modules/problem/list/search/SearchProblemPresenter.java
3057
package thereisnospon.acclient.modules.problem.list.search; import android.util.Log; import java.util.List; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import thereisnospon.acclient.data.SearchProblem; /** * Created by yzr on 16/6/10. */ public class SearchProblemPresenter implements SearchProblemContact.Presenter { SearchProblemContact.View view; SearchProblemContact.Model model; public SearchProblemPresenter(SearchProblemContact.View view) { this.view = view; this.model=new SearchProblemModel(); } @Override public void queryProblem(String query) { Log.d(TAG, "queryProblem: "+query); Observable.just(query) .observeOn(Schedulers.io()) .map(new Func1<String, List<SearchProblem>>() { @Override public List<SearchProblem> call(String s) { return model.queryProblem(s); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<List<SearchProblem>>() { @Override public void call(List<SearchProblem> searchProblems) { if(searchProblems!=null&&searchProblems.size()>0){ view.refreshSuccess(searchProblems); Log.d(TAG, "call: success"+searchProblems.size()); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { view.onFailure(throwable.getMessage()); } }); } private static String TAG="SSEARCH"; @Override public void loadMoreQuery( String query) { Log.d(TAG, "loadMoreQuery: "+query); Observable.just(query) .observeOn(Schedulers.io()) .map(new Func1<String, List<SearchProblem>>() { @Override public List<SearchProblem> call(String s) { return model.loadMoreQuery(s); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<List<SearchProblem>>() { @Override public void call(List<SearchProblem> searchProblems) { if(searchProblems!=null&&searchProblems.size()>0){ view.loadSccess(searchProblems); Log.d(TAG, "call: success "+searchProblems.size()); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { view.onFailure(throwable.getMessage()); } }); } }
apache-2.0
skoulouzis/lobcder
milton/milton-caldav/src/main/java/com/ettrema/http/caldav/PrincipalMatchReport.java
437
package com.ettrema.http.caldav; import com.bradmcevoy.http.Resource; import com.ettrema.http.report.Report; import org.jdom.Document; /** * * @author alex */ public class PrincipalMatchReport implements Report { public String getName() { return "principal-match"; } public String process(String host, String path, Resource r, Document doc) { throw new UnsupportedOperationException("Not supported yet."); } }
apache-2.0
deleidos/digitaledge-platform
webapp-proxy/src/main/java/com/deleidos/rtws/webapp/servlet/proxy/RegisterApiProxyServlet.java
14881
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.deleidos.rtws.webapp.servlet.proxy; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.deleidos.rtws.commons.webapp.auth.RtwsPrincipal; import com.deleidos.rtws.commons.webapp.auth.RtwsPrincipalAccess; import com.deleidos.rtws.commons.webauth.servlet.proxy.dest.TenantApiProxyDestProvider; import com.deleidos.rtws.webapp.model.AuthType; /** * This proxy is used to access the tenantapi registration REST services. * Its main purpose is to ensure any client accessing the registration * services has a valid uuid. */ public class RegisterApiProxyServlet extends PathLimitedRtwsServiceProxy { private Logger logger = Logger.getLogger(this.getClass()); public RegisterApiProxyServlet() { super(); this.requireProxiedUser = false; this.defaultServletPath = "/rtws/registerapi"; this.setDestProvider(new TenantApiProxyDestProvider()); } @Override protected boolean isProxyAuthorized(HttpServletRequest request) { boolean result = false; AuthType authType = null; try { authType = getPathAuthType(request.getPathInfo()); } catch(IllegalArgumentException e) { logger.error("Register proxy call misconfigured. A valid AuthType is required.", e); authType = null; } if(authType != null) { RtwsPrincipal rtwsPrincipal = RtwsPrincipalAccess.INSTANCE.getUserPrincipal(); switch(authType) { case UUID: // These paths just require a valid UUID, this data will be loaded by spring security result = (rtwsPrincipal != null && StringUtils.isNotBlank(rtwsPrincipal.getName())); break; case TenantId: // These paths require a valid UUID mapped to a teanntId, this data will be loaded by spring security result = (rtwsPrincipal != null && StringUtils.isNotBlank(rtwsPrincipal.getName()) && StringUtils.isNotBlank(rtwsPrincipal.getTenantId())); break; default: result = false; } } return result; } @Override protected RtwsPrincipal getProxiedUser(HttpServletRequest request) { RtwsPrincipal result = null; AuthType authType = null; try { authType = getPathAuthType(request.getPathInfo()); switch(authType) { case UUID: // These paths just require a valid UUID and don't have a valid tenantId; therefore, we'll make the request as TMS result = null; break; case TenantId: // These paths have a linked UUID and tenantId, make the request as said tenant. result = RtwsPrincipalAccess.INSTANCE.getUserPrincipal(); break; default: // This case should not have occurred based on the authorization logic throw new IllegalStateException("Unhandled Proxy User Case"); } } catch(IllegalArgumentException e) { // This case should not have occurred based on the authorization logic throw new IllegalStateException("Unhandled AuthType Case"); } return result; } }
apache-2.0
payneteasy/superfly
superfly-web/src/test/java/com/payneteasy/superfly/web/wicket/page/sso/SSOLoginPageTest.java
7149
package com.payneteasy.superfly.web.wicket.page.sso; import com.payneteasy.superfly.model.SSOSession; import com.payneteasy.superfly.model.SubsystemTokenData; import com.payneteasy.superfly.model.ui.subsystem.UISubsystem; import com.payneteasy.superfly.security.csrf.CsrfValidator; import com.payneteasy.superfly.service.SessionService; import com.payneteasy.superfly.service.SubsystemService; import com.payneteasy.superfly.web.wicket.page.AbstractPageTest; import com.payneteasy.superfly.web.wicket.utils.PageParametersBuilder; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import javax.servlet.http.Cookie; import java.util.HashMap; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; /** * @author rpuch */ public class SSOLoginPageTest extends AbstractPageTest { private SessionService sessionService; private SubsystemService subsystemService; private CsrfValidator csrfValidator; @Before public void setUp() { sessionService = EasyMock.createStrictMock(SessionService.class); subsystemService = EasyMock.createStrictMock(SubsystemService.class); csrfValidator = EasyMock.createStrictMock(CsrfValidator.class); expect(csrfValidator.persistTokenIntoSession(anyObject())).andReturn("123").anyTimes(); csrfValidator.validateToken(anyObject()); expectLastCall().anyTimes(); } @Override protected Object getBean(Class<?> type) { if (SessionService.class == type) { return sessionService; } else if (SubsystemService.class == type) { return subsystemService; } else if (type == CsrfValidator.class) { return csrfValidator; } return super.getBean(type); } @Test public void testNoSSOCookie() { UISubsystem subsystem = createTestSubsystem(); expect(subsystemService.getSubsystemByName("test-subsystem")) .andReturn(subsystem).anyTimes(); replay(subsystemService, csrfValidator); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test-subsystem"); put("targetUrl", "/target"); }})); tester.assertRenderedPage(SSOLoginPasswordPage.class); assertEquals("the subsystem", tester.getSession().getSsoLoginData().getSubsystemTitle()); assertEquals("subsystem-url", tester.getSession().getSsoLoginData().getSubsystemUrl()); verify(subsystemService, csrfValidator); } private UISubsystem createTestSubsystem() { UISubsystem subsystem = new UISubsystem(); subsystem.setId(1L); subsystem.setName("test-subsystem"); subsystem.setTitle("the subsystem"); subsystem.setSubsystemUrl("subsystem-url"); return subsystem; } @Test public void testWithSSOCookieAndNoValidSession() { expect(sessionService.getValidSSOSession("super-session-id")) .andReturn(null); expect(subsystemService.getSubsystemByName("test-subsystem")) .andReturn(createTestSubsystem()).anyTimes(); replay(sessionService, subsystemService, csrfValidator); tester.getRequest().addCookie(new Cookie("SSOSESSIONID", "super-session-id")); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test-subsystem"); put("targetUrl", "/target"); }})); tester.assertRenderedPage(SSOLoginPasswordPage.class); verify(sessionService, subsystemService, csrfValidator); } @Test public void testWithSSOCookieAndValidSessionAndCanNotLogin() { expect(sessionService.getValidSSOSession("super-session-id")) .andReturn(new SSOSession(1, "super-session-id")); expect(subsystemService.issueSubsystemTokenIfCanLogin(1, "test-subsystem")) .andReturn(null); replay(sessionService, subsystemService); tester.getRequest().addCookie(new Cookie("SSOSESSIONID", "super-session-id")); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test-subsystem"); put("targetUrl", "/target"); }})); tester.assertRenderedPage(SSOLoginErrorPage.class); tester.assertLabel("message", "Can&#039;t login to test-subsystem"); verify(sessionService, subsystemService); } @Test public void testWithSSOCookieAndValidSessionAndCanLogin() { expect(sessionService.getValidSSOSession("super-session-id")) .andReturn(new SSOSession(1, "super-session-id")); expect(subsystemService.issueSubsystemTokenIfCanLogin(1, "test-subsystem")) .andReturn(new SubsystemTokenData("abcdef", "http://some.host.test/landing-url")); replay(sessionService, subsystemService); tester.getRequest().addCookie(new Cookie("SSOSESSIONID", "super-session-id")); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test-subsystem"); put("targetUrl", "/target"); }})); tester.assertRedirectUrl("http://some.host.test/landing-url?subsystemToken=abcdef&targetUrl=%2Ftarget"); verify(sessionService, subsystemService); } @Test public void testWithSSOCookieAndValidSessionAndCanLoginShortenedUrl() { expect(sessionService.getValidSSOSession("super-session-id")) .andReturn(new SSOSession(1, "super-session-id")); expect(subsystemService.issueSubsystemTokenIfCanLogin(1, "test-subsystem")) .andReturn(new SubsystemTokenData("abcdef", "http://some.host.test/landing-url")); replay(sessionService, subsystemService); tester.getRequest().addCookie(new Cookie("SSOSESSIONID", "super-session-id")); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test-subsystem"); put("targetUrl", "http://some.domain/target"); }})); tester.assertRedirectUrl("http://some.host.test/landing-url?subsystemToken=abcdef&targetUrl=%2Ftarget"); verify(sessionService, subsystemService); } @Test public void testNoParams() { tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("subsystemIdentifier", "test"); }})); tester.assertRenderedPage(SSOLoginErrorPage.class); tester.assertLabel("message", "No targetUrl parameter specified"); tester.startPage(SSOLoginPage.class, PageParametersBuilder.fromMap(new HashMap<String, Object>() {{ put("targetUrl", "/target"); }})); tester.assertRenderedPage(SSOLoginErrorPage.class); tester.assertLabel("message", "No subsystemIdentifier parameter specified"); } }
apache-2.0
mdogan/hazelcast
hazelcast/src/main/java/com/hazelcast/client/config/package-info.java
735
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Contains classes related to config for com.hazelcast.client */ package com.hazelcast.client.config;
apache-2.0
ok2c/httpclient
httpclient5-cache/src/main/java/org/apache/hc/client5/http/schedule/package-info.java
1299
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ /** * Scheduling strategies used by HTTP cache implementations. */ package org.apache.hc.client5.http.schedule;
apache-2.0
zwets/flowable-engine
modules/flowable-form-engine/src/main/java/org/flowable/form/engine/impl/deployer/ParsedDeployment.java
3142
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.form.engine.impl.deployer; import java.util.List; import java.util.Map; import org.flowable.form.engine.impl.parser.FormDefinitionParse; import org.flowable.form.engine.impl.persistence.entity.FormDefinitionEntity; import org.flowable.form.engine.impl.persistence.entity.FormDeploymentEntity; import org.flowable.form.engine.impl.persistence.entity.FormResourceEntity; import org.flowable.form.model.FormModel; /** * An intermediate representation of a DeploymentEntity which keeps track of all of the entity's DecisionTableEntities and resources, and BPMN parses, models, and processes associated with each * DecisionTableEntity - all produced by parsing the deployment. * * The DecisionTableEntities are expected to be "not fully set-up" - they may be inconsistent with the DeploymentEntity and/or the persisted versions, and if the deployment is new, they will not yet * be persisted. */ public class ParsedDeployment { protected FormDeploymentEntity deploymentEntity; protected List<FormDefinitionEntity> formDefinitions; protected Map<FormDefinitionEntity, FormDefinitionParse> mapFormDefinitionsToParses; protected Map<FormDefinitionEntity, FormResourceEntity> mapFormDefinitionsToResources; public ParsedDeployment( FormDeploymentEntity entity, List<FormDefinitionEntity> formDefinitions, Map<FormDefinitionEntity, FormDefinitionParse> mapFormDefinitionsToParses, Map<FormDefinitionEntity, FormResourceEntity> mapFormDefinitionsToResources) { this.deploymentEntity = entity; this.formDefinitions = formDefinitions; this.mapFormDefinitionsToParses = mapFormDefinitionsToParses; this.mapFormDefinitionsToResources = mapFormDefinitionsToResources; } public FormDeploymentEntity getDeployment() { return deploymentEntity; } public List<FormDefinitionEntity> getAllFormDefinitions() { return formDefinitions; } public FormResourceEntity getResourceForFormDefinition(FormDefinitionEntity formDefinition) { return mapFormDefinitionsToResources.get(formDefinition); } public FormDefinitionParse getFormDefinitionParseForFormDefinition(FormDefinitionEntity formDefinition) { return mapFormDefinitionsToParses.get(formDefinition); } public FormModel getFormModelForFormDefinition(FormDefinitionEntity formDefinition) { FormDefinitionParse parse = getFormDefinitionParseForFormDefinition(formDefinition); return (parse == null ? null : parse.getFormModel()); } }
apache-2.0
apache/solr
solr/modules/extraction/src/java/org/apache/solr/handler/extraction/SolrContentHandler.java
10650
/* * 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.solr.handler.extraction; import java.lang.invoke.MethodHandles; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.SolrParams; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.TikaMetadataKeys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * The class responsible for handling Tika events and translating them into {@link * org.apache.solr.common.SolrInputDocument}s. <B>This class is not thread-safe.</B> * * <p>This class cannot be reused, you have to create a new instance per document! * * <p>User's may wish to override this class to provide their own functionality. * * @see org.apache.solr.handler.extraction.SolrContentHandlerFactory * @see org.apache.solr.handler.extraction.ExtractingRequestHandler * @see org.apache.solr.handler.extraction.ExtractingDocumentLoader */ public class SolrContentHandler extends DefaultHandler implements ExtractingParams { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static final String contentFieldName = "content"; protected final SolrInputDocument document; protected final Metadata metadata; protected final SolrParams params; protected final StringBuilder catchAllBuilder = new StringBuilder(2048); protected final IndexSchema schema; protected final Map<String, StringBuilder> fieldBuilders; private final Deque<StringBuilder> bldrStack = new ArrayDeque<>(); protected final boolean captureAttribs; protected final boolean lowerNames; protected final String unknownFieldPrefix; protected final String defaultField; private final boolean literalsOverride; private Set<String> literalFieldNames = null; public SolrContentHandler(Metadata metadata, SolrParams params, IndexSchema schema) { this.document = new SolrInputDocument(); this.metadata = metadata; this.params = params; this.schema = schema; this.lowerNames = params.getBool(LOWERNAMES, false); this.captureAttribs = params.getBool(CAPTURE_ATTRIBUTES, false); this.literalsOverride = params.getBool(LITERALS_OVERRIDE, true); this.unknownFieldPrefix = params.get(UNKNOWN_FIELD_PREFIX, ""); this.defaultField = params.get(DEFAULT_FIELD, ""); String[] captureFields = params.getParams(CAPTURE_ELEMENTS); if (captureFields != null && captureFields.length > 0) { fieldBuilders = new HashMap<>(); for (int i = 0; i < captureFields.length; i++) { fieldBuilders.put(captureFields[i], new StringBuilder()); } } else { fieldBuilders = Collections.emptyMap(); } bldrStack.add(catchAllBuilder); } /** * This is called by a consumer when it is ready to deal with a new SolrInputDocument. Overriding * classes can use this hook to add in or change whatever they deem fit for the document at that * time. The base implementation adds the metadata as fields, allowing for potential remapping. * * @return The {@link org.apache.solr.common.SolrInputDocument}. * @see #addMetadata() * @see #addCapturedContent() * @see #addContent() * @see #addLiterals() */ public SolrInputDocument newDocument() { // handle the literals from the params. NOTE: This MUST be called before the others in order for // literals to override other values addLiterals(); // handle the metadata extracted from the document addMetadata(); // add in the content addContent(); // add in the captured content addCapturedContent(); if (log.isDebugEnabled()) { log.debug("Doc: {}", document); } return document; } /** * Add the per field captured content to the Solr Document. Default implementation uses the {@link * #fieldBuilders} info */ protected void addCapturedContent() { for (Map.Entry<String, StringBuilder> entry : fieldBuilders.entrySet()) { if (entry.getValue().length() > 0) { String fieldName = entry.getKey(); if (literalsOverride && literalFieldNames.contains(fieldName)) continue; addField(fieldName, entry.getValue().toString(), null); } } } /** * Add in the catch all content to the field. Default impl. uses the {@link #contentFieldName} and * the {@link #catchAllBuilder} */ protected void addContent() { if (literalsOverride && literalFieldNames.contains(contentFieldName)) return; addField(contentFieldName, catchAllBuilder.toString(), null); } /** * Add in the literals to the document using the {@link #params} and the {@link #LITERALS_PREFIX}. */ protected void addLiterals() { Iterator<String> paramNames = params.getParameterNamesIterator(); literalFieldNames = new HashSet<>(); while (paramNames.hasNext()) { String pname = paramNames.next(); if (!pname.startsWith(LITERALS_PREFIX)) continue; String name = pname.substring(LITERALS_PREFIX.length()); addField(name, null, params.getParams(pname)); literalFieldNames.add(name); } } /** Add in any metadata using {@link #metadata} as the source. */ protected void addMetadata() { for (String name : metadata.names()) { if (literalsOverride && literalFieldNames.contains(name)) continue; String[] vals = metadata.getValues(name); addField(name, null, vals); } } // Naming rules: // 1) optionally map names to nicenames (lowercase+underscores) // 2) execute "map" commands // 3) if resulting field is unknown, map it to a common prefix protected void addField(String fname, String fval, String[] vals) { if (lowerNames) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fname.length(); i++) { char ch = fname.charAt(i); if (!Character.isLetterOrDigit(ch)) ch = '_'; else ch = Character.toLowerCase(ch); sb.append(ch); } fname = sb.toString(); } String name = findMappedName(fname); SchemaField sf = schema.getFieldOrNull(name); if (sf == null && unknownFieldPrefix.length() > 0) { name = unknownFieldPrefix + name; sf = schema.getFieldOrNull(name); } else if (sf == null && defaultField.length() > 0 && name.equals(TikaMetadataKeys.RESOURCE_NAME_KEY) == false /*let the fall through below handle this*/) { name = defaultField; sf = schema.getFieldOrNull(name); } // Arguably we should handle this as a special case. Why? Because unlike basically // all the other fields in metadata, this one was probably set not by Tika by in // ExtractingDocumentLoader.load(). You shouldn't have to define a mapping for this // field just because you specified a resource.name parameter to the handler, should // you? if (sf == null && unknownFieldPrefix.length() == 0 && name == TikaMetadataKeys.RESOURCE_NAME_KEY) { return; } // normalize val params so vals.length>1 if (vals != null && vals.length == 1) { fval = vals[0]; vals = null; } // single valued field with multiple values... catenate them. if (sf != null && !sf.multiValued() && vals != null) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String val : vals) { if (first) { first = false; } else { builder.append(' '); } builder.append(val); } fval = builder.toString(); vals = null; } if (fval != null) { document.addField(name, fval); } if (vals != null) { for (String val : vals) { document.addField(name, val); } } // no value set - throw exception for debugging // if (vals==null && fval==null) throw new RuntimeException(name + " has no non-null value "); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { StringBuilder theBldr = fieldBuilders.get(localName); if (theBldr != null) { // we need to switch the currentBuilder bldrStack.add(theBldr); } if (captureAttribs == true) { for (int i = 0; i < attributes.getLength(); i++) { addField(localName, attributes.getValue(i), null); } } else { for (int i = 0; i < attributes.getLength(); i++) { bldrStack.getLast().append(' ').append(attributes.getValue(i)); } } bldrStack.getLast().append(' '); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { StringBuilder theBldr = fieldBuilders.get(localName); if (theBldr != null) { // pop the stack bldrStack.removeLast(); assert (bldrStack.size() >= 1); } bldrStack.getLast().append(' '); } @Override public void characters(char[] chars, int offset, int length) throws SAXException { bldrStack.getLast().append(chars, offset, length); } /** Treat the same as any other characters */ @Override public void ignorableWhitespace(char[] chars, int offset, int length) throws SAXException { characters(chars, offset, length); } /** * Get the name mapping * * @param name The name to check to see if there is a mapping * @return The new name, if there is one, else <code>name</code> */ protected String findMappedName(String name) { return params.get(MAP_PREFIX + name, name); } }
apache-2.0
apache/incubator-taverna-engine
taverna-stringconstant-activity/src/main/java/org/apache/taverna/activities/stringconstant/StringConstantActivity.java
3771
/* * 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.taverna.activities.stringconstant; import java.util.HashMap; import java.util.Map; import org.apache.taverna.annotation.annotationbeans.MimeType; import org.apache.taverna.reference.ReferenceService; import org.apache.taverna.reference.ReferenceServiceException; import org.apache.taverna.reference.T2Reference; import org.apache.taverna.workflowmodel.EditException; import org.apache.taverna.workflowmodel.processor.activity.AbstractAsynchronousActivity; import org.apache.taverna.workflowmodel.processor.activity.ActivityConfigurationException; import org.apache.taverna.workflowmodel.processor.activity.ActivityOutputPort; import org.apache.taverna.workflowmodel.processor.activity.AsynchronousActivityCallback; import org.apache.log4j.Logger; import com.fasterxml.jackson.databind.JsonNode; /** * An Activity that holds a constant string value. * <p> * It is automatically configured to have no input ports and only one output port named * <em>value</em>. * * @author Stuart Owen * @author David Withers */ public class StringConstantActivity extends AbstractAsynchronousActivity<JsonNode> { public static final String URI = "http://ns.taverna.org.uk/2010/activity/constant"; private static final Logger logger = Logger.getLogger(StringConstantActivity.class); private String value; private JsonNode json; @Override public void configure(JsonNode json) throws ActivityConfigurationException { this.json = json; this.value = json.get("string").asText(); // if (outputPorts.size() == 0) { // addOutput("value", 0, "text/plain"); // } } public String getStringValue() { return json.get("string").asText(); } @Override public JsonNode getConfiguration() { return json; } @Override public void executeAsynch(final Map<String, T2Reference> data, final AsynchronousActivityCallback callback) { callback.requestRun(new Runnable() { @Override public void run() { ReferenceService referenceService = callback.getContext().getReferenceService(); try { T2Reference id = referenceService.register(value, 0, true, callback.getContext()); Map<String, T2Reference> outputData = new HashMap<String, T2Reference>(); outputData.put("value", id); callback.receiveResult(outputData, new int[0]); } catch (ReferenceServiceException e) { callback.fail(e.getMessage(), e); } } }); } // protected void addOutput(String portName, int portDepth, String type) { // ActivityOutputPort port = edits.createActivityOutputPort(portName, portDepth, portDepth); // MimeType mimeType = new MimeType(); // mimeType.setText(type); // try { // edits.getAddAnnotationChainEdit(port, mimeType).doEdit(); // } catch (EditException e) { // logger.debug("Error adding MimeType annotation to port", e); // } // outputPorts.add(port); // } public String getExtraDescription() { if (value.length() > 60) { return value.substring(0, 60 - 3) + "..."; } return value; } }
apache-2.0
jonathan-caryl/picasso
picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java
3868
/* * Copyright (C) 2013 Square, 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.squareup.picasso; import android.content.Context; import android.net.Uri; import android.net.http.HttpResponseCache; import android.os.Build; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import static com.squareup.picasso.Utils.parseResponseSourceHeader; /** * A {@link Downloader} which uses {@link HttpURLConnection} to download images. A disk cache of 2% * of the total available space will be used (capped at 50MB) will automatically be installed in the * application's cache directory, when available. */ public class UrlConnectionDownloader implements Downloader { static final String RESPONSE_SOURCE = "X-Android-Response-Source"; private static final Object lock = new Object(); static volatile Object cache; private final Context context; public UrlConnectionDownloader(Context context) { this.context = context.getApplicationContext(); } protected HttpURLConnection openConnection(Uri path) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(path.toString()).openConnection(); connection.setConnectTimeout(Utils.DEFAULT_CONNECT_TIMEOUT); connection.setReadTimeout(Utils.DEFAULT_READ_TIMEOUT); return connection; } @Override public Response load(Uri uri, boolean localCacheOnly) throws IOException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { installCacheIfNeeded(context); } HttpURLConnection connection = openConnection(uri); connection.setUseCaches(true); if (localCacheOnly) { connection.setRequestProperty("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE); } int responseCode = connection.getResponseCode(); if (responseCode >= 300) { connection.disconnect(); throw new ResponseException(responseCode + " " + connection.getResponseMessage()); } long contentLength = connection.getHeaderFieldInt("Content-Length", -1); boolean fromCache = parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE)); return new Response(connection.getInputStream(), fromCache, contentLength); } @Override public void shutdown() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && cache != null) { ResponseCacheIcs.close(cache); } } private static void installCacheIfNeeded(Context context) { // DCL + volatile should be safe after Java 5. if (cache == null) { try { synchronized (lock) { if (cache == null) { cache = ResponseCacheIcs.install(context); } } } catch (IOException ignored) { } } } private static class ResponseCacheIcs { static Object install(Context context) throws IOException { File cacheDir = Utils.createDefaultCacheDir(context); HttpResponseCache cache = HttpResponseCache.getInstalled(); if (cache == null) { long maxSize = Utils.calculateDiskCacheSize(cacheDir); cache = HttpResponseCache.install(cacheDir, maxSize); } return cache; } static void close(Object cache) { try { ((HttpResponseCache) cache).close(); } catch (IOException ignored) { } } } }
apache-2.0
IllusionRom-deprecated/android_platform_tools_idea
xml/tests/src/com/intellij/xml/XmlNamespacesTest.java
16598
package com.intellij.xml; import com.intellij.codeInsight.actions.OptimizeImportsProcessor; import com.intellij.codeInsight.daemon.impl.analysis.XmlUnusedNamespaceInspection; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.htmlInspections.XmlInspectionToolProvider; import com.intellij.javaee.ExternalResourceManagerExImpl; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.testFramework.IdeaTestCase; import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase; /** * @author Dmitry Avdeev */ public class XmlNamespacesTest extends CodeInsightFixtureTestCase { @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public XmlNamespacesTest() { IdeaTestCase.initPlatformPrefix(); } public void testUnusedNamespaces() throws Exception { doUnusedDeclarationTest( "<all xmlns=\"http://www.w3.org/2001/XMLSchema\" <warning descr=\"Namespace declaration is never used\">xmlns:xsi=\"http://www.w3.org/2001/XMLSc<caret>hema-instance\"</warning>/>", "<all xmlns=\"http://www.w3.org/2001/XMLSchema\"/>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME); } public void testUnusedDefaultNamespace() throws Exception { doUnusedDeclarationTest("<schema:schema \n" + " xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns=\"http://www.w3.org/2001/X<caret>Include\"</warning>\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " <warning descr=\"Namespace location is never used\">xsi:noNamespaceSchemaLocation=\"http://www.w3.org/2001/XInclude\"</warning>>\n" + "</schema:schema>", "<schema:schema\n" + " xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " >\n" + "</schema:schema>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME, false); doOptimizeImportsTest("<schema:schema \n" + " xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " >\n" + "</schema:schema>"); } public void testDifferentPrefixes() throws Exception { doUnusedDeclarationTest( "<x:all <warning descr=\"Namespace declaration is never used\">xmlns=\"http://www.w3.org/2001/XMLS<caret>chema\"</warning>\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:y=\"http://www.w3.org/2001/XMLSchema\"</warning>/>", "<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:y=\"http://www.w3.org/2001/XMLSchema\"/>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME, false); doOptimizeImportsTest("<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " />"); } public void testUnusedLocation() throws Exception { doUnusedDeclarationTest("<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XML<caret>Sche</warning> " + "<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XMLSchema.xsd</warning>\"/>", "<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " />", XmlUnusedNamespaceInspection.RemoveNamespaceLocationFix.NAME); } public void testUnusedLocationOnly() throws Exception { doUnusedDeclarationTest("<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:y=\"http://www.w3.org/2001/XInclude\"</warning>\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XI<caret>nclude</warning> <warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XInclude.xsd</warning>\n" + " http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\"/>", "<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\"/>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME); } public void testUnusedDefaultLocation() throws Exception { doUnusedDeclarationTest("<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " <warning descr=\"Namespace location is never used\">xsi:noNamespaceSc<caret>hemaLocation=\"<error descr=\"Cannot resolve file 'zzz'\">zzz</error>\"</warning> />", "<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " />", XmlUnusedNamespaceInspection.RemoveNamespaceLocationFix.NAME); } public void testKeepFormatting() throws Exception { doUnusedDeclarationTest("<xs:schema attributeFormDefault=\"unqualified\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:xsi=\"http://www.w3.org/20<caret>01/XMLSchema-instance\"</warning>\n" + " elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + "\n" + " <!-- keep formatting here-->\n" + " <xs:element name=\"a\" type=\"aType\"/>\n" + " <xs:complexType name=\"aType\">\n" + "\n" + " </xs:complexType>\n" + "</xs:schema>", "<xs:schema attributeFormDefault=\"unqualified\"\n" + " elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + "\n" + " <!-- keep formatting here-->\n" + " <xs:element name=\"a\" type=\"aType\"/>\n" + " <xs:complexType name=\"aType\">\n" + "\n" + " </xs:complexType>\n" + "</xs:schema>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME); } public void testImplicitPrefixUsage() throws Exception { myFixture.configureByText("a.xml", "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:x2=\"http://www.w3.org/2001/XMLSchema\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:x3=\"http://www.w3.org/2001/XMLSchema\"</warning> >\n" + " <xs:element name=\"a\" type=\"x2:string\"/>\n" + "</xs:schema>"); myFixture.testHighlighting(); } public void testUnusedLocationDetection() throws Exception { myFixture.configureByFile("web-app_2_5.xsd"); myFixture.configureByText("a.xml", "<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"</warning>\n" + " xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n" + " web-app_2_5.xsd\"\n" + " version=\"2.5\">\n" + "</web-app>"); myFixture.testHighlighting(); } public void testWSDD() throws Exception { myFixture.configureByText("a.xml", "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\">\n" + "<typeMapping deserializer=\"org.apache.axis.encoding.ser.BeanDeserializerFactory\" encodingStyle=\"\" qname=\"ns38:AxisAnalysis\" serializer=\"org.apache.axis.encoding.ser.BeanSerializerFactory\" languageSpecificType=\"java:com.pls.xactservice.axis.bindings.AxisAnalysis\"/>\n" + "</deployment>"); myFixture.testHighlighting(); } public void testPrefixesInTagValues() throws Exception { myFixture.configureByText("a.xml", "<<info descr=\"Namespace '' is not bound\">nodeTypes</info> xmlns:nt=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://www.jcp.org/jcr/nt/1.0</error>\" xmlns:customns=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://customurl</error>\">\n" + "<nodeType name=\"customns:item\" isMixin=\"false\" hasOrderableChildNodes=\"false\">\n" + " <supertypes>\n" + " <supertype>nt:folder</supertype>\n" + " </supertypes>\n" + "</nodeType>\n" + "</<info descr=\"Namespace '' is not bound\">nodeTypes</info>>"); myFixture.testHighlighting(); } public void testLocallyUsedNamespace() throws Exception { myFixture.configureByText("a.xml", "<x:all\n" + " xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\n" + " http://www.w3.org/2001/XInclude http://www.w3.org/2001/XInclude.xsd\">\n" + "\n" + " <<error descr=\"An 'include' failed, and no 'fallback' element was found.\">include</error> xmlns=\"http://www.w3.org/2001/XInclude\" href=\"<error descr=\"Cannot resolve file 'a.xml'\">a.xml</error>\"/>\n" + "</x:all>"); myFixture.testHighlighting(); } public void testLocallyUsedNamespaceWithPrefix() throws Exception { myFixture.configureByText("a.xml", "<s:foo xmlns:s=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://foo</error>\"\n" + " <warning descr=\"Namespace declaration is never used\">xmlns:bar=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://bar</error>\"</warning>\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://bar <error descr=\"Cannot resolve file 'bar.xsd'\">bar.xsd</error> http://foo <error descr=\"Cannot resolve file 'foo.xsd'\">foo.xsd</error>\">\n" + "\n" + " <bar xmlns=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://bar</error>\"/>\n" + "\n" + "</s:foo>"); myFixture.testHighlighting(); } public void testSubDirectory() throws Exception { myFixture.testHighlighting("moved.xml", "trg/move-def.xsd"); } public void testSuppressedOptimize() throws Exception { myFixture.configureByFile("web-app_2_5.xsd"); String text = "<!--suppress XmlUnusedNamespaceDeclaration -->\n" + "<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n" + " web-app_2_5.xsd\"\n" + " version=\"2.5\">\n" + "</web-app>"; myFixture.configureByText("a.xml", text); doOptimizeImportsTest(text); } public void testUsedInXmlns() throws Exception { myFixture.testHighlighting("spring.xml", "spring-beans-2.5.xsd", "spring-batch-2.1.xsd"); IntentionAction action = myFixture.getAvailableIntention(XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME); assertNotNull(action); myFixture.launchAction(action); myFixture.checkResultByFile("spring_after.xml"); } public void testXsiType() throws Exception { myFixture.testHighlighting("import.xml", "import.xsd"); } private void doUnusedDeclarationTest(String text, String after, String name) throws Exception { doUnusedDeclarationTest(text, after, name, true); } private void doUnusedDeclarationTest(String text, String after, String name, boolean testOptimizeImports) throws Exception { myFixture.configureByText("a.xml", text); myFixture.testHighlighting(); IntentionAction action = myFixture.getAvailableIntention(name); assertNotNull(name + " not found", action); myFixture.launchAction(action); myFixture.checkResult(after); myFixture.configureByText("a.xml", text); if (testOptimizeImports) { doOptimizeImportsTest(after); } } private void doOptimizeImportsTest(String after) { myFixture.testHighlighting(); new WriteCommandAction(getProject(), getFile()) { @Override protected void run(Result result) throws Throwable { new OptimizeImportsProcessor(getProject(), getFile()).runWithoutProgress(); } }.execute(); myFixture.checkResult(after); } @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(new XmlInspectionToolProvider()); ExternalResourceManagerExImpl.registerResourceTemporarily("http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd", getTestDataPath() + "/web-app_2_5.xsd", getTestRootDisposable()); ExternalResourceManagerExImpl.registerResourceTemporarily("http://xml.apache.org/axis/wsdd/", getTestDataPath() + "/wsdd.dtd", getTestRootDisposable()); ExternalResourceManagerExImpl.registerResourceTemporarily("http://xml.apache.org/axis/wsdd/providers/java", getTestDataPath() + "/wsdd_provider_java.xsd", getTestRootDisposable()); } @Override protected String getBasePath() { return "/xml/tests/testData/unusedNs"; } @Override protected boolean isCommunity() { return true; } }
apache-2.0
adichad/lucene-new
contrib/gdata-server/src/core/src/java/org/apache/lucene/gdata/server/GDataResponse.java
16455
/** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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.lucene.gdata.server; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Date; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.gdata.server.GDataRequest.OutputFormat; import org.apache.lucene.gdata.server.registry.ProvidedService; import org.apache.lucene.gdata.utils.DateFormater; import com.google.gdata.data.BaseEntry; import com.google.gdata.data.BaseFeed; import com.google.gdata.data.DateTime; import com.google.gdata.data.ExtensionProfile; import com.google.gdata.util.common.xml.XmlWriter; import com.google.gdata.util.common.xml.XmlWriter.Namespace; /** * The FeedRequest Class wraps the current HttpServletResponse. Any action on the * HttpServletRequest will be executed via this class. This represents an * abstraction on the plain {@link HttpServletResponse}. Any action which has * to be performed on the underlying {@link HttpServletResponse} will be * executed within this class. * <p> * The GData basically writes two different kinds of response to the output * stream. * <ol> * <li>update, delete or insert requests will respond with a status code and if * successful the feed entry modified or created</li> * <li>get requests will respond with a status code and if successful the * requested feed</li> * </ol> * * For this purpose the {@link GDataResponse} class provides the overloaded * method * {@link org.apache.lucene.gdata.server.GDataResponse#sendResponse(BaseEntry, ExtensionProfile)} * which sends the entry e.g feed to the output stream. * </p> * <p> * This class will set the HTTP <tt>Last-Modified</tt> Header to enable * clients to send <tt>If-Modified-Since</tt> request header to avoid * retrieving the content again if it hasn't changed. If the content hasn't * changed since the If-Modified-Since time, then the GData service returns a * 304 (Not Modified) HTTP response. * </p> * * * * * @author Simon Willnauer * */ public class GDataResponse { /** * Response code bad request */ public static final int BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST; /** * Response code version conflict */ public static final int CONFLICT = HttpServletResponse.SC_CONFLICT; /** * Response code forbidden access */ public static final int FORBIDDEN = HttpServletResponse.SC_FORBIDDEN; /** * Response code internal server error */ public static final int SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; /** * Response code not found */ public static final int NOT_FOUND = HttpServletResponse.SC_NOT_FOUND; /** * Response code not modified since */ public static final int NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED; /** * Response code created */ public static final int CREATED = HttpServletResponse.SC_CREATED; /** * Response code unauthorized access */ public static final int UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED; static final Log LOG = LogFactory.getLog(GDataResponse.class); private int error; private boolean isError = false; private String encoding; private OutputFormat outputFormat; private final HttpServletResponse response; protected static final String XMLMIME_ATOM = "text/xml"; protected static final String XMLMIME_RSS = "text/xml"; private static final String HEADER_LASTMODIFIED = "Last-Modified"; /** * Creates a new GDataResponse * * @param response - * The underlying {@link HttpServletResponse} */ public GDataResponse(HttpServletResponse response) { if (response == null) throw new IllegalArgumentException("response must not be null"); this.response = response; } /** * Sets an error code to this FeedResponse. * * @param errorCode - * {@link HttpServletResponse} error code */ public void setError(int errorCode) { this.isError = true; this.error = errorCode; } /** * Sets the status of the underlying response * * @see HttpServletResponse * @param responseCode - * the status of the response */ public void setResponseCode(int responseCode) { this.response.setStatus(responseCode); } /** * This method sends the specified error to the user if set * * @throws IOException - * if an I/O Exception occurs */ public void sendError() throws IOException { if (this.isError) this.response.sendError(this.error); } /** * @return - the {@link HttpServletResponse} writer * @throws IOException - * If an I/O exception occurs */ public Writer getWriter() throws IOException { return this.response.getWriter(); } /** * Sends a response for a get e.g. query request. This method must not * invoked in a case of an error performing the requested action. * * @param feed - * the feed to respond to the client * @param service - the service to render the feed * * @throws IOException - * if an I/O exception occurs, often caused by an already * closed Writer or OutputStream * */ public void sendResponse(final BaseFeed feed, final ProvidedService service) throws IOException { if (feed == null) throw new IllegalArgumentException("feed must not be null"); if (service == null) throw new IllegalArgumentException( "provided service must not be null"); DateTime time = feed.getUpdated(); if (time != null) setLastModifiedHeader(time.getValue()); FormatWriter writer = FormatWriter.getFormatWriter(this,service); writer.generateOutputFormat(feed,this.response); } /** * * Sends a response for an update, insert or delete request. This method * must not invoked in a case of an error performing the requested action. If * the specified response format is ATOM the default namespace will be set * to ATOM. * * @param entry - * the modified / created entry to send * @param service - the service to render the feed * @throws IOException - * if an I/O exception occurs, often caused by an already * closed Writer or OutputStream */ public void sendResponse(BaseEntry entry, ProvidedService service) throws IOException { if (entry == null) throw new IllegalArgumentException("entry must not be null"); if (service == null) throw new IllegalArgumentException( "service must not be null"); DateTime time = entry.getUpdated(); if (time != null) setLastModifiedHeader(time.getValue()); FormatWriter writer = FormatWriter.getFormatWriter(this,service); writer.generateOutputFormat(entry,this.response); } /** * This encoding will be used to encode the xml representation of feed or * entry written to the {@link HttpServletResponse} output stream. * * @return - the entry / feed encoding */ public String getEncoding() { return this.encoding; } /** * This encoding will be used to encode the xml representation of feed or * entry written to the {@link HttpServletResponse} output stream. <i>UTF-8</i> * <i>ISO-8859-1</i> * * @param encoding - * string represents the encoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * @return - the response * {@link org.apache.lucene.gdata.server.GDataRequest.OutputFormat} */ public OutputFormat getOutputFormat() { return this.outputFormat; } /** * @param outputFormat - * the response * {@link org.apache.lucene.gdata.server.GDataRequest.OutputFormat} */ public void setOutputFormat(OutputFormat outputFormat) { this.outputFormat = outputFormat; } /** * @see Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(" GDataResponse: "); builder.append("Error: ").append(this.error); builder.append(" outputFormat: ").append(getOutputFormat()); builder.append(" encoding: ").append(this.encoding); return builder.toString(); } protected void setLastModifiedHeader(long lastModified) { String lastMod = DateFormater.formatDate(new Date(lastModified), DateFormater.HTTP_HEADER_DATE_FORMAT); this.response.setHeader(HEADER_LASTMODIFIED, lastMod); } /** * @see HttpServletResponse#setStatus(int) * @param status - the request status code */ public void setStatus(int status){ this.response.setStatus(status); } private static abstract class FormatWriter{ static FormatWriter getFormatWriter(final GDataResponse response, final ProvidedService service ){ OutputFormat format = response.getOutputFormat(); if(format == OutputFormat.HTML){ return new HTMLFormatWriter(service); } return new SyndicateFormatWriter(service,format,response.getEncoding()); } abstract void generateOutputFormat(final BaseFeed feed, final HttpServletResponse response) throws IOException; abstract void generateOutputFormat(final BaseEntry entry, final HttpServletResponse response) throws IOException; private static class HTMLFormatWriter extends FormatWriter{ private static final String CONTENT_TYPE = "text/html"; private final ProvidedService service; HTMLFormatWriter(final ProvidedService service){ this.service = service; } @Override void generateOutputFormat(BaseFeed feed, final HttpServletResponse response) throws IOException { Templates template = this.service.getTransformTemplate(); response.setContentType(CONTENT_TYPE); if(template == null){ sendNotAvailable(response); return; } StringWriter writer = new StringWriter(); XmlWriter xmlWriter = new XmlWriter(writer); feed.generateAtom(xmlWriter,this.service.getExtensionProfile()); try { writeHtml(template,response.getWriter(),writer); } catch (TransformerException e) { LOG.error("Can not transform feed for service "+this.service.getName(),e); sendNotAvailable(response); } } @Override void generateOutputFormat(BaseEntry entry, final HttpServletResponse response) throws IOException{ Templates template = this.service.getTransformTemplate(); response.setContentType(CONTENT_TYPE); if(template == null){ sendNotAvailable(response); return; } StringWriter writer = new StringWriter(); XmlWriter xmlWriter = new XmlWriter(writer); entry.generateAtom(xmlWriter,this.service.getExtensionProfile()); try { writeHtml(template,response.getWriter(),writer); } catch (TransformerException e) { LOG.error("Can not transform feed for service "+this.service.getName(),e); sendNotAvailable(response); } } private void writeHtml(final Templates template, final Writer writer, final StringWriter source ) throws TransformerException{ Transformer transformer = template.newTransformer(); Source tranformSource = new StreamSource(new StringReader(source.toString())); transformer.transform(tranformSource,new StreamResult(writer)); } private void sendNotAvailable(final HttpServletResponse response) throws IOException{ response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "No transformation stylesheet available"); } } private static class SyndicateFormatWriter extends FormatWriter{ private static final String DEFAUL_NAMESPACE_URI = "http://www.w3.org/2005/Atom"; private static final Namespace DEFAULT_NAMESPACE = new Namespace("", DEFAUL_NAMESPACE_URI); private final ProvidedService service; private final String encoding; private final OutputFormat format; SyndicateFormatWriter(final ProvidedService service,final OutputFormat format, String encoding){ this.service = service; this.format = format; this.encoding = encoding; } @Override void generateOutputFormat(final BaseFeed feed, final HttpServletResponse response) throws IOException { XmlWriter writer = null; try{ writer = createWriter(response.getWriter()); if (this.format == OutputFormat.ATOM) { response.setContentType(XMLMIME_ATOM); feed.generateAtom(writer, this.service.getExtensionProfile()); } else { response.setContentType(XMLMIME_RSS); feed.generateRss(writer, this.service.getExtensionProfile()); } }finally{ if(writer != null) writer.close(); } } @Override void generateOutputFormat(final BaseEntry entry, final HttpServletResponse response) throws IOException { XmlWriter writer = null; try{ writer = createWriter(response.getWriter()); if (this.format == OutputFormat.ATOM) { response.setContentType(XMLMIME_ATOM); entry.generateAtom(writer, this.service.getExtensionProfile()); } else { response.setContentType(XMLMIME_RSS); entry.generateRss(writer, this.service.getExtensionProfile()); } }finally{ if(writer != null) writer.close(); } } private XmlWriter createWriter(final Writer target) throws IOException { XmlWriter writer = new XmlWriter(target, this.encoding); // set the default namespace to Atom if Atom is the response format if (this.format == OutputFormat.ATOM) writer.setDefaultNamespace(DEFAULT_NAMESPACE); return writer; } } } }
apache-2.0
sujitbehera27/MyRoboticsProjects-Arduino
src/org/myrobotlab/service/interfaces/AuthorizationProvider.java
363
package org.myrobotlab.service.interfaces; import java.util.HashMap; import org.myrobotlab.framework.Message; public interface AuthorizationProvider { boolean isAuthorized(Message msg); // from remote not all inbound boolean isAuthorized(HashMap<String,String> security, String serviceName, String method); boolean allowExport(String serviceName); }
apache-2.0
fschopp/cloudkeeper
cloudkeeper-core/cloudkeeper-model/src/main/java/xyz/cloudkeeper/model/api/UserException.java
1233
package xyz.cloudkeeper.model.api; /** * Signals that an exception occurred while executing user-defined code. * * <p>Note that exceptions may have other CloudKeeper exceptions in the cause chain; for instance, if a module fails * because it called a {@link xyz.cloudkeeper.model.api.ModuleConnector} method that threw an exception, then the * cause chain could contain an {@link xyz.cloudkeeper.model.api.staging.StagingException}. */ public class UserException extends ExecutionException { private static final long serialVersionUID = -4084143140406749997L; /** * Constructs a new exception with the specified detail message and cause. * * @param message detail message (which is saved for later retrieval by the {@link #getMessage()} method) * @param cause cause (which is saved for later retrieval by the {@link #getCause()} method) */ public UserException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause. * * @param cause cause (which is saved for later retrieval by the {@link #getCause()} method) */ public UserException(Throwable cause) { super(cause); } }
apache-2.0
2947721120/ChromeRestClient
gwt-chrome-api/src/com/google/gwt/chrome/runtime/ManifestDetails.java
777
package com.google.gwt.chrome.runtime; import com.google.gwt.core.client.JavaScriptObject; public class ManifestDetails extends JavaScriptObject { protected ManifestDetails() { } /** * * @return The version of the extension/app */ public final native String getVersion() /*-{ return this.version; }-*/; /** * * @return The name of the extension/app */ public final native String getName() /*-{ return this.name; }-*/; /** * * @return Extension/app permissions array or null */ public final native String[] getPermissions() /*-{ return this.permissions || null; }-*/; /** * * @return Extension/app manifest version or null */ public final native Integer getManifestVersion() /*-{ return this.manifest_version || null; }-*/; }
apache-2.0
bradwoo8621/nest-old
arcteryx-meta-beans/src/main/java/com/github/nest/arcteryx/meta/beans/annotation/NumberFormat.java
2047
/** * */ package com.github.nest.arcteryx.meta.beans.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.github.nest.arcteryx.meta.beans.ConstraintApplyTo; import com.github.nest.arcteryx.meta.beans.ConstraintSeverity; import com.github.nest.arcteryx.meta.beans.constraints.NumberFormatConstraint; /** * number format * * @author brad.wu */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) @Constraint(constraintClass = NumberFormatConstraint.class) public @interface NumberFormat { /** * name of constraint * * @return */ String name() default ""; /** * message template * * @return */ String messageTemplate() default ""; /** * error code * * @return */ String errorCode() default ""; /** * profiles * * @return */ String[] profiles() default {}; /** * severity * * @return */ ConstraintSeverity severity() default ConstraintSeverity.ERROR; /** * when * * @return */ String when() default ""; /** * applies to * * @return */ ConstraintApplyTo appliesTo() default ConstraintApplyTo.VALUES; /** * target * * @return */ String target() default ""; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) @Constraints public @interface List { NumberFormat[] values(); } /** * min integer digits * * @return */ int minIntegerDigits() default 0; /** * min fraction digits * * @return */ int minFractionDigits() default 0; /** * max integer digits * * @return */ int maxIntegerDigits() default Integer.MAX_VALUE; /** * max fraction digits * * @return */ int maxFractionDigits() default Integer.MAX_VALUE; }
apache-2.0
goldmansachs/gs-collections
jmh-tests/src/main/java/com/gs/collections/impl/jmh/map/TroveMutableMapGetTest.java
2957
/* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.gs.collections.impl.jmh.map; import java.util.Random; import java.util.concurrent.TimeUnit; import com.gs.collections.impl.jmh.runner.AbstractJMHTestRunner; import gnu.trove.map.TMap; import gnu.trove.map.hash.THashMap; import org.apache.commons.lang.RandomStringUtils; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; @State(Scope.Thread) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public class TroveMutableMapGetTest extends AbstractJMHTestRunner { private static final int RANDOM_COUNT = 9; @Param({"250000", "500000", "750000", "1000000", "1250000", "1500000", "1750000", "2000000", "2250000", "2500000", "2750000", "3000000", "3250000", "3500000", "3750000", "4000000", "4250000", "4500000", "4750000", "5000000", "5250000", "5500000", "5750000", "6000000", "6250000", "6500000", "6750000", "7000000", "7250000", "7500000", "7750000", "8000000", "8250000", "8500000", "8750000", "9000000", "9250000", "9500000", "9750000", "10000000"}) public int size; private String[] elements; private TMap<String, String> troveMap; @Setup public void setUp() { Random random = new Random(123456789012345L); this.elements = new String[this.size]; this.troveMap = new THashMap<>(this.size); for (int i = 0; i < this.size; i++) { String element = RandomStringUtils.random(RANDOM_COUNT, 0, 0, false, true, null, random); this.elements[i] = element; this.troveMap.put(element, "dummy"); } } @Benchmark public void get() { int localSize = this.size; String[] localElements = this.elements; TMap<String, String> localTroveMap = this.troveMap; for (int i = 0; i < localSize; i++) { if (localTroveMap.get(localElements[i]) == null) { throw new AssertionError(i); } } } }
apache-2.0
jaxio/jpa-query-by-example
src/main/java/com/jaxio/jpa/querybyexample/OrderBy.java
2885
/* * Copyright 2015 JAXIO http://www.jaxio.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.jaxio.jpa.querybyexample; import org.apache.commons.lang.builder.ToStringBuilder; import javax.persistence.metamodel.Attribute; import java.io.Serializable; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.jaxio.jpa.querybyexample.OrderByDirection.ASC; import static com.jaxio.jpa.querybyexample.OrderByDirection.DESC; /** * Holder class for search ordering used by the {@link SearchParameters}. */ public class OrderBy implements Serializable { private static final long serialVersionUID = 1L; private final PathHolder pathHolder; private OrderByDirection direction = ASC; public OrderBy(OrderByDirection direction, Attribute<?, ?>... attributes) { this.direction = checkNotNull(direction); this.pathHolder = new PathHolder(checkNotNull(attributes)); } public OrderBy(OrderByDirection direction, String path, Class<?> from) { this.direction = checkNotNull(direction); this.pathHolder = new PathHolder(checkNotNull(path), checkNotNull(from)); } public List<Attribute<?, ?>> getAttributes() { return pathHolder.getAttributes(); } public String getPath() { return pathHolder.getPath(); } public OrderByDirection getDirection() { return direction; } public boolean isOrderDesc() { return DESC == direction; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pathHolder == null) ? 0 : pathHolder.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } OrderBy other = (OrderBy) obj; if (pathHolder == null) { if (other.pathHolder != null) { return false; } } else if (!pathHolder.equals(other.pathHolder)) { return false; } return true; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
apache-2.0
jpallas/beakerx
kernel/base/src/test/java/com/twosigma/beakerx/chart/ColorTest.java
4296
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.twosigma.beakerx.chart; import org.assertj.core.api.Assertions; import org.junit.Test; public class ColorTest { @Test public void createColorWithIntRGBParams_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = new Color(100, 150, 200); //then Assertions.assertThat(color.getRed()).isEqualTo(100); Assertions.assertThat(color.getGreen()).isEqualTo(150); Assertions.assertThat(color.getBlue()).isEqualTo(200); } @Test public void createColorWithFloatRGBParams_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = new Color(0.1f, 0.2f, 0.3f); //then Assertions.assertThat(color.getRed()).isEqualTo(26); Assertions.assertThat(color.getGreen()).isEqualTo(51); Assertions.assertThat(color.getBlue()).isEqualTo(77); } @Test public void createColorWithFourFloatParams_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = new Color(0.1f, 0.2f, 0.3f, 0.4f); //then Assertions.assertThat(color.getRed()).isEqualTo(26); Assertions.assertThat(color.getGreen()).isEqualTo(51); Assertions.assertThat(color.getBlue()).isEqualTo(77); } @Test public void createColorWithIndAndFalseParams_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = new Color(200, false); //then Assertions.assertThat(color.getRed()).isEqualTo(0); Assertions.assertThat(color.getGreen()).isEqualTo(0); Assertions.assertThat(color.getBlue()).isEqualTo(200); } @Test public void createColorWithIntAndTrueParams_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = new Color(200, true); //then Assertions.assertThat(color.getRed()).isEqualTo(0); Assertions.assertThat(color.getGreen()).isEqualTo(0); Assertions.assertThat(color.getBlue()).isEqualTo(200); } @Test public void createColorByDecodeString_ColorHasRGBValues() throws IllegalArgumentException { //when Color color = Color.decode("200"); //then Assertions.assertThat(color.getRed()).isEqualTo(0); Assertions.assertThat(color.getGreen()).isEqualTo(0); Assertions.assertThat(color.getBlue()).isEqualTo(200); } @Test public void hashCode_returnRGBValue() throws IllegalArgumentException { //given Color color = new Color(100, 150, 200); //when //then Assertions.assertThat(color.hashCode()).isEqualTo(color.getRGB()); } @Test public void toString_returnStringRGBValues() throws IllegalArgumentException { //given Color color = new Color(100, 150, 200); //when //then Assertions.assertThat(color.toString()).contains(Integer.toString(color.getBlue())); Assertions.assertThat(color.toString()).contains(Integer.toString(color.getGreen())); Assertions.assertThat(color.toString()).contains(Integer.toString(color.getRed())); } @Test public void createColorWithAwtColorParam_ColorHasRGBValues() { //when Color color = new Color(new java.awt.Color(100, 150, 200)); //then Assertions.assertThat(color.getRed()).isEqualTo(100); Assertions.assertThat(color.getGreen()).isEqualTo(150); Assertions.assertThat(color.getBlue()).isEqualTo(200); } @Test(expected = IllegalArgumentException.class) public void createColorWithIllegalIntRGBParams_ThrowIllegalArgumentException() throws IllegalArgumentException { new Color(300, 150, 200); } @Test(expected = IllegalArgumentException.class) public void createColorWithIllegalFloatRGBParams_ThrowIllegalArgumentException() throws IllegalArgumentException { new Color(100.1f, 0.2f, 0.3f); } }
apache-2.0
hardfish/justTest
profitbricks/src/main/java/org/jclouds/profitbricks/binder/nic/UpdateNicRequestBinder.java
1943
/* * 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.jclouds.profitbricks.binder.nic; import org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder; import org.jclouds.profitbricks.domain.Nic; import static java.lang.String.format; public class UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { private final StringBuilder requestBuilder; UpdateNicRequestBinder() { super("nic"); this.requestBuilder = new StringBuilder(128 * 2); } @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } }
apache-2.0
lengyubing/wint
wint-framework/src/main/java/wint/sessionx/filter/filters/InitializeFilter.java
793
package wint.sessionx.filter.filters; import wint.sessionx.constants.AttrKeys; import wint.sessionx.filter.FilterContext; import wint.sessionx.provider.sessionid.SessionIdGenerators; import javax.servlet.ServletContext; /** * Created by pister on 14-2-26. */ public class InitializeFilter extends AbstractFilter { private ServletContext servletContext; public InitializeFilter(ServletContext servletContext) { this.servletContext = servletContext; } public void doFilter(FilterContext filterContext) { filterContext.setAttribute(AttrKeys.SERVLET_CONTEXT, servletContext); filterContext.setAttribute(AttrKeys.SESSION_ID_GENERATOR, SessionIdGenerators.getSessionIdGenerator()); filterContext.invokeNext(); } }
apache-2.0
ServiceComb/java-chassis
foundations/foundation-test-scaffolding/src/main/java/org/apache/servicecomb/foundation/test/scaffolding/log/LogCollector.java
2589
/* * 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.servicecomb.foundation.test.scaffolding.log; import java.io.Closeable; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; public class LogCollector implements Closeable { List<LoggingEvent> events = new ArrayList<>(); Appender appender = new AppenderSkeleton() { @Override public void append(LoggingEvent event) { events.add(event); } @Override public void close() { } @Override public boolean requiresLayout() { return false; } }; public LogCollector() { Logger.getRootLogger().addAppender(appender); } public LogCollector setLogLevel(String logName, Level level) { Logger.getLogger(logName).setLevel(level); return this; } public List<LoggingEvent> getEvents() { return events; } public LoggingEvent getLastEvents() { return events.get(events.size() - 1); } public List<Throwable> getThrowables() { return events.stream() .filter(e -> e.getThrowableInformation() != null) .map(e -> e.getThrowableInformation().getThrowable()) .collect(Collectors.toList()); } public List<String> getThrowableMessages() { return events.stream() .filter(e -> e.getThrowableInformation() != null) .map(e -> e.getThrowableInformation().getThrowable().getMessage()) .collect(Collectors.toList()); } public void teardown() { Logger.getRootLogger().removeAppender(appender); } public void clear() { events = new ArrayList<>(); } @Override public void close() { teardown(); } }
apache-2.0
rrenomeron/cas
api/cas-server-core-api-events/src/main/java/org/apereo/cas/support/events/service/CasRegisteredServiceLoadedEvent.java
928
package org.apereo.cas.support.events.service; import org.apereo.cas.services.RegisteredService; import lombok.Getter; import lombok.ToString; /** * This is {@link CasRegisteredServiceLoadedEvent} that is signaled * when a registered service is loaded from the registry. * * @author Misagh Moayyed * @since 5.1.0 */ @ToString(callSuper = true) @Getter public class CasRegisteredServiceLoadedEvent extends BaseCasRegisteredServiceEvent { private static final long serialVersionUID = 290988299766263298L; private final RegisteredService registeredService; /** * Instantiates a new cas sso event. * * @param source the source * @param registeredService the registered service */ public CasRegisteredServiceLoadedEvent(final Object source, final RegisteredService registeredService) { super(source); this.registeredService = registeredService; } }
apache-2.0
xasx/assertj-core
src/test/java/org/assertj/core/api/atomic/integer/AtomicIntegerAssert_hasNonNegativeValue_Test.java
1172
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2019 the original author or authors. */ package org.assertj.core.api.atomic.integer; import static org.mockito.Mockito.verify; import org.assertj.core.api.AtomicIntegerAssert; import org.assertj.core.api.AtomicIntegerAssertBaseTest; public class AtomicIntegerAssert_hasNonNegativeValue_Test extends AtomicIntegerAssertBaseTest { @Override protected AtomicIntegerAssert invoke_api_method() { return assertions.hasNonNegativeValue(); } @Override protected void verify_internal_effects() { verify(integers).assertIsNotNegative(getInfo(assertions), getActual(assertions).get()); } }
apache-2.0
shudo/overlayweaver
src/ow/tool/memcached/commands/IncrCommand.java
1080
/* * Copyright 2008 Kazuyuki Shudo, and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ow.tool.memcached.commands; import ow.dht.memcached.Memcached; import ow.tool.util.shellframework.ShellContext; public final class IncrCommand extends AbstractIncrDecrCommand { private final static String[] NAMES = {"incr"}; public String[] getNames() { return NAMES; } public String getHelp() { return "incr <key> <value> [noreply]"; } public boolean execute(ShellContext<Memcached> context) { return super.incrOrDecr(context, true); } }
apache-2.0
terrestris/shogun2
src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/PersonDao.java
593
package de.terrestris.shoguncore.dao; import org.springframework.stereotype.Repository; import de.terrestris.shoguncore.model.Person; @Repository("personDao") public class PersonDao<E extends Person> extends GenericHibernateDao<E, Integer> { /** * Public default constructor for this DAO. */ @SuppressWarnings("unchecked") public PersonDao() { super((Class<E>) Person.class); } /** * Constructor that has to be called by subclasses. * * @param clazz */ protected PersonDao(Class<E> clazz) { super(clazz); } }
apache-2.0
punkhorn/camel-upstream
core/camel-core/src/test/java/org/apache/camel/impl/RoutePolicyCallbackTest.java
4349
/** * 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.impl; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.Route; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.support.RoutePolicySupport; import org.junit.Test; /** * */ public class RoutePolicyCallbackTest extends ContextTestSupport { protected MyRoutePolicy policy = new MyRoutePolicy(); public static class MyRoutePolicy extends RoutePolicySupport { boolean begin; boolean done; boolean init; boolean remove; boolean resume; boolean start; boolean stop; boolean suspend; boolean doStart; boolean doStop; @Override public void onExchangeBegin(Route route, Exchange exchange) { begin = true; } @Override public void onExchangeDone(Route route, Exchange exchange) { done = true; } @Override public void onInit(Route route) { init = true; } @Override public void onRemove(Route route) { remove = true; } @Override public void onResume(Route route) { resume = true; } @Override public void onStart(Route route) { start = true; } @Override public void onStop(Route route) { stop = true; } @Override public void onSuspend(Route route) { suspend = true; } @Override protected void doStop() throws Exception { doStop = true; } @Override protected void doStart() throws Exception { doStart = true; } } protected MyRoutePolicy getAndInitMyRoutePolicy() { return policy; } @Test public void testCallback() throws Exception { policy = getAndInitMyRoutePolicy(); assertTrue(policy.doStart); assertTrue(policy.init); assertFalse(policy.begin); assertFalse(policy.done); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); assertTrue(policy.begin); assertTrue(policy.done); assertFalse(policy.suspend); context.getRouteController().suspendRoute("foo"); assertTrue(policy.suspend); assertFalse(policy.resume); context.getRouteController().resumeRoute("foo"); assertTrue(policy.resume); assertFalse(policy.stop); context.getRouteController().stopRoute("foo"); assertTrue(policy.stop); // previously started, so force flag to be false policy.start = false; assertFalse(policy.start); context.getRouteController().startRoute("foo"); assertTrue(policy.start); assertFalse(policy.remove); context.getRouteController().stopRoute("foo"); context.removeRoute("foo"); assertTrue(policy.remove); // stop camel which should stop policy as well context.stop(); assertTrue(policy.doStop); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("foo").routePolicy(policy) .to("mock:result"); } }; } }
apache-2.0
tweise/beam
sdks/java/core/src/test/java/org/apache/beam/sdk/io/AvroIOGeneratedClassTest.java
10166
/* * 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.beam.sdk.io; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.testing.NeedsRunner; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Tests for AvroIO Read and Write transforms, using classes generated from {@code user.avsc}. */ // TODO: Stop requiring local files @RunWith(JUnit4.class) public class AvroIOGeneratedClassTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); private File avroFile; @Before public void prepareAvroFileBeforeAnyTest() throws IOException { avroFile = tmpFolder.newFile("file.avro"); } private final String schemaString = "{\"namespace\": \"example.avro\",\n" + " \"type\": \"record\",\n" + " \"name\": \"AvroGeneratedUser\",\n" + " \"fields\": [\n" + " {\"name\": \"name\", \"type\": \"string\"},\n" + " {\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]},\n" + " {\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]}\n" + " ]\n" + "}"; private final Schema.Parser parser = new Schema.Parser(); private final Schema schema = parser.parse(schemaString); private AvroGeneratedUser[] generateAvroObjects() { AvroGeneratedUser user1 = new AvroGeneratedUser(); user1.setName("Bob"); user1.setFavoriteNumber(256); AvroGeneratedUser user2 = new AvroGeneratedUser(); user2.setName("Alice"); user2.setFavoriteNumber(128); AvroGeneratedUser user3 = new AvroGeneratedUser(); user3.setName("Ted"); user3.setFavoriteColor("white"); return new AvroGeneratedUser[] { user1, user2, user3 }; } private GenericRecord[] generateAvroGenericRecords() { GenericRecord user1 = new GenericData.Record(schema); user1.put("name", "Bob"); user1.put("favorite_number", 256); GenericRecord user2 = new GenericData.Record(schema); user2.put("name", "Alice"); user2.put("favorite_number", 128); GenericRecord user3 = new GenericData.Record(schema); user3.put("name", "Ted"); user3.put("favorite_color", "white"); return new GenericRecord[] { user1, user2, user3 }; } private void generateAvroFile(AvroGeneratedUser[] elements) throws IOException { DatumWriter<AvroGeneratedUser> userDatumWriter = new SpecificDatumWriter<>(AvroGeneratedUser.class); try (DataFileWriter<AvroGeneratedUser> dataFileWriter = new DataFileWriter<>(userDatumWriter)) { dataFileWriter.create(elements[0].getSchema(), avroFile); for (AvroGeneratedUser user : elements) { dataFileWriter.append(user); } } } private List<AvroGeneratedUser> readAvroFile() throws IOException { DatumReader<AvroGeneratedUser> userDatumReader = new SpecificDatumReader<>(AvroGeneratedUser.class); List<AvroGeneratedUser> users = new ArrayList<>(); try (DataFileReader<AvroGeneratedUser> dataFileReader = new DataFileReader<>(avroFile, userDatumReader)) { while (dataFileReader.hasNext()) { users.add(dataFileReader.next()); } } return users; } <T> void runTestRead( String applyName, AvroIO.Read.Bound<T> read, String expectedName, T[] expectedOutput) throws Exception { generateAvroFile(generateAvroObjects()); TestPipeline p = TestPipeline.create(); PCollection<T> output = p.apply(applyName, read); PAssert.that(output).containsInAnyOrder(expectedOutput); p.run(); assertEquals(expectedName, output.getName()); } <T> void runTestRead(AvroIO.Read.Bound<T> read, String expectedName, T[] expectedOutput) throws Exception { generateAvroFile(generateAvroObjects()); TestPipeline p = TestPipeline.create(); PCollection<T> output = p.apply(read); PAssert.that(output).containsInAnyOrder(expectedOutput); p.run(); assertEquals(expectedName, output.getName()); } @Test @Category(NeedsRunner.class) public void testReadFromGeneratedClass() throws Exception { runTestRead( AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), "AvroIO.Read/Read.out", generateAvroObjects()); runTestRead( AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), "AvroIO.Read/Read.out", generateAvroObjects()); runTestRead("MyRead", AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), "MyRead/Read.out", generateAvroObjects()); runTestRead("MyRead", AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), "MyRead/Read.out", generateAvroObjects()); runTestRead("HerRead", AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), "HerRead/Read.out", generateAvroObjects()); } @Test @Category(NeedsRunner.class) public void testReadFromSchema() throws Exception { runTestRead( AvroIO.Read.from(avroFile.getPath()).withSchema(schema), "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead( AvroIO.Read.withSchema(schema).from(avroFile.getPath()), "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead("MyRead", AvroIO.Read.from(avroFile.getPath()).withSchema(schema), "MyRead/Read.out", generateAvroGenericRecords()); runTestRead("MyRead", AvroIO.Read.withSchema(schema).from(avroFile.getPath()), "MyRead/Read.out", generateAvroGenericRecords()); runTestRead("HerRead", AvroIO.Read.from(avroFile.getPath()).withSchema(schema), "HerRead/Read.out", generateAvroGenericRecords()); runTestRead("HerRead", AvroIO.Read.from(avroFile.getPath()).withSchema(schema), "HerRead/Read.out", generateAvroGenericRecords()); } @Test @Category(NeedsRunner.class) public void testReadFromSchemaString() throws Exception { runTestRead( AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString), "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead( AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()), "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead("MyRead", AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString), "MyRead/Read.out", generateAvroGenericRecords()); runTestRead("HerRead", AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()), "HerRead/Read.out", generateAvroGenericRecords()); } <T> void runTestWrite(AvroIO.Write.Bound<T> write, String expectedName) throws Exception { AvroGeneratedUser[] users = generateAvroObjects(); TestPipeline p = TestPipeline.create(); @SuppressWarnings("unchecked") PCollection<T> input = p.apply(Create.of(Arrays.asList((T[]) users)) .withCoder((Coder<T>) AvroCoder.of(AvroGeneratedUser.class))); input.apply(write.withoutSharding()); p.run(); assertEquals(expectedName, write.getName()); assertThat(readAvroFile(), containsInAnyOrder(users)); } @Test @Category(NeedsRunner.class) public void testWriteFromGeneratedClass() throws Exception { runTestWrite( AvroIO.Write.to(avroFile.getPath()).withSchema(AvroGeneratedUser.class), "AvroIO.Write"); runTestWrite( AvroIO.Write.withSchema(AvroGeneratedUser.class).to(avroFile.getPath()), "AvroIO.Write"); } @Test @Category(NeedsRunner.class) public void testWriteFromSchema() throws Exception { runTestWrite( AvroIO.Write.to(avroFile.getPath()).withSchema(schema), "AvroIO.Write"); runTestWrite( AvroIO.Write.withSchema(schema).to(avroFile.getPath()), "AvroIO.Write"); } @Test @Category(NeedsRunner.class) public void testWriteFromSchemaString() throws Exception { runTestWrite( AvroIO.Write.to(avroFile.getPath()).withSchema(schemaString), "AvroIO.Write"); runTestWrite( AvroIO.Write.withSchema(schemaString).to(avroFile.getPath()), "AvroIO.Write"); } // TODO: for Write only, test withSuffix, withNumShards, // withShardNameTemplate and withoutSharding. }
apache-2.0
cbeams-archive/spring-framework-2.5.x
test/org/springframework/beans/propertyeditors/URIEditorTests.java
3936
/* * Copyright 2002-2007 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.springframework.beans.propertyeditors; import java.beans.PropertyEditor; import java.net.URI; import junit.framework.TestCase; import org.springframework.util.ClassUtils; /** * @author Juergen Hoeller */ public class URIEditorTests extends TestCase { public void testStandardURI() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("mailto:juergen.hoeller@interface21.com"); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); } public void testStandardURL() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("http://www.springframework.org"); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); } public void testStandardURLWithWhitespace() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(" http://www.springframework.org "); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); } public void testClasspathURL() throws Exception { PropertyEditor uriEditor = new URIEditor(getClass().getClassLoader()); uriEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); assertTrue(!uri.getScheme().startsWith("classpath")); } public void testClasspathURLWithWhitespace() throws Exception { PropertyEditor uriEditor = new URIEditor(getClass().getClassLoader()); uriEditor.setAsText(" classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class "); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); assertTrue(!uri.getScheme().startsWith("classpath")); } public void testClasspathURLAsIs() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("classpath:test.txt"); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); assertTrue(uri.getScheme().startsWith("classpath")); } public void testWithNonExistentResource() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening"); Object value = uriEditor.getValue(); assertTrue(value instanceof URI); URI uri = (URI) value; assertEquals(uri.toString(), uriEditor.getAsText()); } public void testSetAsTextWithNull() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(null); assertNull(uriEditor.getValue()); assertEquals("", uriEditor.getAsText()); } public void testGetAsTextReturnsEmptyStringIfValueNotSet() throws Exception { PropertyEditor uriEditor = new URIEditor(); assertEquals("", uriEditor.getAsText()); } }
apache-2.0
muroc-lab/muice
muice/src/main/java/pl/chalapuk/muice/BindingModule.java
1355
/* * Copyright (C) 2013 Maciej Chałapuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.chalapuk.muice; /** * Client code must implement this interface to configure binding information * (using {@link Binder Guice Binding EDSL}) used to create {@link Injector}. * <p> * The same module instance may be used to configure multiple injectors. * Dependencies between bindings located in different modules are supported. * * @see Muice#createInjector(BindingModule...) * @author maciej@chalapuk.pl (Maciej Chałapuk) */ public interface BindingModule { /** * Called by Muice during injector creation process. * <p> * Implementation should use given binder to configure bindings. * * @param binder binder connected with an {@link Injector} instance. */ void configure(Binder binder); }
apache-2.0
pkarmstr/NYBC
solr-4.2.1/lucene/suggest/src/java/org/apache/lucene/search/spell/DirectSpellChecker.java
18965
package org.apache.lucene.search.spell; /* * 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. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.search.BoostAttribute; import org.apache.lucene.search.FuzzyTermsEnum; import org.apache.lucene.search.MaxNonCompetitiveBoostAttribute; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.AttributeSource; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRef; import org.apache.lucene.util.UnicodeUtil; import org.apache.lucene.util.automaton.LevenshteinAutomata; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Locale; import java.util.PriorityQueue; /** * Simple automaton-based spellchecker. * <p> * Candidates are presented directly from the term dictionary, based on * Levenshtein distance. This is an alternative to {@link SpellChecker} * if you are using an edit-distance-like metric such as Levenshtein * or {@link JaroWinklerDistance}. * <p> * A practical benefit of this spellchecker is that it requires no additional * datastructures (neither in RAM nor on disk) to do its work. * * @see LevenshteinAutomata * @see FuzzyTermsEnum * * @lucene.experimental */ public class DirectSpellChecker { /** The default StringDistance, Damerau-Levenshtein distance implemented internally * via {@link LevenshteinAutomata}. * <p> * Note: this is the fastest distance metric, because Damerau-Levenshtein is used * to draw candidates from the term dictionary: this just re-uses the scoring. */ public static final StringDistance INTERNAL_LEVENSHTEIN = new LuceneLevenshteinDistance(); /** maximum edit distance for candidate terms */ private int maxEdits = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE; /** minimum prefix for candidate terms */ private int minPrefix = 1; /** maximum number of top-N inspections per suggestion */ private int maxInspections = 5; /** minimum accuracy for a term to match */ private float accuracy = SpellChecker.DEFAULT_ACCURACY; /** value in [0..1] (or absolute number >=1) representing the minimum * number of documents (of the total) where a term should appear. */ private float thresholdFrequency = 0f; /** minimum length of a query word to return suggestions */ private int minQueryLength = 4; /** value in [0..1] (or absolute number >=1) representing the maximum * number of documents (of the total) a query term can appear in to * be corrected. */ private float maxQueryFrequency = 0.01f; /** true if the spellchecker should lowercase terms */ private boolean lowerCaseTerms = true; /** the comparator to use */ private Comparator<SuggestWord> comparator = SuggestWordQueue.DEFAULT_COMPARATOR; /** the string distance to use */ private StringDistance distance = INTERNAL_LEVENSHTEIN; /** Creates a DirectSpellChecker with default configuration values */ public DirectSpellChecker() {} /** Get the maximum number of Levenshtein edit-distances to draw * candidate terms from. */ public int getMaxEdits() { return maxEdits; } /** Sets the maximum number of Levenshtein edit-distances to draw * candidate terms from. This value can be 1 or 2. The default is 2. * <p> * Note: a large number of spelling errors occur with an edit distance * of 1, by setting this value to 1 you can increase both performance * and precision at the cost of recall. */ public void setMaxEdits(int maxEdits) { if (maxEdits < 1 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) throw new UnsupportedOperationException("Invalid maxEdits"); this.maxEdits = maxEdits; } /** * Get the minimal number of characters that must match exactly */ public int getMinPrefix() { return minPrefix; } /** * Sets the minimal number of initial characters (default: 1) * that must match exactly. * <p> * This can improve both performance and accuracy of results, * as misspellings are commonly not the first character. */ public void setMinPrefix(int minPrefix) { this.minPrefix = minPrefix; } /** * Get the maximum number of top-N inspections per suggestion */ public int getMaxInspections() { return maxInspections; } /** * Set the maximum number of top-N inspections (default: 5) per suggestion. * <p> * Increasing this number can improve the accuracy of results, at the cost * of performance. */ public void setMaxInspections(int maxInspections) { this.maxInspections = maxInspections; } /** * Get the minimal accuracy from the StringDistance for a match */ public float getAccuracy() { return accuracy; } /** * Set the minimal accuracy required (default: 0.5f) from a StringDistance * for a suggestion match. */ public void setAccuracy(float accuracy) { this.accuracy = accuracy; } /** * Get the minimal threshold of documents a term must appear for a match */ public float getThresholdFrequency() { return thresholdFrequency; } /** * Set the minimal threshold of documents a term must appear for a match. * <p> * This can improve quality by only suggesting high-frequency terms. Note that * very high values might decrease performance slightly, by forcing the spellchecker * to draw more candidates from the term dictionary, but a practical value such * as <code>1</code> can be very useful towards improving quality. * <p> * This can be specified as a relative percentage of documents such as 0.5f, * or it can be specified as an absolute whole document frequency, such as 4f. * Absolute document frequencies may not be fractional. */ public void setThresholdFrequency(float thresholdFrequency) { if (thresholdFrequency >= 1f && thresholdFrequency != (int) thresholdFrequency) throw new IllegalArgumentException("Fractional absolute document frequencies are not allowed"); this.thresholdFrequency = thresholdFrequency; } /** Get the minimum length of a query term needed to return suggestions */ public int getMinQueryLength() { return minQueryLength; } /** * Set the minimum length of a query term (default: 4) needed to return suggestions. * <p> * Very short query terms will often cause only bad suggestions with any distance * metric. */ public void setMinQueryLength(int minQueryLength) { this.minQueryLength = minQueryLength; } /** * Get the maximum threshold of documents a query term can appear in order * to provide suggestions. */ public float getMaxQueryFrequency() { return maxQueryFrequency; } /** * Set the maximum threshold (default: 0.01f) of documents a query term can * appear in order to provide suggestions. * <p> * Very high-frequency terms are typically spelled correctly. Additionally, * this can increase performance as it will do no work for the common case * of correctly-spelled input terms. * <p> * This can be specified as a relative percentage of documents such as 0.5f, * or it can be specified as an absolute whole document frequency, such as 4f. * Absolute document frequencies may not be fractional. */ public void setMaxQueryFrequency(float maxQueryFrequency) { if (maxQueryFrequency >= 1f && maxQueryFrequency != (int) maxQueryFrequency) throw new IllegalArgumentException("Fractional absolute document frequencies are not allowed"); this.maxQueryFrequency = maxQueryFrequency; } /** true if the spellchecker should lowercase terms */ public boolean getLowerCaseTerms() { return lowerCaseTerms; } /** * True if the spellchecker should lowercase terms (default: true) * <p> * This is a convenience method, if your index field has more complicated * analysis (such as StandardTokenizer removing punctuation), its probably * better to turn this off, and instead run your query terms through your * Analyzer first. * <p> * If this option is not on, case differences count as an edit! */ public void setLowerCaseTerms(boolean lowerCaseTerms) { this.lowerCaseTerms = lowerCaseTerms; } /** * Get the current comparator in use. */ public Comparator<SuggestWord> getComparator() { return comparator; } /** * Set the comparator for sorting suggestions. * The default is {@link SuggestWordQueue#DEFAULT_COMPARATOR} */ public void setComparator(Comparator<SuggestWord> comparator) { this.comparator = comparator; } /** * Get the string distance metric in use. */ public StringDistance getDistance() { return distance; } /** * Set the string distance metric. * The default is {@link #INTERNAL_LEVENSHTEIN} * <p> * Note: because this spellchecker draws its candidates from the term * dictionary using Damerau-Levenshtein, it works best with an edit-distance-like * string metric. If you use a different metric than the default, * you might want to consider increasing {@link #setMaxInspections(int)} * to draw more candidates for your metric to rank. */ public void setDistance(StringDistance distance) { this.distance = distance; } /** * Calls {@link #suggestSimilar(Term, int, IndexReader, SuggestMode) * suggestSimilar(term, numSug, ir, SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX)} */ public SuggestWord[] suggestSimilar(Term term, int numSug, IndexReader ir) throws IOException { return suggestSimilar(term, numSug, ir, SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX); } /** * Calls {@link #suggestSimilar(Term, int, IndexReader, SuggestMode, float) * suggestSimilar(term, numSug, ir, suggestMode, this.accuracy)} * */ public SuggestWord[] suggestSimilar(Term term, int numSug, IndexReader ir, SuggestMode suggestMode) throws IOException { return suggestSimilar(term, numSug, ir, suggestMode, this.accuracy); } /** * Suggest similar words. * * <p>Unlike {@link SpellChecker}, the similarity used to fetch the most * relevant terms is an edit distance, therefore typically a low value * for numSug will work very well. * * @param term Term you want to spell check on * @param numSug the maximum number of suggested words * @param ir IndexReader to find terms from * @param suggestMode specifies when to return suggested words * @param accuracy return only suggested words that match with this similarity * @return sorted list of the suggested words according to the comparator * @throws IOException If there is a low-level I/O error. */ public SuggestWord[] suggestSimilar(Term term, int numSug, IndexReader ir, SuggestMode suggestMode, float accuracy) throws IOException { final CharsRef spare = new CharsRef(); String text = term.text(); if (minQueryLength > 0 && text.codePointCount(0, text.length()) < minQueryLength) return new SuggestWord[0]; if (lowerCaseTerms) { term = new Term(term.field(), text.toLowerCase(Locale.ROOT)); } int docfreq = ir.docFreq(term); if (suggestMode==SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX && docfreq > 0) { return new SuggestWord[0]; } int maxDoc = ir.maxDoc(); if (maxQueryFrequency >= 1f && docfreq > maxQueryFrequency) { return new SuggestWord[0]; } else if (docfreq > (int) Math.ceil(maxQueryFrequency * (float)maxDoc)) { return new SuggestWord[0]; } if (suggestMode!=SuggestMode.SUGGEST_MORE_POPULAR) docfreq = 0; if (thresholdFrequency >= 1f) { docfreq = Math.max(docfreq, (int) thresholdFrequency); } else if (thresholdFrequency > 0f) { docfreq = Math.max(docfreq, (int)(thresholdFrequency * (float)maxDoc)-1); } Collection<ScoreTerm> terms = null; int inspections = numSug * maxInspections; // try ed=1 first, in case we get lucky terms = suggestSimilar(term, inspections, ir, docfreq, 1, accuracy, spare); if (maxEdits > 1 && terms.size() < inspections) { HashSet<ScoreTerm> moreTerms = new HashSet<ScoreTerm>(); moreTerms.addAll(terms); moreTerms.addAll(suggestSimilar(term, inspections, ir, docfreq, maxEdits, accuracy, spare)); terms = moreTerms; } // create the suggestword response, sort it, and trim it to size. SuggestWord suggestions[] = new SuggestWord[terms.size()]; int index = suggestions.length - 1; for (ScoreTerm s : terms) { SuggestWord suggestion = new SuggestWord(); if (s.termAsString == null) { UnicodeUtil.UTF8toUTF16(s.term, spare); s.termAsString = spare.toString(); } suggestion.string = s.termAsString; suggestion.score = s.score; suggestion.freq = s.docfreq; suggestions[index--] = suggestion; } ArrayUtil.mergeSort(suggestions, Collections.reverseOrder(comparator)); if (numSug < suggestions.length) { SuggestWord trimmed[] = new SuggestWord[numSug]; System.arraycopy(suggestions, 0, trimmed, 0, numSug); suggestions = trimmed; } return suggestions; } /** * Provide spelling corrections based on several parameters. * * @param term The term to suggest spelling corrections for * @param numSug The maximum number of spelling corrections * @param ir The index reader to fetch the candidate spelling corrections from * @param docfreq The minimum document frequency a potential suggestion need to have in order to be included * @param editDistance The maximum edit distance candidates are allowed to have * @param accuracy The minimum accuracy a suggested spelling correction needs to have in order to be included * @param spare a chars scratch * @return a collection of spelling corrections sorted by <code>ScoreTerm</code>'s natural order. * @throws IOException If I/O related errors occur */ protected Collection<ScoreTerm> suggestSimilar(Term term, int numSug, IndexReader ir, int docfreq, int editDistance, float accuracy, final CharsRef spare) throws IOException { AttributeSource atts = new AttributeSource(); MaxNonCompetitiveBoostAttribute maxBoostAtt = atts.addAttribute(MaxNonCompetitiveBoostAttribute.class); Terms terms = MultiFields.getTerms(ir, term.field()); if (terms == null) { return Collections.emptyList(); } FuzzyTermsEnum e = new FuzzyTermsEnum(terms, atts, term, editDistance, Math.max(minPrefix, editDistance-1), true); final PriorityQueue<ScoreTerm> stQueue = new PriorityQueue<ScoreTerm>(); BytesRef queryTerm = new BytesRef(term.text()); BytesRef candidateTerm; ScoreTerm st = new ScoreTerm(); BoostAttribute boostAtt = e.attributes().addAttribute(BoostAttribute.class); while ((candidateTerm = e.next()) != null) { final float boost = boostAtt.getBoost(); // ignore uncompetitive hits if (stQueue.size() >= numSug && boost <= stQueue.peek().boost) continue; // ignore exact match of the same term if (queryTerm.bytesEquals(candidateTerm)) continue; int df = e.docFreq(); // check docFreq if required if (df <= docfreq) continue; final float score; final String termAsString; if (distance == INTERNAL_LEVENSHTEIN) { // delay creating strings until the end termAsString = null; // undo FuzzyTermsEnum's scale factor for a real scaled lev score score = boost / e.getScaleFactor() + e.getMinSimilarity(); } else { UnicodeUtil.UTF8toUTF16(candidateTerm, spare); termAsString = spare.toString(); score = distance.getDistance(term.text(), termAsString); } if (score < accuracy) continue; // add new entry in PQ st.term = BytesRef.deepCopyOf(candidateTerm); st.boost = boost; st.docfreq = df; st.termAsString = termAsString; st.score = score; stQueue.offer(st); // possibly drop entries from queue st = (stQueue.size() > numSug) ? stQueue.poll() : new ScoreTerm(); maxBoostAtt.setMaxNonCompetitiveBoost((stQueue.size() >= numSug) ? stQueue.peek().boost : Float.NEGATIVE_INFINITY); } return stQueue; } /** * Holds a spelling correction for internal usage inside {@link DirectSpellChecker}. */ protected static class ScoreTerm implements Comparable<ScoreTerm> { /** * The actual spellcheck correction. */ public BytesRef term; /** * The boost representing the similarity from the FuzzyTermsEnum (internal similarity score) */ public float boost; /** * The df of the spellcheck correction. */ public int docfreq; /** * The spellcheck correction represented as string, can be <code>null</code>. */ public String termAsString; /** * The similarity score. */ public float score; /** * Constructor. */ public ScoreTerm() { } @Override public int compareTo(ScoreTerm other) { if (term.bytesEquals(other.term)) return 0; // consistent with equals if (this.boost == other.boost) return other.term.compareTo(this.term); else return Float.compare(this.boost, other.boost); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((term == null) ? 0 : term.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ScoreTerm other = (ScoreTerm) obj; if (term == null) { if (other.term != null) return false; } else if (!term.bytesEquals(other.term)) return false; return true; } } }
apache-2.0
greg-pendlebury/bamboo
ui/src/bamboo/core/PandasImport.java
1475
package bamboo.core; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class PandasImport { /* void importInstance(long seriesId, long instanceId) throws IOException { try (Db db = bamboo.dbPool.take(); PandasDb pandasDb = bamboo.pandasDbPool.take()) { PandasDb.InstanceSummary instance = pandasDb.fetchInstanceSummary(instanceId); db.createPandasCrawl(instance.titleName, seriesId, instanceId, listWarcs(instance)); } } List<PandasWarc> listWarcs(PandasDb.InstanceSummary instance) throws IOException { List<PandasWarc> warcs = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(resolveTitlePath(instance.pi))) { for (Path entry : stream) { String filename = entry.getFileName().toString(); if (filename.startsWith("nla.arc-" + instance.pi + "-" + instance.date + "-") && filename.endsWith(".warc.gz")) { System.out.println(entry); warcs.add(new PandasWarc(entry)); } } } return warcs; } Path resolveTitlePath(long pi) { return pandasWarcDir.resolve(String.format("%03d", pi / 1000)).resolve(Long.toString(pi)); } */ }
apache-2.0
springml/DataflowJavaSDK
sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java
12159
/******************************************************************************* * Copyright (C) 2015 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.cloud.dataflow.sdk.runners.worker; import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration; import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudTime; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Sleeper; import com.google.api.services.dataflow.Dataflow; import com.google.api.services.dataflow.model.LeaseWorkItemRequest; import com.google.api.services.dataflow.model.LeaseWorkItemResponse; import com.google.api.services.dataflow.model.ReportWorkItemStatusRequest; import com.google.api.services.dataflow.model.ReportWorkItemStatusResponse; import com.google.api.services.dataflow.model.WorkItem; import com.google.api.services.dataflow.model.WorkItemServiceState; import com.google.api.services.dataflow.model.WorkItemStatus; import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingFormatter; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer; import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.common.worker.WorkProgressUpdater; import com.google.common.collect.ImmutableList; import org.joda.time.DateTime; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import javax.annotation.concurrent.ThreadSafe; /** * This is a harness for executing WorkItem tasks in Java workers. * <p> * The worker fetches WorkItem units from the Dataflow Service. * When the work is complete, the program sends results via the worker service API. * <p> * Returns status code 0 on successful completion, 1 on any uncaught failures. * <p> * TODO: add support for VM initialization via config. * During initialization, we should take a configuration that specifies * an initialization function, allowing user code to run on VM startup. */ public class DataflowWorkerHarness { private static final Logger LOG = LoggerFactory.getLogger(DataflowWorkerHarness.class); private static final String APPLICATION_NAME = "DataflowWorkerHarness"; // ExponentialBackOff parameters for the task retry strategy. Visible for testing. static final int BACKOFF_INITIAL_INTERVAL_MILLIS = 5000; // 5 second static final int BACKOFF_MAX_ATTEMPTS = 10; // 10 attempts will take approx. 15 min. /** * This uncaught exception handler logs the {@link Throwable} to the logger, {@link System#err} * and exits the application with status code 1. */ static class WorkerUncaughtExceptionHandler implements UncaughtExceptionHandler { static final WorkerUncaughtExceptionHandler INSTANCE = new WorkerUncaughtExceptionHandler(); @Override public void uncaughtException(Thread t, Throwable e) { LOG.error("Uncaught exception in main thread. Exiting with status code 1.", e); System.err.println("Uncaught exception in main thread. Exiting with status code 1."); e.printStackTrace(); System.exit(1); } } /** * Helper for initializing the BackOff used for retries. */ private static BackOff createBackOff() { return new AttemptBoundedExponentialBackOff( BACKOFF_MAX_ATTEMPTS, BACKOFF_INITIAL_INTERVAL_MILLIS); } /** * Fetches and processes work units from the Dataflow service. */ public static void main(String[] args) throws Exception { Thread.setDefaultUncaughtExceptionHandler(WorkerUncaughtExceptionHandler.INSTANCE); DataflowWorkerLoggingInitializer.initialize(); DataflowWorkerHarnessOptions pipelineOptions = PipelineOptionsFactory.createFromSystemPropertiesInternal(); DataflowWorkerLoggingInitializer.configure(pipelineOptions); final Sleeper sleeper = Sleeper.DEFAULT; final DataflowWorker worker = create(pipelineOptions); processWork(pipelineOptions, worker, sleeper); } /** * A thread that repeatedly fetches and processes work units from the Dataflow service. */ private static class WorkerThread implements Callable<Boolean> { // sleeper is used to sleep the appropriate amount of time WorkerThread(final DataflowWorker worker, final Sleeper sleeper) { this.worker = worker; this.sleeper = sleeper; this.backOff = createBackOff(); } @Override public Boolean call() { boolean success = true; try { do { // We loop getting and processing work. try { LOG.debug("Thread starting getAndPerformWork."); success = worker.getAndPerformWork(); LOG.debug("{} processing one WorkItem.", success ? "Finished" : "Failed"); } catch (IOException e) { // If there is a problem getting work. success = false; } if (success) { backOff.reset(); } // Sleeping a while if there is a problem with the work, then go on with the next work. } while (success || BackOffUtils.next(sleeper, backOff)); } catch (IOException e) { // Failure of BackOff. LOG.error("Already tried several attempts at working on tasks. Aborting.", e); } catch (InterruptedException e) { LOG.error("Interrupted during thread execution or sleep.", e); } return false; } private final DataflowWorker worker; private final Sleeper sleeper; private final BackOff backOff; } // Visible for testing. static void processWork(DataflowWorkerHarnessOptions pipelineOptions, final DataflowWorker worker, Sleeper sleeper) throws InterruptedException { int numThreads = Math.max(Runtime.getRuntime().availableProcessors(), 1); ExecutorService executor = pipelineOptions.getExecutorService(); final List<Callable<Boolean>> tasks = new LinkedList<>(); LOG.debug("Starting {} worker threads", numThreads); // We start the appropriate number of threads. for (int i = 0; i < numThreads; ++i) { tasks.add(new WorkerThread(worker, sleeper)); } LOG.debug("Waiting for {} worker threads", numThreads); // We wait forever unless there is a big problem. executor.invokeAll(tasks); } static DataflowWorker create(DataflowWorkerHarnessOptions options) { DataflowWorkerLoggingFormatter.setJobId(options.getJobId()); DataflowWorkerLoggingFormatter.setWorkerId(options.getWorkerId()); options.setAppName(APPLICATION_NAME); // Configure standard IO factories. IOChannelUtils.setIOFactory("gs", new GcsIOChannelFactory(options)); DataflowWorkUnitClient client = DataflowWorkUnitClient.fromOptions(options); return new DataflowWorker(client, options); } /** * A Dataflow WorkUnit client that fetches WorkItems from the Dataflow service. */ @ThreadSafe static class DataflowWorkUnitClient extends DataflowWorker.WorkUnitClient { private final Dataflow dataflow; private final DataflowWorkerHarnessOptions options; /** * Creates a client that fetches WorkItems from the Dataflow service. * * @param options The pipeline options. * @return A WorkItemClient that fetches WorkItems from the Dataflow service. */ static DataflowWorkUnitClient fromOptions(DataflowWorkerHarnessOptions options) { return new DataflowWorkUnitClient( Transport.newDataflowClient(options).build(), options); } /** * Package private constructor for testing. */ DataflowWorkUnitClient(Dataflow dataflow, DataflowWorkerHarnessOptions options) { this.dataflow = dataflow; this.options = options; } /** * Gets a WorkItem from the Dataflow service. */ @Override public WorkItem getWorkItem() throws IOException { LeaseWorkItemRequest request = new LeaseWorkItemRequest(); request.setFactory(Transport.getJsonFactory()); request.setWorkItemTypes(ImmutableList.<String>of( "map_task", "seq_map_task", "remote_source_task")); // All remote sources require the "remote_source" capability. Dataflow's // custom sources are further tagged with the format "custom_source". request.setWorkerCapabilities(ImmutableList.<String>of( options.getWorkerId(), "remote_source", PropertyNames.CUSTOM_SOURCE_FORMAT)); request.setWorkerId(options.getWorkerId()); request.setCurrentWorkerTime(toCloudTime(DateTime.now())); // This shouldn't be necessary, but a valid cloud duration string is // required by the Google API parsing framework. TODO: Fix the framework // so that an empty or not-present string can be used as a default value. request.setRequestedLeaseDuration( toCloudDuration(Duration.millis(WorkProgressUpdater.DEFAULT_LEASE_DURATION_MILLIS))); LOG.debug("Leasing work: {}", request); LeaseWorkItemResponse response = dataflow.v1b3().projects().jobs().workItems().lease( options.getProject(), options.getJobId(), request).execute(); LOG.debug("Lease work response: {}", response); List<WorkItem> workItems = response.getWorkItems(); if (workItems == null || workItems.isEmpty()) { // We didn't lease any work return null; } else if (workItems.size() > 1){ throw new IOException( "This version of the SDK expects no more than one work item from the service: " + response); } WorkItem work = response.getWorkItems().get(0); if (work == null || work.getId() == null) { return null; } DataflowWorkerLoggingFormatter.setWorkId(Long.toString(work.getId())); // Looks like the work's a'ight. return work; } @Override public WorkItemServiceState reportWorkItemStatus(WorkItemStatus workItemStatus) throws IOException { workItemStatus.setFactory(Transport.getJsonFactory()); LOG.debug("Reporting work status: {}", workItemStatus); ReportWorkItemStatusResponse result = dataflow.v1b3().projects().jobs().workItems().reportStatus( options.getProject(), options.getJobId(), new ReportWorkItemStatusRequest() .setWorkerId(options.getWorkerId()) .setWorkItemStatuses(Collections.singletonList(workItemStatus)) .setCurrentWorkerTime(toCloudTime(DateTime.now()))) .execute(); if (result == null || result.getWorkItemServiceStates() == null || result.getWorkItemServiceStates().size() != 1) { throw new IOException( "This version of the SDK expects exactly one work item service state from the service"); } WorkItemServiceState state = result.getWorkItemServiceStates().get(0); LOG.debug("ReportWorkItemStatus result: {}", state); return state; } } }
apache-2.0
machristie/airavata
airavata-api/airavata-client-sdks/java-client-samples/src/main/java/org/apache/airavata/client/samples/SampleEchoExperiment.java
10114
/* * * 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.airavata.client.samples; import org.apache.airavata.api.Airavata; import org.apache.airavata.api.client.AiravataClientFactory; import org.apache.airavata.client.tools.RegisterSampleApplicationsUtils; import org.apache.airavata.model.appcatalog.computeresource.*; import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; import org.apache.airavata.model.application.io.DataType; import org.apache.airavata.model.application.io.InputDataObjectType; import org.apache.airavata.model.application.io.OutputDataObjectType; import org.apache.airavata.model.data.movement.DataMovementInterface; import org.apache.airavata.model.data.movement.DataMovementProtocol; import org.apache.airavata.model.error.AiravataClientException; import org.apache.airavata.model.experiment.ExperimentModel; import org.apache.airavata.model.experiment.UserConfigurationDataModel; import org.apache.airavata.model.parallelism.ApplicationParallelismType; import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; import org.apache.airavata.model.security.AuthzToken; import org.apache.airavata.model.workspace.Gateway; import org.apache.airavata.model.workspace.GatewayApprovalStatus; import org.apache.airavata.model.workspace.Project; import org.apache.thrift.TException; import java.util.ArrayList; import java.util.List; public class SampleEchoExperiment { private static final String THRIFT_SERVER_HOST = "127.0.0.1"; private static final int THRIFT_SERVER_PORT = 8930; private Airavata.Client airavataClient; private String localhostId ; private String echoModuleId; private String echoInterfaceId; private String echoExperimentId; private String gatewayId = "default"; private String userId = "default-user"; public static void main(String[] args) throws AiravataClientException, TException { SampleEchoExperiment sampleEchoExperiment = new SampleEchoExperiment(); sampleEchoExperiment.register(); } public void register() throws TException { airavataClient = AiravataClientFactory.createAiravataClient(THRIFT_SERVER_HOST, THRIFT_SERVER_PORT); gatewayId = registerGateway(); registerLocalhost(); registerGatewayProfile(); registerEchoModule(); registerEchoDeployment(); registerEchoInterface(); createEchoExperiment(); } private String registerGateway() throws TException { Gateway gateway = new Gateway(); gateway.setGatewayName(gatewayId); gateway.setGatewayId(gatewayId); gateway.setGatewayApprovalStatus(GatewayApprovalStatus.APPROVED); return airavataClient.addGateway(new AuthzToken(""), gateway); } private void registerLocalhost() { try { System.out.println("\n #### Registering Localhost Computational Resource #### \n"); ComputeResourceDescription computeResourceDescription = RegisterSampleApplicationsUtils. createComputeResourceDescription("localhost", "LocalHost", null, null); DataMovementInterface dataMovementInterface = new DataMovementInterface("localhost_data_movement_interface", DataMovementProtocol.LOCAL, 1); computeResourceDescription.addToDataMovementInterfaces(dataMovementInterface); JobSubmissionInterface jobSubmissionInterface = new JobSubmissionInterface("localhost_job_submission_interface", JobSubmissionProtocol.LOCAL, 1); computeResourceDescription.addToJobSubmissionInterfaces(jobSubmissionInterface); localhostId = airavataClient.registerComputeResource(new AuthzToken(""), computeResourceDescription); ResourceJobManager resourceJobManager = RegisterSampleApplicationsUtils. createResourceJobManager(ResourceJobManagerType.FORK, null, null, null); LOCALSubmission submission = new LOCALSubmission(); submission.setResourceJobManager(resourceJobManager); String localSubmission = airavataClient.addLocalSubmissionDetails(new AuthzToken(""), localhostId, 1, submission); System.out.println(localSubmission); System.out.println("LocalHost Resource Id is " + localhostId); } catch (TException e) { e.printStackTrace(); } } private void registerGatewayProfile() throws TException { GatewayResourceProfile gatewayResourceProfile = new GatewayResourceProfile(); ComputeResourcePreference localhostResourcePreference = RegisterSampleApplicationsUtils. createComputeResourcePreference(localhostId, gatewayId, false, null, null, null, "/tmp"); gatewayResourceProfile.setGatewayID(gatewayId); gatewayResourceProfile.addToComputeResourcePreferences(localhostResourcePreference); airavataClient.registerGatewayResourceProfile(new AuthzToken(""), gatewayResourceProfile); } private void registerEchoModule() throws TException { //Register Echo echoModuleId = airavataClient.registerApplicationModule(new AuthzToken(""), gatewayId, RegisterSampleApplicationsUtils.createApplicationModule( "Echo", "1.0", "Echo application description")); } private void registerEchoDeployment() throws TException { System.out.println("#### Registering Application Deployments on Localhost ####"); //Register Echo String echoAppDeployId = airavataClient.registerApplicationDeployment(new AuthzToken(""), gatewayId, RegisterSampleApplicationsUtils.createApplicationDeployment(echoModuleId, localhostId, "/bin/echo", ApplicationParallelismType.SERIAL, "Echo application description", null, null, null)); System.out.println("Successfully registered Echo application on localhost, application Id = " + echoAppDeployId); } private void registerEchoInterface() { try { System.out.println("#### Registering Echo Interface ####"); List<String> appModules = new ArrayList<String>(); appModules.add(echoModuleId); InputDataObjectType input1 = RegisterSampleApplicationsUtils.createAppInput("Input_to_Echo", "Hello World", DataType.STRING, null, 1, true,true, false, "A test string to Echo", null); List<InputDataObjectType> applicationInputs = new ArrayList<InputDataObjectType>(); applicationInputs.add(input1); OutputDataObjectType output1 = RegisterSampleApplicationsUtils.createAppOutput("Echoed_Output", "", DataType.STRING, true, false, null); List<OutputDataObjectType> applicationOutputs = new ArrayList<OutputDataObjectType>(); applicationOutputs.add(output1); echoInterfaceId = airavataClient.registerApplicationInterface(new AuthzToken(""), gatewayId, RegisterSampleApplicationsUtils.createApplicationInterfaceDescription("Echo", "Echo application description", appModules, applicationInputs, applicationOutputs)); System.out.println("Echo Application Interface Id " + echoInterfaceId); } catch (TException e) { e.printStackTrace(); } } private void createEchoExperiment() throws TException { Project project = new Project(); project.setName("default-project"); project.setOwner(userId); String projectId = airavataClient.createProject(new AuthzToken(""), gatewayId, project); ExperimentModel experimentModel = new ExperimentModel(); experimentModel.setExperimentName("dummy-echo-experiment"); experimentModel.setProjectId(projectId); experimentModel.setUserName(userId); experimentModel.setGatewayId(gatewayId); experimentModel.setExecutionId(echoInterfaceId); UserConfigurationDataModel userConfigurationDataModel = new UserConfigurationDataModel(); ComputationalResourceSchedulingModel computationalResourceSchedulingModel = new ComputationalResourceSchedulingModel(); computationalResourceSchedulingModel.setNodeCount(1); computationalResourceSchedulingModel.setTotalCPUCount(1); computationalResourceSchedulingModel.setTotalPhysicalMemory(512); computationalResourceSchedulingModel.setResourceHostId(localhostId); userConfigurationDataModel.setComputationalResourceScheduling(computationalResourceSchedulingModel); experimentModel.setUserConfigurationData(userConfigurationDataModel); List<InputDataObjectType> experimentInputs = new ArrayList<>(); experimentInputs.add(RegisterSampleApplicationsUtils.createAppInput("Input_to_Echo", "Hello World", DataType.STRING, null, 1, true,true, false, "A test string to Echo", null)); experimentModel.setExperimentInputs(experimentInputs); experimentModel.setExperimentOutputs(airavataClient.getApplicationOutputs(new AuthzToken(""), echoInterfaceId)); echoExperimentId = airavataClient.createExperiment(new AuthzToken(""), gatewayId, experimentModel); } }
apache-2.0
BisnodeInformatics/gemini.blueprint
core/src/test/java/org/eclipse/gemini/blueprint/blueprint/config/ComponentHolder.java
1046
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc. * 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: * VMware Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.blueprint.config; /** * @author Costin Leau */ public class ComponentHolder { private Object property; public Object getProperty() { return property; } public void setProperty(Object property) { this.property = property; } }
apache-2.0
aircjm/JavaSE
day17/code/day17_Set_Son/src/cn/itcast_05/TreeSetDemo2.java
1014
package cn.itcast_05; import java.util.TreeSet; /* * TreeSet存储自定义对象并保证排序和唯一。 * * A:你没有告诉我们怎么排序 * 自然排序,按照年龄从小到大排序 * B:元素什么情况算唯一你也没告诉我 * 成员变量值都相同即为同一个元素 */ public class TreeSetDemo2 { public static void main(String[] args) { // 创建集合对象 TreeSet<Student> ts = new TreeSet<Student>(); // 创建元素 Student s1 = new Student("linqingxia", 27); Student s2 = new Student("zhangguorong", 29); Student s3 = new Student("wanglihong", 23); Student s4 = new Student("linqingxia", 27); Student s5 = new Student("liushishi", 22); Student s6 = new Student("wuqilong", 40); Student s7 = new Student("fengqingy", 22); // 添加元素 ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); ts.add(s7); // 遍历 for (Student s : ts) { System.out.println(s.getName() + "---" + s.getAge()); } } }
apache-2.0
akomakom/ehcache3
impl/src/test/java/org/ehcache/impl/serialization/GetFieldTest.java
4103
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.impl.serialization; import org.ehcache.spi.serialization.StatefulSerializer; import org.junit.Test; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.ByteBuffer; import static org.ehcache.impl.serialization.SerializerTestUtilities.createClassNameRewritingLoader; import static org.ehcache.impl.serialization.SerializerTestUtilities.newClassName; import static org.ehcache.impl.serialization.SerializerTestUtilities.popTccl; import static org.ehcache.impl.serialization.SerializerTestUtilities.pushTccl; /** * * @author cdennis */ public class GetFieldTest { @Test public void testGetField() throws Exception { @SuppressWarnings("unchecked") StatefulSerializer<Serializable> s = new CompactJavaSerializer(null); s.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(Foo_A.class); Serializable a = (Serializable) loaderA.loadClass(newClassName(Foo_A.class)).newInstance(); ByteBuffer encodedA = s.serialize(a); pushTccl(createClassNameRewritingLoader(Foo_B.class)); try { s.read(encodedA.duplicate()); } finally { popTccl(); } pushTccl(createClassNameRewritingLoader(Foo_C.class)); try { s.read(encodedA.duplicate()); } finally { popTccl(); } } public static class Foo_A implements Serializable { private static final long serialVersionUID = 0L; boolean z = true; byte b = 5; char c = '5'; short s = 5; int i = 5; long j = 5; float f = 5.0f; double d = 5.0; String str = "5"; } public static class Foo_B implements Serializable { private static final long serialVersionUID = 0L; int blargh; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); if (!fields.defaulted("blargh")) { throw new Error(); } try { fields.defaulted("nonexistant"); throw new Error(); } catch (IllegalArgumentException ex) { } if ((fields.get("z", false) != true) || (fields.get("b", (byte) 0) != 5) || (fields.get("c", '0') != '5') || (fields.get("s", (short) 0) != 5) || (fields.get("i", 0) != 5) || (fields.get("j", 0l) != 5) || (fields.get("f", 0.0f) != 5.0f) || (fields.get("d", 0.0) != 5.0) || (!fields.get("str", null).equals("5"))) { throw new Error(); } } } public static class Foo_C implements Serializable { private static final long serialVersionUID = 0L; boolean z; byte b; char c; short s; int i; long j; float f; double d; String str; Object extra; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); if ((fields.get("z", false) != true) || (fields.get("b", (byte) 0) != 5) || (fields.get("c", '0') != '5') || (fields.get("s", (short) 0) != 5) || (fields.get("i", 0) != 5) || (fields.get("j", 0l) != 5) || (fields.get("f", 0.0f) != 5.0f) || (fields.get("d", 0.0) != 5.0) || (!fields.get("str", null).equals("5"))) { throw new Error(); } } } }
apache-2.0
bocon13/buck
src/com/facebook/buck/android/UnzipAar.java
10395
/* * Copyright 2015-present Facebook, 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.facebook.buck.android; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.java.JarDirectoryStepHelper; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.rules.AbstractBuildRule; import com.facebook.buck.rules.AddToRuleKey; import com.facebook.buck.rules.BuildContext; import com.facebook.buck.rules.BuildOutputInitializer; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildTargetSourcePath; import com.facebook.buck.rules.BuildableContext; import com.facebook.buck.rules.InitializableFromDisk; import com.facebook.buck.rules.OnDiskBuildInfo; import com.facebook.buck.rules.RecordFileSha1Step; import com.facebook.buck.rules.Sha1HashCode; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.step.AbstractExecutionStep; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.fs.CopyStep; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.facebook.buck.step.fs.MkdirStep; import com.facebook.buck.step.fs.TouchStep; import com.facebook.buck.zip.UnzipStep; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import java.io.IOException; import java.nio.file.Path; import java.util.regex.Pattern; import javax.annotation.Nullable; public class UnzipAar extends AbstractBuildRule implements InitializableFromDisk<UnzipAar.BuildOutput> { private static final String METADATA_KEY_FOR_R_DOT_JAVA_PACKAGE = "R_DOT_JAVA_PACKAGE"; private static final String METADATA_KEY_FOR_R_DOT_TXT_SHA1 = "R_DOT_TXT_SHA1"; @AddToRuleKey private final SourcePath aarFile; private final Path unpackDirectory; private final Path uberClassesJar; private final Path pathToTextSymbolsDir; private final Path pathToTextSymbolsFile; private final Path pathToRDotJavaPackageFile; private final BuildOutputInitializer<BuildOutput> outputInitializer; UnzipAar( BuildRuleParams buildRuleParams, SourcePathResolver resolver, SourcePath aarFile) { super(buildRuleParams, resolver); this.aarFile = aarFile; BuildTarget buildTarget = buildRuleParams.getBuildTarget(); this.unpackDirectory = BuildTargets.getScratchPath(buildTarget, "__unpack_%s__"); this.uberClassesJar = BuildTargets.getScratchPath( buildTarget, "__uber_classes_%s__/classes.jar"); pathToTextSymbolsDir = BuildTargets.getGenPath(buildTarget, "__%s_text_symbols__"); pathToTextSymbolsFile = pathToTextSymbolsDir.resolve("R.txt"); pathToRDotJavaPackageFile = pathToTextSymbolsDir.resolve("RDotJavaPackage.txt"); this.outputInitializer = new BuildOutputInitializer<>(buildTarget, this); } @Override public ImmutableList<Step> getBuildSteps( BuildContext context, BuildableContext buildableContext) { ImmutableList.Builder<Step> steps = ImmutableList.builder(); steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), unpackDirectory)); steps.add( new UnzipStep( getProjectFilesystem(), getResolver().getAbsolutePath(aarFile), unpackDirectory)); steps.add(new TouchStep(getProjectFilesystem(), getProguardConfig())); steps.add( new MkdirStep( getProjectFilesystem(), getResolver().getAbsolutePath(getAssetsDirectory()))); steps.add(new MkdirStep(getProjectFilesystem(), getNativeLibsDirectory())); steps.add(new TouchStep(getProjectFilesystem(), getTextSymbolsFile())); // We take the classes.jar file that is required to exist in an .aar and merge it with any // .jar files under libs/ into an "uber" jar. We do this for simplicity because we do not know // how many entries there are in libs/ at graph enhancement time, but we need to make sure // that all of the .class files in the .aar get packaged. As it is implemented today, an // android_library that depends on an android_prebuilt_aar can compile against anything in the // .aar's classes.jar or libs/. steps.add(new MkdirStep(getProjectFilesystem(), uberClassesJar.getParent())); steps.add(new AbstractExecutionStep("create_uber_classes_jar") { @Override public int execute(ExecutionContext context) { Path libsDirectory = unpackDirectory.resolve("libs"); boolean dirDoesNotExistOrIsEmpty; if (!getProjectFilesystem().exists(libsDirectory)) { dirDoesNotExistOrIsEmpty = true; } else { try { dirDoesNotExistOrIsEmpty = getProjectFilesystem().getDirectoryContents(libsDirectory).isEmpty(); } catch (IOException e) { context.logError(e, "Failed to get directory contents of %s", libsDirectory); return 1; } } Path classesJar = unpackDirectory.resolve("classes.jar"); if (!getProjectFilesystem().exists(classesJar)) { try { JarDirectoryStepHelper.createEmptyJarFile(getProjectFilesystem(), classesJar, context); } catch (IOException e) { context.logError(e, "Failed to create empty jar %s", classesJar); return 1; } } if (dirDoesNotExistOrIsEmpty) { try { getProjectFilesystem().copy( classesJar, uberClassesJar, ProjectFilesystem.CopySourceMode.FILE); } catch (IOException e) { context.logError(e, "Failed to copy from %s to %s", classesJar, uberClassesJar); return 1; } } else { // Glob all of the contents from classes.jar and the entries in libs/ into a single JAR. ImmutableSortedSet.Builder<Path> entriesToJarBuilder = ImmutableSortedSet.naturalOrder(); entriesToJarBuilder.add(classesJar); try { entriesToJarBuilder.addAll( getProjectFilesystem().getDirectoryContents(libsDirectory)); } catch (IOException e) { context.logError(e, "Failed to get directory contents of %s", libsDirectory); return 1; } ImmutableSortedSet<Path> entriesToJar = entriesToJarBuilder.build(); try { JarDirectoryStepHelper.createJarFile( getProjectFilesystem(), uberClassesJar, entriesToJar, /* mainClass */ Optional.<String>absent(), /* manifestFile */ Optional.<Path>absent(), /* mergeManifests */ true, /* blacklist */ ImmutableList.<Pattern>of(), context); } catch (IOException e) { context.logError(e, "Failed to jar %s into %s", entriesToJar, uberClassesJar); return 1; } } return 0; } }); steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), pathToTextSymbolsDir)); steps.add( new ExtractFromAndroidManifestStep( getAndroidManifest(), getProjectFilesystem(), buildableContext, METADATA_KEY_FOR_R_DOT_JAVA_PACKAGE, pathToRDotJavaPackageFile)); steps.add( new RecordFileSha1Step( getProjectFilesystem(), getTextSymbolsFile(), METADATA_KEY_FOR_R_DOT_TXT_SHA1, buildableContext)); steps.add( CopyStep.forFile(getProjectFilesystem(), getTextSymbolsFile(), pathToTextSymbolsFile)); buildableContext.recordArtifact(unpackDirectory); buildableContext.recordArtifact(uberClassesJar); buildableContext.recordArtifact(pathToTextSymbolsFile); buildableContext.recordArtifact(pathToRDotJavaPackageFile); return steps.build(); } @Override public BuildOutput initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) throws IOException { Optional<String> rDotPackage = onDiskBuildInfo.getValue(METADATA_KEY_FOR_R_DOT_JAVA_PACKAGE); Optional<Sha1HashCode> sha1 = onDiskBuildInfo.getHash(METADATA_KEY_FOR_R_DOT_TXT_SHA1); Preconditions.checkState(rDotPackage.isPresent()); Preconditions.checkState(sha1.isPresent()); return new BuildOutput(rDotPackage.get(), sha1.get()); } @Override public BuildOutputInitializer<BuildOutput> getBuildOutputInitializer() { return outputInitializer; } static class BuildOutput { private final String rDotJavaPackage; private final Sha1HashCode rDotTxtHash; BuildOutput(String rDotJavaPackage, Sha1HashCode rDotTxtHash) { this.rDotJavaPackage = rDotJavaPackage; this.rDotTxtHash = rDotTxtHash; } } @Override @Nullable public Path getPathToOutput() { return pathToTextSymbolsDir; } Path getPathToClassesJar() { return uberClassesJar; } SourcePath getResDirectory() { return new BuildTargetSourcePath(getBuildTarget(), unpackDirectory.resolve("res")); } String getRDotJavaPackage() { return outputInitializer.getBuildOutput().rDotJavaPackage; } Path getTextSymbolsFile() { return unpackDirectory.resolve("R.txt"); } Sha1HashCode getTextSymbolsHash() { return outputInitializer.getBuildOutput().rDotTxtHash; } SourcePath getAssetsDirectory() { return new BuildTargetSourcePath(getBuildTarget(), unpackDirectory.resolve("assets")); } Path getAndroidManifest() { return unpackDirectory.resolve("AndroidManifest.xml"); } Path getProguardConfig() { return unpackDirectory.resolve("proguard.txt"); } Path getNativeLibsDirectory() { return unpackDirectory.resolve("jni"); } }
apache-2.0
davidvgalbraith/elasticsearch
core/src/main/java/org/elasticsearch/index/mapper/geo/BaseGeoPointFieldMapper.java
23649
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index.mapper.geo; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.util.GeoHashUtils; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.Version; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Iterators; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.core.DoubleFieldMapper; import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.mapper.core.StringFieldMapper; import org.elasticsearch.index.mapper.object.ArrayValueMapperParser; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.index.mapper.MapperBuilders.doubleField; import static org.elasticsearch.index.mapper.MapperBuilders.stringField; import static org.elasticsearch.index.mapper.core.TypeParsers.parseField; import static org.elasticsearch.index.mapper.core.TypeParsers.parseMultiField; /** * GeoPointFieldMapper base class to maintain backward compatibility */ public abstract class BaseGeoPointFieldMapper extends FieldMapper implements ArrayValueMapperParser { public static final String CONTENT_TYPE = "geo_point"; public static class Names { public static final String LAT = "lat"; public static final String LAT_SUFFIX = "." + LAT; public static final String LON = "lon"; public static final String LON_SUFFIX = "." + LON; public static final String GEOHASH = "geohash"; public static final String GEOHASH_SUFFIX = "." + GEOHASH; public static final String IGNORE_MALFORMED = "ignore_malformed"; } public static class Defaults { public static final boolean ENABLE_LATLON = false; public static final boolean ENABLE_GEOHASH = false; public static final boolean ENABLE_GEOHASH_PREFIX = false; public static final int GEO_HASH_PRECISION = GeoHashUtils.PRECISION; public static final Explicit<Boolean> IGNORE_MALFORMED = new Explicit(false, false); } public abstract static class Builder<T extends Builder, Y extends BaseGeoPointFieldMapper> extends FieldMapper.Builder<T, Y> { protected boolean enableLatLon = Defaults.ENABLE_LATLON; protected Integer precisionStep; protected boolean enableGeoHash = Defaults.ENABLE_GEOHASH; protected boolean enableGeoHashPrefix = Defaults.ENABLE_GEOHASH_PREFIX; protected int geoHashPrecision = Defaults.GEO_HASH_PRECISION; protected Boolean ignoreMalformed; public Builder(String name, GeoPointFieldType fieldType) { super(name, fieldType, fieldType); } @Override public GeoPointFieldType fieldType() { return (GeoPointFieldType)fieldType; } @Override public T fieldDataSettings(Settings settings) { this.fieldDataSettings = settings; return builder; } public T enableLatLon(boolean enableLatLon) { this.enableLatLon = enableLatLon; return builder; } public T precisionStep(int precisionStep) { this.precisionStep = precisionStep; return builder; } public T enableGeoHash(boolean enableGeoHash) { this.enableGeoHash = enableGeoHash; return builder; } public T geoHashPrefix(boolean enableGeoHashPrefix) { this.enableGeoHashPrefix = enableGeoHashPrefix; return builder; } public T geoHashPrecision(int precision) { this.geoHashPrecision = precision; return builder; } public T ignoreMalformed(boolean ignoreMalformed) { this.ignoreMalformed = ignoreMalformed; return builder; } protected Explicit<Boolean> ignoreMalformed(BuilderContext context) { if (ignoreMalformed != null) { return new Explicit<>(ignoreMalformed, true); } if (context.indexSettings() != null) { return new Explicit<>(IGNORE_MALFORMED_SETTING.get(context.indexSettings()), false); } return Defaults.IGNORE_MALFORMED; } public abstract Y build(BuilderContext context, String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings, DoubleFieldMapper latMapper, DoubleFieldMapper lonMapper, StringFieldMapper geoHashMapper, MultiFields multiFields, Explicit<Boolean> ignoreMalformed, CopyTo copyTo); public Y build(Mapper.BuilderContext context) { GeoPointFieldType geoPointFieldType = (GeoPointFieldType)fieldType; DoubleFieldMapper latMapper = null; DoubleFieldMapper lonMapper = null; context.path().add(name); if (enableLatLon) { NumberFieldMapper.Builder<?, ?> latMapperBuilder = doubleField(Names.LAT).includeInAll(false); NumberFieldMapper.Builder<?, ?> lonMapperBuilder = doubleField(Names.LON).includeInAll(false); if (precisionStep != null) { latMapperBuilder.precisionStep(precisionStep); lonMapperBuilder.precisionStep(precisionStep); } latMapper = (DoubleFieldMapper) latMapperBuilder.includeInAll(false).store(fieldType.stored()).docValues(false).build(context); lonMapper = (DoubleFieldMapper) lonMapperBuilder.includeInAll(false).store(fieldType.stored()).docValues(false).build(context); geoPointFieldType.setLatLonEnabled(latMapper.fieldType(), lonMapper.fieldType()); } StringFieldMapper geoHashMapper = null; if (enableGeoHash || enableGeoHashPrefix) { // TODO: possible also implicitly enable geohash if geohash precision is set geoHashMapper = stringField(Names.GEOHASH).index(true).tokenized(false).includeInAll(false).store(fieldType.stored()) .omitNorms(true).indexOptions(IndexOptions.DOCS).build(context); geoPointFieldType.setGeoHashEnabled(geoHashMapper.fieldType(), geoHashPrecision, enableGeoHashPrefix); } context.path().remove(); return build(context, name, fieldType, defaultFieldType, context.indexSettings(), latMapper, lonMapper, geoHashMapper, multiFieldsBuilder.build(this, context), ignoreMalformed(context), copyTo); } } public abstract static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder; if (parserContext.indexVersionCreated().before(Version.V_2_2_0)) { builder = new GeoPointFieldMapperLegacy.Builder(name); } else { builder = new GeoPointFieldMapper.Builder(name); } parseField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("lat_lon")) { builder.enableLatLon(XContentMapValues.nodeBooleanValue(propNode)); iterator.remove(); } else if (propName.equals("precision_step")) { builder.precisionStep(XContentMapValues.nodeIntegerValue(propNode)); iterator.remove(); } else if (propName.equals("geohash")) { builder.enableGeoHash(XContentMapValues.nodeBooleanValue(propNode)); iterator.remove(); } else if (propName.equals("geohash_prefix")) { builder.geoHashPrefix(XContentMapValues.nodeBooleanValue(propNode)); if (XContentMapValues.nodeBooleanValue(propNode)) { builder.enableGeoHash(true); } iterator.remove(); } else if (propName.equals("geohash_precision")) { if (propNode instanceof Integer) { builder.geoHashPrecision(XContentMapValues.nodeIntegerValue(propNode)); } else { builder.geoHashPrecision(GeoUtils.geoHashLevelsForPrecision(propNode.toString())); } iterator.remove(); } else if (propName.equals(Names.IGNORE_MALFORMED)) { builder.ignoreMalformed(XContentMapValues.nodeBooleanValue(propNode)); iterator.remove(); } else if (parseMultiField(builder, name, parserContext, propName, propNode)) { iterator.remove(); } } if (builder instanceof GeoPointFieldMapperLegacy.Builder) { return GeoPointFieldMapperLegacy.parse((GeoPointFieldMapperLegacy.Builder) builder, node, parserContext); } return (GeoPointFieldMapper.Builder) builder; } } public static class GeoPointFieldType extends MappedFieldType { protected MappedFieldType geoHashFieldType; protected int geoHashPrecision; protected boolean geoHashPrefixEnabled; protected MappedFieldType latFieldType; protected MappedFieldType lonFieldType; GeoPointFieldType() {} GeoPointFieldType(GeoPointFieldType ref) { super(ref); this.geoHashFieldType = ref.geoHashFieldType; // copying ref is ok, this can never be modified this.geoHashPrecision = ref.geoHashPrecision; this.geoHashPrefixEnabled = ref.geoHashPrefixEnabled; this.latFieldType = ref.latFieldType; // copying ref is ok, this can never be modified this.lonFieldType = ref.lonFieldType; // copying ref is ok, this can never be modified } @Override public MappedFieldType clone() { return new GeoPointFieldType(this); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; GeoPointFieldType that = (GeoPointFieldType) o; return geoHashPrecision == that.geoHashPrecision && geoHashPrefixEnabled == that.geoHashPrefixEnabled && java.util.Objects.equals(geoHashFieldType, that.geoHashFieldType) && java.util.Objects.equals(latFieldType, that.latFieldType) && java.util.Objects.equals(lonFieldType, that.lonFieldType); } @Override public int hashCode() { return java.util.Objects.hash(super.hashCode(), geoHashFieldType, geoHashPrecision, geoHashPrefixEnabled, latFieldType, lonFieldType); } @Override public String typeName() { return CONTENT_TYPE; } @Override public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) { super.checkCompatibility(fieldType, conflicts, strict); GeoPointFieldType other = (GeoPointFieldType)fieldType; if (isLatLonEnabled() != other.isLatLonEnabled()) { conflicts.add("mapper [" + name() + "] has different [lat_lon]"); } if (isLatLonEnabled() && other.isLatLonEnabled() && latFieldType().numericPrecisionStep() != other.latFieldType().numericPrecisionStep()) { conflicts.add("mapper [" + name() + "] has different [precision_step]"); } if (isGeoHashEnabled() != other.isGeoHashEnabled()) { conflicts.add("mapper [" + name() + "] has different [geohash]"); } if (geoHashPrecision() != other.geoHashPrecision()) { conflicts.add("mapper [" + name() + "] has different [geohash_precision]"); } if (isGeoHashPrefixEnabled() != other.isGeoHashPrefixEnabled()) { conflicts.add("mapper [" + name() + "] has different [geohash_prefix]"); } } public boolean isGeoHashEnabled() { return geoHashFieldType != null; } public MappedFieldType geoHashFieldType() { return geoHashFieldType; } public int geoHashPrecision() { return geoHashPrecision; } public boolean isGeoHashPrefixEnabled() { return geoHashPrefixEnabled; } public void setGeoHashEnabled(MappedFieldType geoHashFieldType, int geoHashPrecision, boolean geoHashPrefixEnabled) { checkIfFrozen(); this.geoHashFieldType = geoHashFieldType; this.geoHashPrecision = geoHashPrecision; this.geoHashPrefixEnabled = geoHashPrefixEnabled; } public boolean isLatLonEnabled() { return latFieldType != null; } public MappedFieldType latFieldType() { return latFieldType; } public MappedFieldType lonFieldType() { return lonFieldType; } public void setLatLonEnabled(MappedFieldType latFieldType, MappedFieldType lonFieldType) { checkIfFrozen(); this.latFieldType = latFieldType; this.lonFieldType = lonFieldType; } } protected DoubleFieldMapper latMapper; protected DoubleFieldMapper lonMapper; protected StringFieldMapper geoHashMapper; protected Explicit<Boolean> ignoreMalformed; protected BaseGeoPointFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings, DoubleFieldMapper latMapper, DoubleFieldMapper lonMapper, StringFieldMapper geoHashMapper, MultiFields multiFields, Explicit<Boolean> ignoreMalformed, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo); this.latMapper = latMapper; this.lonMapper = lonMapper; this.geoHashMapper = geoHashMapper; this.ignoreMalformed = ignoreMalformed; } @Override public GeoPointFieldType fieldType() { return (GeoPointFieldType) super.fieldType(); } @Override protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); BaseGeoPointFieldMapper gpfmMergeWith = (BaseGeoPointFieldMapper) mergeWith; if (gpfmMergeWith.ignoreMalformed.explicit()) { this.ignoreMalformed = gpfmMergeWith.ignoreMalformed; } } @Override public Iterator<Mapper> iterator() { List<Mapper> extras = new ArrayList<>(); if (fieldType().isGeoHashEnabled()) { extras.add(geoHashMapper); } if (fieldType().isLatLonEnabled()) { extras.add(latMapper); extras.add(lonMapper); } return Iterators.concat(super.iterator(), extras.iterator()); } @Override protected String contentType() { return CONTENT_TYPE; } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { throw new UnsupportedOperationException("Parsing is implemented in parse(), this method should NEVER be called"); } protected void parse(ParseContext context, GeoPoint point, String geoHash) throws IOException { if (fieldType().isGeoHashEnabled()) { if (geoHash == null) { geoHash = GeoHashUtils.stringEncode(point.lon(), point.lat()); } addGeoHashField(context, geoHash); } if (fieldType().isLatLonEnabled()) { latMapper.parse(context.createExternalValueContext(point.lat())); lonMapper.parse(context.createExternalValueContext(point.lon())); } multiFields.parse(this, context.createExternalValueContext(point)); } @Override public Mapper parse(ParseContext context) throws IOException { context.path().add(simpleName()); GeoPoint sparse = context.parseExternalValue(GeoPoint.class); if (sparse != null) { parse(context, sparse, null); } else { sparse = new GeoPoint(); XContentParser.Token token = context.parser().currentToken(); if (token == XContentParser.Token.START_ARRAY) { token = context.parser().nextToken(); if (token == XContentParser.Token.START_ARRAY) { // its an array of array of lon/lat [ [1.2, 1.3], [1.4, 1.5] ] while (token != XContentParser.Token.END_ARRAY) { parse(context, GeoUtils.parseGeoPoint(context.parser(), sparse), null); token = context.parser().nextToken(); } } else { // its an array of other possible values if (token == XContentParser.Token.VALUE_NUMBER) { double lon = context.parser().doubleValue(); token = context.parser().nextToken(); double lat = context.parser().doubleValue(); while ((token = context.parser().nextToken()) != XContentParser.Token.END_ARRAY); parse(context, sparse.reset(lat, lon), null); } else { while (token != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.VALUE_STRING) { parsePointFromString(context, sparse, context.parser().text()); } else { parse(context, GeoUtils.parseGeoPoint(context.parser(), sparse), null); } token = context.parser().nextToken(); } } } } else if (token == XContentParser.Token.VALUE_STRING) { parsePointFromString(context, sparse, context.parser().text()); } else if (token != XContentParser.Token.VALUE_NULL) { parse(context, GeoUtils.parseGeoPoint(context.parser(), sparse), null); } } context.path().remove(); return null; } private void addGeoHashField(ParseContext context, String geoHash) throws IOException { int len = Math.min(fieldType().geoHashPrecision(), geoHash.length()); int min = fieldType().isGeoHashPrefixEnabled() ? 1 : len; for (int i = len; i >= min; i--) { // side effect of this call is adding the field geoHashMapper.parse(context.createExternalValueContext(geoHash.substring(0, i))); } } private void parsePointFromString(ParseContext context, GeoPoint sparse, String point) throws IOException { if (point.indexOf(',') < 0) { parse(context, sparse.resetFromGeoHash(point), point); } else { parse(context, sparse.resetFromString(point), null); } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || fieldType().isLatLonEnabled() != GeoPointFieldMapper.Defaults.ENABLE_LATLON) { builder.field("lat_lon", fieldType().isLatLonEnabled()); } if (fieldType().isLatLonEnabled() && (includeDefaults || fieldType().latFieldType().numericPrecisionStep() != NumericUtils.PRECISION_STEP_DEFAULT)) { builder.field("precision_step", fieldType().latFieldType().numericPrecisionStep()); } if (includeDefaults || fieldType().isGeoHashEnabled() != Defaults.ENABLE_GEOHASH) { builder.field("geohash", fieldType().isGeoHashEnabled()); } if (includeDefaults || fieldType().isGeoHashPrefixEnabled() != Defaults.ENABLE_GEOHASH_PREFIX) { builder.field("geohash_prefix", fieldType().isGeoHashPrefixEnabled()); } if (fieldType().isGeoHashEnabled() && (includeDefaults || fieldType().geoHashPrecision() != Defaults.GEO_HASH_PRECISION)) { builder.field("geohash_precision", fieldType().geoHashPrecision()); } if (includeDefaults || ignoreMalformed.explicit()) { builder.field(Names.IGNORE_MALFORMED, ignoreMalformed.value()); } } @Override public FieldMapper updateFieldType(Map<String, MappedFieldType> fullNameToFieldType) { BaseGeoPointFieldMapper updated = (BaseGeoPointFieldMapper) super.updateFieldType(fullNameToFieldType); StringFieldMapper geoUpdated = geoHashMapper == null ? null : (StringFieldMapper) geoHashMapper.updateFieldType(fullNameToFieldType); DoubleFieldMapper latUpdated = latMapper == null ? null : (DoubleFieldMapper) latMapper.updateFieldType(fullNameToFieldType); DoubleFieldMapper lonUpdated = lonMapper == null ? null : (DoubleFieldMapper) lonMapper.updateFieldType(fullNameToFieldType); if (updated == this && geoUpdated == geoHashMapper && latUpdated == latMapper && lonUpdated == lonMapper) { return this; } if (updated == this) { updated = (BaseGeoPointFieldMapper) updated.clone(); } updated.geoHashMapper = geoUpdated; updated.latMapper = latUpdated; updated.lonMapper = lonUpdated; return updated; } }
apache-2.0
markharwood/elasticsearch
core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java
49671
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.cluster.routing.allocation.allocator; import com.carrotsearch.hppc.cursors.ObjectCursor; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.IntroSorter; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.StartedRerouteAllocation; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders; import org.elasticsearch.cluster.routing.allocation.decider.Decision; import org.elasticsearch.cluster.routing.allocation.decider.Decision.Type; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.gateway.PriorityComparator; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING; /** * The {@link BalancedShardsAllocator} re-balances the nodes allocations * within an cluster based on a {@link WeightFunction}. The clusters balance is defined by four parameters which can be set * in the cluster update API that allows changes in real-time: * <ul><li><code>cluster.routing.allocation.balance.shard</code> - The <b>shard balance</b> defines the weight factor * for shards allocated on a {@link RoutingNode}</li> * <li><code>cluster.routing.allocation.balance.index</code> - The <b>index balance</b> defines a factor to the number * of {@link org.elasticsearch.cluster.routing.ShardRouting}s per index allocated on a specific node</li> * <li><code>cluster.routing.allocation.balance.threshold</code> - A <b>threshold</b> to set the minimal optimization * value of operations that should be performed</li> * </ul> * <p> * These parameters are combined in a {@link WeightFunction} that allows calculation of node weights which * are used to re-balance shards based on global as well as per-index factors. */ public class BalancedShardsAllocator extends AbstractComponent implements ShardsAllocator { public static final Setting<Float> INDEX_BALANCE_FACTOR_SETTING = Setting.floatSetting("cluster.routing.allocation.balance.index", 0.55f, true, Setting.Scope.CLUSTER); public static final Setting<Float> SHARD_BALANCE_FACTOR_SETTING = Setting.floatSetting("cluster.routing.allocation.balance.shard", 0.45f, true, Setting.Scope.CLUSTER); public static final Setting<Float> THRESHOLD_SETTING = Setting.floatSetting("cluster.routing.allocation.balance.threshold", 1.0f, 0.0f, true, Setting.Scope.CLUSTER); private volatile WeightFunction weightFunction; private volatile float threshold; public BalancedShardsAllocator(Settings settings) { this(settings, new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)); } @Inject public BalancedShardsAllocator(Settings settings, ClusterSettings clusterSettings) { super(settings); setWeightFunction(INDEX_BALANCE_FACTOR_SETTING.get(settings), SHARD_BALANCE_FACTOR_SETTING.get(settings)); setThreshold(THRESHOLD_SETTING.get(settings)); clusterSettings.addSettingsUpdateConsumer(INDEX_BALANCE_FACTOR_SETTING, SHARD_BALANCE_FACTOR_SETTING, this::setWeightFunction); clusterSettings.addSettingsUpdateConsumer(THRESHOLD_SETTING, this::setThreshold); } private void setWeightFunction(float indexBalance, float shardBalanceFactor) { weightFunction = new WeightFunction(indexBalance, shardBalanceFactor); } private void setThreshold(float threshold) { this.threshold = threshold; } @Override public void applyStartedShards(StartedRerouteAllocation allocation) { /* ONLY FOR GATEWAYS */ } @Override public void applyFailedShards(FailedRerouteAllocation allocation) { /* ONLY FOR GATEWAYS */ } @Override public boolean allocateUnassigned(RoutingAllocation allocation) { final Balancer balancer = new Balancer(logger, allocation, weightFunction, threshold); return balancer.allocateUnassigned(); } @Override public boolean rebalance(RoutingAllocation allocation) { final Balancer balancer = new Balancer(logger, allocation, weightFunction, threshold); return balancer.balance(); } @Override public boolean move(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { final Balancer balancer = new Balancer(logger, allocation, weightFunction, threshold); return balancer.move(shardRouting, node); } /** * Returns the currently configured delta threshold */ public float getThreshold() { return threshold; } /** * Returns the index related weight factor. */ public float getIndexBalance() { return weightFunction.indexBalance; } /** * Returns the shard related weight factor. */ public float getShardBalance() { return weightFunction.shardBalance; } /** * This class is the primary weight function used to create balanced over nodes and shards in the cluster. * Currently this function has 3 properties: * <ul> * <li><code>index balance</code> - balance property over shards per index</li> * <li><code>shard balance</code> - balance property over shards per cluster</li> * </ul> * <p> * Each of these properties are expressed as factor such that the properties factor defines the relative importance of the property for the * weight function. For example if the weight function should calculate the weights only based on a global (shard) balance the index balance * can be set to <tt>0.0</tt> and will in turn have no effect on the distribution. * </p> * The weight per index is calculated based on the following formula: * <ul> * <li> * <code>weight<sub>index</sub>(node, index) = indexBalance * (node.numShards(index) - avgShardsPerNode(index))</code> * </li> * <li> * <code>weight<sub>node</sub>(node, index) = shardBalance * (node.numShards() - avgShardsPerNode)</code> * </li> * </ul> * <code>weight(node, index) = weight<sub>index</sub>(node, index) + weight<sub>node</sub>(node, index)</code> */ public static class WeightFunction { private final float indexBalance; private final float shardBalance; private final float theta0; private final float theta1; public WeightFunction(float indexBalance, float shardBalance) { float sum = indexBalance + shardBalance; if (sum <= 0.0f) { throw new IllegalArgumentException("Balance factors must sum to a value > 0 but was: " + sum); } theta0 = shardBalance / sum; theta1 = indexBalance / sum; this.indexBalance = indexBalance; this.shardBalance = shardBalance; } public float weight(Balancer balancer, ModelNode node, String index) { return weight(balancer, node, index, 0); } public float weightShardAdded(Balancer balancer, ModelNode node, String index) { return weight(balancer, node, index, 1); } public float weightShardRemoved(Balancer balancer, ModelNode node, String index) { return weight(balancer, node, index, -1); } private float weight(Balancer balancer, ModelNode node, String index, int numAdditionalShards) { final float weightShard = (node.numShards() + numAdditionalShards - balancer.avgShardsPerNode()); final float weightIndex = (node.numShards(index) + numAdditionalShards - balancer.avgShardsPerNode(index)); return theta0 * weightShard + theta1 * weightIndex; } } /** * A {@link Balancer} */ public static class Balancer { private final ESLogger logger; private final Map<String, ModelNode> nodes = new HashMap<>(); private final HashSet<String> indices = new HashSet<>(); private final RoutingAllocation allocation; private final RoutingNodes routingNodes; private final WeightFunction weight; private final float threshold; private final MetaData metaData; private final float avgShardsPerNode; private final Predicate<ShardRouting> assignedFilter = shard -> shard.assignedToNode(); public Balancer(ESLogger logger, RoutingAllocation allocation, WeightFunction weight, float threshold) { this.logger = logger; this.allocation = allocation; this.weight = weight; this.threshold = threshold; this.routingNodes = allocation.routingNodes(); for (RoutingNode node : routingNodes) { nodes.put(node.nodeId(), new ModelNode(node.nodeId())); } metaData = routingNodes.metaData(); avgShardsPerNode = ((float) metaData.totalNumberOfShards()) / nodes.size(); } /** * Returns an array view on the nodes in the balancer. Nodes should not be removed from this list. */ private ModelNode[] nodesArray() { return nodes.values().toArray(new ModelNode[nodes.size()]); } /** * Returns the average of shards per node for the given index */ public float avgShardsPerNode(String index) { return ((float) metaData.index(index).getTotalNumberOfShards()) / nodes.size(); } /** * Returns the global average of shards per node */ public float avgShardsPerNode() { return avgShardsPerNode; } /** * Returns a new {@link NodeSorter} that sorts the nodes based on their * current weight with respect to the index passed to the sorter. The * returned sorter is not sorted. Use {@link NodeSorter#reset(String)} * to sort based on an index. */ private NodeSorter newNodeSorter() { return new NodeSorter(nodesArray(), weight, this); } private boolean initialize(RoutingNodes routing, RoutingNodes.UnassignedShards unassigned) { if (logger.isTraceEnabled()) { logger.trace("Start distributing Shards"); } for (ObjectCursor<String> index : allocation.routingTable().indicesRouting().keys()) { indices.add(index.value); } buildModelFromAssigned(routing.shards(assignedFilter)); return allocateUnassigned(unassigned); } private static float absDelta(float lower, float higher) { assert higher >= lower : higher + " lt " + lower +" but was expected to be gte"; return Math.abs(higher - lower); } private static boolean lessThan(float delta, float threshold) { /* deltas close to the threshold are "rounded" to the threshold manually to prevent floating point problems if the delta is very close to the threshold ie. 1.000000002 which can trigger unnecessary balance actions*/ return delta <= (threshold + 0.001f); } /** * Allocates all possible unassigned shards * @return <code>true</code> if the current configuration has been * changed, otherwise <code>false</code> */ final boolean allocateUnassigned() { return balance(true); } /** * Balances the nodes on the cluster model according to the weight * function. The configured threshold is the minimum delta between the * weight of the maximum node and the minimum node according to the * {@link WeightFunction}. This weight is calculated per index to * distribute shards evenly per index. The balancer tries to relocate * shards only if the delta exceeds the threshold. If the default case * the threshold is set to <tt>1.0</tt> to enforce gaining relocation * only, or in other words relocations that move the weight delta closer * to <tt>0.0</tt> * * @return <code>true</code> if the current configuration has been * changed, otherwise <code>false</code> */ public boolean balance() { return balance(false); } private boolean balance(boolean onlyAssign) { if (this.nodes.isEmpty()) { /* with no nodes this is pointless */ return false; } if (logger.isTraceEnabled()) { if (onlyAssign) { logger.trace("Start balancing cluster"); } else { logger.trace("Start assigning unassigned shards"); } } final RoutingNodes.UnassignedShards unassigned = routingNodes.unassigned(); boolean changed = initialize(routingNodes, unassigned); if (onlyAssign == false && changed == false && allocation.deciders().canRebalance(allocation).type() == Type.YES) { NodeSorter sorter = newNodeSorter(); if (nodes.size() > 1) { /* skip if we only have one node */ AllocationDeciders deciders = allocation.deciders(); final ModelNode[] modelNodes = sorter.modelNodes; final float[] weights = sorter.weights; for (String index : buildWeightOrderedIndices(sorter)) { IndexMetaData indexMetaData = metaData.index(index); // find nodes that have a shard of this index or where shards of this index are allowed to stay // move these nodes to the front of modelNodes so that we can only balance based on these nodes int relevantNodes = 0; for (int i = 0; i < modelNodes.length; i++) { ModelNode modelNode = modelNodes[i]; if (modelNode.getIndex(index) != null || deciders.canAllocate(indexMetaData, modelNode.getRoutingNode(routingNodes), allocation).type() != Type.NO) { // swap nodes at position i and relevantNodes modelNodes[i] = modelNodes[relevantNodes]; modelNodes[relevantNodes] = modelNode; relevantNodes++; } } if (relevantNodes < 2) { continue; } sorter.reset(index, 0, relevantNodes); int lowIdx = 0; int highIdx = relevantNodes - 1; while (true) { final ModelNode minNode = modelNodes[lowIdx]; final ModelNode maxNode = modelNodes[highIdx]; advance_range: if (maxNode.numShards(index) > 0) { final float delta = absDelta(weights[lowIdx], weights[highIdx]); if (lessThan(delta, threshold)) { if (lowIdx > 0 && highIdx-1 > 0 // is there a chance for a higher delta? && (absDelta(weights[0], weights[highIdx-1]) > threshold) // check if we need to break at all ) { /* This is a special case if allocations from the "heaviest" to the "lighter" nodes is not possible * due to some allocation decider restrictions like zone awareness. if one zone has for instance * less nodes than another zone. so one zone is horribly overloaded from a balanced perspective but we * can't move to the "lighter" shards since otherwise the zone would go over capacity. * * This break jumps straight to the condition below were we start moving from the high index towards * the low index to shrink the window we are considering for balance from the other direction. * (check shrinking the window from MAX to MIN) * See #3580 */ break advance_range; } if (logger.isTraceEnabled()) { logger.trace("Stop balancing index [{}] min_node [{}] weight: [{}] max_node [{}] weight: [{}] delta: [{}]", index, maxNode.getNodeId(), weights[highIdx], minNode.getNodeId(), weights[lowIdx], delta); } break; } if (logger.isTraceEnabled()) { logger.trace("Balancing from node [{}] weight: [{}] to node [{}] weight: [{}] delta: [{}]", maxNode.getNodeId(), weights[highIdx], minNode.getNodeId(), weights[lowIdx], delta); } /* pass the delta to the replication function to prevent relocations that only swap the weights of the two nodes. * a relocation must bring us closer to the balance if we only achieve the same delta the relocation is useless */ if (tryRelocateShard(minNode, maxNode, index, delta)) { /* * TODO we could be a bit smarter here, we don't need to fully sort necessarily * we could just find the place to insert linearly but the win might be minor * compared to the added complexity */ weights[lowIdx] = sorter.weight(modelNodes[lowIdx]); weights[highIdx] = sorter.weight(modelNodes[highIdx]); sorter.sort(0, relevantNodes); lowIdx = 0; highIdx = relevantNodes - 1; changed = true; continue; } } if (lowIdx < highIdx - 1) { /* Shrinking the window from MIN to MAX * we can't move from any shard from the min node lets move on to the next node * and see if the threshold still holds. We either don't have any shard of this * index on this node of allocation deciders prevent any relocation.*/ lowIdx++; } else if (lowIdx > 0) { /* Shrinking the window from MAX to MIN * now we go max to min since obviously we can't move anything to the max node * lets pick the next highest */ lowIdx = 0; highIdx--; } else { /* we are done here, we either can't relocate anymore or we are balanced */ break; } } } } } return changed; } /** * This builds a initial index ordering where the indices are returned * in most unbalanced first. We need this in order to prevent over * allocations on added nodes from one index when the weight parameters * for global balance overrule the index balance at an intermediate * state. For example this can happen if we have 3 nodes and 3 indices * with 3 shards and 1 shard. At the first stage all three nodes hold * 2 shard for each index. now we add another node and the first index * is balanced moving 3 two of the nodes over to the new node since it * has no shards yet and global balance for the node is way below * average. To re-balance we need to move shards back eventually likely * to the nodes we relocated them from. */ private String[] buildWeightOrderedIndices(NodeSorter sorter) { final String[] indices = this.indices.toArray(new String[this.indices.size()]); final float[] deltas = new float[indices.length]; for (int i = 0; i < deltas.length; i++) { sorter.reset(indices[i]); deltas[i] = sorter.delta(); } new IntroSorter() { float pivotWeight; @Override protected void swap(int i, int j) { final String tmpIdx = indices[i]; indices[i] = indices[j]; indices[j] = tmpIdx; final float tmpDelta = deltas[i]; deltas[i] = deltas[j]; deltas[j] = tmpDelta; } @Override protected int compare(int i, int j) { return Float.compare(deltas[j], deltas[i]); } @Override protected void setPivot(int i) { pivotWeight = deltas[i]; } @Override protected int comparePivot(int j) { return Float.compare(deltas[j], pivotWeight); } }.sort(0, deltas.length); return indices; } /** * This function executes a move operation moving the given shard from * the given node to the minimal eligible node with respect to the * weight function. Iff the shard is moved the shard will be set to * {@link ShardRoutingState#RELOCATING} and a shadow instance of this * shard is created with an incremented version in the state * {@link ShardRoutingState#INITIALIZING}. * * @return <code>true</code> iff the shard has successfully been moved. */ public boolean move(ShardRouting shard, RoutingNode node ) { if (nodes.isEmpty() || !shard.started()) { /* with no nodes or a not started shard this is pointless */ return false; } if (logger.isTraceEnabled()) { logger.trace("Try moving shard [{}] from [{}]", shard, node); } final RoutingNodes.UnassignedShards unassigned = routingNodes.unassigned(); boolean changed = initialize(routingNodes, unassigned); if (!changed) { final ModelNode sourceNode = nodes.get(node.nodeId()); assert sourceNode != null; final NodeSorter sorter = newNodeSorter(); sorter.reset(shard.getIndexName()); final ModelNode[] nodes = sorter.modelNodes; assert sourceNode.containsShard(shard); /* * the sorter holds the minimum weight node first for the shards index. * We now walk through the nodes until we find a node to allocate the shard. * This is not guaranteed to be balanced after this operation we still try best effort to * allocate on the minimal eligible node. */ for (ModelNode currentNode : nodes) { if (currentNode.getNodeId().equals(node.nodeId())) { continue; } RoutingNode target = currentNode.getRoutingNode(routingNodes); Decision allocationDecision = allocation.deciders().canAllocate(shard, target, allocation); Decision rebalanceDecision = allocation.deciders().canRebalance(shard, allocation); Decision decision = new Decision.Multi().add(allocationDecision).add(rebalanceDecision); if (decision.type() == Type.YES) { // TODO maybe we can respect throttling here too? sourceNode.removeShard(shard); ShardRouting targetRelocatingShard = routingNodes.relocate(shard, target.nodeId(), allocation.clusterInfo().getShardSize(shard, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)); currentNode.addShard(targetRelocatingShard, decision); if (logger.isTraceEnabled()) { logger.trace("Moved shard [{}] to node [{}]", shard, currentNode.getNodeId()); } changed = true; break; } } } return changed; } /** * Builds the internal model from all shards in the given * {@link Iterable}. All shards in the {@link Iterable} must be assigned * to a node. This method will skip shards in the state * {@link ShardRoutingState#RELOCATING} since each relocating shard has * a shadow shard in the state {@link ShardRoutingState#INITIALIZING} * on the target node which we respect during the allocation / balancing * process. In short, this method recreates the status-quo in the cluster. */ private void buildModelFromAssigned(Iterable<ShardRouting> shards) { for (ShardRouting shard : shards) { assert shard.assignedToNode(); /* we skip relocating shards here since we expect an initializing shard with the same id coming in */ if (shard.state() == RELOCATING) { continue; } ModelNode node = nodes.get(shard.currentNodeId()); assert node != null; node.addShard(shard, Decision.single(Type.YES, "Already allocated on node", node.getNodeId())); if (logger.isTraceEnabled()) { logger.trace("Assigned shard [{}] to node [{}]", shard, node.getNodeId()); } } } /** * Allocates all given shards on the minimal eligable node for the shards index * with respect to the weight function. All given shards must be unassigned. */ private boolean allocateUnassigned(RoutingNodes.UnassignedShards unassigned) { assert !nodes.isEmpty(); if (logger.isTraceEnabled()) { logger.trace("Start allocating unassigned shards"); } if (unassigned.isEmpty()) { return false; } boolean changed = false; /* * TODO: We could be smarter here and group the shards by index and then * use the sorter to save some iterations. */ final AllocationDeciders deciders = allocation.deciders(); final PriorityComparator secondaryComparator = PriorityComparator.getAllocationComparator(allocation); final Comparator<ShardRouting> comparator = (o1, o2) -> { if (o1.primary() ^ o2.primary()) { return o1.primary() ? -1 : o2.primary() ? 1 : 0; } final int indexCmp; if ((indexCmp = o1.getIndexName().compareTo(o2.getIndexName())) == 0) { return o1.getId() - o2.getId(); } // this comparator is more expensive than all the others up there // that's why it's added last even though it could be easier to read // if we'd apply it earlier. this comparator will only differentiate across // indices all shards of the same index is treated equally. final int secondary = secondaryComparator.compare(o1, o2); return secondary == 0 ? indexCmp : secondary; }; /* * we use 2 arrays and move replicas to the second array once we allocated an identical * replica in the current iteration to make sure all indices get allocated in the same manner. * The arrays are sorted by primaries first and then by index and shard ID so a 2 indices with 2 replica and 1 shard would look like: * [(0,P,IDX1), (0,P,IDX2), (0,R,IDX1), (0,R,IDX1), (0,R,IDX2), (0,R,IDX2)] * if we allocate for instance (0, R, IDX1) we move the second replica to the secondary array and proceed with * the next replica. If we could not find a node to allocate (0,R,IDX1) we move all it's replicas to ingoreUnassigned. */ ShardRouting[] primary = unassigned.drain(); ShardRouting[] secondary = new ShardRouting[primary.length]; int secondaryLength = 0; int primaryLength = primary.length; ArrayUtil.timSort(primary, comparator); final Set<ModelNode> throttledNodes = Collections.newSetFromMap(new IdentityHashMap<ModelNode, Boolean>()); do { for (int i = 0; i < primaryLength; i++) { ShardRouting shard = primary[i]; if (!shard.primary()) { boolean drop = deciders.canAllocate(shard, allocation).type() == Type.NO; if (drop) { unassigned.ignoreShard(shard); while(i < primaryLength-1 && comparator.compare(primary[i], primary[i+1]) == 0) { unassigned.ignoreShard(primary[++i]); } continue; } else { while(i < primaryLength-1 && comparator.compare(primary[i], primary[i+1]) == 0) { secondary[secondaryLength++] = primary[++i]; } } } assert !shard.assignedToNode() : shard; /* find an node with minimal weight we can allocate on*/ float minWeight = Float.POSITIVE_INFINITY; ModelNode minNode = null; Decision decision = null; if (throttledNodes.size() < nodes.size()) { /* Don't iterate over an identity hashset here the * iteration order is different for each run and makes testing hard */ for (ModelNode node : nodes.values()) { if (throttledNodes.contains(node)) { continue; } if (!node.containsShard(shard)) { // simulate weight if we would add shard to node float currentWeight = weight.weightShardAdded(this, node, shard.getIndexName()); /* * Unless the operation is not providing any gains we * don't check deciders */ if (currentWeight <= minWeight) { Decision currentDecision = deciders.canAllocate(shard, node.getRoutingNode(routingNodes), allocation); NOUPDATE: if (currentDecision.type() == Type.YES || currentDecision.type() == Type.THROTTLE) { if (currentWeight == minWeight) { /* we have an equal weight tie breaking: * 1. if one decision is YES prefer it * 2. prefer the node that holds the primary for this index with the next id in the ring ie. * for the 3 shards 2 replica case we try to build up: * 1 2 0 * 2 0 1 * 0 1 2 * such that if we need to tie-break we try to prefer the node holding a shard with the minimal id greater * than the id of the shard we need to assign. This works find when new indices are created since * primaries are added first and we only add one shard set a time in this algorithm. */ if (currentDecision.type() == decision.type()) { final int repId = shard.id(); final int nodeHigh = node.highestPrimary(shard.index().getName()); final int minNodeHigh = minNode.highestPrimary(shard.getIndexName()); if ((((nodeHigh > repId && minNodeHigh > repId) || (nodeHigh < repId && minNodeHigh < repId)) && (nodeHigh < minNodeHigh)) || (nodeHigh > minNodeHigh && nodeHigh > repId && minNodeHigh < repId)) { minNode = node; minWeight = currentWeight; decision = currentDecision; } else { break NOUPDATE; } } else if (currentDecision.type() != Type.YES) { break NOUPDATE; } } minNode = node; minWeight = currentWeight; decision = currentDecision; } } } } } assert decision != null && minNode != null || decision == null && minNode == null; if (minNode != null) { minNode.addShard(shard, decision); if (decision.type() == Type.YES) { if (logger.isTraceEnabled()) { logger.trace("Assigned shard [{}] to [{}]", shard, minNode.getNodeId()); } routingNodes.initialize(shard, minNode.getNodeId(), allocation.clusterInfo().getShardSize(shard, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)); changed = true; continue; // don't add to ignoreUnassigned } else { final RoutingNode node = minNode.getRoutingNode(routingNodes); if (deciders.canAllocate(node, allocation).type() != Type.YES) { if (logger.isTraceEnabled()) { logger.trace("Can not allocate on node [{}] remove from round decision [{}]", node, decision.type()); } throttledNodes.add(minNode); } } if (logger.isTraceEnabled()) { logger.trace("No eligable node found to assign shard [{}] decision [{}]", shard, decision.type()); } } else if (logger.isTraceEnabled()) { logger.trace("No Node found to assign shard [{}]", shard); } unassigned.ignoreShard(shard); if (!shard.primary()) { // we could not allocate it and we are a replica - check if we can ignore the other replicas while(secondaryLength > 0 && comparator.compare(shard, secondary[secondaryLength-1]) == 0) { unassigned.ignoreShard(secondary[--secondaryLength]); } } } primaryLength = secondaryLength; ShardRouting[] tmp = primary; primary = secondary; secondary = tmp; secondaryLength = 0; } while (primaryLength > 0); // clear everything we have either added it or moved to ingoreUnassigned return changed; } /** * Tries to find a relocation from the max node to the minimal node for an arbitrary shard of the given index on the * balance model. Iff this method returns a <code>true</code> the relocation has already been executed on the * simulation model as well as on the cluster. */ private boolean tryRelocateShard(ModelNode minNode, ModelNode maxNode, String idx, float minCost) { final ModelIndex index = maxNode.getIndex(idx); Decision decision = null; if (index != null) { if (logger.isTraceEnabled()) { logger.trace("Try relocating shard for index index [{}] from node [{}] to node [{}]", idx, maxNode.getNodeId(), minNode.getNodeId()); } ShardRouting candidate = null; final AllocationDeciders deciders = allocation.deciders(); for (ShardRouting shard : index.getAllShards()) { if (shard.started()) { // skip initializing, unassigned and relocating shards we can't relocate them anyway Decision allocationDecision = deciders.canAllocate(shard, minNode.getRoutingNode(routingNodes), allocation); Decision rebalanceDecision = deciders.canRebalance(shard, allocation); if (((allocationDecision.type() == Type.YES) || (allocationDecision.type() == Type.THROTTLE)) && ((rebalanceDecision.type() == Type.YES) || (rebalanceDecision.type() == Type.THROTTLE))) { if (maxNode.containsShard(shard)) { // simulate moving shard from maxNode to minNode final float delta = weight.weightShardAdded(this, minNode, idx) - weight.weightShardRemoved(this, maxNode, idx); if (delta < minCost || (candidate != null && delta == minCost && candidate.id() > shard.id())) { /* this last line is a tie-breaker to make the shard allocation alg deterministic * otherwise we rely on the iteration order of the index.getAllShards() which is a set.*/ minCost = delta; candidate = shard; decision = new Decision.Multi().add(allocationDecision).add(rebalanceDecision); } } } } } if (candidate != null) { /* allocate on the model even if not throttled */ maxNode.removeShard(candidate); minNode.addShard(candidate, decision); if (decision.type() == Type.YES) { /* only allocate on the cluster if we are not throttled */ if (logger.isTraceEnabled()) { logger.trace("Relocate shard [{}] from node [{}] to node [{}]", candidate, maxNode.getNodeId(), minNode.getNodeId()); } /* now allocate on the cluster - if we are started we need to relocate the shard */ if (candidate.started()) { routingNodes.relocate(candidate, minNode.getNodeId(), allocation.clusterInfo().getShardSize(candidate, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)); } else { routingNodes.initialize(candidate, minNode.getNodeId(), allocation.clusterInfo().getShardSize(candidate, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)); } return true; } } } if (logger.isTraceEnabled()) { logger.trace("Couldn't find shard to relocate from node [{}] to node [{}] allocation decision [{}]", maxNode.getNodeId(), minNode.getNodeId(), decision == null ? "NO" : decision.type().name()); } return false; } } static class ModelNode implements Iterable<ModelIndex> { private final String id; private final Map<String, ModelIndex> indices = new HashMap<>(); private int numShards = 0; // lazily calculated private RoutingNode routingNode; public ModelNode(String id) { this.id = id; } public ModelIndex getIndex(String indexId) { return indices.get(indexId); } public String getNodeId() { return id; } public RoutingNode getRoutingNode(RoutingNodes routingNodes) { if (routingNode == null) { routingNode = routingNodes.node(id); } return routingNode; } public int numShards() { return numShards; } public int numShards(String idx) { ModelIndex index = indices.get(idx); return index == null ? 0 : index.numShards(); } public int highestPrimary(String index) { ModelIndex idx = indices.get(index); if (idx != null) { return idx.highestPrimary(); } return -1; } public void addShard(ShardRouting shard, Decision decision) { ModelIndex index = indices.get(shard.getIndexName()); if (index == null) { index = new ModelIndex(shard.getIndexName()); indices.put(index.getIndexId(), index); } index.addShard(shard, decision); numShards++; } public Decision removeShard(ShardRouting shard) { ModelIndex index = indices.get(shard.getIndexName()); Decision removed = null; if (index != null) { removed = index.removeShard(shard); if (removed != null && index.numShards() == 0) { indices.remove(shard.getIndexName()); } } numShards--; return removed; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Node(").append(id).append(")"); return sb.toString(); } @Override public Iterator<ModelIndex> iterator() { return indices.values().iterator(); } public boolean containsShard(ShardRouting shard) { ModelIndex index = getIndex(shard.getIndexName()); return index == null ? false : index.containsShard(shard); } } static final class ModelIndex { private final String id; private final Map<ShardRouting, Decision> shards = new HashMap<>(); private int highestPrimary = -1; public ModelIndex(String id) { this.id = id; } public int highestPrimary() { if (highestPrimary == -1) { int maxId = -1; for (ShardRouting shard : shards.keySet()) { if (shard.primary()) { maxId = Math.max(maxId, shard.id()); } } return highestPrimary = maxId; } return highestPrimary; } public String getIndexId() { return id; } public int numShards() { return shards.size(); } public Collection<ShardRouting> getAllShards() { return shards.keySet(); } public Decision removeShard(ShardRouting shard) { highestPrimary = -1; return shards.remove(shard); } public void addShard(ShardRouting shard, Decision decision) { highestPrimary = -1; assert decision != null; assert !shards.containsKey(shard) : "Shard already allocated on current node: " + shards.get(shard) + " " + shard; shards.put(shard, decision); } public boolean containsShard(ShardRouting shard) { return shards.containsKey(shard); } } static final class NodeSorter extends IntroSorter { final ModelNode[] modelNodes; /* the nodes weights with respect to the current weight function / index */ final float[] weights; private final WeightFunction function; private String index; private final Balancer balancer; private float pivotWeight; public NodeSorter(ModelNode[] modelNodes, WeightFunction function, Balancer balancer) { this.function = function; this.balancer = balancer; this.modelNodes = modelNodes; weights = new float[modelNodes.length]; } /** * Resets the sorter, recalculates the weights per node and sorts the * nodes by weight, with minimal weight first. */ public void reset(String index, int from, int to) { this.index = index; for (int i = from; i < to; i++) { weights[i] = weight(modelNodes[i]); } sort(from, to); } public void reset(String index) { reset(index, 0, modelNodes.length); } public float weight(ModelNode node) { return function.weight(balancer, node, index); } @Override protected void swap(int i, int j) { final ModelNode tmpNode = modelNodes[i]; modelNodes[i] = modelNodes[j]; modelNodes[j] = tmpNode; final float tmpWeight = weights[i]; weights[i] = weights[j]; weights[j] = tmpWeight; } @Override protected int compare(int i, int j) { return Float.compare(weights[i], weights[j]); } @Override protected void setPivot(int i) { pivotWeight = weights[i]; } @Override protected int comparePivot(int j) { return Float.compare(pivotWeight, weights[j]); } public float delta() { return weights[weights.length - 1] - weights[0]; } } }
apache-2.0