repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
auroreallibe/Silverpeas-Components
spaceMembers/spaceMembers-war/src/main/java/org/silverpeas/components/spacemembers/servlets/SpaceMembersRequestRouter.java
3270
/* * Copyright (C) 2000 - 2016 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.components.spacemembers.servlets; import org.silverpeas.core.web.mvc.controller.ComponentContext; import org.silverpeas.core.web.mvc.controller.MainSessionController; import org.silverpeas.core.web.mvc.route.ComponentRequestRouter; import org.silverpeas.components.spacemembers.control.SpaceMembersSessionController; import org.silverpeas.core.web.http.HttpRequest; public class SpaceMembersRequestRouter extends ComponentRequestRouter<SpaceMembersSessionController> { private static final long serialVersionUID = -4334545961842905383L; @Override public SpaceMembersSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { return new SpaceMembersSessionController(mainSessionCtrl, context); } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" * @return */ @Override public String getSessionControlBeanName() { return "spaceMembers"; } /** * This method has to be implemented by the component request rooter it has to compute a * destination page * * @param function The entering request function (ex : "Main.jsp") * @param hyperlinkSCC The component Session Control, build and initialised. * @param request * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, SpaceMembersSessionController spaceMembersSCC, HttpRequest request) { String destination = ""; if (function.startsWith("Main") || function.startsWith("portlet")) { destination = "/Rdirectory/jsp/Main?SpaceId="+spaceMembersSCC.getSpaceId(); //Affichage page d'accueil : Seulement les membres connectés if(spaceMembersSCC.isHomePageDisplayOnlyConnectedMembers()) { destination += "&View=connected"; } } else { destination = "/Rdirectory/jsp/"+function; } return destination; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Assessment/src/ims/assessment/forms/patientfindingscopy/FormInfo.java
3156
//############################################################################# //# # //# 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.assessment.forms.patientfindingscopy; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Assessment"; } public String getFormName() { return "PatientFindingsCopy"; } public int getWidth() { return 496; } public int getHeight() { return 360; } public String[] getContextVariables() { return new String[] { "_cv_Core.PatientAssessmentFull", "_cv_Assessment.PatientGraphicAssessmentFinding", "_cv_Assessment.AutoSubmit" }; } public String getLocalVariablesPrefix() { return "_lv_Assessment.PatientFindingsCopy.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[0]; return componentsInfo; } public String getImagePath() { return "Images/Assessment/findings_48.png"; } }
agpl-3.0
erdincay/lpclientpc
src/com/lp/client/projekt/PanelProjekterledigungsgrund.java
8126
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * 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 theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * 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/>. * * Contact: developers@heliumv.com ******************************************************************************/ package com.lp.client.projekt; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.util.EventObject; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.border.Border; import com.lp.client.frame.HelperClient; import com.lp.client.frame.component.InternalFrame; import com.lp.client.frame.component.ItemChangedEvent; import com.lp.client.frame.component.PanelBasis; import com.lp.client.frame.component.WrapperLabel; import com.lp.client.frame.component.WrapperTextField; import com.lp.client.frame.delegate.DelegateFactory; import com.lp.client.pc.LPMain; import com.lp.server.personal.service.PersonalFac; import com.lp.server.projekt.service.ProjekterledigungsgrundDto; @SuppressWarnings("static-access") public class PanelProjekterledigungsgrund extends PanelBasis { /** * */ private static final long serialVersionUID = 1L; // von hier ... private GridBagLayout gridBagLayoutAll = null; private JPanel jpaWorkingOn = new JPanel(); private JPanel jpaButtonAction = null; private Border border = null; private GridBagLayout gridBagLayoutWorkingPanel = null; private WrapperLabel wlaBezeichnung = new WrapperLabel(); private WrapperTextField wtfBezeichnung = new WrapperTextField(); private ProjekterledigungsgrundDto projekterledigungsgrundDto = null; public PanelProjekterledigungsgrund(InternalFrame internalFrame, String add2TitleI, Object pk) throws Throwable { super(internalFrame, add2TitleI, pk); jbInit(); setDefaults(); initComponents(); enableAllComponents(this, false); } protected void setDefaults() { } protected JComponent getFirstFocusableComponent() throws Exception { return wtfBezeichnung; } public void eventActionNew(EventObject eventObject, boolean bLockMeI, boolean bNeedNoNewI) throws Throwable { super.eventActionNew(eventObject, true, false); projekterledigungsgrundDto = new ProjekterledigungsgrundDto(); // getInternalFrame().setKeyWasForLockMe(LPMain.getLockMeForNew()); leereAlleFelder(this); } /** * Hier kommen die events meiner speziellen Buttons an. * * @param e * ActionEvent * @throws Throwable */ protected void eventActionSpecial(ActionEvent e) throws Throwable { } protected void eventActionDelete(ActionEvent e, boolean bAdministrateLockKeyI, boolean bNeedNoDeleteI) throws Throwable { DelegateFactory .getInstance() .getProjektServiceDelegate() .removeProjekterledigungsgrund( projekterledigungsgrundDto.getIId()); this.setKeyWhenDetailPanel(null); super.eventActionDelete(e, false, false); } protected void components2Dto() throws Throwable{ projekterledigungsgrundDto.setCBez(wtfBezeichnung.getText()); projekterledigungsgrundDto.setMandantCNr(LPMain.getTheClient().getMandant()); } protected void dto2Components() { wtfBezeichnung.setText(projekterledigungsgrundDto.getCBez()); } public void eventActionSave(ActionEvent e, boolean bNeedNoSaveI) throws Throwable { if (allMandatoryFieldsSetDlg()) { components2Dto(); if (projekterledigungsgrundDto.getIId() == null) { projekterledigungsgrundDto.setIId(DelegateFactory .getInstance() .getProjektServiceDelegate() .createProjekterledigungsgrund( projekterledigungsgrundDto)); setKeyWhenDetailPanel(projekterledigungsgrundDto.getIId()); } else { DelegateFactory .getInstance() .getProjektServiceDelegate() .updateProjekterledigungsgrund( projekterledigungsgrundDto); } super.eventActionSave(e, true); if (getInternalFrame().getKeyWasForLockMe() == null) { getInternalFrame().setKeyWasForLockMe( projekterledigungsgrundDto.getIId() + ""); } eventYouAreSelected(false); } } protected void eventItemchanged(EventObject eI) throws Throwable { ItemChangedEvent e = (ItemChangedEvent) eI; } private void jbInit() throws Throwable { // von hier ... border = BorderFactory.createEmptyBorder(10, 10, 10, 10); setBorder(border); // das Aussenpanel hat immer das Gridbaglayout. gridBagLayoutAll = new GridBagLayout(); this.setLayout(gridBagLayoutAll); // Actionpanel von Oberklasse holen und anhaengen. jpaButtonAction = getToolsPanel(); this.setActionMap(null); wlaBezeichnung.setText(LPMain.getInstance().getTextRespectUISPr( "lp.bezeichnung")); wtfBezeichnung.setColumnsMax(PersonalFac.MAX_LOHNGRUPPE_BEZEICHNUNG); wtfBezeichnung.setText(""); wtfBezeichnung.setMandatoryField(true); getInternalFrame().addItemChangedListener(this); this.add(jpaButtonAction, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); // jetzt meine felder jpaWorkingOn = new JPanel(); gridBagLayoutWorkingPanel = new GridBagLayout(); jpaWorkingOn.setLayout(gridBagLayoutWorkingPanel); this.add(jpaWorkingOn, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); this.add(getPanelStatusbar(), new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); jpaWorkingOn.add(wlaBezeichnung, new GridBagConstraints(0, 0, 1, 1, 0.1, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); jpaWorkingOn.add(wtfBezeichnung, new GridBagConstraints(1, 0, 1, 1, 0.3, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0)); String[] aWhichButtonIUse = { ACTION_UPDATE, ACTION_SAVE, ACTION_DELETE, ACTION_DISCARD, }; enableToolsPanelButtons(aWhichButtonIUse); } protected String getLockMeWer() throws Exception { return HelperClient.LOCKME_PROJEKTERLEDIGUNGSGRUND; } public void eventYouAreSelected(boolean bNeedNoYouAreSelectedI) throws Throwable { super.eventYouAreSelected(false); Object key = getKeyWhenDetailPanel(); if (key == null || (key.equals(LPMain.getLockMeForNew()))) { leereAlleFelder(this); clearStatusbar(); } else { projekterledigungsgrundDto = DelegateFactory.getInstance() .getProjektServiceDelegate() .projekterledigungsgrundFindByPrimaryKey((Integer) key); dto2Components(); } } }
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/new_plotter/templates/gui/SeriesTemplatePanel.java
11147
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.new_plotter.templates.gui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Observable; import java.util.Observer; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.rapidminer.gui.actions.ExportPdfAction; import com.rapidminer.gui.new_plotter.templates.SeriesTemplate; import com.rapidminer.gui.new_plotter.templates.actions.ExportImageAction; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.tools.I18N; /** * This class contains the GUI for the {@link SeriesTemplate}. * * @author Marco Boeck * */ public class SeriesTemplatePanel extends PlotterTemplatePanel implements Observer { /** the {@link SeriesTemplate} for this panel */ private SeriesTemplate seriesTemplate; /** for selecting the x-axis attribute */ private JComboBox lowerBoundComboBox; /** for selecting the y-axis attribute */ private JComboBox upperBoundComboBox; /** for selecting the color attribute */ private JComboBox indexDimensionComboBox; /** list for selecting the plot column(s) */ private JList plotSeriesList; /** the checkbox indicating whether to use relative utilities or not */ private JCheckBox useRelativeUtilitiesCheckBox; /** the plot list selection listener */ private ListSelectionListener updatePlotListSelectionListener; // /** checkbox for rotating labels */ // private JCheckBox rotateLabelsCheckBox; private static final long serialVersionUID = -4999581517852957478L; /** * Creates a new GUI for a {@link SeriesTemplate}. * @param scatterTemplate */ public SeriesTemplatePanel(SeriesTemplate seriesTemplate) { super(seriesTemplate); this.seriesTemplate = seriesTemplate; this.updatePlotListSelectionListener = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { SeriesTemplatePanel.this.seriesTemplate.setPlotSelection(plotSeriesList.getSelectedValues()); } } }; setupGUI(); } /** * Setup GUI. */ private void setupGUI() { // start layout this.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTH; gbc.weightx = 1; gbc.weighty = 0; gbc.insets = new Insets(2, 5, 2, 5); JLabel upperBoundLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.upper_bound.column.label")); upperBoundLabel.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.upper_bound.column.tip")); this.add(upperBoundLabel, gbc); gbc.gridx = 1; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; this.add(errorIndicatorLabel, gbc); upperBoundComboBox = new JComboBox(); upperBoundComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { seriesTemplate.setUpperBoundName(String.valueOf(upperBoundComboBox.getSelectedItem())); } }); upperBoundComboBox.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.upper_bound.column.tip")); gbc.insets = new Insets(2, 5, 2, 5); gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTH; gbc.weightx = 1; gbc.gridwidth = 2; this.add(upperBoundComboBox, gbc); JLabel lowerBoundLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.lower_bound.column.label")); lowerBoundLabel.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.lower_bound.column.tip")); gbc.gridy = 2; this.add(lowerBoundLabel, gbc); lowerBoundComboBox = new JComboBox(); lowerBoundComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { seriesTemplate.setLowerBoundName(String.valueOf(lowerBoundComboBox.getSelectedItem())); } }); lowerBoundComboBox.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.lower_bound.column.tip")); gbc.gridy = 3; this.add(lowerBoundComboBox, gbc); JLabel indexDimensionLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.index_dimension.column.label")); indexDimensionLabel.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.index_dimension.column.tip")); gbc.gridy = 4; this.add(indexDimensionLabel, gbc); indexDimensionComboBox = new JComboBox(); indexDimensionComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { seriesTemplate.setIndexDimensionName(String.valueOf(indexDimensionComboBox.getSelectedItem())); } }); indexDimensionComboBox.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.index_dimension.column.tip")); gbc.gridy = 5; this.add(indexDimensionComboBox, gbc); JLabel plotSeriesLabel = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.plot_series.column.label")); plotSeriesLabel.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.plot_series.column.tip")); gbc.gridy = 6; this.add(plotSeriesLabel, gbc); plotSeriesList = new JList(); plotSeriesList.setBorder(BorderFactory.createLoweredBevelBorder()); plotSeriesList.addListSelectionListener(updatePlotListSelectionListener); plotSeriesList.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.plot_series.column.tip")); gbc.gridy = 7; gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; ExtendedJScrollPane plotSeriesScrollPane = new ExtendedJScrollPane(plotSeriesList); this.add(plotSeriesScrollPane, gbc); useRelativeUtilitiesCheckBox = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.relative_utilities.label")); useRelativeUtilitiesCheckBox.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.series.relative_utilities.tip")); useRelativeUtilitiesCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { seriesTemplate.setUseRelativeUtilities(useRelativeUtilitiesCheckBox.isSelected()); } }); gbc.gridy = 8; this.add(useRelativeUtilitiesCheckBox, gbc); JPanel exportPanel = new JPanel(new BorderLayout()); JButton exportImageButton = new JButton(new ExportImageAction(seriesTemplate)); JButton exportPdfButton = new JButton(new ExportPdfAction(seriesTemplate)); exportPanel.add(exportPdfButton, BorderLayout.PAGE_START); exportPanel.add(exportImageButton, BorderLayout.PAGE_END); gbc.gridy = 9; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0; this.add(exportPanel, gbc); } @Override public void update(Observable o, Object arg) { if (o instanceof SeriesTemplate) { final SeriesTemplate seriesTemplate = (SeriesTemplate)o; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // update list & combo boxes DefaultListModel modelPlotsList = new DefaultListModel(); Vector<String> attrNameVector = new Vector<String>(seriesTemplate.getDataTable().getColumnNames().length); attrNameVector.add(I18N.getMessage(I18N.getGUIBundle(), "gui.plotter.column.empty_selection.label")); for (String attName : seriesTemplate.getDataTable().getColumnNames()) { modelPlotsList.addElement(attName); attrNameVector.add(attName); } plotSeriesList.removeListSelectionListener(updatePlotListSelectionListener); plotSeriesList.setModel(modelPlotsList); int[] selectedIndicies = new int[modelPlotsList.size()]; Arrays.fill(selectedIndicies, -1); int i = 0; for (Object plot : seriesTemplate.getPlotSelection()) { selectedIndicies[i++] = modelPlotsList.indexOf(plot); } plotSeriesList.setSelectedIndices(selectedIndicies); plotSeriesList.addListSelectionListener(updatePlotListSelectionListener); DefaultComboBoxModel modelLowerBound = new DefaultComboBoxModel(attrNameVector); DefaultComboBoxModel modelUpperBound = new DefaultComboBoxModel(attrNameVector); DefaultComboBoxModel modelIndexDimension = new DefaultComboBoxModel(attrNameVector); lowerBoundComboBox.setModel(modelLowerBound); upperBoundComboBox.setModel(modelUpperBound); indexDimensionComboBox.setModel(modelIndexDimension); // select correct values (and make sure they don't fire events) ActionListener[] actionListeners = indexDimensionComboBox.getActionListeners(); for (ActionListener l : actionListeners) { indexDimensionComboBox.removeActionListener(l); } indexDimensionComboBox.setSelectedItem(seriesTemplate.getIndexDimensionName()); for (ActionListener l : actionListeners) { indexDimensionComboBox.addActionListener(l); } actionListeners = lowerBoundComboBox.getActionListeners(); for (ActionListener l : actionListeners) { lowerBoundComboBox.removeActionListener(l); } lowerBoundComboBox.setSelectedItem(seriesTemplate.getLowerBoundName()); for (ActionListener l : actionListeners) { lowerBoundComboBox.addActionListener(l); } actionListeners = upperBoundComboBox.getActionListeners(); for (ActionListener l : actionListeners) { upperBoundComboBox.removeActionListener(l); } upperBoundComboBox.setSelectedItem(seriesTemplate.getUpperBoundName()); for (ActionListener l : actionListeners) { upperBoundComboBox.addActionListener(l); } useRelativeUtilitiesCheckBox.setSelected(seriesTemplate.isUsingRelativeUtilities()); } }); } } }
agpl-3.0
lpellegr/scheduling-portal
common-portal/src/main/java/org/ow2/proactive_grid_cloud_portal/common/shared/ServiceException.java
627
package org.ow2.proactive_grid_cloud_portal.common.shared; import org.ow2.proactive_grid_cloud_portal.common.server.Service; import com.google.gwt.user.client.rpc.IsSerializable; /** * Thrown by {@link Service} upon internal logic failure detection * * @author mschnoor * */ @SuppressWarnings("serial") public class ServiceException extends Exception implements IsSerializable { public ServiceException() { super(); } public ServiceException(String message) { super(message); } public ServiceException(String message, Throwable cause) { super(message, cause); } }
agpl-3.0
fqqb/yamcs
yamcs-core/src/test/java/org/yamcs/cli/XtceDbTest.java
1251
package org.yamcs.cli; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.yamcs.YConfiguration; public class XtceDbTest extends AbstractCliTest { @Before public void resetConfig() { YConfiguration.setupTest(null); } @Test public void testXtceDbPrintCli() throws Exception { YamcsAdminCli yamcsCli = new YamcsAdminCli(); yamcsCli.parse(new String[] { "mdb", "print", "refmdb" }); yamcsCli.validate(); yamcsCli.execute(); String out = mconsole.output(); assertTrue(out.contains("SpaceSystem /REFMDB")); assertTrue(out.contains("SequenceContainer name: PKT3")); assertTrue(out.contains("Algorithm name: ctx_param_test")); assertTrue(out.contains("MetaCommand name: CALIB_TC")); } @Test public void testXtceDbVerifyCli() throws Exception { YConfiguration.setupTest("src/test/resources/"); YamcsAdminCli yamcsCli = new YamcsAdminCli(); yamcsCli.parse(new String[] { "mdb", "verify", "refmdb" }); yamcsCli.validate(); yamcsCli.execute(); String out = mconsole.output(); assertTrue(out.contains("MDB loaded successfully")); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/nursing/assessment/domain/objects/PersonalHygieneActivities.java
13379
//############################################################################# //# # //# 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 * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.nursing.assessment.domain.objects; /** * * @author Sinead McDermott * Generated. */ public class PersonalHygieneActivities extends ims.domain.DomainObject implements java.io.Serializable { public static final int CLASSID = 1012100043; private static final long serialVersionUID = 1012100043L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } private ims.domain.lookups.LookupInstance activities; private ims.domain.lookups.LookupInstance ability; private String aidsUsed; public PersonalHygieneActivities (Integer id, int ver) { super(id, ver); } public PersonalHygieneActivities () { super(); } public PersonalHygieneActivities (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.nursing.assessment.domain.objects.PersonalHygieneActivities.class; } public ims.domain.lookups.LookupInstance getActivities() { return activities; } public void setActivities(ims.domain.lookups.LookupInstance activities) { this.activities = activities; } public ims.domain.lookups.LookupInstance getAbility() { return ability; } public void setAbility(ims.domain.lookups.LookupInstance ability) { this.ability = ability; } public String getAidsUsed() { return aidsUsed; } public void setAidsUsed(String aidsUsed) { this.aidsUsed = aidsUsed; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*activities* :"); if (activities != null) auditStr.append(activities.getText()); auditStr.append("; "); auditStr.append("\r\n*ability* :"); if (ability != null) auditStr.append(ability.getText()); auditStr.append("; "); auditStr.append("\r\n*aidsUsed* :"); auditStr.append(aidsUsed); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "PersonalHygieneActivities"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getActivities() != null) { sb.append("<activities>"); sb.append(this.getActivities().toXMLString()); sb.append("</activities>"); } if (this.getAbility() != null) { sb.append("<ability>"); sb.append(this.getAbility().toXMLString()); sb.append("</ability>"); } if (this.getAidsUsed() != null) { sb.append("<aidsUsed>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getAidsUsed().toString())); sb.append("</aidsUsed>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); PersonalHygieneActivities domainObject = getPersonalHygieneActivitiesfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); PersonalHygieneActivities domainObject = getPersonalHygieneActivitiesfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static PersonalHygieneActivities getPersonalHygieneActivitiesfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getPersonalHygieneActivitiesfromXML(doc.getRootElement(), factory, domMap); } public static PersonalHygieneActivities getPersonalHygieneActivitiesfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!PersonalHygieneActivities.class.getName().equals(className)) { Class clz = Class.forName(className); if (!PersonalHygieneActivities.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the PersonalHygieneActivities class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (PersonalHygieneActivities)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(PersonalHygieneActivities.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } PersonalHygieneActivities ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (PersonalHygieneActivities)factory.getImportedDomainObject(PersonalHygieneActivities.class, externalSource, extId); if (ret == null) { ret = new PersonalHygieneActivities(); } String keyClassName = "PersonalHygieneActivities"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (PersonalHygieneActivities)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, PersonalHygieneActivities obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("activities"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setActivities(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("ability"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setAbility(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("aidsUsed"); if(fldEl != null) { obj.setAidsUsed(new String(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ }; } public static class FieldNames { public static final String ID = "id"; public static final String Activities = "activities"; public static final String Ability = "ability"; public static final String AidsUsed = "aidsUsed"; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/MyOrderComponentVoCollection.java
8283
//############################################################################# //# # //# 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.ocrr.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; public class MyOrderComponentVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<MyOrderComponentVo> { private static final long serialVersionUID = 1L; private ArrayList<MyOrderComponentVo> col = new ArrayList<MyOrderComponentVo>(); public String getBoClassName() { return null; } public boolean add(MyOrderComponentVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, MyOrderComponentVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(MyOrderComponentVo instance) { return col.indexOf(instance); } public MyOrderComponentVo get(int index) { return this.col.get(index); } public boolean set(int index, MyOrderComponentVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(MyOrderComponentVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(MyOrderComponentVo instance) { return indexOf(instance) >= 0; } public Object clone() { MyOrderComponentVoCollection clone = new MyOrderComponentVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((MyOrderComponentVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; 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]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public MyOrderComponentVoCollection sort() { return sort(SortOrder.ASCENDING); } public MyOrderComponentVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public MyOrderComponentVoCollection sort(SortOrder order) { return sort(new MyOrderComponentVoComparator(order)); } public MyOrderComponentVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new MyOrderComponentVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public MyOrderComponentVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public MyOrderComponentVo[] toArray() { MyOrderComponentVo[] arr = new MyOrderComponentVo[col.size()]; col.toArray(arr); return arr; } public Iterator<MyOrderComponentVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class MyOrderComponentVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public MyOrderComponentVoComparator() { this(SortOrder.ASCENDING); } public MyOrderComponentVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public MyOrderComponentVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { MyOrderComponentVo voObj1 = (MyOrderComponentVo)obj1; MyOrderComponentVo voObj2 = (MyOrderComponentVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.ocrr.vo.beans.MyOrderComponentVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.ocrr.vo.beans.MyOrderComponentVoBean[] getBeanCollectionArray() { ims.ocrr.vo.beans.MyOrderComponentVoBean[] result = new ims.ocrr.vo.beans.MyOrderComponentVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { MyOrderComponentVo vo = ((MyOrderComponentVo)col.get(i)); result[i] = (ims.ocrr.vo.beans.MyOrderComponentVoBean)vo.getBean(); } return result; } public static MyOrderComponentVoCollection buildFromBeanCollection(java.util.Collection beans) { MyOrderComponentVoCollection coll = new MyOrderComponentVoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.ocrr.vo.beans.MyOrderComponentVoBean)iter.next()).buildVo()); } return coll; } public static MyOrderComponentVoCollection buildFromBeanCollection(ims.ocrr.vo.beans.MyOrderComponentVoBean[] beans) { MyOrderComponentVoCollection coll = new MyOrderComponentVoCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Scheduling/src/ims/scheduling/forms/bookingslotstatus/BaseLogic.java
4550
//############################################################################# //# # //# 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.scheduling.forms.bookingslotstatus; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.domain.DomainInterface.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.domain.DomainInterface domain) { setContext(engine, form); this.domain = domain; } protected final void oncmbStatusReasonValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatusReason().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.Status_Reason existingInstance = (ims.scheduling.vo.lookups.Status_Reason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusReasonLookup(); return; } } } } else if(value instanceof ims.scheduling.vo.lookups.Status_Reason) { ims.scheduling.vo.lookups.Status_Reason instance = (ims.scheduling.vo.lookups.Status_Reason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusReasonLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.Status_Reason existingInstance = (ims.scheduling.vo.lookups.Status_Reason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatusReason().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusReasonLookup() { this.form.cmbStatusReason().clear(); ims.scheduling.vo.lookups.Status_ReasonCollection lookupCollection = ims.scheduling.vo.lookups.LookupHelper.getStatus_Reason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatusReason().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusReasonLookupValue(int id) { ims.scheduling.vo.lookups.Status_Reason instance = ims.scheduling.vo.lookups.LookupHelper.getStatus_ReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatusReason().setValue(instance); } protected final void defaultcmbStatusReasonLookupValue() { this.form.cmbStatusReason().setValue((ims.scheduling.vo.lookups.Status_Reason)domain.getLookupService().getDefaultInstance(ims.scheduling.vo.lookups.Status_Reason.class, engine.getFormName().getID(), ims.scheduling.vo.lookups.Status_Reason.TYPE_ID)); } public final void free() { super.free(); domain = null; } protected ims.domain.DomainInterface domain; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/admin/vo/Opcs4VoCollection.java
7792
//############################################################################# //# # //# 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.admin.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to core.clinical.coding.Opcs4 business object (ID: 1065100001). */ public class Opcs4VoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<Opcs4Vo> { private static final long serialVersionUID = 1L; private ArrayList<Opcs4Vo> col = new ArrayList<Opcs4Vo>(); public String getBoClassName() { return "ims.core.clinical.coding.domain.objects.Opcs4"; } public boolean add(Opcs4Vo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, Opcs4Vo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(Opcs4Vo instance) { return col.indexOf(instance); } public Opcs4Vo get(int index) { return this.col.get(index); } public boolean set(int index, Opcs4Vo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(Opcs4Vo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(Opcs4Vo instance) { return indexOf(instance) >= 0; } public Object clone() { Opcs4VoCollection clone = new Opcs4VoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((Opcs4Vo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; 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]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public Opcs4VoCollection sort() { return sort(SortOrder.ASCENDING); } public Opcs4VoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public Opcs4VoCollection sort(SortOrder order) { return sort(new Opcs4VoComparator(order)); } public Opcs4VoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new Opcs4VoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public Opcs4VoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.core.clinical.coding.vo.Opcs4RefVoCollection toRefVoCollection() { ims.core.clinical.coding.vo.Opcs4RefVoCollection result = new ims.core.clinical.coding.vo.Opcs4RefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public Opcs4Vo[] toArray() { Opcs4Vo[] arr = new Opcs4Vo[col.size()]; col.toArray(arr); return arr; } public Iterator<Opcs4Vo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class Opcs4VoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public Opcs4VoComparator() { this(SortOrder.ASCENDING); } public Opcs4VoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public Opcs4VoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { Opcs4Vo voObj1 = (Opcs4Vo)obj1; Opcs4Vo voObj2 = (Opcs4Vo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.admin.vo.beans.Opcs4VoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.admin.vo.beans.Opcs4VoBean[] getBeanCollectionArray() { ims.admin.vo.beans.Opcs4VoBean[] result = new ims.admin.vo.beans.Opcs4VoBean[col.size()]; for(int i = 0; i < col.size(); i++) { Opcs4Vo vo = ((Opcs4Vo)col.get(i)); result[i] = (ims.admin.vo.beans.Opcs4VoBean)vo.getBean(); } return result; } public static Opcs4VoCollection buildFromBeanCollection(java.util.Collection beans) { Opcs4VoCollection coll = new Opcs4VoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.admin.vo.beans.Opcs4VoBean)iter.next()).buildVo()); } return coll; } public static Opcs4VoCollection buildFromBeanCollection(ims.admin.vo.beans.Opcs4VoBean[] beans) { Opcs4VoCollection coll = new Opcs4VoCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/fallassessmentdialog/GenForm.java
48844
//############################################################################# //# # //# 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.nursing.forms.fallassessmentdialog; 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 grdRiskAssessmentRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdRiskAssessmentRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setIsParentRow(boolean value) { super.setIsParentRow(value); } public boolean isParentRow() { return super.isParentRow(); } public void setExpanded(boolean value) { super.setExpanded(value); } public boolean isExpanded() { return super.isExpanded(); } public void setRiskReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isRiskReadOnly() { return super.row.isReadOnly(0); } public void showRiskOpened() { super.row.showOpened(0); } public String getRisk() { return (String)super.row.get(0); } public void setRisk(String value) { super.row.set(0, value); } public void setCellRiskTooltip(String value) { super.row.setTooltip(0, value); } public void setSelectReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean isSelectReadOnly() { return super.row.isReadOnly(1); } public void showSelectOpened() { super.row.showOpened(1); } public boolean getSelect() { return ((Boolean)super.row.get(1)).booleanValue(); } public void setSelect(boolean value) { super.row.set(1, new Boolean(value)); } public void setCellSelectTooltip(String value) { super.row.setTooltip(1, value); } public String getValue() { return (String)super.row.getValue(); } public void setValue(String value) { super.row.setValue(value); } public grdRiskAssessmentRow getParentRow() { return super.row.getParent() == null ? null : new grdRiskAssessmentRow(super.row.getParent()); } public grdRiskAssessmentRowCollection getRows() { if(this.collection == null) this.collection = new grdRiskAssessmentRowCollection(super.row.getRows()); return this.collection; } private grdRiskAssessmentRowCollection collection; } public static class grdRiskAssessmentRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdRiskAssessmentRowCollection(GridRowCollection collection) { super(collection); } public grdRiskAssessmentRow get(int index) { return new grdRiskAssessmentRow(super.collection.get(index)); } public grdRiskAssessmentRow newRow() { return new grdRiskAssessmentRow(super.collection.newRow()); } public grdRiskAssessmentRow newRow(boolean autoSelect) { return new grdRiskAssessmentRow(super.collection.newRow(autoSelect)); } public grdRiskAssessmentRow newRowAt(int index) { return new grdRiskAssessmentRow(super.collection.newRowAt(index)); } public grdRiskAssessmentRow newRowAt(int index, boolean autoSelect) { return new grdRiskAssessmentRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdRiskAssessmentGrid extends GridBridge { private static final long serialVersionUID = 1L; public GenForm.grdRiskAssessmentRow[] getAllRows() { java.util.ArrayList rows = new java.util.ArrayList(); for(int x = 0; x < getRows().size(); x++) { GenForm.grdRiskAssessmentRow row = getRows().get(x); rows.add(row); GenForm.grdRiskAssessmentRow[] childRows = getAllRows(row); for(int i = 0; i < childRows.length; i++) { rows.add(childRows[i]); } } GenForm.grdRiskAssessmentRow[] result = new GenForm.grdRiskAssessmentRow[rows.size()]; for(int x = 0; x < rows.size(); x++) { result[x] = (GenForm.grdRiskAssessmentRow)rows.get(x); } return result; } public GenForm.grdRiskAssessmentRow[] getAllRows(GenForm.grdRiskAssessmentRow parentRow) { java.util.ArrayList rows = new java.util.ArrayList(); for(int x = 0; x < parentRow.getRows().size(); x++) { GenForm.grdRiskAssessmentRow row = parentRow.getRows().get(x); rows.add(row); GenForm.grdRiskAssessmentRow[] childRows = getAllRows(row); for(int i = 0; i < childRows.length; i++) { rows.add(childRows[i]); } } GenForm.grdRiskAssessmentRow[] result = new GenForm.grdRiskAssessmentRow[rows.size()]; for(int x = 0; x < rows.size(); x++) { result[x] = (GenForm.grdRiskAssessmentRow)rows.get(x); } return result; } public void expandAll() { expandCollapseAll(true); } public void collapseAll() { expandCollapseAll(false); } private void expandCollapseAll(boolean expand) { for(int x = 0; x < getRows().size(); x++) { GenForm.grdRiskAssessmentRow row = getRows().get(x); row.setExpanded(expand); expandCollapseRow(row, expand); } } private void expandCollapseRow(GenForm.grdRiskAssessmentRow parentRow, boolean expand) { for(int x = 0; x < parentRow.getRows().size(); x++) { GenForm.grdRiskAssessmentRow row = parentRow.getRows().get(x); row.setExpanded(expand); expandCollapseRow(row, expand); } } private void addTreeColumn(String caption, int captionAlignment, int width, boolean bold, boolean canGrow) { super.grid.addTreeColumn(caption, captionAlignment, width, bold, canGrow); } private void addBoolColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean autoPostBack, int sortOrder, boolean canGrow) { super.grid.addBoolColumn(caption, captionAlignment, alignment, width, readOnly, autoPostBack, sortOrder, canGrow); } 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 grdRiskAssessmentRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdRiskAssessmentRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdRiskAssessmentRowCollection getRows() { return new grdRiskAssessmentRowCollection(super.grid.getRows()); } public grdRiskAssessmentRow getRowByValue(String value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdRiskAssessmentRow(row); } public void setRiskHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getRiskHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setSelectHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getSelectHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } } private void validateContext(ims.framework.Context context) { if(context == null) return; if(!context.isValidContextType(ims.core.vo.CareContextShortVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.CareContextShortVo' of the global context variable 'Core.CurrentCareContext' is not supported."); if(!context.isValidContextType(ims.core.vo.PatientShort.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.PatientShort' of the global context variable 'Core.PatientShort' is not supported."); if(!context.isValidContextType(ims.core.vo.ClinicalContactShortVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.ClinicalContactShortVo' of the global context variable 'Core.CurrentClinicalContact' is not supported."); } 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(); this.globalContext = new GlobalContext(context); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(832, 512); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class)); super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class)); super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false)); super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier)); // Panel Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 816, 464, ims.framework.enumerations.ControlAnchoring.TOPLEFT); 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.TOPLEFT,"", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 26, 32, 70, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.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.TOPLEFT, "Date/Time:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 303, 32, 92, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.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.TOPLEFT, "Authoring HCP:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 744, 480, 75, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Button.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()), new Integer(startTabIndex.intValue() + 3), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 664, 480, 75, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Button.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()), new Integer(startTabIndex.intValue() + 2), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Save", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // TextBox Controls RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 400, 30, 416, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(TextBox.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()), new Integer(-1), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.FALSE, new Integer(0), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // Date Controls RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 96, 30, 120, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(DateControl.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()), new Integer(-1), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null})); // Grid Controls RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 24, 64, 792, 392, ims.framework.enumerations.ControlAnchoring.TOPLEFT); Grid m_grdRiskAssessmentTemp = (Grid)factory.getControl(Grid.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()), new Integer(startTabIndex.intValue() + 1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.FALSE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdRiskAssessmentTemp); grdRiskAssessmentGrid grdRiskAssessment = (grdRiskAssessmentGrid)GridFlyweightFactory.getInstance().createGridBridge(grdRiskAssessmentGrid.class, m_grdRiskAssessmentTemp); grdRiskAssessment.addTreeColumn("Risk factor / Description", 0, 700, false, true); grdRiskAssessment.addBoolColumn("Select", 1, 1, -1, false, false, 0, true); super.addGrid(grdRiskAssessment); // Time Controls RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 224, 30, 48, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(TimeControl.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()), new Integer(-1), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.FALSE, null, Boolean.FALSE, ""})); } public Forms getForms() { return (Forms)super.getFormReferences(); } public Images getImages() { return (Images)super.getImageReferences(); } public Button btnCancel() { return (Button)super.getControl(3); } public Button btnSave() { return (Button)super.getControl(4); } public TextBox txtHcp() { return (TextBox)super.getControl(5); } public DateControl dteDate() { return (DateControl)super.getControl(6); } public grdRiskAssessmentGrid grdRiskAssessment() { return (grdRiskAssessmentGrid)super.getGrid(0); } public TimeControl timTime() { return (TimeControl)super.getControl(8); } public static class Forms implements java.io.Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; private LocalFormName(int name) { super(name); } } private Forms() { Core = new CoreForms(); } public final class CoreForms implements java.io.Serializable { private static final long serialVersionUID = 1L; private CoreForms() { OkDialog = new LocalFormName(102122); } public final FormName OkDialog; } public CoreForms Core; } 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() { GreenSquare = new ImageHelper(102124, "Images/Core/circle_green.png", new Integer(16), new Integer(16)); Right = new ImageHelper(102112, "Images/Core/right.gif", new Integer(16), new Integer(16)); AnswerBox_Yes = new ImageHelper(102101, "Images/Core/answer_yes.png", new Integer(10), new Integer(10)); } public final ims.framework.utils.Image GreenSquare; public final ims.framework.utils.Image Right; public final ims.framework.utils.Image AnswerBox_Yes; } public final CoreImages Core; } public GlobalContext getGlobalContext() { return this.globalContext; } public static class GlobalContextBridge extends ContextBridge { private static final long serialVersionUID = 1L; } public LocalContext getLocalContext() { return (LocalContext)super.getLocalCtx(); } public class LocalContext extends ContextBridge { private static final long serialVersionUID = 1L; public LocalContext(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { super.setContext(context); String prefix = formInfo.getLocalVariablesPrefix(); cxl_Hcp = new ims.framework.ContextVariable("Hcp", prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier + ""); } public boolean getHcpIsNotNull() { return !cxl_Hcp.getValueIsNull(context); } public ims.core.vo.HcpLiteVo getHcp() { return (ims.core.vo.HcpLiteVo)cxl_Hcp.getValue(context); } public void setHcp(ims.core.vo.HcpLiteVo value) { cxl_Hcp.setValue(context, value); } private ims.framework.ContextVariable cxl_Hcp = null; } 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[167]; 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"); fields[144] = new ims.framework.ReportField(this.context, "_cv_COE.CurrentFallRiskAssessment", "BO-1003100002-ID", "ID_Assessment"); fields[145] = new ims.framework.ReportField(this.context, "_cv_COE.CurrentFallRiskAssessment", "BO-1003100002-DATETIMEINITIATED", "DateTimeInitiated"); fields[146] = new ims.framework.ReportField(this.context, "_cv_COE.CurrentFallRiskAssessment", "BO-1003100002-CLINICALCONTACT", "ClinicalContact"); fields[147] = new ims.framework.ReportField(this.context, "_cv_COE.CurrentFallRiskAssessment", "BO-1003100002-CARECONTEXT", "CareContext"); fields[148] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-ID", "ID_AssessmentComponent"); fields[149] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-ISCOMPLETE", "IsComplete"); fields[150] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-COPY", "Copy"); fields[151] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-COMPONENTTYPE", "ComponentType"); fields[152] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1015100001-ID", "ID_AssessmentComponent"); fields[153] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1015100001-ISCOMPLETE", "IsComplete"); fields[154] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1015100001-COPY", "Copy"); fields[155] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1015100001-COMPONENTTYPE", "ComponentType"); fields[156] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1012100030-ASSISTANCEWITHMOBILITY", "AssistanceWithMobility"); fields[157] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1012100030-NOTES", "Notes"); fields[158] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1012100030-BEDTYPE", "BedType"); fields[159] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1012100030-CHAIRTYPE", "ChairType"); fields[160] = new ims.framework.ReportField(this.context, "_cv_COE.AssessmentMobility", "BO-1012100030-FALLASSESSMENTSCORE", "FallAssessmentScore"); fields[161] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-ID", "ID_Hcp"); fields[162] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-HCPTYPE", "HcpType"); fields[163] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-ISACTIVE", "IsActive"); fields[164] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[165] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[166] = new ims.framework.ReportField(this.context, prefix + "_lv_Nursing.FallAssessmentDialog.__internal_x_context__Hcp_" + componentIdentifier, "BO-1006100000-ISHCPAENDOSCOPIST", "IsHCPaEndoscopist"); 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 GlobalContext globalContext = null; private IReportField[] reportFields = null; }
agpl-3.0
hyc/BerkeleyDB
lang/java/src/com/sleepycat/db/RunRecoveryException.java
820
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1997, 2013 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ package com.sleepycat.db; import com.sleepycat.db.internal.DbEnv; /** Thrown when the database environment needs to be recovered. * Errors can occur in where the only solution is to shut down the application and run recovery. When a fatal error occurs, this exception will be thrown, and all subsequent calls will also fail in the same way. When this occurs, recovery should be performed. */ public class RunRecoveryException extends DatabaseException { /* package */ RunRecoveryException(final String s, final int errno, final DbEnv dbenv) { super(s, errno, dbenv); } }
agpl-3.0
Kunagi/kunagi
src/main/java/scrum/client/tasks/TaskBlock.java
3924
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * 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 General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.tasks; import ilarkesto.gwt.client.AnchorPanel; import scrum.client.collaboration.EmoticonsWidget; import scrum.client.common.ABlockWidget; import scrum.client.common.AScrumAction; import scrum.client.common.BlockHeaderWidget; import scrum.client.common.BlockWidgetFactory; import scrum.client.dnd.TrashSupport; import scrum.client.img.Img; import scrum.client.journal.ActivateChangeHistoryAction; import scrum.client.sprint.ClaimTaskAction; import scrum.client.sprint.CloseTaskAction; import scrum.client.sprint.ConvertTaskToIssueAction; import scrum.client.sprint.CreateTaskImpedimentAction; import scrum.client.sprint.DeleteTaskAction; import scrum.client.sprint.ReopenTaskAction; import scrum.client.sprint.Task; import scrum.client.sprint.UnclaimTaskAction; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; public class TaskBlock extends ABlockWidget<Task> implements TrashSupport { private AnchorPanel statusIcon; private TaskBlockContainer container; public TaskBlock(TaskBlockContainer container) { this.container = container; } @Override protected void onInitializationHeader(BlockHeaderWidget header) { Task task = getObject(); statusIcon = header.addIconWrapper(); header.addText(task.getLabelModel()); if (container.isShowOwner()) header.addText(task.getOwnerModel(), true); header.appendOuterCell(new EmoticonsWidget(task), null, true); header.addMenuAction(new ClaimTaskAction(task)); header.addMenuAction(new CloseTaskAction(task)); header.addMenuAction(new ReopenTaskAction(task)); header.addMenuAction(new UnclaimTaskAction(task)); header.addMenuAction(new CreateTaskImpedimentAction(task)); header.addMenuAction(new ConvertTaskToIssueAction(task)); header.addMenuAction(new DeleteTaskAction(task)); header.addMenuAction(new ActivateChangeHistoryAction(task)); } @Override protected void onUpdateHeader(BlockHeaderWidget header) { Task task = getObject(); header.setDragHandle(task.getReference()); Image statusImage = null; if (task.isClosed()) { statusImage = Img.tskClosed(); statusImage.setTitle("Closed."); } else if (task.isBlocked()) { statusImage = Img.tskBlocked(); statusImage.setTitle("Blocked by " + task.getBlockingImpedimentLabelsAsText() + "."); } else if (task.isOwnerSet()) { statusImage = Img.tskClaimed(); statusImage.setTitle("Claimed by " + task.getOwner().getName() + "."); } statusIcon.setWidget(statusImage); } @Override protected Widget onExtendedInitialization() { return new TaskWidget(getObject()); } @Override public AScrumAction getTrashAction() { return new DeleteTaskAction(getObject()); } public TaskBlockContainer getContainer() { return this.container; } public static class TaskBlockFactory implements BlockWidgetFactory<Task> { private TaskBlockContainer container; public TaskBlockFactory(TaskBlockContainer container) { this.container = container; } @Override public ABlockWidget<Task> createBlock() { return new TaskBlock(container); } } }
agpl-3.0
neo4j-attic/graphdb
ha/src/test/java/slavetest/CommonJobs.java
22075
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package slavetest; import java.io.Serializable; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Map; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.ha.StandaloneDatabase; import org.neo4j.kernel.Config; import org.neo4j.kernel.DeadlockDetectedException; import org.neo4j.kernel.IdType; import org.neo4j.kernel.ha.LockableNode; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.nioneo.store.IdGenerator; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.LockType; public abstract class CommonJobs { public static final RelationshipType REL_TYPE = DynamicRelationshipType.withName( "HA_TEST" ); public static final RelationshipType KNOWS = DynamicRelationshipType.withName( "KNOWS" ); public static abstract class AbstractJob<T> implements Job<T> { protected Config getConfig( GraphDatabaseService db ) { Config config = null; try { return (Config) db.getClass().getDeclaredMethod( "getConfig" ).invoke( db ); } catch ( Exception e ) { // Won't happen throw new RuntimeException( e ); } } } public static abstract class TransactionalJob<T> extends AbstractJob<T> { public final T execute( GraphDatabaseService db ) throws RemoteException { Transaction tx = db.beginTx(); try { return executeInTransaction( db, tx ); } catch ( RuntimeException e ) { e.printStackTrace( System.out ); throw e; } finally { beforeFinish(); tx.finish(); } } protected void beforeFinish() { } protected abstract T executeInTransaction( GraphDatabaseService db, Transaction tx ); } public static class CreateSubRefNodeJob extends TransactionalJob<Long> { private final String type; private final String key; private final Object value; public CreateSubRefNodeJob( String type, String key, Object value ) { this.type = type; this.key = key; this.value = value; } @Override protected Long executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node node = db.createNode(); Relationship rel = db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( type ) ); rel.setProperty( "something else", "Somewhat different" ); if ( value != null ) { node.setProperty( key, value ); } tx.success(); return node.getId(); } } public static class CreateSubRefNodeWithRelCountJob extends TransactionalJob<Integer> { private final String type; private final String[] typesToAsk; public CreateSubRefNodeWithRelCountJob( String type, String... typesToAsk ) { this.type = type; this.typesToAsk = typesToAsk; } @Override protected Integer executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node node = db.createNode(); db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( type ) ); int counter = 0; for ( Relationship rel : db.getReferenceNode().getRelationships( toRelationshipTypes( typesToAsk ) ) ) { counter++; } tx.success(); return counter; } } public static class CreateSubRefNodeMasterFailJob implements Job<Serializable[]> { private final CommonJobs.ShutdownDispatcher shutdownDispatcher; public CreateSubRefNodeMasterFailJob( CommonJobs.ShutdownDispatcher shutdownDispatcher ) { this.shutdownDispatcher = shutdownDispatcher; } public Serializable[] execute( GraphDatabaseService db ) throws RemoteException { Transaction tx = db.beginTx(); boolean successful = false; long nodeId = 0; try { Node node = db.createNode(); nodeId = node.getId(); db.getReferenceNode().createRelationshipTo( node, REL_TYPE ); tx.success(); } finally { this.shutdownDispatcher.doShutdown(); try { tx.finish(); successful = true; } catch ( RuntimeException e ) { } } return new Serializable[] { successful, nodeId }; } } public static class SetSubRefPropertyJob extends TransactionalJob<Object> { private final String key; private final Object value; public SetSubRefPropertyJob( String key, Object value ) { this.key = key; this.value = value; } @Override protected Object executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node refNode = db.getReferenceNode(); // To force it to pull updates refNode.removeProperty( "yoyoyoyo" ); Node node = refNode.getSingleRelationship( REL_TYPE, Direction.OUTGOING ).getEndNode(); Object oldValue = node.getProperty( key, null ); node.setProperty( key, value ); tx.success(); return oldValue; } } public static class CreateSomeEntitiesJob extends TransactionalJob<Void> { @Override protected Void executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node node1 = db.createNode(); Relationship rel1 = db.getReferenceNode().createRelationshipTo( node1, REL_TYPE ); node1.setProperty( "name", "Mattias" ); rel1.setProperty( "something else", "Somewhat different" ); Node node2 = db.createNode(); Relationship rel2 = node1.createRelationshipTo( node2, REL_TYPE ); node2.setProperty( "why o why", "Stuff" ); rel2.setProperty( "random integer", "4" ); tx.success(); return null; } } public static class GetNodeByIdJob implements Job<Boolean> { private final long id; public GetNodeByIdJob( long id ) { this.id = id; } public Boolean execute( GraphDatabaseService db ) { try { db.getNodeById( id ); return Boolean.TRUE; } catch ( NotFoundException e ) { return Boolean.FALSE; } } } public interface ShutdownDispatcher extends Remote { void doShutdown() throws RemoteException; } public static class ShutdownJvm extends UnicastRemoteObject implements ShutdownDispatcher { private final StandaloneDatabase jvm; public ShutdownJvm( StandaloneDatabase jvm ) throws RemoteException { super(); this.jvm = jvm; } public void doShutdown() { this.jvm.shutdown(); } } public static class DeleteNodeJob implements Job<Boolean> { private final long id; private final boolean deleteIndexing; public DeleteNodeJob( long id, boolean deleteIndexing ) { this.id = id; this.deleteIndexing = deleteIndexing; } public Boolean execute( GraphDatabaseService db ) throws RemoteException { Transaction tx = db.beginTx(); boolean successful = false; try { Node node = db.getNodeById( id ); // if ( deleteIndexing ) // { // IndexService index = ((HighlyAvailableGraphDatabase) db).getIndexService(); // for ( String key : node.getPropertyKeys() ) // { // index.removeIndex( node, key, node.getProperty( key ) ); // } // } node.delete(); tx.success(); } finally { try { tx.finish(); successful = true; } catch ( RuntimeException e ) { } } return successful; } } public static class GetRelationshipCountJob implements Job<Integer> { private final String[] types; public GetRelationshipCountJob( String... types ) { this.types = types; } public Integer execute( GraphDatabaseService db ) { int counter = 0; for ( Relationship rel : db.getReferenceNode().getRelationships( toRelationshipTypes( types ) ) ) { counter++; } return counter; } } private static RelationshipType[] toRelationshipTypes( String... names ) { RelationshipType[] types = new RelationshipType[names.length]; for ( int i = 0; i < names.length; i++ ) { types[i] = DynamicRelationshipType.withName( names[i] ); } return types; } public static class CreateNodeOutsideOfTxJob implements Job<Boolean> { public Boolean execute( GraphDatabaseService db ) throws RemoteException { try { db.getReferenceNode().createRelationshipTo( db.createNode(), REL_TYPE ); return Boolean.TRUE; } catch ( Exception e ) { return Boolean.FALSE; } } } public static class CreateNodeJob extends TransactionalJob<Long> { @Override protected Long executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node node = db.createNode(); tx.success(); return node.getId(); } } public static class SetNodePropertyJob extends TransactionalJob<Boolean> { private final long id; private final String key; private final Object value; public SetNodePropertyJob( long id, String key, Object value ) { this.id = id; this.key = key; this.value = value; } @Override protected Boolean executeInTransaction( GraphDatabaseService db, Transaction tx ) { try { db.getNodeById( id ).setProperty( key, value ); tx.success(); return Boolean.TRUE; } catch ( Exception e ) { return Boolean.FALSE; } } } public static class CreateNodesJob extends TransactionalJob<Long[]> { private final int count; public CreateNodesJob( int count ) { this.count = count; } @Override protected Long[] executeInTransaction( GraphDatabaseService db, Transaction tx ) { Long[] result = new Long[count]; for ( int i = 0; i < count; i++ ) { result[i] = db.createNode().getId(); } tx.success(); return result; } } public static class Worker1Job extends TransactionalJob<Boolean[]> { private final long node1; private final long node2; private final Fetcher<DoubleLatch> fetcher; public Worker1Job( long node1, long node2, Fetcher<DoubleLatch> fetcher ) { this.node1 = node1; this.node2 = node2; this.fetcher = fetcher; } @Override protected Boolean[] executeInTransaction( GraphDatabaseService db, Transaction tx ) { boolean success = false; boolean deadlock = false; try { DoubleLatch latch = fetcher.fetch(); db.getNodeById( node1 ).setProperty( "1", "T1 1" ); latch.countDownSecond(); latch.awaitFirst(); db.getNodeById( node2 ).removeProperty( "2" ); db.getNodeById( node1 ).removeProperty( "1" ); tx.success(); success = true; } catch ( DeadlockDetectedException e ) { deadlock = true; } catch ( Exception e ) { throw new RuntimeException( e ); } return new Boolean[] { success, deadlock }; } } public static class Worker2Job extends TransactionalJob<Boolean[]> { private final long node1; private final long node2; private final Fetcher<DoubleLatch> fetcher; public Worker2Job( long node1, long node2, Fetcher<DoubleLatch> fetcher ) { this.node1 = node1; this.node2 = node2; this.fetcher = fetcher; } @Override protected Boolean[] executeInTransaction( GraphDatabaseService db, Transaction tx ) { boolean success = false; boolean deadlock = false; try { DoubleLatch latch = fetcher.fetch(); db.getNodeById( node2 ).setProperty( "2", "T2 2" ); latch.countDownFirst(); latch.awaitSecond(); db.getNodeById( node1 ).setProperty( "1", "T2 2" ); tx.success(); success = true; } catch ( DeadlockDetectedException e ) { deadlock = true; } catch ( Exception e ) { throw new RuntimeException( e ); } return new Boolean[] { success, deadlock }; } } public static class PerformanceAcquireWriteLocksJob extends TransactionalJob<Void> { private final int amount; public PerformanceAcquireWriteLocksJob( int amount ) { this.amount = amount; } @Override protected Void executeInTransaction( GraphDatabaseService db, Transaction tx ) { Config config = getConfig( db ); LockManager lockManager = config.getLockManager(); LockReleaser lockReleaser = config.getLockReleaser(); for ( int i = 0; i < amount; i++ ) { Object resource = new LockableNode( i ); lockManager.getWriteLock( resource ); lockReleaser.addLockToTransaction( resource, LockType.WRITE ); } return null; } } public static class PerformanceIdAllocationJob extends AbstractJob<Void> { private final int count; public PerformanceIdAllocationJob( int count ) { this.count = count; } public Void execute( GraphDatabaseService db ) { Config config = getConfig( db ); IdGenerator generator = config.getIdGeneratorFactory().get( IdType.NODE ); for ( int i = 0; i < count; i++ ) { generator.nextId(); } return null; } } public static class PerformanceCreateNodesJob extends AbstractJob<Void> { private final int numTx; private final int numNodesInEach; public PerformanceCreateNodesJob( int numTx, int numNodesInEach ) { this.numTx = numTx; this.numNodesInEach = numNodesInEach; } public Void execute( GraphDatabaseService db ) throws RemoteException { for ( int i = 0; i < numTx; i++ ) { Transaction tx = db.beginTx(); try { for ( int ii = 0; ii < numNodesInEach; ii++ ) { db.createNode(); } tx.success(); } finally { tx.finish(); } } return null; } } public static class CreateNodeAndIndexJob extends TransactionalJob<Long> { private final String key; private final Object value; public CreateNodeAndIndexJob( String key, Object value ) { this.key = key; this.value = value; } @Override protected Long executeInTransaction( GraphDatabaseService db, Transaction tx ) { // IndexService index = db instanceof HighlyAvailableGraphDatabase ? // ((HighlyAvailableGraphDatabase) db).getIndexService() : // new LuceneIndexService( db ); Node node = db.createNode(); node.setProperty( key, value ); // index.index( node, key, value ); tx.success(); return node.getId(); } } public static class CreateNodeAndNewIndexJob extends TransactionalJob<Long> { private final String key; private final Object value; private final String indexName; private final String key2; private final Object value2; public CreateNodeAndNewIndexJob( String indexName, String key, Object value, String key2, Object value2 ) { this.indexName = indexName; this.key = key; this.value = value; this.key2 = key2; this.value2 = value2; } @Override protected Long executeInTransaction( GraphDatabaseService db, Transaction tx ) { Node node = db.createNode(); node.setProperty( key, value ); node.setProperty( key2, value2 ); Index<Node> index = db.index().forNodes( indexName ); index.add( node, key, value ); index.add( node, key2, value2 ); tx.success(); return node.getId(); } } public static class AddIndex extends TransactionalJob<Void> { private final Map<String, Object> properties; private final long nodeId; public AddIndex( long nodeId, Map<String, Object> properties ) { this.nodeId = nodeId; this.properties = properties; } @Override protected Void executeInTransaction( GraphDatabaseService db, Transaction tx ) { // IndexService index = ((HighlyAvailableGraphDatabase) db).getIndexService(); Node node = db.getNodeById( nodeId ); for ( Map.Entry<String, Object> entry : properties.entrySet() ) { // index.index( node, entry.getKey(), entry.getValue() ); } tx.success(); return null; } } public static class LargeTransactionJob extends AbstractJob<Void> { private final int txSizeMb; private final int numTxs; public LargeTransactionJob( int txSizeMb, int numTxs ) { this.txSizeMb = txSizeMb; this.numTxs = numTxs; } public Void execute( GraphDatabaseService db ) throws RemoteException { byte[] largeArray = new byte[1*1024*1021]; /* 1021 So that it doesn't align with block size in BlockLogBuffer and all that :) */ for ( int t = 0; t < numTxs; t++ ) { Transaction tx = db.beginTx(); try { for ( int i = 0; i < largeArray.length; i++ ) { largeArray[i] = (byte) (i % 256); } for ( int i = 0; i < txSizeMb; i++ ) { Node node = db.createNode(); node.setProperty( "data", largeArray ); } tx.success(); } finally { tx.finish(); } } return null; } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/nursing/vo/CarePlanTemplateObjectiveCollection.java
9166
//############################################################################# //# # //# 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.nursing.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to nursing.care plans.Care Plan Template Objective business object (ID: 1010100001). */ public class CarePlanTemplateObjectiveCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<CarePlanTemplateObjective> { private static final long serialVersionUID = 1L; private ArrayList<CarePlanTemplateObjective> col = new ArrayList<CarePlanTemplateObjective>(); public String getBoClassName() { return "ims.nursing.careplans.domain.objects.CarePlanTemplateObjective"; } public boolean add(CarePlanTemplateObjective value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, CarePlanTemplateObjective value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(CarePlanTemplateObjective instance) { return col.indexOf(instance); } public CarePlanTemplateObjective get(int index) { return this.col.get(index); } public boolean set(int index, CarePlanTemplateObjective value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(CarePlanTemplateObjective instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(CarePlanTemplateObjective instance) { return indexOf(instance) >= 0; } public Object clone() { CarePlanTemplateObjectiveCollection clone = new CarePlanTemplateObjectiveCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((CarePlanTemplateObjective)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; 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]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public CarePlanTemplateObjectiveCollection sort() { return sort(SortOrder.ASCENDING); } public CarePlanTemplateObjectiveCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public CarePlanTemplateObjectiveCollection sort(SortOrder order) { return sort(new CarePlanTemplateObjectiveComparator(order)); } public CarePlanTemplateObjectiveCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new CarePlanTemplateObjectiveComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public CarePlanTemplateObjectiveCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.nursing.careplans.vo.CarePlanTemplateObjectiveRefVoCollection toRefVoCollection() { ims.nursing.careplans.vo.CarePlanTemplateObjectiveRefVoCollection result = new ims.nursing.careplans.vo.CarePlanTemplateObjectiveRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public CarePlanTemplateObjective[] toArray() { CarePlanTemplateObjective[] arr = new CarePlanTemplateObjective[col.size()]; col.toArray(arr); return arr; } public Iterator<CarePlanTemplateObjective> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class CarePlanTemplateObjectiveComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public CarePlanTemplateObjectiveComparator() { this(SortOrder.ASCENDING); } public CarePlanTemplateObjectiveComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public CarePlanTemplateObjectiveComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { CarePlanTemplateObjective voObj1 = (CarePlanTemplateObjective)obj1; CarePlanTemplateObjective voObj2 = (CarePlanTemplateObjective)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.nursing.vo.beans.CarePlanTemplateObjectiveBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.nursing.vo.beans.CarePlanTemplateObjectiveBean[] getBeanCollectionArray() { ims.nursing.vo.beans.CarePlanTemplateObjectiveBean[] result = new ims.nursing.vo.beans.CarePlanTemplateObjectiveBean[col.size()]; for(int i = 0; i < col.size(); i++) { CarePlanTemplateObjective vo = ((CarePlanTemplateObjective)col.get(i)); result[i] = (ims.nursing.vo.beans.CarePlanTemplateObjectiveBean)vo.getBean(); } return result; } public static CarePlanTemplateObjectiveCollection buildFromBeanCollection(java.util.Collection beans) { CarePlanTemplateObjectiveCollection coll = new CarePlanTemplateObjectiveCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.nursing.vo.beans.CarePlanTemplateObjectiveBean)iter.next()).buildVo()); } return coll; } public static CarePlanTemplateObjectiveCollection buildFromBeanCollection(ims.nursing.vo.beans.CarePlanTemplateObjectiveBean[] beans) { CarePlanTemplateObjectiveCollection coll = new CarePlanTemplateObjectiveCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/PendingTransfersVoAssembler.java
20769
//############################################################################# //# # //# 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 * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Peter Martin */ public class PendingTransfersVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.PendingTransfersVo copy(ims.core.vo.PendingTransfersVo valueObjectDest, ims.core.vo.PendingTransfersVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_PendingTransfers(valueObjectSrc.getID_PendingTransfers()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // InpatientEpisode valueObjectDest.setInpatientEpisode(valueObjectSrc.getInpatientEpisode()); // DestinationWard valueObjectDest.setDestinationWard(valueObjectSrc.getDestinationWard()); // WardType valueObjectDest.setWardType(valueObjectSrc.getWardType()); // TransferRequestDateTime valueObjectDest.setTransferRequestDateTime(valueObjectSrc.getTransferRequestDateTime()); // CurrentStatus valueObjectDest.setCurrentStatus(valueObjectSrc.getCurrentStatus()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createPendingTransfersVoCollectionFromPendingTransfers(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.admin.pas.domain.objects.PendingTransfers objects. */ public static ims.core.vo.PendingTransfersVoCollection createPendingTransfersVoCollectionFromPendingTransfers(java.util.Set domainObjectSet) { return createPendingTransfersVoCollectionFromPendingTransfers(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.admin.pas.domain.objects.PendingTransfers objects. */ public static ims.core.vo.PendingTransfersVoCollection createPendingTransfersVoCollectionFromPendingTransfers(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.PendingTransfersVoCollection voList = new ims.core.vo.PendingTransfersVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.admin.pas.domain.objects.PendingTransfers domainObject = (ims.core.admin.pas.domain.objects.PendingTransfers) iterator.next(); ims.core.vo.PendingTransfersVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.admin.pas.domain.objects.PendingTransfers objects. */ public static ims.core.vo.PendingTransfersVoCollection createPendingTransfersVoCollectionFromPendingTransfers(java.util.List domainObjectList) { return createPendingTransfersVoCollectionFromPendingTransfers(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.admin.pas.domain.objects.PendingTransfers objects. */ public static ims.core.vo.PendingTransfersVoCollection createPendingTransfersVoCollectionFromPendingTransfers(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.PendingTransfersVoCollection voList = new ims.core.vo.PendingTransfersVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.admin.pas.domain.objects.PendingTransfers domainObject = (ims.core.admin.pas.domain.objects.PendingTransfers) domainObjectList.get(i); ims.core.vo.PendingTransfersVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.admin.pas.domain.objects.PendingTransfers set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractPendingTransfersSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVoCollection voCollection) { return extractPendingTransfersSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractPendingTransfersSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.core.vo.PendingTransfersVo vo = voCollection.get(i); ims.core.admin.pas.domain.objects.PendingTransfers domainObject = PendingTransfersVoAssembler.extractPendingTransfers(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.admin.pas.domain.objects.PendingTransfers list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractPendingTransfersList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVoCollection voCollection) { return extractPendingTransfersList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractPendingTransfersList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.core.vo.PendingTransfersVo vo = voCollection.get(i); ims.core.admin.pas.domain.objects.PendingTransfers domainObject = PendingTransfersVoAssembler.extractPendingTransfers(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.admin.pas.domain.objects.PendingTransfers object. * @param domainObject ims.core.admin.pas.domain.objects.PendingTransfers */ public static ims.core.vo.PendingTransfersVo create(ims.core.admin.pas.domain.objects.PendingTransfers domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.admin.pas.domain.objects.PendingTransfers object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.PendingTransfersVo create(DomainObjectMap map, ims.core.admin.pas.domain.objects.PendingTransfers domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.PendingTransfersVo valueObject = (ims.core.vo.PendingTransfersVo) map.getValueObject(domainObject, ims.core.vo.PendingTransfersVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.PendingTransfersVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.admin.pas.domain.objects.PendingTransfers */ public static ims.core.vo.PendingTransfersVo insert(ims.core.vo.PendingTransfersVo valueObject, ims.core.admin.pas.domain.objects.PendingTransfers domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.admin.pas.domain.objects.PendingTransfers */ public static ims.core.vo.PendingTransfersVo insert(DomainObjectMap map, ims.core.vo.PendingTransfersVo valueObject, ims.core.admin.pas.domain.objects.PendingTransfers domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_PendingTransfers(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // InpatientEpisode valueObject.setInpatientEpisode(ims.core.vo.domain.InpatientEpisodeForTransfersVoAssembler.create(map, domainObject.getInpatientEpisode()) ); // DestinationWard valueObject.setDestinationWard(ims.core.vo.domain.LocationLiteVoAssembler.create(map, domainObject.getDestinationWard()) ); // WardType ims.domain.lookups.LookupInstance instance3 = domainObject.getWardType(); if ( null != instance3 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance3.getImage() != null) { img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath()); } color = instance3.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.WardType voLookup3 = new ims.core.vo.lookups.WardType(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color); ims.core.vo.lookups.WardType parentVoLookup3 = voLookup3; ims.domain.lookups.LookupInstance parent3 = instance3.getParent(); while (parent3 != null) { if (parent3.getImage() != null) { img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() ); } else { img = null; } color = parent3.getColor(); if (color != null) color.getValue(); parentVoLookup3.setParent(new ims.core.vo.lookups.WardType(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color)); parentVoLookup3 = parentVoLookup3.getParent(); parent3 = parent3.getParent(); } valueObject.setWardType(voLookup3); } // TransferRequestDateTime java.util.Date TransferRequestDateTime = domainObject.getTransferRequestDateTime(); if ( null != TransferRequestDateTime ) { valueObject.setTransferRequestDateTime(new ims.framework.utils.DateTime(TransferRequestDateTime) ); } // CurrentStatus ims.domain.lookups.LookupInstance instance5 = domainObject.getCurrentStatus(); if ( null != instance5 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance5.getImage() != null) { img = new ims.framework.utils.ImagePath(instance5.getImage().getImageId(), instance5.getImage().getImagePath()); } color = instance5.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.TransferStatus voLookup5 = new ims.core.vo.lookups.TransferStatus(instance5.getId(),instance5.getText(), instance5.isActive(), null, img, color); ims.core.vo.lookups.TransferStatus parentVoLookup5 = voLookup5; ims.domain.lookups.LookupInstance parent5 = instance5.getParent(); while (parent5 != null) { if (parent5.getImage() != null) { img = new ims.framework.utils.ImagePath(parent5.getImage().getImageId(), parent5.getImage().getImagePath() ); } else { img = null; } color = parent5.getColor(); if (color != null) color.getValue(); parentVoLookup5.setParent(new ims.core.vo.lookups.TransferStatus(parent5.getId(),parent5.getText(), parent5.isActive(), null, img, color)); parentVoLookup5 = parentVoLookup5.getParent(); parent5 = parent5.getParent(); } valueObject.setCurrentStatus(voLookup5); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.admin.pas.domain.objects.PendingTransfers extractPendingTransfers(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVo valueObject) { return extractPendingTransfers(domainFactory, valueObject, new HashMap()); } public static ims.core.admin.pas.domain.objects.PendingTransfers extractPendingTransfers(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PendingTransfersVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_PendingTransfers(); ims.core.admin.pas.domain.objects.PendingTransfers domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.admin.pas.domain.objects.PendingTransfers)domMap.get(valueObject); } // ims.core.vo.PendingTransfersVo ID_PendingTransfers field is unknown domainObject = new ims.core.admin.pas.domain.objects.PendingTransfers(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_PendingTransfers()); if (domMap.get(key) != null) { return (ims.core.admin.pas.domain.objects.PendingTransfers)domMap.get(key); } domainObject = (ims.core.admin.pas.domain.objects.PendingTransfers) domainFactory.getDomainObject(ims.core.admin.pas.domain.objects.PendingTransfers.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_PendingTransfers()); domainObject.setInpatientEpisode(ims.core.vo.domain.InpatientEpisodeForTransfersVoAssembler.extractInpatientEpisode(domainFactory, valueObject.getInpatientEpisode(), domMap)); domainObject.setDestinationWard(ims.core.vo.domain.LocationLiteVoAssembler.extractLocation(domainFactory, valueObject.getDestinationWard(), domMap)); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value3 = null; if ( null != valueObject.getWardType() ) { value3 = domainFactory.getLookupInstance(valueObject.getWardType().getID()); } domainObject.setWardType(value3); ims.framework.utils.DateTime dateTime4 = valueObject.getTransferRequestDateTime(); java.util.Date value4 = null; if ( dateTime4 != null ) { value4 = dateTime4.getJavaDate(); } domainObject.setTransferRequestDateTime(value4); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value5 = null; if ( null != valueObject.getCurrentStatus() ) { value5 = domainFactory.getLookupInstance(valueObject.getCurrentStatus().getID()); } domainObject.setCurrentStatus(value5); return domainObject; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/beans/ServiceFunctionVoBean.java
4540
//############################################################################# //# # //# 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.core.vo.beans; public class ServiceFunctionVoBean extends ims.vo.ValueObjectBean { public ServiceFunctionVoBean() { } public ServiceFunctionVoBean(ims.core.vo.ServiceFunctionVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.function = vo.getFunction() == null ? null : (ims.vo.LookupInstanceBean)vo.getFunction().getBean(); this.service = vo.getService() == null ? null : (ims.core.vo.beans.ServiceShortVoBean)vo.getService().getBean(); this.taxonomymap = vo.getTaxonomyMap() == null ? null : vo.getTaxonomyMap().getBeanCollection(); this.isactive = vo.getIsActive(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.ServiceFunctionVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.function = vo.getFunction() == null ? null : (ims.vo.LookupInstanceBean)vo.getFunction().getBean(); this.service = vo.getService() == null ? null : (ims.core.vo.beans.ServiceShortVoBean)vo.getService().getBean(map); this.taxonomymap = vo.getTaxonomyMap() == null ? null : vo.getTaxonomyMap().getBeanCollection(); this.isactive = vo.getIsActive(); } public ims.core.vo.ServiceFunctionVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.core.vo.ServiceFunctionVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.core.vo.ServiceFunctionVo vo = null; if(map != null) vo = (ims.core.vo.ServiceFunctionVo)map.getValueObject(this); if(vo == null) { vo = new ims.core.vo.ServiceFunctionVo(); 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.vo.LookupInstanceBean getFunction() { return this.function; } public void setFunction(ims.vo.LookupInstanceBean value) { this.function = value; } public ims.core.vo.beans.ServiceShortVoBean getService() { return this.service; } public void setService(ims.core.vo.beans.ServiceShortVoBean value) { this.service = value; } public ims.core.vo.beans.TaxonomyMapBean[] getTaxonomyMap() { return this.taxonomymap; } public void setTaxonomyMap(ims.core.vo.beans.TaxonomyMapBean[] value) { this.taxonomymap = value; } public Boolean getIsActive() { return this.isactive; } public void setIsActive(Boolean value) { this.isactive = value; } private Integer id; private int version; private ims.vo.LookupInstanceBean function; private ims.core.vo.beans.ServiceShortVoBean service; private ims.core.vo.beans.TaxonomyMapBean[] taxonomymap; private Boolean isactive; }
agpl-3.0
openhealthcare/openMAXIMS
openmaxims_workspace/Emergency/src/ims/emergency/forms/bedawaitingbedavailable/GlobalContext.java
5120
//############################################################################# //# # //# 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.emergency.forms.bedawaitingbedavailable; 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); Emergency = new EmergencyContext(context); Core = new CoreContext(context); } public final class EmergencyContext implements Serializable { private static final long serialVersionUID = 1L; private EmergencyContext(ims.framework.Context context) { this.context = context; } public boolean getTrackingIsNotNull() { return !cx_EmergencyTracking.getValueIsNull(context); } public ims.emergency.vo.TrackingRefVo getTracking() { return (ims.emergency.vo.TrackingRefVo)cx_EmergencyTracking.getValue(context); } private ims.framework.ContextVariable cx_EmergencyTracking = new ims.framework.ContextVariable("Emergency.Tracking", "_cv_Emergency.Tracking"); public boolean getTrackingAttendanceStatusIsNotNull() { return !cx_EmergencyTrackingAttendanceStatus.getValueIsNull(context); } public ims.emergency.vo.TrackingAttendanceStatusVo getTrackingAttendanceStatus() { return (ims.emergency.vo.TrackingAttendanceStatusVo)cx_EmergencyTrackingAttendanceStatus.getValue(context); } public void setTrackingAttendanceStatus(ims.emergency.vo.TrackingAttendanceStatusVo value) { cx_EmergencyTrackingAttendanceStatus.setValue(context, value); } private ims.framework.ContextVariable cx_EmergencyTrackingAttendanceStatus = new ims.framework.ContextVariable("Emergency.TrackingAttendanceStatus", "_cv_Emergency.TrackingAttendanceStatus"); private ims.framework.Context context; } public final class CoreContext implements Serializable { private static final long serialVersionUID = 1L; private CoreContext(ims.framework.Context context) { this.context = context; } public boolean getPatientShortIsNotNull() { return !cx_CorePatientShort.getValueIsNull(context); } public ims.core.vo.PatientShort getPatientShort() { return (ims.core.vo.PatientShort)cx_CorePatientShort.getValue(context); } private ims.framework.ContextVariable cx_CorePatientShort = new ims.framework.ContextVariable("Core.PatientShort", "_cvp_Core.PatientShort"); public boolean getCurrentCareContextIsNotNull() { return !cx_CoreCurrentCareContext.getValueIsNull(context); } public ims.core.vo.CareContextShortVo getCurrentCareContext() { return (ims.core.vo.CareContextShortVo)cx_CoreCurrentCareContext.getValue(context); } private ims.framework.ContextVariable cx_CoreCurrentCareContext = new ims.framework.ContextVariable("Core.CurrentCareContext", "_cvp_Core.CurrentCareContext"); public boolean getEpisodeofCareShortIsNotNull() { return !cx_CoreEpisodeofCareShort.getValueIsNull(context); } public ims.core.vo.EpisodeofCareShortVo getEpisodeofCareShort() { return (ims.core.vo.EpisodeofCareShortVo)cx_CoreEpisodeofCareShort.getValue(context); } private ims.framework.ContextVariable cx_CoreEpisodeofCareShort = new ims.framework.ContextVariable("Core.EpisodeofCareShort", "_cvp_Core.EpisodeofCareShort"); private ims.framework.Context context; } public EmergencyContext Emergency; public CoreContext Core; }
agpl-3.0
skyvers/wildcat
skyve-ejb/src/test/java/modules/test/ArcTests.java
3921
package modules.test; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.skyve.domain.messages.DomainException; import org.skyve.util.Util; import modules.test.domain.AnyDerived1; import modules.test.domain.AnyDerived2; import modules.test.domain.ArcOneToMany; import modules.test.domain.ArcOneToOne; /** * The arc tests fail as the class attributes of the any and many-to-any tags don't map correctly to * the entity-name s used in the current domain generation. * * @author mike * */ public class ArcTests extends AbstractSkyveTest { /** * This just wont work... * * @throws Exception */ @Test(expected = DomainException.class) public void testOneToManyPersist() throws Exception { ArcOneToMany test = Util.constructRandomInstance(u, m, ao2m, 0); test = p.save(test); test.getArcs().add(p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0))); test.getArcs().add(p.save((AnyDerived2) Util.constructRandomInstance(u, m, ad2, 0))); test = p.save(test); p.evictAllCached(); test = p.retrieve(ao2m, test.getBizId()); } /** * This works as long as the arc is saved first * * @throws Exception */ @Test @Ignore // One to one arcs are screwed public void testOneToOnePersist() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); test = p.save(test); test.setArc(p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0))); test = p.save(test); p.evictAllCached(); test = p.retrieve(ao2o, test.getBizId()); Assert.assertNotNull(test.getArc()); } /** * This doesn't work as the arc was not saved first * * @throws Exception */ @Test(expected = DomainException.class) public void testOneToOnePersistArcTransient() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); test = p.save(test); test.setArc((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0)); test = p.save(test); p.evictAllCached(); test = p.retrieve(ao2o, test.getBizId()); Assert.assertNotNull(test.getArc()); } /** * This works when the arc is saved first * * @throws Exception */ @Test @Ignore // One to one arcs are screwed public void testOneToOnePersistPartlyTransient() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); test.setArc(p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0))); test = p.save(test); p.evictAllCached(); test = p.retrieve(ao2o, test.getBizId()); Assert.assertNotNull(test.getArc()); } /** * This doesn't work when everything is transient - arc should be saved first * * @throws Exception */ @Test(expected = DomainException.class) public void testOneToOnePersistFullyTransient() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); test.setArc((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0)); test = p.save(test); } @Test public void testOneToOneUpsertInsert() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); test.setArc(p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0))); p.upsertBeanTuple(test); p.evictAllCached(); test = p.retrieve(ao2o, test.getBizId()); Assert.assertNotNull(test.getArc()); } @Test @Ignore // One to one arcs are screwed public void testOneToOneUpsertUpdate() throws Exception { ArcOneToOne test = Util.constructRandomInstance(u, m, ao2o, 0); AnyDerived1 arc1 = p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0)); AnyDerived1 arc2 = p.save((AnyDerived1) Util.constructRandomInstance(u, m, ad1, 0)); test.setArc(arc1); test = p.save(test); test.setArc(arc2); p.upsertBeanTuple(test); p.evictAllCached(); test = p.retrieve(ao2o, test.getBizId()); Assert.assertNotNull(test.getArc()); Assert.assertEquals(arc2.getBizId(), test.getArc().getBizId()); } }
lgpl-2.1
it-tavis/opencms-core
src/org/opencms/ade/containerpage/shared/rpc/I_CmsContainerpageService.java
14846
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, 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.ade.containerpage.shared.rpc; import org.opencms.ade.containerpage.shared.CmsCntPageData; import org.opencms.ade.containerpage.shared.CmsContainer; import org.opencms.ade.containerpage.shared.CmsContainerElement; import org.opencms.ade.containerpage.shared.CmsContainerElementData; import org.opencms.ade.containerpage.shared.CmsCreateElementData; import org.opencms.ade.containerpage.shared.CmsGroupContainer; import org.opencms.ade.containerpage.shared.CmsGroupContainerSaveResult; import org.opencms.ade.containerpage.shared.CmsInheritanceContainer; import org.opencms.ade.containerpage.shared.CmsRemovedElementStatus; import org.opencms.gwt.CmsRpcException; import org.opencms.util.CmsUUID; import java.util.Collection; import java.util.List; import java.util.Map; import com.google.gwt.user.client.rpc.RemoteService; /** * The RPC service interface used by the container-page editor.<p> * * @since 8.0.0 */ public interface I_CmsContainerpageService extends RemoteService { /** * Adds an element specified by it's id to the favorite list.<p> * * @param clientId the element id * * @throws CmsRpcException if something goes wrong processing the request */ void addToFavoriteList(String clientId) throws CmsRpcException; /** * Adds an element specified by it's id to the recent list.<p> * * @param clientId the element id * * @throws CmsRpcException if something goes wrong processing the request */ void addToRecentList(String clientId) throws CmsRpcException; /** * Check if a page or its elements have been changed.<p> * * @param structureId the structure id of the resource * @param detailContentId the structure id of the detail content (may be null) * * @return true if there were changes in the page or its elements * * @throws CmsRpcException if the RPC call fails */ boolean checkContainerpageOrElementsChanged(CmsUUID structureId, CmsUUID detailContentId) throws CmsRpcException; /** * To create a new element of the given type this method will check if a model resource needs to be selected, otherwise creates the new element. * Returns a bean containing either the new element data or a list of model resources to select.<p> * * @param pageStructureId the container page structure id * @param clientId the client id of the new element (this will be the structure id of the configured new resource) * @param resourceType the resource tape of the new element * @param locale the content locale * * @return the bean containing either the new element data or a list of model resources to select * * @throws CmsRpcException if something goes wrong processing the request */ CmsCreateElementData checkCreateNewElement( CmsUUID pageStructureId, String clientId, String resourceType, String locale) throws CmsRpcException; /** * Checks whether the Acacia widgets are available for all fields of the content.<p> * * @param structureId the structure id of the content * @return true if Acacia widgets are available for all fields * * @throws CmsRpcException if something goes wrong */ boolean checkNewWidgetsAvailable(CmsUUID structureId) throws CmsRpcException; /** * Creates a new element with a given model element and returns the copy'S structure id.<p> * * @param pageId the container page id * @param originalElementId the model element id * @return the structure id of the copy * * @throws CmsRpcException if something goes wrong */ CmsUUID copyElement(CmsUUID pageId, CmsUUID originalElementId) throws CmsRpcException; /** * Creates a new element of the given type and returns the new element data containing structure id and site path.<p> * * @param pageStructureId the container page structure id * @param clientId the client id of the new element (this will be the structure id of the configured new resource) * @param resourceType the resource tape of the new element * @param modelResourceStructureId the model resource structure id * @param locale the content locale * * @return the new element data containing structure id and site path * * @throws CmsRpcException if something goes wrong processing the request */ CmsContainerElement createNewElement( CmsUUID pageStructureId, String clientId, String resourceType, CmsUUID modelResourceStructureId, String locale) throws CmsRpcException; /** * This method is used for serialization purposes only.<p> * * @return element info */ CmsContainerElement getElementInfo(); /** * Returns container element data by client id.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param reqParams optional request parameters * @param clientIds the requested element id's * @param containers the containers of the current page * @param locale the content locale * * @return the element data * * @throws CmsRpcException if something goes wrong processing the request */ Map<String, CmsContainerElementData> getElementsData( CmsUUID pageStructureId, CmsUUID detailContentId, String reqParams, Collection<String> clientIds, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Gets the element data for an id and a map of settings.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param reqParams optional request parameters * @param clientId the requested element ids * @param settings the settings for which the element data should be loaded * @param containers the containers of the current page * @param locale the content locale * * @return the element data * * @throws CmsRpcException if something goes wrong processing the request */ CmsContainerElementData getElementWithSettings( CmsUUID pageStructureId, CmsUUID detailContentId, String reqParams, String clientId, Map<String, String> settings, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Returns the container element data of the favorite list.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param containers the containers of the current page * @param locale the content locale * * @return the favorite list element data * * @throws CmsRpcException if something goes wrong processing the request */ List<CmsContainerElementData> getFavoriteList( CmsUUID pageStructureId, CmsUUID detailContentId, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Returns new container element data for the given resource type name.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param reqParams optional request parameters * @param resourceType the requested element resource type name * @param containers the containers of the current page * @param locale the content locale * * @return the element data * * @throws CmsRpcException if something goes wrong processing the request */ CmsContainerElementData getNewElementData( CmsUUID pageStructureId, CmsUUID detailContentId, String reqParams, String resourceType, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Returns the container element data of the recent list.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param containers the containers of the current page * @param locale the content locale * * @return the recent list element data * * @throws CmsRpcException if something goes wrong processing the request */ List<CmsContainerElementData> getRecentList( CmsUUID pageStructureId, CmsUUID detailContentId, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Gets the status of a removed element.<p> * * @param id the client id of the removed element * @param containerpageId the id of the page which should be excluded from the relation check, or null if no page should be excluded * * @return the status of the removed element * * @throws CmsRpcException */ CmsRemovedElementStatus getRemovedElementStatus(String id, CmsUUID containerpageId) throws CmsRpcException; /** * Returns the initialization data.<p> * * @return the initialization data * * @throws CmsRpcException if something goes wrong */ CmsCntPageData prefetch() throws CmsRpcException; /** * Saves the container-page.<p> * * @param pageStructureId the container page structure id * @param containers the container-page's containers * @param locale the content locale * * @throws CmsRpcException if something goes wrong processing the request */ void saveContainerpage(CmsUUID pageStructureId, List<CmsContainer> containers, String locale) throws CmsRpcException; /** * Saves the detail containers.<p> * * @param detailContainerResource the detail container resource path * @param containers the container-page's containers * @param locale the content locale * * @throws CmsRpcException if something goes wrong processing the request */ void saveDetailContainers(String detailContainerResource, List<CmsContainer> containers, String locale) throws CmsRpcException; /** * Saves the favorite list.<p> * * @param clientIds favorite list element id's * * @throws CmsRpcException if something goes wrong processing the request */ void saveFavoriteList(List<String> clientIds) throws CmsRpcException; /** * Saves a group-container element.<p> * * @param pageStructureId the container page structure id * @param detailContentId the detail content structure id * @param reqParams optional request parameters * @param groupContainer the group-container to save * @param containers the containers of the current page * @param locale the content locale * * @return the data of the saved group container * * @throws CmsRpcException if something goes wrong processing the request */ CmsGroupContainerSaveResult saveGroupContainer( CmsUUID pageStructureId, CmsUUID detailContentId, String reqParams, CmsGroupContainer groupContainer, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Saves an inheritance container.<p> * * @param pageStructureId the current page's structure id * @param detailContentId the detail content structure id * @param inheritanceContainer the inheritance container to save * @param containers the containers of the current page * @param locale the requested locale * * @return the element data of the saved container * * @throws CmsRpcException if something goes wrong */ Map<String, CmsContainerElementData> saveInheritanceContainer( CmsUUID pageStructureId, CmsUUID detailContentId, CmsInheritanceContainer inheritanceContainer, Collection<CmsContainer> containers, String locale) throws CmsRpcException; /** * Saves the recent list.<p> * * @param clientIds recent list element id's * * @throws CmsRpcException if something goes wrong processing the request */ void saveRecentList(List<String> clientIds) throws CmsRpcException; /** * Enables or disables editing for small elements on page load.<p> * * @param editSmallElements the defautl setting for the small element editability * * @throws CmsRpcException if something goes wrong */ void setEditSmallElements(boolean editSmallElements) throws CmsRpcException; /** * Saves the container-page in a synchronized RPC call.<p> * * @param pageStructureId the container page structure id * @param containers the container-page's containers * @param locale the content locale * * @throws CmsRpcException if something goes wrong processing the request */ void syncSaveContainerpage(CmsUUID pageStructureId, List<CmsContainer> containers, String locale) throws CmsRpcException; /** * Saves the detail containers.<p> * * @param detailContainerResource the detail container resource path * @param containers the container-page's containers * @param locale the content locale * * @throws CmsRpcException if something goes wrong processing the request */ void syncSaveDetailContainers(String detailContainerResource, List<CmsContainer> containers, String locale) throws CmsRpcException; }
lgpl-2.1
gwenniger/joshua
src/joshua/decoder/ff/tm/hash_based/ExtensionIterator.java
1106
package joshua.decoder.ff.tm.hash_based; import java.util.HashMap; import java.util.Iterator; public class ExtensionIterator implements Iterator<Integer> { private Iterator<Integer> iterator; private boolean terminal; private boolean done; private int next; public ExtensionIterator(HashMap<Integer, ?> map, boolean terminal) { this.terminal = terminal; done = false; if (map == null) { done = true; } else { this.iterator = map.keySet().iterator(); forward(); } } private void forward() { if (done) return; while (iterator.hasNext()) { int candidate = iterator.next(); if ((terminal && candidate > 0) || (!terminal && candidate < 0)) { next = candidate; return; } } done = true; } @Override public boolean hasNext() { return !done; } @Override public Integer next() { if (done) throw new RuntimeException(); int consumed = next; forward(); return consumed; } @Override public void remove() { throw new UnsupportedOperationException(); } }
lgpl-2.1
joewiz/exist
test/src/org/exist/collections/triggers/XQueryTriggerTest.java
30169
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2016 The eXist Project * http://exist-db.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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.collections.triggers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.net.URISyntaxException; import javax.xml.transform.OutputKeys; import org.exist.TestUtils; import org.exist.test.ExistXmldbEmbeddedServer; import org.exist.util.Base64Decoder; import org.exist.xmldb.CollectionManagementServiceImpl; import org.exist.xmldb.EXistResource; import org.exist.xmldb.IndexQueryService; import org.exist.xmldb.XmldbURI; import org.junit.*; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.BinaryResource; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import org.xmldb.api.modules.XPathQueryService; import org.xmldb.api.modules.XUpdateQueryService; /** class under test : {@link XQueryTrigger} * @author Pierrick Brihaye <pierrick.brihaye@free.fr> */ public class XQueryTriggerTest { @ClassRule public static final ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(false, true); private final static String TEST_COLLECTION = "testXQueryTrigger"; /** XQuery module implementing the trigger under test */ private final static String MODULE_NAME = "XQueryTriggerLogger.xqm"; private final static String COLLECTION_CONFIG = "<exist:collection xmlns:exist='http://exist-db.org/collection-config/1.0'>" + " <exist:triggers>" + " <exist:trigger class='org.exist.collections.triggers.XQueryTrigger'>" + " <exist:parameter " + " name='url' " + " value='" +XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION + "/" + MODULE_NAME + "' " + " />" + " </exist:trigger>" + " </exist:triggers>" + "</exist:collection>"; private final static String EMPTY_COLLECTION_CONFIG = "<exist:collection xmlns:exist='http://exist-db.org/collection-config/1.0'>" + "</exist:collection>"; private final static String DOCUMENT_NAME = "test.xml"; private final static String DOCUMENT_CONTENT = "<test>" + "<item id='1'><price>5.6</price><stock>22</stock></item>" + "<item id='2'><price>7.4</price><stock>43</stock></item>" + "<item id='3'><price>18.4</price><stock>5</stock></item>" + "<item id='4'><price>65.54</price><stock>16</stock></item>" + "</test>"; /** XUpdate document update specification */ private final static String DOCUMENT_UPDATE = "<xu:modifications xmlns:xu='http://www.xmldb.org/xupdate' version='1.0'>" + "<!-- special offer -->" + "<xu:update select='/test/item[@id = \"3\"]/price'>" + "15.2"+ "</xu:update>" + "</xu:modifications>"; // private final static String MODIFIED_DOCUMENT_CONTENT = // DOCUMENT_CONTENT.replaceAll("<price>18.4</price>", "<price>15.2</price>"); private final static String BINARY_DOCUMENT_NAME = "1x1.gif"; private final static String BINARY_DOCUMENT_CONTENT = "R0lGODlhAQABAIABAAD/AP///yH+EUNyZWF0ZWQgd2l0aCBHSU1QACwAAAAAAQABAAACAkQBADs="; /** "log" document that will be updated by the trigger */ private final static String LOG_NAME = "XQueryTriggerLog.xml"; /** initial content of the "log" document */ private final static String EMPTY_LOG = "<events/>"; /** XQuery module implementing the trigger under test; * the log() XQuery function will add an <event> element inside <events> element */ private final static String MODULE = "module namespace trigger='http://exist-db.org/xquery/trigger'; " + "import module namespace xmldb='http://exist-db.org/xquery/xmldb'; " + "import module namespace util='http://exist-db.org/xquery/util'; " + "" + "declare function trigger:logEvent($type as xs:string, $event as xs:string, $objectType as xs:string, $uri as xs:anyURI) {" + "let $log := util:log(\"INFO\", concat($type, ' ', $event, ' ', $objectType, ' ', $uri))" + "let $isLoggedIn := xmldb:login('" + XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION + "', 'admin', '') return " + "xmldb:update(" + "'" + XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION + "', " + "<xu:modifications xmlns:xu='http://www.xmldb.org/xupdate' version='1.0'>" + "<xu:append select='/events'>" + "<xu:element name='event'>" + "<xu:attribute name='time'>{current-dateTime()}</xu:attribute>" + "<xu:attribute name='type'>{$type}</xu:attribute>" + "<xu:attribute name='event'>{$event}</xu:attribute>" + "<xu:attribute name='object-type'>{$objectType}</xu:attribute>" + "<xu:element name='uri'>{$uri}</xu:element>" + "</xu:element>" + "</xu:append>" + "</xu:modifications>" + ")" + "};" + "" + "declare function trigger:before-create-collection($uri as xs:anyURI) {" + "trigger:logEvent('before', 'create', 'collection', $uri)" + "};" + "" + "declare function trigger:after-create-collection($uri as xs:anyURI) {" + "trigger:logEvent('after', 'create', 'collection', $uri)" + "};" + "" + "declare function trigger:before-update-collection($uri as xs:anyURI) {" + "trigger:logEvent('before', 'update', 'collection', $uri)" + "};" + "" + "declare function trigger:after-update-collection($uri as xs:anyURI) {" + "trigger:logEvent('after', 'update', 'collection', $uri)" + "};" + "" + "declare function trigger:before-copy-collection($uri as xs:anyURI, $new-uri as xs:anyURI) {" + "trigger:logEvent('before', 'copy', 'collection', $uri)" + "};" + "" + "declare function trigger:after-copy-collection($new-uri as xs:anyURI, $uri as xs:anyURI) {" + "trigger:logEvent('after', 'copy', 'collection', $new-uri)" + "};" + "" + "declare function trigger:before-move-collection($uri as xs:anyURI, $new-uri as xs:anyURI) {" + "trigger:logEvent('before', 'move', 'collection', $uri)" + "};" + "" + "declare function trigger:after-move-collection($new-uri as xs:anyURI, $uri as xs:anyURI) {" + "trigger:logEvent('after', 'move', 'collection', $new-uri)" + "};" + "" + "declare function trigger:before-delete-collection($uri as xs:anyURI) {" + "trigger:logEvent('before', 'delete', 'collection', $uri)" + "};" + "" + "declare function trigger:after-delete-collection($uri as xs:anyURI) {" + "trigger:logEvent('after', 'delete', 'collection', $uri)" + "};" + "" + //DOCUMENT EVENTS "declare function trigger:before-create-document($uri as xs:anyURI) {" + "trigger:logEvent('before', 'create', 'document', $uri)" + "};" + "" + "declare function trigger:after-create-document($uri as xs:anyURI) {" + "trigger:logEvent('after', 'create', 'document', $uri)" + "};" + "" + "declare function trigger:before-update-document($uri as xs:anyURI) {" + "trigger:logEvent('before', 'update', 'document', $uri)" + "};" + "" + "declare function trigger:after-update-document($uri as xs:anyURI) {" + "trigger:logEvent('after', 'update', 'document', $uri)" + "};" + "" + "declare function trigger:before-copy-document($uri as xs:anyURI, $new-uri as xs:anyURI) {" + "trigger:logEvent('before', 'copy', 'document', $uri)" + "};" + "" + "declare function trigger:after-copy-document($new-uri as xs:anyURI, $uri as xs:anyURI) {" + "trigger:logEvent('after', 'copy', 'document', $new-uri)" + "};" + "" + "declare function trigger:before-move-document($uri as xs:anyURI, $new-uri as xs:anyURI) {" + "trigger:logEvent('before', 'move', 'document', $uri)" + "};" + "" + "declare function trigger:after-move-document($new-uri as xs:anyURI, $uri as xs:anyURI) {" + "trigger:logEvent('after', 'move', 'document', $new-uri)" + "};" + "" + "declare function trigger:before-delete-document($uri as xs:anyURI) {" + "trigger:logEvent('before', 'delete', 'document', $uri)" + "};" + "" + "declare function trigger:after-delete-document($uri as xs:anyURI) {" + "trigger:logEvent('after', 'delete', 'document', $uri)" + "};" + ""; private static Collection testCollection; /** XQuery module implementing the invalid trigger under test */ private final static String INVALID_MODULE = "module namespace log='log'; " + "import module namespace xmldb='http://exist-db.org/xquery/xmldb'; " + "declare variable $log:type external;" + "declare variable $log:collection external;" + "declare variable $log:uri external;" + "declare variable $log:event external;" + "declare function log:log($id as xs:string?) {" + " undeclared-function-causes-trigger-error()" + "};"; private final static String EVENTS = "/events/event"; private final static String BEFORE = EVENTS+"[@type = 'before']"; private final static String AFTER = EVENTS+"[@type = 'after']"; private final static String CREATE = "[@event = 'create']"; private final static String UPDATE = "[@event = 'update']"; private final static String COPY = "[@event = 'copy']"; private final static String MOVE = "[@event = 'move']"; private final static String DELETE = "[@event = 'delete']"; private final static String COLLECTION = "[@object-type = 'collection']"; private final static String DOCUMENT = "[@object-type = 'document']"; private final static String testCollectionURI = "[uri/text() = '/db/testXQueryTrigger/test']"; private final static String testDstCollectionURI = "[uri/text() = '/db/testXQueryTrigger/test-dst']"; private final static String testDstTestCollectionURI = "[uri/text() = '/db/testXQueryTrigger/test-dst/test']"; private final static String documentURI = "[uri/text() = '/db/testXQueryTrigger/test.xml']"; private final static String binaryURI = "[uri/text() = '/db/testXQueryTrigger/1x1.gif']"; /** just create the test collection */ @BeforeClass public static void createTestCollection() throws ClassNotFoundException, IllegalAccessException, InstantiationException, XMLDBException { final CollectionManagementService service = (CollectionManagementService) existEmbeddedServer.getRoot() .getService("CollectionManagementService", "1.0"); testCollection = service.createCollection(TEST_COLLECTION); assertNotNull(testCollection); TestUtils.cleanupDB(); } @AfterClass public static void cleanup() throws XMLDBException { TestUtils.cleanupDB(); testCollection = null; } /** create "log" document that will be updated by the trigger, * and store the XQuery module implementing the trigger under test */ @Before public void storePreliminaryDocuments() throws XMLDBException { TestUtils.cleanupDB(); final CollectionManagementService service = (CollectionManagementService) existEmbeddedServer.getRoot() .getService("CollectionManagementService", "1.0"); testCollection = service.createCollection(TEST_COLLECTION); assertNotNull(testCollection); final XMLResource doc = (XMLResource) testCollection.createResource(LOG_NAME, "XMLResource" ); doc.setContent(EMPTY_LOG); testCollection.storeResource(doc); final BinaryResource module = (BinaryResource) testCollection.createResource(MODULE_NAME, "BinaryResource" ); ((EXistResource)module).setMimeType("application/xquery"); module.setContent(MODULE.getBytes()); testCollection.storeResource(module); } /** test a trigger fired by storing a new Document */ @Test public void documentCreate() throws XMLDBException { // configure the Collection with the trigger under test final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); // this will fire the trigger final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource" ); doc.setContent(DOCUMENT_CONTENT); testCollection.storeResource(doc); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService service = (XPathQueryService) testCollection.getService("XPathQueryService", "1.0"); ResourceSet result = service.query(BEFORE+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(AFTER+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(EVENTS); assertEquals(2, result.getSize()); //TODO: document itself // result = service.query(afterCreate+objDocument+documentURI+"/document/test"); // assertEquals(1, result.getSize()); // assertXMLEqual(DOCUMENT_CONTENT, ((XMLResource)result.getResource(0)).getContent().toString()); } /** test a trigger fired by a Document Update */ @Test public void documentUpdate() throws XMLDBException { final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource" ); doc.setContent(DOCUMENT_CONTENT); testCollection.storeResource(doc); //TODO : trigger UPDATE events ! final XUpdateQueryService update = (XUpdateQueryService) testCollection.getService("XUpdateQueryService", "1.0"); update.updateResource(DOCUMENT_NAME, DOCUMENT_UPDATE); idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService service = (XPathQueryService) testCollection .getService("XPathQueryService", "1.0"); // this is necessary to compare with MODIFIED_DOCUMENT_CONTENT ; TODO better compare with XML diff tool service.setProperty(OutputKeys.INDENT, "no"); ResourceSet result = service.query(BEFORE+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(AFTER+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(BEFORE+UPDATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(AFTER+UPDATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(EVENTS); assertEquals(4, result.getSize()); //TODO: document itself // result = service.query("/events/event[@id = 'trigger2']/document/test"); // assertEquals(2, result.getSize()); // assertXMLEqual(DOCUMENT_CONTENT, result.getResource(0).getContent().toString()); // assertXMLEqual(MODIFIED_DOCUMENT_CONTENT, result.getResource(1).getContent().toString()); } /** test a trigger fired by a Document Delete */ @Test public void documentDelete() throws XMLDBException { final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource" ); doc.setContent(DOCUMENT_CONTENT); testCollection.storeResource(doc); testCollection.removeResource(testCollection.getResource(DOCUMENT_NAME)); idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService service = (XPathQueryService) testCollection .getService("XPathQueryService", "1.0"); service.setProperty(OutputKeys.INDENT, "no"); ResourceSet result = service.query(BEFORE+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(AFTER+CREATE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(BEFORE+DELETE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(AFTER+DELETE+DOCUMENT+documentURI); assertEquals(1, result.getSize()); result = service.query(EVENTS); assertEquals(4, result.getSize()); //TODO: document itself // result = service.query("/events/event[@id = 'trigger3']/document/test"); // assertEquals(1, result.getSize()); // assertXMLEqual(MODIFIED_DOCUMENT_CONTENT, result.getResource(0).getContent().toString()); } /** test a trigger fired by creating a new Binary Document */ @Test public void documentBinaryCreate() throws XMLDBException { // configure the Collection with the trigger under test final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); // this will fire the trigger final Resource res = testCollection.createResource(BINARY_DOCUMENT_NAME, "BinaryResource"); Base64Decoder dec = new Base64Decoder(); dec.translate(BINARY_DOCUMENT_CONTENT); res.setContent(dec.getByteArray()); testCollection.storeResource(res); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService service = (XPathQueryService) testCollection.getService("XPathQueryService", "1.0"); //TODO : understand why it is necessary ! service.setProperty(OutputKeys.INDENT, "no"); ResourceSet result = service.query(BEFORE+CREATE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(AFTER+CREATE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(EVENTS); assertEquals(2, result.getSize()); //TODO: document itself // result = service.query("/events/event[@id = 'trigger1'][@type = 'finish'][collection = '" + DBBroker.ROOT_COLLECTION + "/" + TEST_COLLECTION + "'][uri = '" + DBBroker.ROOT_COLLECTION + "/" + TEST_COLLECTION + "/" + BINARY_DOCUMENT_NAME + "'][event = 'CREATE-DOCUMENT']/document"); // assertEquals(1, result.getSize()); // assertEquals("<document>" + BINARY_DOCUMENT_CONTENT + "</document>", result.getResource(0).getContent().toString()); } /** test a trigger fired by a Binary Document Delete */ @Test public void documentBinaryDelete() throws XMLDBException { final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); // this will fire the trigger final Resource res = testCollection.createResource(BINARY_DOCUMENT_NAME, "BinaryResource"); final Base64Decoder dec = new Base64Decoder(); dec.translate(BINARY_DOCUMENT_CONTENT); res.setContent(dec.getByteArray()); testCollection.storeResource(res); testCollection.removeResource(testCollection.getResource(BINARY_DOCUMENT_NAME)); idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService service = (XPathQueryService) testCollection .getService("XPathQueryService", "1.0"); service.setProperty(OutputKeys.INDENT, "no"); ResourceSet result = service.query(BEFORE+CREATE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(AFTER+CREATE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(BEFORE+DELETE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(AFTER+DELETE+DOCUMENT+binaryURI); assertEquals(1, result.getSize()); result = service.query(EVENTS); assertEquals(4, result.getSize()); //TODO: document itself // result = service.query("/events/event[@id = 'trigger3'][@type = 'prepare'][collection = '" + DBBroker.ROOT_COLLECTION + "/" + TEST_COLLECTION + "'][uri = '" + DBBroker.ROOT_COLLECTION + "/" + TEST_COLLECTION + "/" + BINARY_DOCUMENT_NAME + "'][event = 'DELETE-DOCUMENT']/document"); // assertEquals(1, result.getSize()); // assertEquals("<document>" + BINARY_DOCUMENT_CONTENT + "</document>", result.getResource(0).getContent().toString()); } /** test a trigger fired by a Collection manipulations */ @Test public void collectionCreate() throws XMLDBException { final IndexQueryService idxConf = (IndexQueryService) existEmbeddedServer.getRoot().getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final CollectionManagementService service = (CollectionManagementService) testCollection.getService("CollectionManagementService", "1.0"); final Collection collection = service.createCollection("test"); assertNotNull(collection); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); final XPathQueryService query = (XPathQueryService) existEmbeddedServer.getRoot().getService("XPathQueryService", "1.0"); ResourceSet result = query.query(BEFORE+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = query.query(AFTER+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = query.query(EVENTS); assertEquals(2, result.getSize()); } /** test a trigger fired by a Collection manipulations */ @Test public void collectionCopy() throws XMLDBException, URISyntaxException { final IndexQueryService idxConf = (IndexQueryService) existEmbeddedServer.getRoot().getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final XmldbURI srcURI = XmldbURI.xmldbUriFor("/db/testXQueryTrigger/test"); final XmldbURI dstURI = XmldbURI.xmldbUriFor("/db/testXQueryTrigger/test-dst"); final CollectionManagementServiceImpl service = (CollectionManagementServiceImpl) testCollection.getService("CollectionManagementService", "1.0"); final Collection src = service.createCollection("test"); assertNotNull(src); final Collection dst = service.createCollection("test-dst"); assertNotNull(dst); service.copy(srcURI, dstURI, null); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); ResourceSet result = existEmbeddedServer.executeQuery(BEFORE+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(BEFORE+CREATE+COLLECTION+testDstCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+CREATE+COLLECTION+testDstCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(BEFORE+COPY+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+COPY+COLLECTION+testDstTestCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(EVENTS); assertEquals(6, result.getSize()); } /** test a trigger fired by a Collection manipulations */ @Test public void collectionMove() throws XMLDBException, URISyntaxException { final IndexQueryService idxConf = (IndexQueryService) existEmbeddedServer.getRoot().getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final XmldbURI srcURI = XmldbURI.xmldbUriFor("/db/testXQueryTrigger/test"); final XmldbURI dstURI = XmldbURI.xmldbUriFor("/db/testXQueryTrigger/test-dst"); final CollectionManagementServiceImpl service = (CollectionManagementServiceImpl) testCollection.getService("CollectionManagementService", "1.0"); final Collection src = service.createCollection("test"); assertNotNull(src); final Collection dst = service.createCollection("test-dst"); assertNotNull(dst); service.move(srcURI, dstURI, null); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); ResourceSet result = existEmbeddedServer.executeQuery(BEFORE+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(BEFORE+CREATE+COLLECTION+testDstCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+CREATE+COLLECTION+testDstCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(BEFORE+MOVE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+MOVE+COLLECTION+testDstTestCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(EVENTS); assertEquals(6, result.getSize()); } /** test a trigger fired by a Collection manipulations */ @Test public void collectionDelete() throws XMLDBException { final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final CollectionManagementService service = (CollectionManagementService) testCollection.getService("CollectionManagementService", "1.0"); final Collection collection = service.createCollection("test"); assertNotNull(collection); service.removeCollection("test"); // remove the trigger for the Collection under test idxConf.configureCollection(EMPTY_COLLECTION_CONFIG); ResourceSet result = existEmbeddedServer.executeQuery(BEFORE+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+CREATE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(BEFORE+DELETE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery(AFTER+DELETE+COLLECTION+testCollectionURI); assertEquals(1, result.getSize()); result = existEmbeddedServer.executeQuery("/events/event"); assertEquals(4, result.getSize()); } @Test public void storeDocument_invalidTriggerForPrepare() throws XMLDBException { final BinaryResource invalidModule = (BinaryResource) testCollection.createResource(MODULE_NAME, "BinaryResource" ); ((EXistResource)invalidModule).setMimeType("application/xquery"); invalidModule.setContent(INVALID_MODULE.getBytes()); testCollection.storeResource(invalidModule); // configure the Collection with the trigger under test final IndexQueryService idxConf = (IndexQueryService)testCollection.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); final int max_store_attempts = 10; int count_prepare_exceptions = 0; for(int i = 0; i < max_store_attempts; i++) { try { // this will fire the trigger final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource"); doc.setContent(DOCUMENT_CONTENT); testCollection.storeResource(doc); } catch(XMLDBException xdbe) { if(xdbe.getCause() instanceof TriggerException) { if(xdbe.getCause().getMessage().equals(XQueryTrigger.PREPARE_EXCEPTION_MESSAGE)) { count_prepare_exceptions++; } } } } assertEquals(max_store_attempts, count_prepare_exceptions); } }
lgpl-2.1
mp911de/hibernate-ogm
core/src/test/java/org/hibernate/ogm/utils/InvokedOperationsLoggingDialect.java
9938
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.utils; import java.io.IOException; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.hibernate.ogm.datastore.spi.DatastoreProvider; import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateAssociationOperation; import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateTupleOperation; import org.hibernate.ogm.dialect.batch.spi.Operation; import org.hibernate.ogm.dialect.batch.spi.OperationsQueue; import org.hibernate.ogm.dialect.batch.spi.RemoveAssociationOperation; import org.hibernate.ogm.dialect.batch.spi.RemoveTupleOperation; import org.hibernate.ogm.dialect.impl.ForwardingGridDialect; import org.hibernate.ogm.dialect.query.spi.BackendQuery; import org.hibernate.ogm.dialect.query.spi.ClosableIterator; import org.hibernate.ogm.dialect.query.spi.QueryParameters; import org.hibernate.ogm.dialect.spi.AssociationContext; import org.hibernate.ogm.dialect.spi.GridDialect; import org.hibernate.ogm.dialect.spi.TupleContext; import org.hibernate.ogm.model.key.spi.AssociationKey; import org.hibernate.ogm.model.key.spi.EntityKey; import org.hibernate.ogm.model.key.spi.EntityKeyMetadata; import org.hibernate.ogm.model.key.spi.RowKey; import org.hibernate.ogm.model.spi.Association; import org.hibernate.ogm.model.spi.Tuple; import org.hibernate.ogm.util.impl.StringHelper; /** * A testing dialect wrapper which logs all the invoked {@link GridDialect} operations. * * @author Gunnar Morling */ public class InvokedOperationsLoggingDialect extends ForwardingGridDialect<Serializable> { /** * Path for the logging file to be created, relative to the current working directory. */ private static final String PATH = "invocations.log"; /** * Set to {@code true} if a log with all the ops and their parameters should be written into the file specified * above. */ private final boolean writeFile = false; private int opIndex = 0; private Path file; private final List<String> operations = new ArrayList<String>(); public InvokedOperationsLoggingDialect(DatastoreProvider provider) { super( TestHelper.getCurrentGridDialect( provider ) ); if ( writeFile ) { resetFile(); } } public List<String> getOperations() { return Collections.unmodifiableList( operations ); } public void reset() { operations.clear(); if ( writeFile ) { resetFile(); } } @Override public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Tuple tuple = super.getTuple( key, tupleContext ); log( "getTuple", key.toString(), tuple != null ? tuple.toString() : "null" ); return tuple; } @Override public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) { List<Tuple> tuples = super.getTuples( keys, tupleContext ); log( "getTuples", Arrays.toString( keys ), tuples != null ? tuples.toString() : "null" ); return tuples; } @Override public Tuple createTuple(EntityKey key, TupleContext tupleContext) { Tuple tuple = super.createTuple( key, tupleContext ); log( "createTuple", key.toString(), tuple != null ? tuple.toString() : "null" ); return tuple; } @Override public void insertOrUpdateTuple(EntityKey key, Tuple tuple, TupleContext tupleContext) { super.insertOrUpdateTuple( key, tuple, tupleContext ); log( "insertOrUpdateTuple", key.toString() + ", " + tuple.toString(), "VOID" ); } @Override public void removeTuple(EntityKey key, TupleContext tupleContext) { super.removeTuple( key, tupleContext ); log( "removeTuple", key.toString(), "VOID" ); } @Override public Association getAssociation(AssociationKey key, AssociationContext associationContext) { Association association = super.getAssociation( key, associationContext ); log( "getAssociation", key.toString(), toShortString( association ) ); return association; } @Override public Association createAssociation(AssociationKey key, AssociationContext associationContext) { Association association = super.createAssociation( key, associationContext ); log( "createAssociation", key.toString(), toShortString( association ) ); return association; } @Override public void insertOrUpdateAssociation(AssociationKey key, Association association, AssociationContext associationContext) { super.insertOrUpdateAssociation( key, association, associationContext ); log( "insertOrUpdateAssociation", key.toString() + ", " + toShortString( association ), "VOID" ); } @Override public void removeAssociation(AssociationKey key, AssociationContext associationContext) { super.removeAssociation( key, associationContext ); log( "removeAssociation", key.toString(), "VOID" ); } @Override public boolean updateTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, Tuple tuple, TupleContext tupleContext) { boolean success = super.updateTupleWithOptimisticLock( entityKey, oldLockState, tuple, tupleContext ); log( "updateTuple", entityKey.toString() + ", " + tuple.toString(), String.valueOf( success ) ); return success; } @Override public boolean removeTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, TupleContext tupleContext) { boolean success = super.removeTupleWithOptimisticLock( entityKey, oldLockState, tupleContext ); log( "removeTuple", entityKey.toString(), String.valueOf( success ) ); return success; } @Override public Tuple createTuple(EntityKeyMetadata entityKeyMetadata, TupleContext tupleContext) { return super.createTuple( entityKeyMetadata, tupleContext ); } @Override public void insertTuple(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext) { super.insertTuple( entityKeyMetadata, tuple, tupleContext ); log( "insertTuple", entityKeyMetadata.toString() + ", " + tuple.toString(), "VOID" ); } @Override public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<Serializable> query, QueryParameters queryParameters, TupleContext tupleContext) { ClosableIterator<Tuple> result = super.executeBackendQuery( query, queryParameters, tupleContext ); log( "executeBackendQuery", query.toString() + ", " + queryParameters.toString(), "tbd." ); return result; } @Override public void executeBatch(OperationsQueue queue) { OperationsQueue newQueue = new OperationsQueue(); StringBuilder sb = new StringBuilder(); if ( !queue.isClosed() ) { Operation operation = queue.poll(); while ( operation != null ) { newQueue.add( operation ); if ( operation instanceof InsertOrUpdateTupleOperation ) { sb.append( "InsertOrUpdateTuple(" ).append( ( (InsertOrUpdateTupleOperation) operation ).getEntityKey() ).append( " )" ); } else if ( operation instanceof RemoveTupleOperation ) { sb.append( "RemoveTuple(" ).append( ( (RemoveTupleOperation) operation ).getEntityKey() ).append( " )" ); } else if ( operation instanceof InsertOrUpdateAssociationOperation ) { sb.append( "InsertOrUpdateAssociation(" ).append( ( (InsertOrUpdateAssociationOperation) operation ).getAssociationKey() ).append( " )" ); } else if ( operation instanceof RemoveAssociationOperation ) { sb.append( "RemoveAssociation(" ).append( ( (RemoveAssociationOperation) operation ).getAssociationKey() ).append( " )" ); } operation = queue.poll(); if ( operation != null ) { sb.append( ", " ); } } } super.executeBatch( newQueue ); log( "executeBatch", sb.toString(), "VOID" ); } private void log(String operation, String parameters, String returnValue) { operations.add( operation ); if ( !writeFile ) { return; } String line = opIndex + "\t| " + operation + "\t| " + parameters + "\t| " + returnValue + System.lineSeparator(); try { Files.write( file, line.getBytes(), StandardOpenOption.APPEND ); } catch (IOException e) { throw new RuntimeException( e ); } opIndex++; } private String toShortString(Association association) { if ( association == null ) { return null; } StringBuilder sb = new StringBuilder( "Association["); Iterator<RowKey> rowKeys = association.getKeys().iterator(); while ( rowKeys.hasNext() ) { RowKey rowKey = rowKeys.next(); sb.append( toShortString( rowKey ) ).append( "=" ).append( toShortString( association.get( rowKey ) ) ); if ( rowKeys.hasNext() ) { sb.append( "," ).append( StringHelper.lineSeparator() ); } } sb.append( "]" ); return sb.toString(); } private String toShortString(RowKey rowKey) { final StringBuilder sb = new StringBuilder(); sb.append( "(" ); int i = 0; for ( String column : rowKey.getColumnNames() ) { sb.append( column ).append( "=" ).append( rowKey.getColumnValue( column ) ); i++; if ( i < rowKey.getColumnNames().length ) { sb.append( ", " ); } } sb.append( ")" ); return sb.toString(); } private String toShortString(Tuple tuple) { StringBuilder sb = new StringBuilder( "("); int i = 0; for ( String column : tuple.getColumnNames() ) { sb.append( column ).append( "=" ).append( tuple.get( column ) ); i++; if ( i < tuple.getColumnNames().size() ) { sb.append( ", " ); } } sb.append( ")" ); return sb.toString(); } private void resetFile() { file = Paths.get( PATH ); try { if ( !Files.exists( file ) ) { file = Files.createFile( file ); } Files.write( file, ( "#\top\tparameters\tresult" + System.lineSeparator() ).getBytes(), StandardOpenOption.TRUNCATE_EXISTING ); } catch (IOException e) { throw new RuntimeException( e ); } } }
lgpl-2.1
tomazzupan/wildfly
testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/console/XFrameOptionsHeaderTestCase.java
4731
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * 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 org.jboss.as.test.integration.management.console; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.http.Authentication; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests presence of X-Frame-Options header in response from management console * * @author Jan Kasik <jkasik@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient public class XFrameOptionsHeaderTestCase { private static final int MGMT_PORT = 9990; @ContainerResource private ManagementClient managementClient; @Test public void checkManagementConsoleForXFrameOptionsHeader() throws IOException, URISyntaxException { URL url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, "/console/App.html"); checkURLForHeader(url, "X-Frame-Options", "SAMEORIGIN"); } private void checkURLForHeader(URL url, String headerName, String expectedHeaderValue) throws URISyntaxException, IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(createCredentialsProvider(url)) .build()) { HttpContext httpContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet, httpContext); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Wrong response code: " + statusCode + " for url '" + url.toString() + "'.", HttpURLConnection.HTTP_OK, statusCode); Header[] headers = response.getHeaders(headerName); assertNotNull("Unexpected behaviour of HttpResponse#getHeaders() returned null!", headers); assertTrue("There is no '" + headerName + "' header present! Headers present: " + Arrays.toString(response.getAllHeaders()), headers.length > 0); for (Header header : headers) { if (header.getValue().equals(expectedHeaderValue)) { return; } } fail("No header '" + headerName + "' with value '" + expectedHeaderValue + "' found!"); } } private CredentialsProvider createCredentialsProvider(URL url) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm"), credentials); return credentialsProvider; } }
lgpl-2.1
shabanovd/exist
src/org/exist/scheduler/ScheduledJobInfo.java
4732
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2006 The eXist team * http://exist-db.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 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $Id$ */ package org.exist.scheduler; import java.util.Date; import org.quartz.CronTrigger; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleTrigger; import org.quartz.Trigger; /** * Information about a Scheduled Job. * * @author Adam Retter <adam.retter@googlemail.com> */ public class ScheduledJobInfo { public enum TriggerState { ERROR, NONE, NORMAL, PAUSED, BLOCKED, COMPLETE; } private final Scheduler scheduler; private final Trigger trigger; public ScheduledJobInfo(final Scheduler scheduler, final Trigger trigger) { this.scheduler = scheduler; this.trigger = trigger; } /** * Get the Job's Name. * * @return the Job's Name */ public String getName() { return trigger.getJobKey().getName(); } /** * Get the Job's Group. * * @return the Job's Group */ public String getGroup() { return trigger.getJobKey().getGroup(); } /** * Get the Name of the Job's Trigger. * * @return the Name of the Job's Trigger */ public String getTriggerName() { return trigger.getKey().getName(); } /** * Get the Start time of the Job. * * @return the Start time of the Job */ public Date getStartTime() { return trigger.getStartTime(); } /** * Get the End time of the Job. * * @return the End time of the Job, or null of the job is Scheduled forever */ public Date getEndTime() { return trigger.getEndTime(); } /** * Get the Previous Fired time of the Job. * * @return the time the Job was Previously Fired, or null if the job hasnt fired yet */ public Date getPreviousFireTime() { return trigger.getPreviousFireTime(); } /** * Get the Time the Job will Next be Fired. * * @return the time the Job will Next be Fired, or null if the job wont fire again */ public Date getNextFireTime() { return trigger.getNextFireTime(); } /** * Get the Final Time the Job will be Fired. * * @return the time the Job will be Fired for the Final time, or null if the job is Scheduled forever */ public Date getFinalFireTime() { return trigger.getFinalFireTime(); } /** * Get the Expression that was used to configure the Triggers firing pattern. * * @return The expression that was used to configure the Triggers firing pattern */ public String getTriggerExpression(){ if(trigger instanceof CronTrigger) { return ((CronTrigger)trigger).getCronExpression(); } else if(trigger instanceof SimpleTrigger) { return String.valueOf(((SimpleTrigger)trigger).getRepeatInterval()); } return null; } /** * Get the State of the Job's Trigger. * * @return the TRIGGER_STATE_* */ public TriggerState getTriggerState() { try { switch(scheduler.getTriggerState(trigger.getKey())) { case ERROR: return TriggerState.ERROR; case NONE: return TriggerState.NONE; case NORMAL: return TriggerState.NORMAL; case PAUSED: return TriggerState.PAUSED; case BLOCKED: return TriggerState.BLOCKED; case COMPLETE: return TriggerState.COMPLETE; default: return TriggerState.ERROR; } } catch(final SchedulerException se) { return TriggerState.ERROR; } } }
lgpl-2.1
openlimit-signcubes/dss
validation-policy/src/main/java/eu/europa/esig/dss/validation/process/qualification/certificate/QualifiedStatus.java
1351
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * 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 eu.europa.esig.dss.validation.process.qualification.certificate; public enum QualifiedStatus { /* Qualified */ QC("Qualified"), /* Not qualifed */ NOT_QC("Not qualified"); private final String label; QualifiedStatus(String label) { this.label = label; } public String getLabel() { return label; } public static boolean isQC(QualifiedStatus status) { return QC == status; } }
lgpl-2.1
jonmbake/checkstyle
src/main/java/com/puppycrawl/tools/checkstyle/api/FileSetCheck.java
3127
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.io.File; import java.util.SortedSet; /** * Interface for Checking a set of files for some criteria. * * @author lkuehne * @author oliver */ public interface FileSetCheck extends Configurable, Contextualizable { /** * Sets the MessageDispatcher that is used to dispatch error * messages to AuditListeners during processing. * @param dispatcher the dispatcher */ void setMessageDispatcher(MessageDispatcher dispatcher); /** * Initialise the instance. This is the time to verify that everything * required to perform it job. */ void init(); /** Cleans up the object. **/ void destroy(); /** * Called when about to be called to process a set of files. * @param charset the character set used to read the files. */ void beginProcessing(String charset); /** * Request to process a file. The implementation should use the supplied * contents and not read the contents again. This reduces the amount of * file I/O. * <p> * The file set to process might contain files that are not * interesting to the FileSetCheck. Such files should be ignored, * no error message should be fired for them. For example a FileSetCheck * that checks java files should ignore HTML or properties files. * </p> * <p> * The method should return the set of messages to be logged. * </p> * * @param file the file to be processed * @param fileText the contents of the file. * @return the sorted set of messages to be logged. * @throws CheckstyleException if error condition within Checkstyle occurs */ SortedSet<LocalizedMessage> process(File file, FileText fileText) throws CheckstyleException; /** * Called when all the files have been processed. This is the time to * perform any checks that need to be done across a set of files. In this * method, the implementation is responsible for the logging of messages. */ void finishProcessing(); }
lgpl-2.1
it-tavis/opencms-core
src/org/opencms/gwt/shared/CmsCoreData.java
13140
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, 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.gwt.shared; import org.opencms.util.CmsUUID; import java.util.Map; import com.google.gwt.user.client.rpc.IsSerializable; /** * Runtime data bean for prefetching.<p> * * @since 8.0.0 */ public class CmsCoreData implements IsSerializable { /** A enumeration for the ADE context. */ public enum AdeContext { /** Context for container page. */ containerpage, /** Context for classic direct edit provider. */ editprovider, /** Context for sitemap. */ sitemap } /** * Bean class containing info about the current user.<p> */ public static class UserInfo implements IsSerializable { /** True if the user is an administrator. */ private boolean m_isAdmin; /** True if the user is a template developer. */ private boolean m_isDeveloper; /** The user name. */ private String m_name; /** * Creates a new instance.<p> * * @param name the user name * @param isAdmin true if the user is an administrator * @param isDeveloper true if the user is a template developer */ public UserInfo(String name, boolean isAdmin, boolean isDeveloper) { m_isDeveloper = isDeveloper; m_isAdmin = isAdmin; m_name = name; } /** * Default constructor, needed for serialization.<p> */ protected UserInfo() { // empty } /** * Gets the user name.<p> * * @return the user name */ public String getName() { return m_name; } /** * Returns true if the user is an administrator.<p> * * @return true if the user is an administrator */ public boolean isAdmin() { return m_isAdmin; } /** * Returns true if the user is a template developer.<p> * * @return true if the user is a template developer */ public boolean isDeveloper() { return m_isDeveloper; } } /** Name of the used js variable. */ public static final String DICT_NAME = "org_opencms_gwt"; /** The key for the GWT build id property. */ public static final String KEY_GWT_BUILDID = "gwt.buildid"; /** The parameter name for path. */ public static final String PARAM_PATH = "path"; /** The parameter name for the return code. */ public static final String PARAM_RETURNCODE = "returncode"; /** The time sent from the server when loading the data. */ protected long m_serverTime; /** A bean with information about the current user. */ protected UserInfo m_userInfo; /** ADE parameters. */ private Map<String, String> m_adeParameters; /** The XML content editor back-link URL. */ private String m_contentEditorBacklinkUrl; /** The XML content editor delete-link URL. */ private String m_contentEditorDeleteLinkUrl; /** The XML content editor URL. */ private String m_contentEditorUrl; /** The default link to use for opening the workplace. */ private String m_defaultWorkplaceLink; /** The mappings of file extensions to resource types. */ private Map<String, String> m_extensionMapping; /** The show editor help flag. */ private boolean m_isShowEditorHelp; /** Keep-alive setting. */ private boolean m_keepAlive; /** The current request locale. */ private String m_locale; /** The login JSP URL. */ private String m_loginURL; /** The current navigation URI. */ private String m_navigationUri; /** The current site root. */ private String m_siteRoot; /** The structure id of the resource. */ private CmsUUID m_structureId; /** A flag which indicates whether the toolbar should be shown initially. */ private boolean m_toolbarVisible; /** The maximum file size for the upload. */ private long m_uploadFileSizeLimit; /** The current uri. */ private String m_uri; /** The OpenCms VFS prefix. */ private String m_vfsPrefix; /** The current workplace locale. */ private String m_wpLocale; /** * Constructor.<p> */ public CmsCoreData() { // empty } /** * Clone constructor.<p> * * @param clone the instance to clone */ public CmsCoreData(CmsCoreData clone) { this( clone.getContentEditorUrl(), clone.getContentEditorBacklinkUrl(), clone.getContentEditorDeleteLinkUrl(), clone.getLoginURL(), clone.getVfsPrefix(), clone.getSiteRoot(), clone.getLocale(), clone.getWpLocale(), clone.getUri(), clone.getNavigationUri(), clone.getStructureId(), clone.getExtensionMapping(), clone.getServerTime(), clone.isShowEditorHelp(), clone.isToolbarVisible(), clone.getDefaultWorkplaceLink(), clone.getUserInfo(), clone.getUploadFileSizeLimit(), clone.isKeepAlive(), clone.m_adeParameters); } /** * Constructor.<p> * * @param contentEditorUrl the XML content editor URL * @param contentEditorBacklinkUrl the XML content editor back-link URL * @param contentEditorDeleteLinkUrl the XML content editor delete-link URL * @param loginUrl the login JSP URL * @param vfsPrefix the OpenCms VFS prefix * @param siteRoot the current site root * @param locale the current request locale * @param wpLocale the workplace locale * @param uri the current uri * @param structureId the structure id of tbe resource * @param navigationUri the current navigation URI * @param extensionMapping the mappings of file extensions to resource types * @param serverTime the current time * @param isShowEditorHelp the show editor help flag * @param toolbarVisible a flag to indicate whether the toolbar should be visible initially * @param defaultWorkplaceLink the default link to use for opening the workplace * @param userInfo information about the current user * @param uploadFileSizeLimit the file upload size limit * @param isKeepAlive the keep-alive mode * @param adeParameters the map of ADE configuration parameters */ public CmsCoreData( String contentEditorUrl, String contentEditorBacklinkUrl, String contentEditorDeleteLinkUrl, String loginUrl, String vfsPrefix, String siteRoot, String locale, String wpLocale, String uri, String navigationUri, CmsUUID structureId, Map<String, String> extensionMapping, long serverTime, boolean isShowEditorHelp, boolean toolbarVisible, String defaultWorkplaceLink, UserInfo userInfo, long uploadFileSizeLimit, boolean isKeepAlive, Map<String, String> adeParameters) { m_contentEditorUrl = contentEditorUrl; m_contentEditorBacklinkUrl = contentEditorBacklinkUrl; m_contentEditorDeleteLinkUrl = contentEditorDeleteLinkUrl; m_loginURL = loginUrl; m_vfsPrefix = vfsPrefix; m_siteRoot = siteRoot; m_locale = locale; m_wpLocale = wpLocale; m_uri = uri; m_navigationUri = navigationUri; m_extensionMapping = extensionMapping; m_serverTime = serverTime; m_isShowEditorHelp = isShowEditorHelp; m_toolbarVisible = toolbarVisible; m_structureId = structureId; m_defaultWorkplaceLink = defaultWorkplaceLink; m_userInfo = userInfo; m_uploadFileSizeLimit = uploadFileSizeLimit; m_keepAlive = isKeepAlive; m_adeParameters = adeParameters; } /** * Gets the map of ADE configuration parameters.<p> * * @return the ADE configuration parameters */ public Map<String, String> getAdeParameters() { return m_adeParameters; } /** * Returns the XML content editor back-link URL.<p> * * @return the XML content editor back-link URL */ public String getContentEditorBacklinkUrl() { return m_contentEditorBacklinkUrl; } /** * Returns the XML content editor delete-link URL.<p> * * @return the XML content editor delete-link URL */ public String getContentEditorDeleteLinkUrl() { return m_contentEditorDeleteLinkUrl; } /** * Returns the XML content editor URL.<p> * * @return the XML content editor URL */ public String getContentEditorUrl() { return m_contentEditorUrl; } /** * Gets the default link to use for opening the workplace.<p> * * @return the default workplace link */ public String getDefaultWorkplaceLink() { return m_defaultWorkplaceLink; } /** * Returns the extensionMapping.<p> * * @return the extensionMapping */ public Map<String, String> getExtensionMapping() { return m_extensionMapping; } /** * Returns the current request locale.<p> * * @return the current request locale */ public String getLocale() { return m_locale; } /** * Returns the login URL.<p> * * @return the login URL */ public String getLoginURL() { return m_loginURL; } /** * Returns the current navigation (sitemap) URI.<p> * * @return the current navigation URI */ public String getNavigationUri() { return m_navigationUri; } /** * Returns the time of the server when the data was loaded.<p> * * @return the time of the server when the data was loaded */ public long getServerTime() { return m_serverTime; } /** * Returns the current site root.<p> * * @return the current site root */ public String getSiteRoot() { return m_siteRoot; } /** * Gets the structure id of the current resource.<p> * * @return the structure id of the current resource */ public CmsUUID getStructureId() { return m_structureId; } /** * Returns the file upload size limit.<p> * * @return the file upload size limit */ public long getUploadFileSizeLimit() { return m_uploadFileSizeLimit; } /** * Returns the current uri.<p> * * @return the current uri */ public String getUri() { return m_uri; } /** * Gets the information about the current user.<p> * * @return the information about the current user */ public UserInfo getUserInfo() { return m_userInfo; } /** * Returns the OpenCms VFS prefix.<p> * * @return the OpenCms VFS prefix */ public String getVfsPrefix() { return m_vfsPrefix; } /** * Returns the current workplace locale.<p> * * @return the current workplace locale */ public String getWpLocale() { return m_wpLocale; } /** * Returns true if the session should be kept alive even without user actions.<p> * * @return true if keep-alive mode is active */ public boolean isKeepAlive() { return m_keepAlive; } /** * Returns the show editor help flag.<p> * * @return the show editor help flag */ public boolean isShowEditorHelp() { return m_isShowEditorHelp; } /** * Returns true if the toolbar should be visible initially.<p> * * @return true if the toolbar should be visible initially */ public boolean isToolbarVisible() { return m_toolbarVisible; } }
lgpl-2.1
daniel-he/community-edition
projects/repository/source/java/org/alfresco/opencmis/mapping/CanDeleteDocumentEvaluator.java
1231
package org.alfresco.opencmis.mapping; import org.alfresco.opencmis.dictionary.CMISActionEvaluator; import org.alfresco.opencmis.dictionary.CMISNodeInfo; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.security.PermissionService; import org.apache.chemistry.opencmis.commons.enums.Action; public class CanDeleteDocumentEvaluator extends AbstractActionEvaluator { private CMISActionEvaluator currentVersionEvaluator; /** * Construct * * @param serviceRegistry */ protected CanDeleteDocumentEvaluator(ServiceRegistry serviceRegistry) { super(serviceRegistry, Action.CAN_DELETE_OBJECT); this.currentVersionEvaluator = new PermissionActionEvaluator(serviceRegistry, Action.CAN_DELETE_OBJECT, PermissionService.DELETE_NODE); } public boolean isAllowed(CMISNodeInfo nodeInfo) { boolean isAllowed = true; if(!nodeInfo.isCurrentVersion() || nodeInfo.hasPWC()) { // not allowed if not current version or is checked out isAllowed = false; } else { isAllowed = currentVersionEvaluator.isAllowed(nodeInfo); } return isAllowed; } }
lgpl-3.0
kba/lanterna-old
src/test/java/com/googlecode/lanterna/test/terminal/TerminalResizeTest.java
2294
/* * This file is part of lanterna (http://code.google.com/p/lanterna/). * * lanterna 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 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, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010-2012 Martin */ package com.googlecode.lanterna.test.terminal; import com.googlecode.lanterna.input.Key; import com.googlecode.lanterna.terminal.Terminal; import com.googlecode.lanterna.terminal.TerminalSize; import com.googlecode.lanterna.test.TestTerminalFactory; /** * * @author Martin */ public class TerminalResizeTest implements Terminal.ResizeListener { private static Terminal terminal; public static void main(String[] args) throws InterruptedException { terminal = new TestTerminalFactory(args).createTerminal(); terminal.enterPrivateMode(); terminal.clearScreen(); terminal.moveCursor(10, 5); terminal.putCharacter('H'); terminal.putCharacter('e'); terminal.putCharacter('l'); terminal.putCharacter('l'); terminal.putCharacter('o'); terminal.putCharacter('!'); terminal.moveCursor(0, 0); terminal.addResizeListener(new TerminalResizeTest()); while(true) { Key key = terminal.readInput(); if(key == null || key.getCharacter() != 'q') Thread.sleep(1); else break; } terminal.exitPrivateMode(); } public void onResized(TerminalSize newSize) { terminal.moveCursor(0, 0); String string = newSize.getColumns() + "x" + newSize.getRows() + " "; char []chars = string.toCharArray(); for(char c: chars) terminal.putCharacter(c); } }
lgpl-3.0
OldShatterhand77/Portofino
elements/src/main/java/com/manydesigns/elements/configuration/BeanLookup.java
3169
/* * 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.elements.configuration; import com.manydesigns.elements.reflection.ClassAccessor; import com.manydesigns.elements.reflection.JavaClassAccessor; import com.manydesigns.elements.reflection.PropertyAccessor; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.text.StrLookup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @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 BeanLookup extends StrLookup { public static final String copyright = "Copyright (c) 2005-2015, ManyDesigns srl"; //-------------------------------------------------------------------------- // Fields //-------------------------------------------------------------------------- protected final Object bean; protected final ClassAccessor accessor; //-------------------------------------------------------------------------- // Logging //-------------------------------------------------------------------------- public static final Logger logger = LoggerFactory.getLogger(BeanLookup.class); //-------------------------------------------------------------------------- // Constructors //-------------------------------------------------------------------------- public BeanLookup(Object bean) { this.bean = bean; Class clazz = bean.getClass(); accessor = JavaClassAccessor.getClassAccessor(clazz); } //-------------------------------------------------------------------------- // StrLookup implementation //-------------------------------------------------------------------------- @Override public String lookup(String key) { try { PropertyAccessor property = accessor.getProperty(key); return ObjectUtils.toString(property.get(bean)); } catch (NoSuchFieldException e) { logger.warn("Cannot access property '{}' on class '{}'", key, accessor.getName()); return null; } } }
lgpl-3.0
mbring/sonar-java
java-frontend/src/test/resources/IssuableSubscriptionClass.java
36
class IssuableSubscriptionClass { }
lgpl-3.0
simeshev/parabuild-ci
src/org/parabuild/ci/common/CacheUtils.java
1745
/* * Parabuild CI licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.parabuild.ci.common; import java.io.*; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; /** */ public final class CacheUtils { public static void removeHard(final String cacheName) { try { CacheManager.getInstance().removeCache(cacheName); } catch (Exception e) { IoUtils.ignoreExpectedException(e); } } public static Cache createCache(final CacheManager cacheManager, final Cache cache) throws CacheException { cacheManager.addCache(cache); return cacheManager.getCache(cache.getName()); } private CacheUtils() { } public static void resetAllCaches() throws CacheException, IOException { final CacheManager cacheManager = CacheManager.getInstance(); final String[] cacheNames = cacheManager.getCacheNames(); for (int i = 0; i < cacheNames.length; i++) { final String cacheName = cacheNames[i]; if (cacheName.equals("retention_cache")) continue; //if (log.isDebugEnabled()) log.debug("cache hits before setup: " + cacheName + "/" + cache.getHitCount()); cacheManager.getCache(cacheName).removeAll(); } } }
lgpl-3.0
Fiware/i2nd.KIARA
src/main/java/org/fiware/kiara/ps/rtps/builtin/data/ReaderProxyData.java
27666
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages * * Copyright (C) 2015 Proyectos y Sistemas de Mantenimiento S.L. (eProsima) * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package org.fiware.kiara.ps.rtps.builtin.data; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_ENDPOINT_GUID; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_EXPECTS_INLINE_QOS; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_KEY_HASH; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_MULTICAST_LOCATOR; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_PARTICIPANT_GUID; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_PROTOCOL_VERSION; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_TOPIC_NAME; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_TYPE_NAME; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_UNICAST_LOCATOR; import static org.fiware.kiara.ps.qos.parameter.ParameterId.PID_VENDORID; import static org.fiware.kiara.ps.qos.policies.DurabilityQosPolicyKind.TRANSIENT_LOCAL_DURABILITY_QOS; import static org.fiware.kiara.ps.qos.policies.ReliabilityQosPolicyKind.RELIABLE_RELIABILITY_QOS; import static org.fiware.kiara.ps.rtps.common.DurabilityKind.TRANSIENT_LOCAL; import static org.fiware.kiara.ps.rtps.common.DurabilityKind.VOLATILE; import static org.fiware.kiara.ps.rtps.common.EndpointKind.READER; import static org.fiware.kiara.ps.rtps.common.ReliabilityKind.BEST_EFFORT; import static org.fiware.kiara.ps.rtps.common.ReliabilityKind.RELIABLE; import static org.fiware.kiara.ps.rtps.common.TopicKind.NO_KEY; import static org.fiware.kiara.ps.rtps.messages.elements.Parameter.PARAMETER_BOOL_LENGTH; import static org.fiware.kiara.ps.rtps.messages.elements.Parameter.PARAMETER_GUID_LENGTH; import static org.fiware.kiara.ps.rtps.messages.elements.Parameter.PARAMETER_LOCATOR_LENGTH; import java.io.IOException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.fiware.kiara.ps.qos.ReaderQos; import org.fiware.kiara.ps.qos.policies.DeadLineQosPolicy; import org.fiware.kiara.ps.qos.policies.DestinationOrderQosPolicy; import org.fiware.kiara.ps.qos.policies.DurabilityQosPolicy; import org.fiware.kiara.ps.qos.policies.DurabilityServiceQosPolicy; import org.fiware.kiara.ps.qos.policies.GroupDataQosPolicy; import org.fiware.kiara.ps.qos.policies.LatencyBudgetQosPolicy; import org.fiware.kiara.ps.qos.policies.LifespanQosPolicy; import org.fiware.kiara.ps.qos.policies.LivelinessQosPolicy; import org.fiware.kiara.ps.qos.policies.OwnershipQosPolicy; import org.fiware.kiara.ps.qos.policies.PartitionQosPolicy; import org.fiware.kiara.ps.qos.policies.PresentationQosPolicy; import org.fiware.kiara.ps.qos.policies.ReliabilityQosPolicy; import org.fiware.kiara.ps.qos.policies.TimeBasedFilterQosPolicy; import org.fiware.kiara.ps.qos.policies.TopicDataQosPolicy; import org.fiware.kiara.ps.qos.policies.UserDataQosPolicy; import org.fiware.kiara.ps.rtps.attributes.RemoteReaderAttributes; import org.fiware.kiara.ps.rtps.common.Locator; import org.fiware.kiara.ps.rtps.common.LocatorList; import org.fiware.kiara.ps.rtps.common.TopicKind; import org.fiware.kiara.ps.rtps.history.CacheChange; import org.fiware.kiara.ps.rtps.messages.elements.GUID; import org.fiware.kiara.ps.rtps.messages.elements.InstanceHandle; import org.fiware.kiara.ps.rtps.messages.elements.Parameter; import org.fiware.kiara.ps.rtps.messages.elements.ParameterList; import org.fiware.kiara.ps.rtps.messages.elements.SerializedPayload; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterBool; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterGuid; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterKey; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterLocator; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterProtocolVersion; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterString; import org.fiware.kiara.ps.rtps.messages.elements.parameters.ParameterVendorId; import org.fiware.kiara.serialization.impl.BinaryInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class ReaderProxyData, used to represent all the information on a Reader * (both local and remote) with the purpose of implementing the discovery. * * @author Rafael Lara {@literal <rafaellara@eprosima.com>} */ public class ReaderProxyData { /** * {@link ReaderProxyData} GUID */ private final GUID m_guid; /** * Boolean value indicating if the inlineQos are going to be used */ private boolean m_expectsInlineQos; /** * Unicast locator list */ private final LocatorList m_unicastLocatorList; /** * Multicast locator list */ private final LocatorList m_multicastLocatorList; /** * GUID_t of the Reader converted to InstanceHandle_t */ private final InstanceHandle m_key; /** * GUID_t of the participant converted to InstanceHandle */ private InstanceHandle m_RTPSParticipantKey; /** * Type name */ private String m_typeName; /** * Topic name */ private String m_topicName; /** * User defined ID */ private short m_userDefinedId; /** * Reader Qos */ private final ReaderQos m_qos; /** * Field to indicate if the Reader is Alive. */ private boolean m_isAlive; /** * Topic kind */ private TopicKind m_topicKind; /** * Parameter list */ private final ParameterList m_parameterList; /** * Remote Attributes associated with this proxy data. */ private final RemoteReaderAttributes m_remoteAtt; /** * Logging object */ private static final Logger logger = LoggerFactory.getLogger(WriterProxyData.class); /** * Mutex */ private Lock m_mutex = new ReentrantLock(true); /** * Default {@link ReaderProxyData} constructor */ public ReaderProxyData() { this.m_guid = new GUID(); m_unicastLocatorList = new LocatorList(); m_multicastLocatorList = new LocatorList(); m_key = new InstanceHandle(); m_RTPSParticipantKey = new InstanceHandle(); m_typeName = ""; m_topicName = ""; m_userDefinedId = 0; m_qos = new ReaderQos(); m_isAlive = false; m_topicKind = TopicKind.NO_KEY; m_parameterList = new ParameterList(); m_remoteAtt = new RemoteReaderAttributes(); } /** * Get GUID * * @return GUID * @see GUID */ public GUID getGUID() { return this.m_guid; } /** * Set GUID * * @param value GUID * @see GUID */ public void setGUID(GUID value) { m_guid.copy(value); } /** * Set key * * @param value GUID */ public void setKey(GUID value) { m_key.setGuid(m_guid); } /** * Get the Key * * @return InstanceHandle representing the key */ public InstanceHandle getKey() { return this.m_key; } /** * Set key * * @param value instance handle */ public void setKey(InstanceHandle value) { m_key.copy(value); } /** * Get RTPS participant key * * @return RTPS participant key */ public InstanceHandle getRTPSParticipantKey() { return m_RTPSParticipantKey; } /** * Set RTPS participant key * * @param value GUID * @see GUID */ public void setRTPSParticipantKey(GUID value) { m_RTPSParticipantKey.setGuid(m_guid); } /** * Set RTPS participant key * * @param value instance handle * @see InstanceHandle */ public void setRTPSParticipantKey(InstanceHandle value) { m_RTPSParticipantKey.copy(value); } /** * Get expectsInlineQos flag * * @return expectsInlineQos flag */ public boolean getExpectsInlineQos() { return m_expectsInlineQos; } /** * Set expectsInlineQos flag * * @param value expectsInlineQos flag */ public void setExpectsInlineQos(boolean value) { m_expectsInlineQos = value; } /** * Get isAlive flag * * @return isAlive flag */ public boolean getIsAlive() { return m_isAlive; } /** * Set isAlive flag * * @param value isAlive flag */ public void setIsAlive(boolean value) { m_isAlive = value; } /** * Get unicast locator list * * @return unicast locator list * @see LocatorList */ public LocatorList getUnicastLocatorList() { return m_unicastLocatorList; } /** * Set unicast locator list * * @param unicastLocatorList unicast locator list * @see LocatorList */ public void setUnicastLocatorList(LocatorList unicastLocatorList) { this.m_unicastLocatorList.copy(unicastLocatorList); } /** * Get multicast locator list * * @return multicast locator list */ public LocatorList getMulticastLocatorList() { return m_multicastLocatorList; } /** * Set multicast locator list * * @param m_multicastLocatorList multicast locator list */ public void setMulticastLocatorList(LocatorList m_multicastLocatorList) { this.m_multicastLocatorList.copy(m_multicastLocatorList); } /** * Get topic name * * @return topic name */ public String getTopicName() { return m_topicName; } /** * Set topic name * * @param value topic name */ public void setTopicName(String value) { m_topicName = value; } /** * Get type name * * @return type name */ public String getTypeName() { return m_typeName; } /** * Set type name * * @param value type name */ public void setTypeName(String value) { m_typeName = value; } /** * Get topic kind * * @return topic kind */ public TopicKind getTopicKind() { return m_topicKind; } /** * Set topic kind * * @param value topic kind */ public void setTopicKind(TopicKind value) { m_topicKind = value; } /** * Get reader QoS * * @return reader QoS */ public ReaderQos getQos() { return m_qos; } /** * Set reader QoS * * @param value reader QoS */ public void setQos(ReaderQos value) { m_qos.copy(value); } /** * Get user defined ID * * @return user defined ID */ public short getUserDefinedId() { return m_userDefinedId; } /** * Set user defined ID * * @param value user defined ID */ public void setUserDefinedId(short value) { m_userDefinedId = value; } /** * Convert the data to a parameter list to send this information as a RTPS * message. * * @return The ParameterList */ public ParameterList toParameterList() { m_parameterList.deleteParams(); for (Locator lit : m_unicastLocatorList) { ParameterLocator p = new ParameterLocator(PID_UNICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, lit); m_parameterList.addParameter(p); } for (Locator lit : m_multicastLocatorList) { ParameterLocator p = new ParameterLocator(PID_MULTICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, lit); m_parameterList.addParameter(p); } { ParameterBool p = new ParameterBool(PID_EXPECTS_INLINE_QOS, PARAMETER_BOOL_LENGTH, m_expectsInlineQos); m_parameterList.addParameter(p); } { ParameterGuid p = new ParameterGuid(PID_PARTICIPANT_GUID, PARAMETER_GUID_LENGTH, m_RTPSParticipantKey); m_parameterList.addParameter(p); } { ParameterString p = new ParameterString(PID_TOPIC_NAME, (short) 0, m_topicName); m_parameterList.addParameter(p); } { ParameterString p = new ParameterString(PID_TYPE_NAME, (short) 0, m_typeName); m_parameterList.addParameter(p); } { ParameterKey p = new ParameterKey(PID_KEY_HASH, (short) 16, m_key); m_parameterList.addParameter(p); } { ParameterGuid p = new ParameterGuid(PID_ENDPOINT_GUID, (short) 16, m_guid); m_parameterList.addParameter(p); } { ParameterProtocolVersion p = new ParameterProtocolVersion(PID_PROTOCOL_VERSION, (short) 4); m_parameterList.addParameter(p); } { ParameterVendorId p = new ParameterVendorId(PID_VENDORID, (short) 4); m_parameterList.addParameter(p); } if (m_qos.durability.parent.getSendAlways() || m_qos.durability.parent.hasChanged) { DurabilityQosPolicy p = new DurabilityQosPolicy(); p.copy(m_qos.durability); m_parameterList.addParameter(p); } if (m_qos.durabilityService.parent.getSendAlways() || m_qos.durabilityService.parent.hasChanged) { DurabilityServiceQosPolicy p = new DurabilityServiceQosPolicy(); p.copy(m_qos.durabilityService); m_parameterList.addParameter(p); } if (m_qos.deadline.parent.getSendAlways() || m_qos.deadline.parent.hasChanged) { DeadLineQosPolicy p = new DeadLineQosPolicy(); p.copy(m_qos.deadline); m_parameterList.addParameter(p); } if (m_qos.latencyBudget.parent.getSendAlways() || m_qos.latencyBudget.parent.hasChanged) { LatencyBudgetQosPolicy p = new LatencyBudgetQosPolicy(); p.copy(m_qos.latencyBudget); m_parameterList.addParameter(p); } if (m_qos.liveliness.parent.getSendAlways() || m_qos.liveliness.parent.hasChanged) { LivelinessQosPolicy p = new LivelinessQosPolicy(); p.copy(m_qos.liveliness); m_parameterList.addParameter(p); } if (m_qos.reliability.parent.getSendAlways() || m_qos.reliability.parent.hasChanged) { ReliabilityQosPolicy p = new ReliabilityQosPolicy(); p.copy(m_qos.reliability); m_parameterList.addParameter(p); } if (m_qos.lifespan.parent.getSendAlways() || m_qos.lifespan.parent.hasChanged) { LifespanQosPolicy p = new LifespanQosPolicy(); p.copy(m_qos.lifespan); m_parameterList.addParameter(p); } if (m_qos.userData.parent.getSendAlways() || m_qos.userData.parent.hasChanged) { UserDataQosPolicy p = new UserDataQosPolicy(); p.copy(m_qos.userData); m_parameterList.addParameter(p); } if (m_qos.timeBasedFilter.parent.getSendAlways() || m_qos.timeBasedFilter.parent.hasChanged) { TimeBasedFilterQosPolicy p = new TimeBasedFilterQosPolicy(); p.copy(m_qos.timeBasedFilter); m_parameterList.addParameter(p); } if (m_qos.ownership.parent.getSendAlways() || m_qos.ownership.parent.hasChanged) { OwnershipQosPolicy p = new OwnershipQosPolicy(); p.copy(m_qos.ownership); m_parameterList.addParameter(p); } if (m_qos.destinationOrder.parent.getSendAlways() || m_qos.destinationOrder.parent.hasChanged) { DestinationOrderQosPolicy p = new DestinationOrderQosPolicy(); p.copy(m_qos.destinationOrder); m_parameterList.addParameter(p); } if (m_qos.presentation.parent.getSendAlways() || m_qos.presentation.parent.hasChanged) { PresentationQosPolicy p = new PresentationQosPolicy(); p.copy(m_qos.presentation); m_parameterList.addParameter(p); } if (m_qos.partition.parent.getSendAlways() || m_qos.partition.parent.hasChanged) { PartitionQosPolicy p = new PartitionQosPolicy(); p.copy(m_qos.partition); m_parameterList.addParameter(p); } if (m_qos.topicData.parent.getSendAlways() || m_qos.topicData.parent.hasChanged) { TopicDataQosPolicy p = new TopicDataQosPolicy(); p.copy(m_qos.topicData); m_parameterList.addParameter(p); } if (m_qos.groupData.parent.getSendAlways() || m_qos.groupData.parent.hasChanged) { GroupDataQosPolicy p = new GroupDataQosPolicy(); p.copy(m_qos.groupData); m_parameterList.addParameter(p); } if (m_qos.timeBasedFilter.parent.getSendAlways() || m_qos.timeBasedFilter.parent.hasChanged) { TimeBasedFilterQosPolicy p = new TimeBasedFilterQosPolicy(); p.copy(m_qos.timeBasedFilter); m_parameterList.addParameter(p); } this.m_parameterList.addSentinel(); logger.debug("DiscoveredReaderData converted to ParameterList with {} parameters", m_parameterList.getParameters().size()); return this.m_parameterList; } /** * Clear (put to default) the information. */ public void clear() { m_expectsInlineQos = false; m_guid.copy(new GUID()); m_unicastLocatorList.clear(); m_multicastLocatorList.clear(); m_key.copy(new InstanceHandle()); m_RTPSParticipantKey.copy(new InstanceHandle()); m_typeName = ""; m_topicName = ""; m_userDefinedId = 0; m_qos.copy(new ReaderQos()); m_isAlive = true; m_topicKind = NO_KEY; m_parameterList.deleteParams(); m_parameterList.resetList(); } /** * Update the information (only certain fields can be updated). * * @param rdata Poitner to the object from which we are going to update. */ public void update(ReaderProxyData rdata) { m_unicastLocatorList.copy(rdata.m_unicastLocatorList); m_multicastLocatorList.copy(rdata.m_multicastLocatorList); m_qos.setQos(rdata.getQos(), false); m_isAlive = rdata.getIsAlive(); } /** * Copy ALL the information from another object. * * @param rdata Reference to the object from where the information must be * copied. */ public void copy(ReaderProxyData rdata) { m_guid.copy(rdata.m_guid); m_unicastLocatorList.copy(rdata.m_unicastLocatorList); m_multicastLocatorList.copy(rdata.m_multicastLocatorList); m_key.copy(rdata.m_key); m_RTPSParticipantKey.copy(rdata.m_RTPSParticipantKey); m_typeName = rdata.m_typeName; m_topicName = rdata.m_topicName; m_userDefinedId = rdata.m_userDefinedId; m_qos.copy(rdata.m_qos); //cout << "COPYING DATA: expects inlineQOS : " << rdata->m_expectsInlineQos << endl; m_expectsInlineQos = rdata.m_expectsInlineQos; m_isAlive = rdata.m_isAlive; m_topicKind = rdata.m_topicKind; } /** * Convert the ProxyData information to RemoteReaderAttributes object. * * @return Reference to the RemoteReaderAttributes object. */ public RemoteReaderAttributes toRemoteReaderAttributes() { m_remoteAtt.setGUID(m_guid); m_remoteAtt.expectsInlineQos = this.m_expectsInlineQos; m_remoteAtt.endpoint.durabilityKind = m_qos.durability.kind == TRANSIENT_LOCAL_DURABILITY_QOS ? TRANSIENT_LOCAL : VOLATILE; m_remoteAtt.endpoint.endpointKind = READER; m_remoteAtt.endpoint.topicKind = m_topicKind; m_remoteAtt.endpoint.reliabilityKind = m_qos.reliability.kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT; m_remoteAtt.endpoint.unicastLocatorList.copy(this.m_unicastLocatorList); m_remoteAtt.endpoint.multicastLocatorList.copy(this.m_multicastLocatorList); return m_remoteAtt; } /** * Get the ParameterList * * @return The ParameterList */ public ParameterList getParameterList() { return this.m_parameterList; } public boolean readFromCDRMessage(CacheChange change) { this.m_mutex.lock(); try { SerializedPayload payload = change.getSerializedPayload(); payload.updateSerializer(); BinaryInputStream bis = new BinaryInputStream(payload.getBuffer()); ParameterList parameterList = new ParameterList(); try { parameterList.deserialize(payload.getSerializer(), bis, ""); } catch (IOException e) { logger.error(e.getMessage()); return false; //e.printStackTrace(); } for (Parameter param : parameterList.getParameters()) { switch (param.getParameterId()) { case PID_DURABILITY: { DurabilityQosPolicy p = (DurabilityQosPolicy) param; this.m_qos.durability.copy(p); break; } case PID_DURABILITY_SERVICE: { DurabilityServiceQosPolicy p = (DurabilityServiceQosPolicy) param; this.m_qos.durabilityService.copy(p); break; } case PID_DEADLINE: { DeadLineQosPolicy p = (DeadLineQosPolicy) param; this.m_qos.deadline.copy(p); break; } case PID_LATENCY_BUDGET: { LatencyBudgetQosPolicy p = (LatencyBudgetQosPolicy) param; this.m_qos.latencyBudget.copy(p); break; } case PID_LIVELINESS: { LivelinessQosPolicy p = (LivelinessQosPolicy) param; this.m_qos.liveliness.copy(p); break; } case PID_RELIABILITY: { ReliabilityQosPolicy p = (ReliabilityQosPolicy) param; this.m_qos.reliability.copy(p); break; } case PID_LIFESPAN: { LifespanQosPolicy p = (LifespanQosPolicy) param; this.m_qos.lifespan.copy(p); break; } case PID_USER_DATA: { UserDataQosPolicy p = (UserDataQosPolicy) param; this.m_qos.userData.copy(p); break; } case PID_TIME_BASED_FILTER: { TimeBasedFilterQosPolicy p = (TimeBasedFilterQosPolicy) param; this.m_qos.timeBasedFilter.copy(p); break; } case PID_OWNERSHIP: { OwnershipQosPolicy p = (OwnershipQosPolicy) param; this.m_qos.ownership.copy(p); break; } case PID_DESTINATION_ORDER: { DestinationOrderQosPolicy p = (DestinationOrderQosPolicy) param; this.m_qos.destinationOrder.copy(p); break; } case PID_PRESENTATION: { PresentationQosPolicy p = (PresentationQosPolicy) param; this.m_qos.presentation.copy(p); break; } case PID_PARTITION: { PartitionQosPolicy p = (PartitionQosPolicy) param; this.m_qos.partition.copy(p); break; } case PID_TOPIC_DATA: { TopicDataQosPolicy p = (TopicDataQosPolicy) param; this.m_qos.topicData.copy(p); break; } case PID_GROUP_DATA: { GroupDataQosPolicy p = (GroupDataQosPolicy) param; this.m_qos.groupData.copy(p); break; } case PID_TOPIC_NAME: { ParameterString p = (ParameterString) param; this.m_topicName = new String(p.getString()); break; } case PID_TYPE_NAME: { ParameterString p = (ParameterString) param; this.m_typeName = new String(p.getString()); break; } case PID_PARTICIPANT_GUID: { ParameterGuid pGuid = (ParameterGuid) param; this.m_RTPSParticipantKey = new InstanceHandle(pGuid.getGUID()); break; } case PID_ENDPOINT_GUID: { ParameterGuid pGuid = (ParameterGuid) param; this.m_guid.copy(pGuid.getGUID()); break; } case PID_UNICAST_LOCATOR: { ParameterLocator p = (ParameterLocator) param; this.m_unicastLocatorList.pushBack(p.getLocator()); break; } case PID_MULTICAST_LOCATOR: { ParameterLocator p = (ParameterLocator) param; this.m_multicastLocatorList.pushBack(p.getLocator()); break; } case PID_EXPECTS_INLINE_QOS: { ParameterBool p = (ParameterBool) param; this.m_expectsInlineQos = p.getBool(); break; } case PID_KEY_HASH: { ParameterKey p = (ParameterKey) param; this.m_key.copy(p.getKey()); this.m_guid.copy(this.m_key.toGUID()); break; } default: logger.debug("Parameter with ID {} NOT CONSIDERED", param.getParameterId()); break; } } if (this.m_guid.getEntityId().getValue(3) == 0x04) { this.m_topicKind = NO_KEY; } else if (this.m_guid.getEntityId().getValue(3) == 0x07) { this.m_topicKind = TopicKind.WITH_KEY; } } finally { this.m_mutex.unlock(); } return true; } }
lgpl-3.0
skettios/Life-Fiber
src/main/java/skettios/mods/livingthread/LTClientProxy.java
1937
package skettios.mods.livingthread; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.color.IItemColor; import net.minecraft.client.renderer.color.ItemColors; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import skettios.mods.livingthread.enums.EnumSyntheticThread; import skettios.mods.livingthread.enums.EnumThread; import skettios.mods.livingthread.items.LTItems; public class LTClientProxy extends LTCommonProxy { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); MinecraftForge.EVENT_BUS.register(LTClientEvent.class); } @Override public void init(FMLInitializationEvent event) { super.init(event); final ItemModelMesher itemModelMesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher(); for (int i = 0; i < EnumThread.values().length; i++) itemModelMesher.register(LTItems.thread, i, EnumThread.fromMetadata(i).modelResourceLocation); for (int i = 0; i < EnumSyntheticThread.values().length; i++) itemModelMesher.register(LTItems.thread_synthetic, i, EnumSyntheticThread.fromMetadata(i).modelResourceLocation); final ItemColors itemColors = Minecraft.getMinecraft().getItemColors(); itemColors.registerItemColorHandler((IItemColor) LTItems.thread, LTItems.thread); itemColors.registerItemColorHandler((IItemColor) LTItems.thread_synthetic, LTItems.thread_synthetic); } @Override public void postInit(FMLPostInitializationEvent event) { super.postInit(event); } }
lgpl-3.0
alafighting/ccshop
src/cn/jeesoft/core/utils/$Type$Types.java
23586
package cn.jeesoft.core.utils; import static cn.jeesoft.core.utils.$Type$Preconditions.checkArgument; import static cn.jeesoft.core.utils.$Type$Preconditions.checkNotNull; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; /** * 类型获取 * @version v0.1.0 google 2014-11-04 摘自Gson */ class $Type$Types { static final Type[] EMPTY_TYPE_ARRAY = new Type[] {}; private $Type$Types() { } /** * Returns a new parameterized type, applying {@code typeArguments} to * {@code rawType} and enclosed by {@code ownerType}. * * @return a {@link java.io.Serializable serializable} parameterized type. */ public static ParameterizedType newParameterizedTypeWithOwner( Type ownerType, Type rawType, Type... typeArguments) { return new ParameterizedTypeImpl(ownerType, rawType, typeArguments); } /** * Returns an array type whose elements are all instances of * {@code componentType}. * * @return a {@link java.io.Serializable serializable} generic array type. */ public static GenericArrayType arrayOf(Type componentType) { return new GenericArrayTypeImpl(componentType); } /** * Returns a type that represents an unknown type that extends {@code bound} * . For example, if {@code bound} is {@code CharSequence.class}, this * returns {@code ? extends CharSequence}. If {@code bound} is * {@code Object.class}, this returns {@code ?}, which is shorthand for * {@code ? extends Object}. */ public static WildcardType subtypeOf(Type bound) { return new WildcardTypeImpl(new Type[] { bound }, EMPTY_TYPE_ARRAY); } /** * Returns a type that represents an unknown supertype of {@code bound}. For * example, if {@code bound} is {@code String.class}, this returns {@code ? * super String}. */ public static WildcardType supertypeOf(Type bound) { return new WildcardTypeImpl(new Type[] { Object.class }, new Type[] { bound }); } /** * Returns a type that is functionally equal but not necessarily equal * according to {@link Object#equals(Object) Object.equals()}. The returned * type is {@link java.io.Serializable}. */ public static Type canonicalize(Type type) { if (type instanceof Class) { Class<?> c = (Class<?>) type; return c.isArray() ? new GenericArrayTypeImpl( canonicalize(c.getComponentType())) : c; } else if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) type; return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(), p.getActualTypeArguments()); } else if (type instanceof GenericArrayType) { GenericArrayType g = (GenericArrayType) type; return new GenericArrayTypeImpl(g.getGenericComponentType()); } else if (type instanceof WildcardType) { WildcardType w = (WildcardType) type; return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds()); } else { // type is either serializable as-is or unsupported return type; } } public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; // I'm not exactly sure why getRawType() returns Type instead of // Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); checkArgument(rawType instanceof Class); return (Class<?>) rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type) .getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there // are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType) type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass() .getName(); throw new IllegalArgumentException( "Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } } static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Returns true if {@code a} and {@code b} are equal. */ public static boolean equals(Type a, Type b) { if (a == b) { // also handles (a == null && b == null) return true; } else if (a instanceof Class) { // Class already specifies equals(). return a.equals(b); } else if (a instanceof ParameterizedType) { if (!(b instanceof ParameterizedType)) { return false; } // TODO: save a .clone() call ParameterizedType pa = (ParameterizedType) a; ParameterizedType pb = (ParameterizedType) b; return equal(pa.getOwnerType(), pb.getOwnerType()) && pa.getRawType().equals(pb.getRawType()) && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments()); } else if (a instanceof GenericArrayType) { if (!(b instanceof GenericArrayType)) { return false; } GenericArrayType ga = (GenericArrayType) a; GenericArrayType gb = (GenericArrayType) b; return equals(ga.getGenericComponentType(), gb.getGenericComponentType()); } else if (a instanceof WildcardType) { if (!(b instanceof WildcardType)) { return false; } WildcardType wa = (WildcardType) a; WildcardType wb = (WildcardType) b; return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds()) && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds()); } else if (a instanceof TypeVariable) { if (!(b instanceof TypeVariable)) { return false; } TypeVariable<?> va = (TypeVariable<?>) a; TypeVariable<?> vb = (TypeVariable<?>) b; return va.getGenericDeclaration() == vb.getGenericDeclaration() && va.getName().equals(vb.getName()); } else { // This isn't a type we support. Could be a generic array type, // wildcard type, etc. return false; } } private static int hashCodeOrZero(Object o) { return o != null ? o.hashCode() : 0; } public static String typeToString(Type type) { return type instanceof Class ? ((Class<?>) type).getName() : type .toString(); } /** * Returns the generic supertype for {@code supertype}. For example, given a * class {@code IntegerSet}, the result for when supertype is * {@code Set.class} is {@code Set<Integer>} and the result when the * supertype is {@code Collection.class} is {@code Collection<Integer>}. */ static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) { if (toResolve == rawType) { return context; } // we skip searching through interfaces if unknown is an interface if (toResolve.isInterface()) { Class<?>[] interfaces = rawType.getInterfaces(); for (int i = 0, length = interfaces.length; i < length; i++) { if (interfaces[i] == toResolve) { return rawType.getGenericInterfaces()[i]; } else if (toResolve.isAssignableFrom(interfaces[i])) { return getGenericSupertype( rawType.getGenericInterfaces()[i], interfaces[i], toResolve); } } } // check our supertypes if (!rawType.isInterface()) { while (rawType != Object.class) { Class<?> rawSupertype = rawType.getSuperclass(); if (rawSupertype == toResolve) { return rawType.getGenericSuperclass(); } else if (toResolve.isAssignableFrom(rawSupertype)) { return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve); } rawType = rawSupertype; } } // we can't resolve this further return toResolve; } /** * Returns the generic form of {@code supertype}. For example, if this is * {@code ArrayList<String>}, this returns {@code Iterable<String>} given * the input {@code Iterable.class}. * * @param supertype * a superclass of, or interface implemented by, this. */ static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { checkArgument(supertype.isAssignableFrom(contextRawType)); return resolve(context, contextRawType, $Type$Types.getGenericSupertype(context, contextRawType, supertype)); } /** * Returns the component type of this array type. * * @throws ClassCastException * if this type is not an array. */ public static Type getArrayComponentType(Type array) { return array instanceof GenericArrayType ? ((GenericArrayType) array) .getGenericComponentType() : ((Class<?>) array) .getComponentType(); } /** * Returns the element type of this collection type. * * @throws IllegalArgumentException * if this type is not a collection. */ public static Type getCollectionElementType(Type context, Class<?> contextRawType) { Type collectionType = getSupertype(context, contextRawType, Collection.class); if (collectionType instanceof WildcardType) { collectionType = ((WildcardType) collectionType).getUpperBounds()[0]; } if (collectionType instanceof ParameterizedType) { return ((ParameterizedType) collectionType) .getActualTypeArguments()[0]; } return Object.class; } /** * Returns a two element array containing this map's key and value types in * positions 0 and 1 respectively. */ public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) { /* * Work around a problem with the declaration of java.util.Properties. * That class should extend Hashtable<String, String>, but it's declared * to extend Hashtable<Object, Object>. */ if (context == Properties.class) { return new Type[] { String.class, String.class }; // TODO: test // subclasses of // Properties! } Type mapType = getSupertype(context, contextRawType, Map.class); // TODO: strip wildcards? if (mapType instanceof ParameterizedType) { ParameterizedType mapParameterizedType = (ParameterizedType) mapType; return mapParameterizedType.getActualTypeArguments(); } return new Type[] { Object.class, Object.class }; } public static Type resolve(Type context, Class<?> contextRawType, Type toResolve) { // this implementation is made a little more complicated in an attempt // to avoid object-creation while (true) { if (toResolve instanceof TypeVariable) { TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve; toResolve = resolveTypeVariable(context, contextRawType, typeVariable); if (toResolve == typeVariable) { return toResolve; } } else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) { Class<?> original = (Class<?>) toResolve; Type componentType = original.getComponentType(); Type newComponentType = resolve(context, contextRawType, componentType); return componentType == newComponentType ? original : arrayOf(newComponentType); } else if (toResolve instanceof GenericArrayType) { GenericArrayType original = (GenericArrayType) toResolve; Type componentType = original.getGenericComponentType(); Type newComponentType = resolve(context, contextRawType, componentType); return componentType == newComponentType ? original : arrayOf(newComponentType); } else if (toResolve instanceof ParameterizedType) { ParameterizedType original = (ParameterizedType) toResolve; Type ownerType = original.getOwnerType(); Type newOwnerType = resolve(context, contextRawType, ownerType); boolean changed = newOwnerType != ownerType; Type[] args = original.getActualTypeArguments(); for (int t = 0, length = args.length; t < length; t++) { Type resolvedTypeArgument = resolve(context, contextRawType, args[t]); if (resolvedTypeArgument != args[t]) { if (!changed) { args = args.clone(); changed = true; } args[t] = resolvedTypeArgument; } } return changed ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args) : original; } else if (toResolve instanceof WildcardType) { WildcardType original = (WildcardType) toResolve; Type[] originalLowerBound = original.getLowerBounds(); Type[] originalUpperBound = original.getUpperBounds(); if (originalLowerBound.length == 1) { Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]); if (lowerBound != originalLowerBound[0]) { return supertypeOf(lowerBound); } } else if (originalUpperBound.length == 1) { Type upperBound = resolve(context, contextRawType, originalUpperBound[0]); if (upperBound != originalUpperBound[0]) { return subtypeOf(upperBound); } } return original; } else { return toResolve; } } } static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) { Class<?> declaredByRaw = declaringClassOf(unknown); // we can't reduce this further if (declaredByRaw == null) { return unknown; } Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw); if (declaredBy instanceof ParameterizedType) { int index = indexOf(declaredByRaw.getTypeParameters(), unknown); return ((ParameterizedType) declaredBy).getActualTypeArguments()[index]; } return unknown; } private static int indexOf(Object[] array, Object toFind) { for (int i = 0; i < array.length; i++) { if (toFind.equals(array[i])) { return i; } } throw new NoSuchElementException(); } /** * Returns the declaring class of {@code typeVariable}, or {@code null} if * it was not declared by a class. */ private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) { GenericDeclaration genericDeclaration = typeVariable .getGenericDeclaration(); return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null; } private static void checkNotPrimitive(Type type) { checkArgument(!(type instanceof Class<?>) || !((Class<?>) type).isPrimitive()); } private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable { private final Type ownerType; private final Type rawType; private final Type[] typeArguments; public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) { // require an owner type if the raw type needs it if (rawType instanceof Class<?>) { Class<?> rawTypeAsClass = (Class<?>) rawType; boolean isStaticOrTopLevelClass = Modifier .isStatic(rawTypeAsClass.getModifiers()) || rawTypeAsClass.getEnclosingClass() == null; checkArgument(ownerType != null || isStaticOrTopLevelClass); } this.ownerType = ownerType == null ? null : canonicalize(ownerType); this.rawType = canonicalize(rawType); this.typeArguments = typeArguments.clone(); for (int t = 0; t < this.typeArguments.length; t++) { checkNotNull(this.typeArguments[t]); checkNotPrimitive(this.typeArguments[t]); this.typeArguments[t] = canonicalize(this.typeArguments[t]); } } public Type[] getActualTypeArguments() { return typeArguments.clone(); } public Type getRawType() { return rawType; } public Type getOwnerType() { return ownerType; } @Override public boolean equals(Object other) { return other instanceof ParameterizedType && $Type$Types.equals(this, (ParameterizedType) other); } @Override public int hashCode() { return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder( 30 * (typeArguments.length + 1)); stringBuilder.append(typeToString(rawType)); if (typeArguments.length == 0) { return stringBuilder.toString(); } stringBuilder.append("<").append(typeToString(typeArguments[0])); for (int i = 1; i < typeArguments.length; i++) { stringBuilder.append(", ").append( typeToString(typeArguments[i])); } return stringBuilder.append(">").toString(); } private static final long serialVersionUID = 0; } private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable { private final Type componentType; public GenericArrayTypeImpl(Type componentType) { this.componentType = canonicalize(componentType); } public Type getGenericComponentType() { return componentType; } @Override public boolean equals(Object o) { return o instanceof GenericArrayType && $Type$Types.equals(this, (GenericArrayType) o); } @Override public int hashCode() { return componentType.hashCode(); } @Override public String toString() { return typeToString(componentType) + "[]"; } private static final long serialVersionUID = 0; } /** * The WildcardType interface supports multiple upper bounds and multiple * lower bounds. We only support what the Java 6 language needs - at most * one bound. If a lower bound is set, the upper bound must be Object.class. */ private static final class WildcardTypeImpl implements WildcardType, Serializable { private final Type upperBound; private final Type lowerBound; public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) { checkArgument(lowerBounds.length <= 1); checkArgument(upperBounds.length == 1); if (lowerBounds.length == 1) { checkNotNull(lowerBounds[0]); checkNotPrimitive(lowerBounds[0]); checkArgument(upperBounds[0] == Object.class); this.lowerBound = canonicalize(lowerBounds[0]); this.upperBound = Object.class; } else { checkNotNull(upperBounds[0]); checkNotPrimitive(upperBounds[0]); this.lowerBound = null; this.upperBound = canonicalize(upperBounds[0]); } } public Type[] getUpperBounds() { return new Type[] { upperBound }; } public Type[] getLowerBounds() { return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY; } @Override public boolean equals(Object other) { return other instanceof WildcardType && $Type$Types.equals(this, (WildcardType) other); } @Override public int hashCode() { // this equals Arrays.hashCode(getLowerBounds()) ^ // Arrays.hashCode(getUpperBounds()); return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode()); } @Override public String toString() { if (lowerBound != null) { return "? super " + typeToString(lowerBound); } else if (upperBound == Object.class) { return "?"; } else { return "? extends " + typeToString(upperBound); } } private static final long serialVersionUID = 0; } }
lgpl-3.0
lpantano/java_seqbuster
miraligner/src/miraligner/alignment.java
378
package miraligner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author lpantano */ public class alignment { double sc=0; int scmut=0; int hit=0; String mut="0"; String add="0"; int pospre=0; String s3=""; String s5=""; String t3="na"; String t5="na"; int amb=0; }
lgpl-3.0
marcegarba/ethereumj
ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/JSONReader.java
6670
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ 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 3 of the License, or * (at your option) any later version. * * The ethereumJ 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 the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite; import org.ethereum.config.SystemProperties; import org.ethereum.util.FileUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JSONReader { private static Logger logger = LoggerFactory.getLogger("TCK-Test"); static ExecutorService threadPool; private static int MAX_RETRIES = 3; public static List<String> loadJSONsFromCommit(List<String> filenames, final String shacommit) { int threads = 16; if (threadPool == null) { threadPool = Executors.newFixedThreadPool(threads); } List<Future<String>> retF = new ArrayList<>(); for (final String filename : filenames) { Future<String> f = threadPool.submit(() -> loadJSONFromCommit(filename, shacommit)); retF.add(f); } List<String> ret = new ArrayList<>(); for (Future<String> f : retF) { try { ret.add(f.get()); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(String.format("Failed to retrieve %d files from commit %s", filenames.size(), shacommit), e); } } return ret; } public static String loadJSONFromCommit(String filename, String shacommit) throws IOException { String json = ""; if (!SystemProperties.getDefault().githubTestsLoadLocal()) json = getFromUrl("https://raw.githubusercontent.com/ethereum/tests/" + shacommit + "/" + filename); if (!json.isEmpty()) json = json.replaceAll("//", "data"); return json.isEmpty() ? getFromLocal(filename) : json; } public static String getFromLocal(String filename) throws IOException { filename = SystemProperties.getDefault().githubTestsPath() + System.getProperty("file.separator") + filename.replaceAll("/", System.getProperty("file.separator")); logger.info("Loading local file: {}", filename); return new String(Files.readAllBytes(Paths.get(filename))); } public static String getFromUrl(String urlToRead) { String result = null; for (int i = 0; i < MAX_RETRIES; ++i) { try { result = getFromUrlImpl(urlToRead); break; } catch (Exception ex) { logger.debug(String.format("Failed to retrieve %s, retry %d/%d", urlToRead, (i + 1), MAX_RETRIES), ex); if (i < (MAX_RETRIES - 1)) { try { Thread.sleep(2000); // adding delay after fail } catch (InterruptedException e) { } } } } if (result == null) throw new RuntimeException(String.format("Failed to retrieve file from url %s", urlToRead)); return result; } private static String getFromUrlImpl(String urlToRead) throws Exception { URL url; HttpURLConnection conn; BufferedReader rd; StringBuilder result = new StringBuilder(); String line; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.connect(); InputStream in = conn.getInputStream(); rd = new BufferedReader(new InputStreamReader(in), 819200); logger.info("Loading remote file: " + urlToRead); while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); } catch (Throwable e) { logger.debug("Failed to retrieve file.", e); throw e; } return result.toString(); } public static List<String> listJsonBlobsForTreeSha(String sha, String testRoot) throws IOException { if (SystemProperties.getDefault().githubTestsLoadLocal()) { String path = SystemProperties.getDefault().githubTestsPath() + System.getProperty("file.separator") + testRoot.replaceAll("/", ""); List<String> files = FileUtil.recursiveList(path); List<String> jsons = new ArrayList<>(); for (String f : files) { if (f.endsWith(".json")) jsons.add( f.replace(path + System.getProperty("file.separator"), "") .replaceAll(System.getProperty("file.separator"), "/")); } return jsons; } String result = getFromUrl("https://api.github.com/repos/ethereum/tests/git/trees/" + sha + "?recursive=1"); JSONParser parser = new JSONParser(); JSONObject testSuiteObj = null; List<String> blobs = new ArrayList<>(); try { testSuiteObj = (JSONObject) parser.parse(result); JSONArray tree = (JSONArray)testSuiteObj.get("tree"); for (Object oEntry : tree) { JSONObject entry = (JSONObject) oEntry; String type = (String) entry.get("type"); String path = (String) entry.get("path"); if (!type.equals("blob")) continue; if (!path.endsWith(".json")) continue; blobs.add((String) entry.get("path")); } } catch (ParseException e) { e.printStackTrace(); } return blobs; } }
lgpl-3.0
jjettenn/molgenis
molgenis-scripts-core/src/test/java/org/molgenis/script/ScriptTest.java
1157
package org.molgenis.script; import org.molgenis.file.FileStore; import org.springframework.util.FileCopyUtils; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.Map; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.*; public class ScriptTest { @Test public void generateScript() throws IOException { FileStore fileStore = new FileStore(System.getProperty("java.io.tmpdir")); Map<String, Object> parameterValues = Collections.singletonMap("name", "Piet"); Script script = mock(Script.class); when(script.getContent()).thenReturn("Hey ${name}"); when(script.generateScript(fileStore, "txt", parameterValues)).thenCallRealMethod(); File f = script.generateScript(fileStore, "txt", parameterValues); assertNotNull(f); assertTrue(f.exists()); assertTrue(f.getPath().endsWith(".txt")); String s = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(f))); assertEquals("Hey Piet", s); f.delete(); } }
lgpl-3.0
deletethis-github/Civilization
src/main/java/deletethis/civilization/block/BlockCarrot.java
578
package deletethis.civilization.block; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; public class BlockCarrot extends Block { public BlockCarrot() { super(Material.wood); this.setUnlocalizedName("carrot_block"); this.setHardness(2.0F); this.setResistance(5.0F); this.setStepSound(soundTypeWood); this.setCreativeTab(CreativeTabs.tabBlock); } @Override public boolean isOpaqueCube() { return false; } @Override public boolean isFullCube() { return false; } }
lgpl-3.0
ScalaSoft/android-nanodegree
app/src/main/java/com/example/android/sunshine/app/MainActivity.java
5773
/* * Copyright (C) 2014 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.example.android.sunshine.app; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity implements ForecastFragment.Callback { private final String LOG_TAG = MainActivity.class.getSimpleName(); private static final String DETAILFRAGMENT_TAG = "DFTAG"; private boolean mTwoPane; private String mLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLocation = Utility.getPreferredLocation(this); setContentView(R.layout.activity_main); if (findViewById(R.id.weather_detail_container) != null) { // The detail container view will be present only in the large-screen layouts // (res/layout-sw600dp). If this view is present, then the activity should be // in two-pane mode. mTwoPane = true; // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, new DetailFragment(), DETAILFRAGMENT_TAG) .commit(); } } else { mTwoPane = false; getSupportActionBar().setElevation(0f); } ForecastFragment forecastFragment = ((ForecastFragment)getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast)); forecastFragment.setUseTodayLayout(!mTwoPane); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; } if (id == R.id.action_map) { openPreferredLocationInMap(); return true; } return super.onOptionsItemSelected(item); } private void openPreferredLocationInMap() { String location = Utility.getPreferredLocation(this); // Using the URI scheme for showing a location found on a map. This super-handy // intent can is detailed in the "Common Intents" page of Android's developer site: // http://developer.android.com/guide/components/intents-common.html#Maps Uri geoLocation = Uri.parse("geo:0,0?").buildUpon() .appendQueryParameter("q", location) .build(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(geoLocation); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { Log.d(LOG_TAG, "Couldn't call " + location + ", no receiving apps installed!"); } } @Override protected void onResume() { super.onResume(); String location = Utility.getPreferredLocation( this ); // update the location in our second pane using the fragment manager if (location != null && !location.equals(mLocation)) { ForecastFragment ff = (ForecastFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_forecast); if ( null != ff ) { ff.onLocationChanged(); } DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentByTag(DETAILFRAGMENT_TAG); if ( null != df ) { df.onLocationChanged(location); } mLocation = location; } } @Override public void onItemSelected(Uri contentUri) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle args = new Bundle(); args.putParcelable(DetailFragment.DETAIL_URI, contentUri); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAILFRAGMENT_TAG) .commit(); } else { Intent intent = new Intent(this, DetailActivity.class) .setData(contentUri); startActivity(intent); } } }
unlicense
m6s/githubbrowser-android
libraries/network/src/main/java/info/mschmitt/githubbrowser/network/internal/utils/OkHttpUtils.java
1824
package info.mschmitt.githubbrowser.network.internal.utils; import com.google.gson.TypeAdapter; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import rx.Single; import rx.subscriptions.Subscriptions; /** * @author Matthias Schmitt */ public class OkHttpUtils { public static <T> Single<T> toSingle(OkHttpClient client, Request request, TypeAdapter<T> typeAdapter, TypeAdapter<? extends Throwable> errorAdapter) { return Single.create(subscriber -> { if (subscriber.isUnsubscribed()) { return; } Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { if (subscriber.isUnsubscribed()) { return; } subscriber.onError(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (subscriber.isUnsubscribed()) { return; } if (response.isSuccessful()) { T t = typeAdapter.fromJson(response.body().charStream()); subscriber.onSuccess(t); } else { Throwable throwable = errorAdapter.fromJson(response.body().charStream()); subscriber.onError(throwable); } } }); subscriber.add(Subscriptions.create(call::cancel)); }); } }
unlicense
kevin-duan/Imenu
iMenu/src/com/huassit/imenu/android/model/MenuUnit.java
484
package com.huassit.imenu.android.model; import org.json.JSONObject; public class MenuUnit extends BaseModel<MenuUnit> { public String menu_unit_id; public String menu_unit_title; @Override public MenuUnit parse(JSONObject jsonObject) { if (jsonObject != null) { menu_unit_id = jsonObject.optString("menu_unit_id"); menu_unit_title = jsonObject.optString("menu_unit_title"); } return this; } }
apache-2.0
manishgupta88/incubator-carbondata
core/src/main/java/org/apache/carbondata/core/statusmanager/LoadMetadataDetails.java
12619
/* * 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.carbondata.core.statusmanager; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.carbondata.common.logging.LogServiceFactory; import org.apache.carbondata.core.constants.CarbonCommonConstants; import org.apache.log4j.Logger; /* Prior to Carbon 1.3 the the loadMetaData @timestamp and @loadStartTime was stored as as date string format "dd-MM-yyyy HH:mm:ss:SSS". The date string value is specific to the timezone. SO the timestamp in long by the date string will not result into same value if converted to date in different timezone. Json Object of LoadMetaData before CarbonData 1.3 |-------------------------------------------------------------------------------------------| | [{"timestamp":"15-12-2017 16:50:31:703","loadStatus":"Success","loadName":"0", | | "partitionCount":"0","isDeleted":"FALSE","dataSize":"912","indexSize":"700", | | "updateDeltaEndTimestamp":"","updateDeltaStartTimestamp":"","updateStatusFileName":"", | | "loadStartTime":"15-12-2017 16:50:27:493","visibility":"true","fileFormat":"COLUMNAR_V3"}]| |-------------------------------------------------------------------------------------------| Fix: As the System.currentTimeMillis() returns the same value irrespective of timezone. So if Carbon stores the long value for @timestamp and @loadStartTime value then the value will be same irrespective of the timezone. Json Object of LoadMetaData for CarbonData 1.3 |-------------------------------------------------------------------------------------------| | [{"timestamp":"1513336827593","loadStatus":"Success","loadName":"0", | | "partitionCount":"0","isDeleted":"FALSE","dataSize":"912","indexSize":"700", | | "updateDeltaEndTimestamp":"","updateDeltaStartTimestamp":"","updateStatusFileName":"", | | "loadStartTime":"1513336827593","visibility":"true","fileFormat":"COLUMNAR_V3"}] | |-------------------------------------------------------------------------------------------| */ public class LoadMetadataDetails implements Serializable { private static final long serialVersionUID = 1106104914918491724L; private String timestamp; // For backward compatibility, this member is required to read from JSON in the table_status file private SegmentStatus loadStatus; // name of the segment private String loadName; // partition count of this segment private String partitionCount; private String isDeleted = CarbonCommonConstants.KEYWORD_FALSE; private String dataSize; private String indexSize; public String getDataSize() { return dataSize; } public void setDataSize(String dataSize) { this.dataSize = dataSize; } public String getIndexSize() { return indexSize; } public void setIndexSize(String indexSize) { this.indexSize = indexSize; } // update delta end timestamp private String updateDeltaEndTimestamp = ""; // update delta start timestamp private String updateDeltaStartTimestamp = ""; // this will represent the update status file name at that point of time. private String updateStatusFileName = ""; /** * LOGGER */ private static final Logger LOGGER = LogServiceFactory.getLogService(LoadMetadataDetails.class.getName()); // don't remove static as the write will fail. private static final SimpleDateFormat parser = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_MILLIS); /** * Segment modification or deletion time stamp */ private String modificationOrdeletionTimesStamp; private String loadStartTime; private String mergedLoadName; /** * visibility is used to determine whether to the load is visible or not. */ private String visibility = "true"; /** * To know if the segment is a major compacted segment or not. */ private String majorCompacted; /** * the file format of this segment */ private FileFormat fileFormat = FileFormat.COLUMNAR_V3; /** * Segment file name where it has the information of partition information. */ private String segmentFile; public String getPartitionCount() { return partitionCount; } @Deprecated public void setPartitionCount(String partitionCount) { this.partitionCount = partitionCount; } public long getLoadEndTime() { if (timestamp == null) { return CarbonCommonConstants.SEGMENT_LOAD_TIME_DEFAULT; } return convertTimeStampToLong(timestamp); } public void setLoadEndTime(long timestamp) { this.timestamp = Long.toString(timestamp); } public SegmentStatus getSegmentStatus() { return loadStatus; } public void setSegmentStatus(SegmentStatus segmentStatus) { this.loadStatus = segmentStatus; } public String getLoadName() { return loadName; } public void setLoadName(String loadName) { this.loadName = loadName; } /** * @return the modificationOrdeletionTimesStamp */ public long getModificationOrdeletionTimesStamp() { if (null == modificationOrdeletionTimesStamp) { return 0; } return convertTimeStampToLong(modificationOrdeletionTimesStamp); } /** * @param modificationOrdeletionTimesStamp the modificationOrdeletionTimesStamp to set */ public void setModificationOrdeletionTimesStamp(long modificationOrdeletionTimesStamp) { this.modificationOrdeletionTimesStamp = Long.toString(modificationOrdeletionTimesStamp); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((loadName == null) ? 0 : loadName.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof LoadMetadataDetails)) { return false; } LoadMetadataDetails other = (LoadMetadataDetails) obj; if (loadName == null) { if (other.loadName != null) { return false; } } else if (!loadName.equals(other.loadName)) { return false; } return true; } /** * @return the startLoadTime */ public long getLoadStartTime() { if (loadStartTime == null) { return CarbonCommonConstants.SEGMENT_LOAD_TIME_DEFAULT; } return convertTimeStampToLong(loadStartTime); } /** * return loadStartTime * * @return */ public long getLoadStartTimeAsLong() { if (!loadStartTime.isEmpty()) { Long time = getTimeStamp(loadStartTime); if (null != time) { return time; } } return 0; } /** * This method will convert a given timestamp to long value and then to string back * * @param factTimeStamp * @return Long TimeStamp value is milliseconds */ private long convertTimeStampToLong(String factTimeStamp) { try { return Long.parseLong(factTimeStamp); } catch (NumberFormatException nf) { SimpleDateFormat parser = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_MILLIS); // it is the processing for existing table before carbon 1.3 Date dateToStr = null; try { dateToStr = parser.parse(factTimeStamp); return dateToStr.getTime(); } catch (ParseException e) { LOGGER .error("Cannot convert" + factTimeStamp + " to Time/Long type value" + e.getMessage()); parser = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP); try { // if the load is in progress, factTimeStamp will be null, so use current time if (null == factTimeStamp) { return System.currentTimeMillis(); } dateToStr = parser.parse(factTimeStamp); return dateToStr.getTime(); } catch (ParseException e1) { LOGGER.error( "Cannot convert" + factTimeStamp + " to Time/Long type value" + e1.getMessage()); return 0; } } } } /** * returns load start time as long value * * @param loadStartTime * @return Long TimeStamp value is nanoseconds */ public Long getTimeStamp(String loadStartTime) { try { return Long.parseLong(loadStartTime) * 1000L; } catch (NumberFormatException nf) { // it is the processing for existing table before carbon 1.3 Date dateToStr = null; try { dateToStr = parser.parse(loadStartTime); return dateToStr.getTime() * 1000; } catch (ParseException e) { LOGGER.error("Cannot convert" + loadStartTime + " to Time/Long type value" + e.getMessage()); return null; } } } /** * @param loadStartTime */ public void setLoadStartTime(long loadStartTime) { this.loadStartTime = Long.toString(loadStartTime); } /** * @return the mergedLoadName */ public String getMergedLoadName() { return mergedLoadName; } /** * @param mergedLoadName the mergedLoadName to set */ public void setMergedLoadName(String mergedLoadName) { this.mergedLoadName = mergedLoadName; } /** * @return the visibility */ public String getVisibility() { return visibility; } /** * @param visibility the visibility to set */ public void setVisibility(String visibility) { this.visibility = visibility; } /** * Return true if it is a major compacted segment. * @return majorCompacted */ public String isMajorCompacted() { return majorCompacted; } /** * Set true if it is a major compacted segment. * * @param majorCompacted */ public void setMajorCompacted(String majorCompacted) { this.majorCompacted = majorCompacted; } /** * To set isDeleted property. * * @param isDeleted */ public void setIsDeleted(String isDeleted) { this.isDeleted = isDeleted; } /** * To get the update delta end timestamp * * @return updateDeltaEndTimestamp */ public String getUpdateDeltaEndTimestamp() { return updateDeltaEndTimestamp; } /** * To set the update delta end timestamp * * @param updateDeltaEndTimestamp */ public void setUpdateDeltaEndTimestamp(String updateDeltaEndTimestamp) { this.updateDeltaEndTimestamp = updateDeltaEndTimestamp; } /** * To get the update delta start timestamp * * @return updateDeltaStartTimestamp */ public String getUpdateDeltaStartTimestamp() { return updateDeltaStartTimestamp; } /** * To set the update delta start timestamp * * @param updateDeltaStartTimestamp */ public void setUpdateDeltaStartTimestamp(String updateDeltaStartTimestamp) { this.updateDeltaStartTimestamp = updateDeltaStartTimestamp; } /** * To get the updateStatusFileName * * @return updateStatusFileName */ public String getUpdateStatusFileName() { return updateStatusFileName; } /** * To set the updateStatusFileName * * @param updateStatusFileName */ public void setUpdateStatusFileName(String updateStatusFileName) { this.updateStatusFileName = updateStatusFileName; } public FileFormat getFileFormat() { return fileFormat; } public void setFileFormat(FileFormat fileFormat) { this.fileFormat = fileFormat; } public String getSegmentFile() { return segmentFile; } public void setSegmentFile(String segmentFile) { this.segmentFile = segmentFile; } @Override public String toString() { return "LoadMetadataDetails{" + "loadStatus=" + loadStatus + ", loadName='" + loadName + '\'' + ", loadStartTime='" + loadStartTime + '\'' + ", segmentFile='" + segmentFile + '\'' + '}'; } }
apache-2.0
alibaba/fastjson
src/test/java/com/alibaba/json/test/benchmark/encode/ArrayByte1000Encode.java
612
package com.alibaba.json.test.benchmark.encode; import com.alibaba.json.test.benchmark.BenchmarkCase; import com.alibaba.json.test.codec.Codec; public class ArrayByte1000Encode extends BenchmarkCase { private Object object; public ArrayByte1000Encode(){ super("ArrayByte1000Encode"); byte[] array = new byte[1000]; for (int i = 0; i < array.length; ++i) { array[i] = (byte) (i % 100); } this.object = array; } @Override public void execute(Codec codec) throws Exception { codec.encode(object); } }
apache-2.0
gspandy/divconq
divconq.web/src/main/java/w3/html/TextArea.java
1908
/* ************************************************************************ # # DivConq # # http://divconq.com/ # # Copyright: # Copyright 2014 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package w3.html; import divconq.web.WebContext; import divconq.web.dcui.Attributes; import divconq.web.dcui.HtmlUtil; import divconq.web.dcui.ICodeTag; import divconq.web.dcui.MixedElement; import divconq.web.dcui.Nodes; import divconq.xml.XElement; public class TextArea extends MixedElement implements ICodeTag { public TextArea() { super(); } public TextArea(Object... args) { super(args); } @Override public void parseElement(WebContext ctx, Nodes nodes, XElement xel) { Attributes attrs = HtmlUtil.initAttrs(xel); if (xel.hasAttribute("name")) attrs.add("name", xel.getRawAttribute("name")); if (xel.hasAttribute("cols")) attrs.add("cols", xel.getRawAttribute("cols")); if (xel.hasAttribute("rows")) attrs.add("rows", xel.getRawAttribute("rows")); if (xel.hasAttribute("disabled")) attrs.add("disabled", xel.getRawAttribute("disabled")); if (xel.hasAttribute("placeholder")) attrs.add("placeholder", xel.getRawAttribute("placeholder")); if (xel.hasAttribute("maxlength")) attrs.add("maxlength", xel.getRawAttribute("maxlength")); if (xel.hasAttribute("readonly")) attrs.add("readonly", xel.getRawAttribute("readonly")); this.myArguments = new Object[] { attrs, ctx.getDomain().parseXml(ctx, xel) }; nodes.add(this); } @Override public void build(WebContext ctx, Object... args) { super.build(ctx, "textarea", true, args); } }
apache-2.0
RobAltena/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/env/impl/DebugAction.java
1242
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.env.impl; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.nd4j.linalg.env.EnvironmentalAction; import org.nd4j.linalg.factory.Nd4j; @Slf4j public class DebugAction implements EnvironmentalAction { @Override public String targetVariable() { return "ND4J_DEBUG"; } @Override public void process(String value) { val v = Boolean.valueOf(value); Nd4j.getExecutioner().enableDebugMode(v); } }
apache-2.0
kiereleaseuser/uberfire
uberfire-extensions/uberfire-wires/uberfire-wires-core/uberfire-wires-core-grids/src/main/java/org/uberfire/ext/wires/core/grids/client/widget/grid/selections/CellSelectionStrategy.java
1534
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.wires.core.grids.client.widget.grid.selections; import org.uberfire.ext.wires.core.grids.client.model.GridData; /** * Strategy for selection of cells. */ public interface CellSelectionStrategy { /** * Handle a single cell selection. * @param model Underlying GridData model. * @param uiRowIndex Index of row as seen in the UI * @param uiColumnIndex Index of the column as seen in the UI * @param isShiftKeyDown True if the shift key is pressed. * @param isControlKeyDown True if the control key is pressed. * @return true if the selections have changed. */ boolean handleSelection( final GridData model, final int uiRowIndex, final int uiColumnIndex, final boolean isShiftKeyDown, final boolean isControlKeyDown ); }
apache-2.0
mfranklin/abdera
extensions/sharing/src/main/java/org/apache/abdera/ext/sharing/Sharing.java
3015
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.ext.sharing; import java.util.Date; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.AtomDate; import org.apache.abdera.model.Element; import org.apache.abdera.model.ExtensibleElementWrapper; public class Sharing extends ExtensibleElementWrapper { public Sharing(Element internal) { super(internal); } public Sharing(Factory factory, QName qname) { super(factory, qname); } public Date getSince() { String since = getAttributeValue("since"); return since != null ? AtomDate.parse(since) : null; } public void setSince(Date since) { if (since != null) { setAttributeValue("since", AtomDate.format(since)); } else { removeAttribute(new QName("since")); } } public Date getUntil() { String until = getAttributeValue("until"); return until != null ? AtomDate.parse(until) : null; } public void setUntil(Date until) { if (until != null) { setAttributeValue("until", AtomDate.format(until)); } else { removeAttribute(new QName("until")); } } public Date getExpires() { String expires = getAttributeValue("expires"); return expires != null ? AtomDate.parse(expires) : null; } public void setExpires(Date expires) { if (expires != null) { setAttributeValue("expires", AtomDate.format(expires)); } else { removeAttribute(new QName("expires")); } } public List<Related> getRelated() { return getExtensions(SharingHelper.SSE_RELATED); } public void addRelated(Related related) { addExtension(related); } public Related addRelated() { return getFactory().newElement(SharingHelper.SSE_RELATED, this); } public Related addRelated(String link, String title, Related.Type type) { Related related = addRelated(); related.setLink(link); related.setTitle(title); related.setType(type); return related; } }
apache-2.0
00wendi00/MyProject
W_myeclipse/binary/com.sun.java.jdk.win32.x86_1.6.0.013/demo/plugin/jfc/Java2D/src/java2d/demos/Images/JPEGFlip.java
5534
/* * @(#)JPEGFlip.java 1.27 06/08/29 * * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */ /* * @(#)JPEGFlip.java 1.27 06/08/29 */ package java2d.demos.Images; import static java.awt.Color.*; import java.awt.*; import com.sun.image.codec.jpeg.*; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.geom.GeneralPath; import java.io.*; import java2d.Surface; /** * Render a filled star & duke into a BufferedImage, save the BufferedImage * as a JPEG, display the BufferedImage, using the decoded JPEG BufferedImage * DataBuffer flip the elements, display the JPEG flipped BufferedImage. */ public class JPEGFlip extends Surface { private static Image img; public JPEGFlip() { setBackground(WHITE); img = getImage("duke.gif"); } public void render(int w, int h, Graphics2D g2) { int hh = h/2; BufferedImage bi = new BufferedImage(w, hh, BufferedImage.TYPE_INT_RGB); Graphics2D big = bi.createGraphics(); // .. use rendering hints from J2DCanvas .. big.setRenderingHints(g2.getRenderingHints()); big.setBackground(getBackground()); big.clearRect(0, 0, w, hh); big.setColor(GREEN.darker()); GeneralPath p = new GeneralPath(GeneralPath.WIND_NON_ZERO); p.moveTo(- w / 2.0f, - hh / 8.0f); p.lineTo(+ w / 2.0f, - hh / 8.0f); p.lineTo(- w / 4.0f, + hh / 2.0f); p.lineTo(+ 0.0f, - hh / 2.0f); p.lineTo(+ w / 4.0f, + hh / 2.0f); p.closePath(); big.translate(w/2, hh/2); big.fill(p); int iw = img.getWidth(this); int ih = img.getHeight(this); if (hh < ih * 1.5) ih = (int) (ih * ((hh / (ih*1.5)))); big.drawImage(img, -img.getWidth(this)/2, -ih/2, iw, ih, this); g2.drawImage(bi, 0, 0, this); g2.setFont(new Font("Dialog", Font.PLAIN, 10)); g2.setColor(BLACK); g2.drawString("BufferedImage", 4, 12); BufferedImage bi1 = null; try { // To write the jpeg to a file uncomment the File* lines and // comment out the ByteArray*Stream lines. //File file = new File("images", "test.jpg"); //FileOutputStream out = new FileOutputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(1.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(bi); //FileInputStream in = new FileInputStream(file); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in); bi1 = decoder.decodeAsBufferedImage(); } catch (Exception ex) { g2.setColor(RED); g2.drawString("write permissions on images/test.jpg?", 5, hh*2-5); return; } if (bi1 == null) { g2.setColor(RED); g2.drawString("decodeAsBufferedImage=null", 5, hh*2-5); return; } BufferedImage bi2 = new BufferedImage(bi1.getWidth(),bi1.getHeight(),bi1.getType()); DataBuffer db1 = bi1.getRaster().getDataBuffer(); DataBuffer db2 = bi2.getRaster().getDataBuffer(); for (int i = db1.getSize()-1, j = 0; i >= 0; --i, j++) { db2.setElem(j, db1.getElem(i)); } g2.drawImage(bi2, 0, hh, this); g2.drawString("JPEGImage Flipped", 4, hh*2-4); g2.drawLine(0, hh, w, hh); } public static void main(String s[]) { createDemoFrame(new JPEGFlip()); } }
apache-2.0
benson-basis/fastutil
src/it/unimi/dsi/fastutil/io/MeasurableInputStream.java
888
package it.unimi.dsi.fastutil.io; /* * Copyright (C) 2005-2014 Sebastiano Vigna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.InputStream; /** An {@link InputStream} that implements also the {@link MeasurableStream} interface. * * @since 5.0.4 */ public abstract class MeasurableInputStream extends InputStream implements MeasurableStream { }
apache-2.0
aemay2/hapi-fhir
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/BaseJpaResourceProviderObservationDstu3.java
3858
package ca.uhn.fhir.jpa.provider.dstu3; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoObservation; import ca.uhn.fhir.jpa.model.util.JpaConstants; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.DateAndListParam; import ca.uhn.fhir.rest.param.ReferenceAndListParam; import ca.uhn.fhir.rest.param.TokenAndListParam; import org.hl7.fhir.dstu3.model.Observation; import org.hl7.fhir.dstu3.model.UnsignedIntType; import org.hl7.fhir.instance.model.api.IPrimitiveType; /* * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ public class BaseJpaResourceProviderObservationDstu3 extends JpaResourceProviderDstu3<Observation> { /** * Observation/$lastn */ @Operation(name = JpaConstants.OPERATION_LASTN, idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider observationLastN( javax.servlet.http.HttpServletRequest theServletRequest, javax.servlet.http.HttpServletResponse theServletResponse, ca.uhn.fhir.rest.api.server.RequestDetails theRequestDetails, @Description(formalDefinition = "Results from this method are returned across multiple pages. This parameter controls the size of those pages.") @OperationParam(name = Constants.PARAM_COUNT) UnsignedIntType theCount, @Description(shortDefinition="The classification of the type of observation") @OperationParam(name="category") TokenAndListParam theCategory, @Description(shortDefinition="The code of the observation type") @OperationParam(name="code") TokenAndListParam theCode, @Description(shortDefinition="The effective date of the observation") @OperationParam(name="date") DateAndListParam theDate, @Description(shortDefinition="The subject that the observation is about (if patient)") @OperationParam(name="patient") ReferenceAndListParam thePatient, @Description(shortDefinition="The subject that the observation is about") @OperationParam(name="subject" ) ReferenceAndListParam theSubject, @Description(shortDefinition="The maximum number of observations to return for each observation code") @OperationParam(name = "max", typeName = "integer", min = 0, max = 1) IPrimitiveType<Integer> theMax ) { startRequest(theServletRequest); try { SearchParameterMap paramMap = new SearchParameterMap(); paramMap.add(Observation.SP_CATEGORY, theCategory); paramMap.add(Observation.SP_CODE, theCode); paramMap.add(Observation.SP_DATE, theDate); if (thePatient != null) { paramMap.add(Observation.SP_PATIENT, thePatient); } if (theSubject != null) { paramMap.add(Observation.SP_SUBJECT, theSubject); } if (theMax != null) { paramMap.setLastNMax(theMax.getValue()); } if (theCount != null) { paramMap.setCount(theCount.getValue()); } return ((IFhirResourceDaoObservation<Observation>) getDao()).observationsLastN(paramMap, theRequestDetails, theServletResponse); } finally { endRequest(theServletRequest); } } }
apache-2.0
arenadata/ambari
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ViewEntityTest.java
12395
/** * 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.ambari.server.orm.entities; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.controller.spi.Resource; import org.apache.ambari.server.controller.spi.ResourceProvider; import org.apache.ambari.server.view.ViewSubResourceDefinition; import org.apache.ambari.server.view.configuration.ResourceConfig; import org.apache.ambari.server.view.configuration.ResourceConfigTest; import org.apache.ambari.server.view.configuration.ViewConfig; import org.apache.ambari.server.view.configuration.ViewConfigTest; import org.apache.ambari.view.ViewDefinition; import org.apache.ambari.view.ViewInstanceDefinition; import org.apache.ambari.view.validation.ValidationResult; import org.apache.ambari.view.validation.Validator; import org.junit.Assert; import org.junit.Test; import java.util.Collection; import java.util.Properties; import java.util.Set; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; /** * ViewEntity tests. */ public class ViewEntityTest { private static String with_ambari_versions = "<view>\n" + " <name>MY_VIEW</name>\n" + " <label>My View!</label>\n" + " <version>1.0.0</version>\n" + " <min-ambari-version>1.6.1</min-ambari-version>\n" + " <max-ambari-version>2.0.0</max-ambari-version>\n" + "</view>"; public static ViewEntity getViewEntity() throws Exception { return getViewEntity(ViewConfigTest.getConfig()); } public static ViewEntity getViewEntity(ViewConfig viewConfig) throws Exception { Properties properties = new Properties(); properties.put("p1", "v1"); properties.put("p2", "v2"); properties.put("p3", "v3"); Configuration ambariConfig = new Configuration(properties); ViewEntity viewEntity = new ViewEntity(viewConfig, ambariConfig, "view.jar"); viewEntity.setClassLoader(ViewEntityTest.class.getClassLoader()); ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity(); resourceTypeEntity.setId(10); resourceTypeEntity.setName(viewEntity.getName()); viewEntity.setResourceType(resourceTypeEntity); long id = 20L; for (ViewInstanceEntity viewInstanceEntity : viewEntity.getInstances()) { ResourceEntity resourceEntity = new ResourceEntity(); resourceEntity.setId(id++); resourceEntity.setResourceType(resourceTypeEntity); viewInstanceEntity.setResource(resourceEntity); } return viewEntity; } @Test public void testGetName() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("MY_VIEW{1.0.0}", viewDefinition.getName()); } @Test public void testGetCommonName() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("MY_VIEW", viewDefinition.getCommonName()); } @Test public void testGetLabel() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("My View!", viewDefinition.getLabel()); } @Test public void testGetVersion() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("1.0.0", viewDefinition.getVersion()); } @Test public void testGetBuild() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("99", viewDefinition.getBuild()); } @Test public void testGetIcon() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("/this/is/the/icon/url/icon.png", viewDefinition.getIcon()); viewDefinition.setIcon("/a/different/icon.png"); Assert.assertEquals("/a/different/icon.png", viewDefinition.getIcon()); } @Test public void testGetIcon64() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("/this/is/the/icon/url/icon64.png", viewDefinition.getIcon64()); viewDefinition.setIcon64("/a/different/icon.png"); Assert.assertEquals("/a/different/icon.png", viewDefinition.getIcon64()); } @Test public void testSetGetConfiguration() throws Exception { ViewConfig viewConfig = ViewConfigTest.getConfig(); ViewEntity viewDefinition = getViewEntity(viewConfig); Assert.assertEquals(viewConfig, viewDefinition.getConfiguration()); ViewConfig newViewConfig = ViewConfigTest.getConfig(with_ambari_versions); viewDefinition.setConfiguration(newViewConfig); Assert.assertEquals(newViewConfig, viewDefinition.getConfiguration()); } @Test public void testIsClusterConfigurable() throws Exception { ViewConfig viewConfig = ViewConfigTest.getConfig(); ViewEntity viewDefinition = getViewEntity(viewConfig); Assert.assertEquals(viewConfig, viewDefinition.getConfiguration()); ViewConfig newViewConfig = ViewConfigTest.getConfig(); viewDefinition.setConfiguration(newViewConfig); Assert.assertTrue(viewDefinition.isClusterConfigurable()); newViewConfig = ViewConfigTest.getConfig(with_ambari_versions); viewDefinition.setConfiguration(newViewConfig); Assert.assertFalse(viewDefinition.isClusterConfigurable()); } @Test public void testGetAmbariProperty() throws Exception { ViewConfig viewConfig = ViewConfigTest.getConfig(); ViewEntity viewDefinition = getViewEntity(viewConfig); Assert.assertEquals("v1", viewDefinition.getAmbariProperty("p1")); Assert.assertEquals("v2", viewDefinition.getAmbariProperty("p2")); Assert.assertEquals("v3", viewDefinition.getAmbariProperty("p3")); } @Test public void testAddGetResourceProvider() throws Exception { ViewEntity viewDefinition = getViewEntity(); ResourceProvider provider1 = createNiceMock(ResourceProvider.class); Resource.Type type1 = new Resource.Type("myType1"); viewDefinition.addResourceProvider(type1, provider1); Assert.assertEquals(provider1, viewDefinition.getResourceProvider(type1)); ResourceProvider provider2 = createNiceMock(ResourceProvider.class); Resource.Type type2 = new Resource.Type("myType2"); viewDefinition.addResourceProvider(type2, provider2); Assert.assertEquals(provider2, viewDefinition.getResourceProvider(type2)); Set<Resource.Type> types = viewDefinition.getViewResourceTypes(); Assert.assertEquals(2, types.size()); Assert.assertTrue(types.contains(type1)); Assert.assertTrue(types.contains(type2)); } @Test public void testAddGetResourceDefinition() throws Exception { ViewEntity viewDefinition = getViewEntity(); ViewSubResourceDefinition definition = createNiceMock(ViewSubResourceDefinition.class); Resource.Type type = new Resource.Type("myType"); expect(definition.getType()).andReturn(type); replay(definition); viewDefinition.addResourceDefinition(definition); Assert.assertEquals(definition, viewDefinition.getResourceDefinition(type)); verify(definition); } @Test public void testAddGetResourceConfiguration() throws Exception { ViewEntity viewDefinition = getViewEntity(); ResourceConfig config = ResourceConfigTest.getResourceConfigs().get(0); Resource.Type type1 = new Resource.Type("myType"); viewDefinition.addResourceConfiguration(type1, config); Assert.assertEquals(config, viewDefinition.getResourceConfigurations().get(type1)); Resource.Type type2 = new Resource.Type("myType2"); viewDefinition.addResourceConfiguration(type2, config); Assert.assertEquals(config, viewDefinition.getResourceConfigurations().get(type2)); } @Test public void testAddGetInstanceDefinition() throws Exception { ViewEntity viewDefinition = getViewEntity(); ViewInstanceEntity definition = createNiceMock(ViewInstanceEntity.class); expect(definition.getName()).andReturn("instance1").anyTimes(); replay(definition); viewDefinition.addInstanceDefinition(definition); Assert.assertEquals(definition, viewDefinition.getInstanceDefinition("instance1")); Collection<ViewInstanceEntity> definitions = viewDefinition.getInstances(); Assert.assertEquals(1, definitions.size()); Assert.assertTrue(definitions.contains(definition)); verify(definition); } @Test public void testGetClassLoader() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals(ViewEntityTest.class.getClassLoader(), viewDefinition.getClassLoader()); } @Test public void testGetArchive() throws Exception { ViewEntity viewDefinition = getViewEntity(); Assert.assertEquals("view.jar", viewDefinition.getArchive()); } @Test public void testGetAmbariConfiguration() throws Exception { ViewEntity viewDefinition = getViewEntity(); Configuration configuration = viewDefinition.getAmbariConfiguration(); Assert.assertEquals("v1", configuration.getProperty("p1")); Assert.assertEquals("v2", configuration.getProperty("p2")); Assert.assertEquals("v3", configuration.getProperty("p3")); } @Test public void testGetSetStatus() throws Exception { ViewEntity viewDefinition = getViewEntity(); viewDefinition.setStatus(ViewDefinition.ViewStatus.PENDING); Assert.assertEquals(ViewDefinition.ViewStatus.PENDING, viewDefinition.getStatus()); viewDefinition.setStatus(ViewDefinition.ViewStatus.DEPLOYING); Assert.assertEquals(ViewDefinition.ViewStatus.DEPLOYING, viewDefinition.getStatus()); viewDefinition.setStatus(ViewDefinition.ViewStatus.DEPLOYED); Assert.assertEquals(ViewDefinition.ViewStatus.DEPLOYED, viewDefinition.getStatus()); viewDefinition.setStatus(ViewDefinition.ViewStatus.ERROR); Assert.assertEquals(ViewDefinition.ViewStatus.ERROR, viewDefinition.getStatus()); } @Test public void testGetSetStatusDetail() throws Exception { ViewEntity viewDefinition = getViewEntity(); viewDefinition.setStatusDetail("status detail"); Assert.assertEquals("status detail", viewDefinition.getStatusDetail()); } @Test public void testGetSetValidator() throws Exception { ViewEntity viewDefinition = getViewEntity(); Validator validator = new TestValidator(); viewDefinition.setValidator(validator); Assert.assertEquals(validator, viewDefinition.getValidator()); } @Test public void testisDeployed() throws Exception { ViewEntity viewDefinition = getViewEntity(); viewDefinition.setStatus(ViewDefinition.ViewStatus.PENDING); Assert.assertFalse(viewDefinition.isDeployed()); viewDefinition.setStatus(ViewDefinition.ViewStatus.DEPLOYING); Assert.assertFalse(viewDefinition.isDeployed()); viewDefinition.setStatus(ViewDefinition.ViewStatus.DEPLOYED); Assert.assertTrue(viewDefinition.isDeployed()); viewDefinition.setStatus(ViewDefinition.ViewStatus.ERROR); Assert.assertFalse(viewDefinition.isDeployed()); } @Test public void testSetIsSystem() throws Exception { ViewEntity viewDefinition = getViewEntity(); viewDefinition.setSystem(false); Assert.assertFalse(viewDefinition.isSystem()); viewDefinition.setSystem(true); Assert.assertTrue(viewDefinition.isSystem()); } public static class TestValidator implements Validator { ValidationResult result; @Override public ValidationResult validateInstance(ViewInstanceDefinition definition, ValidationContext mode) { return result; } @Override public ValidationResult validateProperty(String property, ViewInstanceDefinition definition, ValidationContext mode) { return result; } } }
apache-2.0
PRECISE/ROSLab
lib/slf4j-1.7.10/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java
1472
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.migrator; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({AternativeApproach.class}) public class PackageTest { }
apache-2.0
jboss-fuse/quickstarts
sap/fuse/sap-qidoc-destination-fuse/src/main/java/org/jboss/quickstarts/fuse/sap_qidoc_destination_fuse/CreateBettyIDoc.java
2724
/** * Copyright 2016 Red Hat, Inc. * * Red Hat 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.jboss.quickstarts.fuse.sap_qidoc_destination_fuse; import org.apache.camel.Exchange; import org.fusesource.camel.component.sap.SapQueuedIDocDestinationEndpoint; import org.fusesource.camel.component.sap.model.idoc.Document; import org.fusesource.camel.component.sap.model.idoc.Segment; /** * A {@link CreateBettyIDoc} is a processor bean which builds a FLCUSTOMER_CREATEFROMDATA01 IDoc * to create a flight customer record in SAP for 'Betty Rubble'. * * @author William Collins (punkhornsw@gmail.com) * */ public class CreateBettyIDoc { public void createRequest(Exchange exchange) throws Exception { // Create document and initialize transmission parameters SapQueuedIDocDestinationEndpoint endpoint = exchange.getContext().getEndpoint("sap-qidoc-destination:quickstartDest:QUICKSTARTQUEUE:FLCUSTOMER_CREATEFROMDATA01", SapQueuedIDocDestinationEndpoint.class); Document document = endpoint.createDocument(); document.setMessageType("FLCUSTOMER_CREATEFROMDATA"); document.setRecipientPartnerNumber("QUICKCLNT"); document.setRecipientPartnerType("LS"); document.setSenderPartnerNumber("QUICKSTART"); document.setSenderPartnerType("LS"); // Retrieve document segments. Segment rootSegment = document.getRootSegment(); Segment headerSegment = rootSegment.getChildren("E1SCU_CRE").add(); Segment newCustomerSegment = headerSegment.getChildren("E1BPSCUNEW").add(); // Fill in New Customer Info newCustomerSegment.put("CUSTNAME", "Betty Rubble"); newCustomerSegment.put("FORM", "Mrs."); newCustomerSegment.put("STREET", "123 Pebble Road"); newCustomerSegment.put("POSTCODE", "98765"); newCustomerSegment.put("CITY", "Flagstone"); newCustomerSegment.put("COUNTR", "US"); newCustomerSegment.put("PHONE", "800-555-1313"); newCustomerSegment.put("EMAIL", "betty@flagstone.com"); newCustomerSegment.put("CUSTTYPE", "P"); newCustomerSegment.put("DISCOUNT", "005"); newCustomerSegment.put("LANGU", "E"); // Set the request in in the body of the exchange's message. exchange.getIn().setBody(document); } }
apache-2.0
gotroy/elasticsearch
src/test/java/org/elasticsearch/discovery/DiscoveryTests.java
2486
/* * 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.discovery; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.elasticsearch.test.ElasticsearchIntegrationTest.Scope; import org.junit.Test; import static org.hamcrest.Matchers.equalTo; @ClusterScope(scope=Scope.SUITE, numNodes=2) public class DiscoveryTests extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.settingsBuilder() .put("discovery.zen.ping.multicast.enabled", false) // Can't use this, b/c at the moment all node will only ping localhost:9300 and the shared // cluster will be running there, which leads of no node joining, because the cluster name // isn't equal. // .put("discovery.zen.ping.unicast.hosts", "localhost") .put("discovery.zen.ping.unicast.hosts", "localhost:25300,localhost:25301") .put("transport.tcp.port", "25300-25400") .put(super.nodeSettings(nodeOrdinal)).build(); } @Test public void testUnicastDiscovery() { ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.nodes().size(), equalTo(2)); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.nodes().size(), equalTo(2)); } }
apache-2.0
mogoweb/365browser
app/src/main/java/org/chromium/chrome/browser/BasicNativePage.java
2930
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.app.Activity; import android.content.res.Resources; import android.view.View; import android.widget.FrameLayout.LayoutParams; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.content_public.browser.LoadUrlParams; /** * A basic implementation of a white {@link NativePage} that docks below the toolbar. */ public abstract class BasicNativePage implements NativePage { private final Activity mActivity; private final NativePageHost mHost; private final int mBackgroundColor; private final int mThemeColor; private String mUrl; public BasicNativePage(Activity activity, NativePageHost host) { initialize(activity, host); mActivity = activity; mHost = host; mBackgroundColor = ApiCompatibilityUtils.getColor(activity.getResources(), R.color.default_primary_color); mThemeColor = ApiCompatibilityUtils.getColor( activity.getResources(), R.color.default_primary_color); Resources res = mActivity.getResources(); int topMargin = 0; int bottomMargin = 0; if (activity instanceof ChromeActivity && ((ChromeActivity) activity).getBottomSheet() != null) { bottomMargin = res.getDimensionPixelSize(R.dimen.bottom_control_container_height); } else { topMargin = res.getDimensionPixelSize(R.dimen.tab_strip_height) + res.getDimensionPixelSize(R.dimen.toolbar_height_no_shadow); } LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.setMargins(0, topMargin, 0, bottomMargin); getView().setLayoutParams(layoutParams); } /** * Subclasses shall implement this method to initialize the UI that they hold. */ protected abstract void initialize(Activity activity, NativePageHost host); @Override public abstract View getView(); @Override public String getUrl() { return mUrl; } @Override public int getBackgroundColor() { return mBackgroundColor; } @Override public int getThemeColor() { return mThemeColor; } @Override public boolean needsToolbarShadow() { return true; } @Override public void updateForUrl(String url) { mUrl = url; } @Override public void destroy() { } /** * Tells the native page framework that the url should be changed. */ public void onStateChange(String url) { if (url.equals(mUrl)) return; mHost.loadUrl(new LoadUrlParams(url), /* incognito = */ false); } }
apache-2.0
sll8192/wpan
app/src/main/java/com/xinyu/mwp/entity/CurrentPositionEntity.java
908
package com.xinyu.mwp.entity; /** * Created by Administrator on 2017/3/28. */ public class CurrentPositionEntity extends BaseEntity{ /** * gid : 12 * id : 7 * name : JL884 */ private long gid; private long id; private String name = ""; private String currentPositionName = ""; public String getCurrentPositionName() { return currentPositionName; } public void setCurrentPositionName(String currentPositionName) { this.currentPositionName = currentPositionName; } public long getGid() { return gid; } public void setGid(long gid) { this.gid = gid; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
apache-2.0
GunoH/intellij-community
platform/platform-api/src/com/intellij/util/net/HttpProxySettingsUi.java
13290
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.net; import com.google.common.net.HostAndPort; import com.google.common.net.InetAddresses; import com.google.common.net.InternetDomainName; import com.intellij.ide.IdeBundle; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ConfigurableUi; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.PortField; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.RelativeFont; import com.intellij.ui.components.JBRadioButton; import com.intellij.ui.jcef.JBCefApp; import com.intellij.util.io.HttpRequests; import com.intellij.util.proxy.CommonProxy; import com.intellij.util.proxy.JavaProxyProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; class HttpProxySettingsUi implements ConfigurableUi<HttpConfigurable> { private JPanel myMainPanel; private JTextField myProxyLoginTextField; private JPasswordField myProxyPasswordTextField; private JCheckBox myProxyAuthCheckBox; private PortField myProxyPortTextField; private JTextField myProxyHostTextField; private JCheckBox myRememberProxyPasswordCheckBox; private JLabel myProxyLoginLabel; private JLabel myProxyPasswordLabel; private JLabel myHostNameLabel; private JLabel myPortNumberLabel; private JBRadioButton myAutoDetectProxyRb; private JBRadioButton myUseHTTPProxyRb; private JLabel mySystemProxyDefined; private JBRadioButton myNoProxyRb; private JBRadioButton myHTTP; private JBRadioButton mySocks; private JButton myClearPasswordsButton; private JLabel myErrorLabel; private JButton myCheckButton; private JLabel myOtherWarning; private JLabel myProxyExceptionsLabel; private RawCommandLineEditor myProxyExceptions; private JLabel myNoProxyForLabel; private JCheckBox myPacUrlCheckBox; private JTextField myPacUrlTextField; @Override public boolean isModified(@NotNull HttpConfigurable settings) { return !Comparing.strEqual(myProxyExceptions.getText().trim(), settings.PROXY_EXCEPTIONS) || settings.USE_PROXY_PAC != myAutoDetectProxyRb.isSelected() || settings.USE_PAC_URL != myPacUrlCheckBox.isSelected() || !Comparing.strEqual(settings.PAC_URL, myPacUrlTextField.getText()) || settings.USE_HTTP_PROXY != myUseHTTPProxyRb.isSelected() || settings.PROXY_AUTHENTICATION != myProxyAuthCheckBox.isSelected() || settings.KEEP_PROXY_PASSWORD != myRememberProxyPasswordCheckBox.isSelected() || settings.PROXY_TYPE_IS_SOCKS != mySocks.isSelected() || !Comparing.strEqual(settings.getProxyLogin(), myProxyLoginTextField.getText()) || !Comparing.strEqual(settings.getPlainProxyPassword(), new String(myProxyPasswordTextField.getPassword())) || settings.PROXY_PORT != myProxyPortTextField.getNumber() || !Comparing.strEqual(settings.PROXY_HOST, myProxyHostTextField.getText()); } HttpProxySettingsUi(@NotNull final HttpConfigurable settings) { ButtonGroup group = new ButtonGroup(); group.add(myUseHTTPProxyRb); group.add(myAutoDetectProxyRb); group.add(myNoProxyRb); myNoProxyRb.setSelected(true); ButtonGroup proxyTypeGroup = new ButtonGroup(); proxyTypeGroup.add(myHTTP); proxyTypeGroup.add(mySocks); myHTTP.setSelected(true); Boolean property = Boolean.getBoolean(JavaProxyProperty.USE_SYSTEM_PROXY); mySystemProxyDefined.setVisible(Boolean.TRUE.equals(property)); if (Boolean.TRUE.equals(property)) { mySystemProxyDefined.setIcon(Messages.getWarningIcon()); RelativeFont.BOLD.install(mySystemProxyDefined); } myProxyAuthCheckBox.addActionListener(e -> enableProxyAuthentication(myProxyAuthCheckBox.isSelected())); myPacUrlCheckBox.addActionListener(e -> myPacUrlTextField.setEnabled(myPacUrlCheckBox.isSelected())); ActionListener listener = e -> enableProxy(myUseHTTPProxyRb.isSelected()); myUseHTTPProxyRb.addActionListener(listener); myAutoDetectProxyRb.addActionListener(listener); myNoProxyRb.addActionListener(listener); myClearPasswordsButton.addActionListener(e -> { settings.clearGenericPasswords(); //noinspection DialogTitleCapitalization Messages.showMessageDialog(myMainPanel, IdeBundle.message("message.text.proxy.passwords.were.cleared"), IdeBundle.message("dialog.title.auto.detected.proxy"), Messages.getInformationIcon()); }); configureCheckButton(); } private void configureCheckButton() { if (HttpConfigurable.getInstance() == null) { myCheckButton.setVisible(false); return; } myCheckButton.addActionListener(event -> { String error = isValid(); if (error != null) { Messages.showErrorDialog(myMainPanel, error); return; } final String title = IdeBundle.message("dialog.title.check.proxy.settings"); final String answer = Messages.showInputDialog(myMainPanel, IdeBundle.message("message.text.enter.url.to.check.connection"), title, Messages.getQuestionIcon(), "http://", null); if (StringUtil.isEmptyOrSpaces(answer)) { return; } final HttpConfigurable settings = HttpConfigurable.getInstance(); try { apply(settings); } catch (ConfigurationException e) { return; } final AtomicReference<IOException> exceptionReference = new AtomicReference<>(); ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { try { HttpRequests.request(answer).readTimeout(3 * 1000).tryConnect(); } catch (IOException e) { exceptionReference.set(e); } }, IdeBundle.message("progress.title.check.connection"), true, null); reset(settings); // since password might have been set final IOException exception = exceptionReference.get(); if (exception == null) { Messages.showMessageDialog(myMainPanel, IdeBundle.message("message.connection.successful"), title, Messages.getInformationIcon()); } else { final String message = exception.getMessage(); if (settings.USE_HTTP_PROXY) { settings.LAST_ERROR = message; } Messages.showErrorDialog(myMainPanel, errorText(message)); } }); } @Override public void reset(@NotNull HttpConfigurable settings) { myNoProxyRb.setSelected(true); // default myAutoDetectProxyRb.setSelected(settings.USE_PROXY_PAC); myPacUrlCheckBox.setSelected(settings.USE_PAC_URL); myPacUrlTextField.setText(settings.PAC_URL); myUseHTTPProxyRb.setSelected(settings.USE_HTTP_PROXY); myProxyAuthCheckBox.setSelected(settings.PROXY_AUTHENTICATION); enableProxy(settings.USE_HTTP_PROXY); myProxyLoginTextField.setText(settings.getProxyLogin()); myProxyPasswordTextField.setText(settings.getPlainProxyPassword()); myProxyPortTextField.setNumber(settings.PROXY_PORT); myProxyHostTextField.setText(settings.PROXY_HOST); myProxyExceptions.setText(StringUtil.notNullize(settings.PROXY_EXCEPTIONS)); myRememberProxyPasswordCheckBox.setSelected(settings.KEEP_PROXY_PASSWORD); mySocks.setSelected(settings.PROXY_TYPE_IS_SOCKS); myHTTP.setSelected(!settings.PROXY_TYPE_IS_SOCKS); boolean showError = !StringUtil.isEmptyOrSpaces(settings.LAST_ERROR); myErrorLabel.setVisible(showError); myErrorLabel.setText(showError ? errorText(settings.LAST_ERROR) : null); final String oldStyleText = CommonProxy.getMessageFromProps(CommonProxy.getOldStyleProperties()); myOtherWarning.setVisible(oldStyleText != null); if (oldStyleText != null) { myOtherWarning.setText(oldStyleText); myOtherWarning.setIcon(Messages.getWarningIcon()); } } private void createUIComponents() { myProxyExceptions = new RawCommandLineEditor(text -> { List<String> result = new ArrayList<>(); for (String token : text.split(",")) { String trimmedToken = token.trim(); if (!trimmedToken.isEmpty()) { result.add(trimmedToken); } } return result; }, strings -> StringUtil.join(strings, ", ")); } @NotNull private static @NlsContexts.DialogMessage String errorText(@NotNull String s) { return IdeBundle.message("dialog.message.problem.with.connection", s); } @Nullable private @NlsContexts.DialogMessage String isValid() { if (myUseHTTPProxyRb.isSelected()) { String host = getText(myProxyHostTextField); if (host == null) { return IdeBundle.message("dialog.message.host.name.empty"); } try { HostAndPort parsedHost = HostAndPort.fromString(host); if (parsedHost.hasPort()) { return IdeBundle.message("dialog.message.invalid.host.value"); } host = parsedHost.getHost(); try { InetAddresses.forString(host); return null; } catch (IllegalArgumentException e) { // it is not an IPv4 or IPv6 literal } InternetDomainName.from(host); } catch (IllegalArgumentException e) { return IdeBundle.message("dialog.message.invalid.host.value"); } if (myProxyAuthCheckBox.isSelected()) { if (StringUtil.isEmptyOrSpaces(myProxyLoginTextField.getText())) { return IdeBundle.message("dialog.message.login.empty"); } if (myProxyPasswordTextField.getPassword().length == 0) { return IdeBundle.message("dialog.message.password.empty"); } } } return null; } @Override public void apply(@NotNull HttpConfigurable settings) throws ConfigurationException { String error = isValid(); if (error != null) { throw new ConfigurationException(error); } boolean modified = isModified(settings); if (modified) { settings.AUTHENTICATION_CANCELLED = false; } settings.USE_PROXY_PAC = myAutoDetectProxyRb.isSelected(); settings.USE_PAC_URL = myPacUrlCheckBox.isSelected(); settings.PAC_URL = getText(myPacUrlTextField); settings.USE_HTTP_PROXY = myUseHTTPProxyRb.isSelected(); settings.PROXY_TYPE_IS_SOCKS = mySocks.isSelected(); settings.PROXY_AUTHENTICATION = myProxyAuthCheckBox.isSelected(); settings.KEEP_PROXY_PASSWORD = myRememberProxyPasswordCheckBox.isSelected(); settings.setProxyLogin(getText(myProxyLoginTextField)); settings.setPlainProxyPassword(new String(myProxyPasswordTextField.getPassword())); settings.PROXY_EXCEPTIONS = StringUtil.nullize(myProxyExceptions.getText(), true); settings.PROXY_PORT = myProxyPortTextField.getNumber(); settings.PROXY_HOST = getText(myProxyHostTextField); if (modified && JBCefApp.isStarted()) { JBCefApp.NOTIFICATION_GROUP.getValue() .createNotification(IdeBundle.message("notification.title.jcef.proxyChanged"), IdeBundle.message("notification.content.jcef.applySettings"), NotificationType.WARNING) .addAction(NotificationAction.createSimple(IdeBundle.message("action.jcef.restart"), () -> ApplicationManager.getApplication().restart())) .notify(null); } } @Nullable private static String getText(@NotNull JTextField field) { return StringUtil.nullize(field.getText(), true); } private void enableProxy(boolean enabled) { myHostNameLabel.setEnabled(enabled); myPortNumberLabel.setEnabled(enabled); myProxyHostTextField.setEnabled(enabled); myProxyPortTextField.setEnabled(enabled); mySocks.setEnabled(enabled); myHTTP.setEnabled(enabled); myProxyExceptions.setEnabled(enabled); myProxyExceptionsLabel.setEnabled(enabled); myNoProxyForLabel.setEnabled(enabled); myProxyAuthCheckBox.setEnabled(enabled); enableProxyAuthentication(enabled && myProxyAuthCheckBox.isSelected()); final boolean autoDetectProxy = myAutoDetectProxyRb.isSelected(); myPacUrlCheckBox.setEnabled(autoDetectProxy); myClearPasswordsButton.setEnabled(autoDetectProxy); myPacUrlTextField.setEnabled(autoDetectProxy && myPacUrlCheckBox.isSelected()); } private void enableProxyAuthentication(boolean enabled) { myProxyLoginLabel.setEnabled(enabled); myProxyLoginTextField.setEnabled(enabled); myProxyPasswordLabel.setEnabled(enabled); myProxyPasswordTextField.setEnabled(enabled); myRememberProxyPasswordCheckBox.setEnabled(enabled); } @Override @NotNull public JComponent getComponent() { return myMainPanel; } }
apache-2.0
apache/geronimo
plugins/j2ee/geronimo-j2ee-builder/src/test/java/org/apache/geronimo/j2ee/deployment/EARConfigBuilder14UnpackedTest.java
2279
/** * 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.geronimo.j2ee.deployment; import java.util.jar.JarFile; import org.apache.geronimo.kernel.util.JarUtils; import org.apache.geronimo.kernel.repository.Artifact; /** * EAR config builder tests for J2EE 1.4 unpacked. * * @version $Rev:386276 $ $Date$ */ public class EARConfigBuilder14UnpackedTest extends EARConfigBuilderTestSupport { protected void setUp() throws Exception { super.setUp(); earFile = JarUtils.createJarFile(resolveFile("target/test-ear-j2ee_1.4-unpacked.ear")); locations.put(null, new Artifact("org.apache.geronimo.testsupport", "test-ear-javaee_5", "3.0-TEST", "ear")); ejbConfigBuilder.ejbModule = new EJBModule(false, ejbModuleName, null, null, null, "ejb.jar/", null, null, null, jndiContext, parentModule); webConfigBuilder.contextRoot = contextRoot; webConfigBuilder.webModule = new WebModule(false, webModuleName, null, null, (JarFile)null, "war.war/", null, null, null, contextRoot, WEB_NAMESPACE, jndiContext, parentModule); connectorConfigBuilder.connectorModule = new ConnectorModule(false, raModuleName, null, null, null, "rar.rar/", null, null, null, jndiContext, parentModule); } protected void tearDown() throws Exception { JarUtils.close(earFile); close(ejbConfigBuilder.ejbModule); close(webConfigBuilder.webModule); close(connectorConfigBuilder.connectorModule); super.tearDown(); } }
apache-2.0
Fabryprog/camel
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/GenericFileProcessStrategySupport.java
6711
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.strategy; import java.io.File; import java.io.IOException; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; import org.apache.camel.component.file.GenericFile; import org.apache.camel.component.file.GenericFileEndpoint; import org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.apache.camel.component.file.GenericFileOperations; import org.apache.camel.component.file.GenericFileProcessStrategy; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.FileUtil; /** * Base class for implementations of {@link GenericFileProcessStrategy}. */ public abstract class GenericFileProcessStrategySupport<T> extends ServiceSupport implements GenericFileProcessStrategy<T>, CamelContextAware { protected GenericFileExclusiveReadLockStrategy<T> exclusiveReadLockStrategy; protected CamelContext camelContext; @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public void prepareOnStartup(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint) throws Exception { if (exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.prepareOnStartup(operations, endpoint); } } public boolean begin(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { // if we use exclusive read then acquire the exclusive read (waiting until we got it) if (exclusiveReadLockStrategy != null) { boolean lock = exclusiveReadLockStrategy.acquireExclusiveReadLock(operations, file, exchange); if (!lock) { // do not begin since we could not get the exclusive read lock return false; } } return true; } public void abort(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { deleteLocalWorkFile(exchange); operations.releaseRetrievedFileResources(exchange); // must release lock last if (exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnAbort(operations, file, exchange); } } public void commit(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { deleteLocalWorkFile(exchange); operations.releaseRetrievedFileResources(exchange); // must release lock last if (exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnCommit(operations, file, exchange); } } public void rollback(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { deleteLocalWorkFile(exchange); operations.releaseRetrievedFileResources(exchange); // must release lock last if (exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnRollback(operations, file, exchange); } } public GenericFileExclusiveReadLockStrategy<T> getExclusiveReadLockStrategy() { return exclusiveReadLockStrategy; } public void setExclusiveReadLockStrategy(GenericFileExclusiveReadLockStrategy<T> exclusiveReadLockStrategy) { this.exclusiveReadLockStrategy = exclusiveReadLockStrategy; } protected GenericFile<T> renameFile(GenericFileOperations<T> operations, GenericFile<T> from, GenericFile<T> to) throws IOException { // deleting any existing files before renaming try { operations.deleteFile(to.getAbsoluteFilePath()); } catch (GenericFileOperationFailedException e) { // ignore the file does not exists } // make parent folder if missing boolean mkdir = operations.buildDirectory(to.getParent(), to.isAbsolute()); if (!mkdir) { throw new GenericFileOperationFailedException("Cannot create directory: " + to.getParent() + " (could be because of denied permissions)"); } log.debug("Renaming file: {} to: {}", from, to); boolean renamed = operations.renameFile(from.getAbsoluteFilePath(), to.getAbsoluteFilePath()); if (!renamed) { throw new GenericFileOperationFailedException("Cannot rename file: " + from + " to: " + to); } return to; } protected void deleteLocalWorkFile(Exchange exchange) { // delete local work file, if it was used (eg by ftp component) File local = exchange.getIn().getHeader(Exchange.FILE_LOCAL_WORK_PATH, File.class); if (local != null && local.exists()) { boolean deleted = FileUtil.deleteFile(local); log.trace("Local work file: {} was deleted: {}", local, deleted); } } @Override protected void doStart() throws Exception { if (exclusiveReadLockStrategy instanceof CamelContextAware) { ((CamelContextAware) exclusiveReadLockStrategy).setCamelContext(camelContext); } ServiceHelper.startService(exclusiveReadLockStrategy); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(exclusiveReadLockStrategy); } @Override protected void doShutdown() throws Exception { ServiceHelper.stopAndShutdownService(exclusiveReadLockStrategy); } }
apache-2.0
hejunbinlan/MVPAndroidBootstrap
app/src/main/java/com/richardradics/cleanaa/repository/api/model/openweatherwrapper/Clouds.java
431
package com.richardradics.cleanaa.repository.api.model.openweatherwrapper; import com.google.gson.annotations.Expose; public class Clouds { @Expose private Integer all; /** * * @return * The all */ public Integer getAll() { return all; } /** * * @param all * The all */ public void setAll(Integer all) { this.all = all; } }
apache-2.0
apache/batik
batik-css/src/main/java/org/apache/batik/css/engine/value/svg12/CIELabColor.java
1652
/* 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.batik.css.engine.value.svg12; /** * This class represents an CIE L*a*b* color value. * * @version $Id$ */ public class CIELabColor extends AbstractCIEColor { public static final String CIE_LAB_COLOR_FUNCTION = "cielab"; /** * Creates a new CIELabColor. * @param l the L* value * @param a the a* value * @param b the b* value * @param whitepoint the white point in CIE XYZ coordinates */ public CIELabColor(float l, float a, float b, float[] whitepoint) { super(new float[] {l, a, b}, whitepoint); } /** * Creates a new CIELabColor with D50 as illuminant. */ public CIELabColor(float l, float a, float b) { this(l, a, b, null); } /** {@inheritDoc} */ public String getFunctionName() { return CIE_LAB_COLOR_FUNCTION; } }
apache-2.0
Sk464036801/geo
src/main/java/com/github/davidmoten/geo/LatLong.java
1290
package com.github.davidmoten.geo; /** * A lat, long pair (WGS84). Immutable. * * @author dave * */ public class LatLong { private final double lat; private final double lon; /** * Constructor. * * @param lat * @param lon */ public LatLong(double lat, double lon) { super(); this.lat = lat; this.lon = lon; } /** * Returns the latitude in decimal degrees. * * @return */ public double getLat() { return lat; } /** * Returns the longitude in decimal degrees. * * @return */ public double getLon() { return lon; } /** * Returns a new {@link LatLong} object with lat, lon increased by deltaLat, * deltaLon. * * @param deltaLat * @param deltaLon * @return */ public LatLong add(double deltaLat, double deltaLon) { return new LatLong(lat + deltaLat, lon + deltaLon); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("LatLong [lat="); builder.append(lat); builder.append(", lon="); builder.append(lon); builder.append("]"); return builder.toString(); } }
apache-2.0
xasx/assertj-core
src/test/java/org/assertj/core/api/intarray/IntArrayAssert_hasSize_Test.java
1203
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT 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.intarray; import org.assertj.core.api.IntArrayAssert; import org.assertj.core.api.IntArrayAssertBaseTest; import static org.mockito.Mockito.verify; /** * Tests for <code>{@link IntArrayAssert#hasSize(int)}</code>. * * @author Alex Ruiz */ public class IntArrayAssert_hasSize_Test extends IntArrayAssertBaseTest { @Override protected IntArrayAssert invoke_api_method() { return assertions.hasSize(6); } @Override protected void verify_internal_effects() { verify(arrays).assertHasSize(getInfo(assertions), getActual(assertions), 6); } }
apache-2.0
apache/jena
jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/DatasetGraphSwitchable.java
4400
/* * 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.jena.tdb2.store; import java.nio.file.Path; import java.util.concurrent.atomic.AtomicReference; import org.apache.jena.atlas.lib.Cache; import org.apache.jena.atlas.lib.CacheFactory; import org.apache.jena.dboe.base.file.Location; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.riot.system.PrefixMap; import org.apache.jena.sparql.core.DatasetGraph; import org.apache.jena.sparql.core.DatasetGraphWrapper; import org.apache.jena.sparql.core.Quad; final public class DatasetGraphSwitchable extends DatasetGraphWrapper { // QueryEngineFactoryWrapper has a QueryEngineFactory that is always loaded that // executes on the unwrapped DSG (recursively). Unwrapping is via getBase, calling // getWrapped() which is implemented with get(). // static { // // QueryEngineRegistry.addFactory(factory()); // } private final AtomicReference<DatasetGraph> dsgx = new AtomicReference<>(); // Null for in-memory datasets. private final Path basePath; private final Location location; private final PrefixMapSwitchable prefixes; public DatasetGraphSwitchable(Path base, Location location, DatasetGraph dsg) { // Don't use the slot in datasetGraphWrapper - use the AtomicReference super(null, dsg.getContext()); dsgx.set(dsg); this.basePath = base; this.location = location; this.prefixes = new PrefixMapSwitchable(this); } /** Is this {@code DatasetGraphSwitchable} just a holder for a {@code DatasetGraph}? * If so, it does not have a location on disk. */ public boolean hasContainerPath() { return basePath != null; } public Path getContainerPath() { return basePath; } public Location getLocation() { return location; } /** The dataset to use for redirection - can be overridden. * It is also guaranteed that this is called only once per * delegated call. Changes to the wrapped object can be * made based on that contract. */ @Override public DatasetGraph get() { return dsgx.get(); } /** Set the base {@link DatasetGraph}. * Returns the old value. */ public DatasetGraph set(DatasetGraph dsg) { return dsgx.getAndSet(dsg); } @Override public PrefixMap prefixes() { return prefixes; } /** Don't do anything on close. * This would not be safe across switches. */ @Override public void close() {} // /** Don't do anything on sync. */ // @Override // public void sync() { } /** * If and only if the current value is the given old value, set the base {@link DatasetGraph} * Returns true if a swap happened. */ public boolean change(DatasetGraph oldDSG, DatasetGraph newDSG) { // No need to clear. ngCache.clear(); return dsgx.compareAndSet(oldDSG, newDSG); } private Graph dftGraph = GraphViewSwitchable.createDefaultGraphSwitchable(this); @Override public Graph getDefaultGraph() { return dftGraph; } @Override public Graph getUnionGraph() { return GraphViewSwitchable.createUnionGraphSwitchable(this); } // private Cache<Node, Graph> ngCache = CacheFactory.createCache(10); private Cache<Node, Graph> ngCache = CacheFactory.createOneSlotCache(); @Override public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(key, ()->GraphViewSwitchable.createNamedGraphSwitchable(this, key)); } }
apache-2.0
nagyist/marketcetera
trunk/photon/plugins/org.marketcetera.photon.strategy.engine.ui/src/main/java/org/marketcetera/photon/strategy/engine/ui/FileDialogButton.java
1346
package org.marketcetera.photon.strategy.engine.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.marketcetera.util.misc.ClassVersion; /* $License$ */ /** * A {@link ScriptSelectionButton} that opens a native {@link FileDialog} to * choose a script file. It works with the native string representation of * files. * * @author <a href="mailto:will@marketcetera.com">Will Horn</a> * @version $Id: FileDialogButton.java 16154 2012-07-14 16:34:05Z colin $ * @since 2.0.0 */ @ClassVersion("$Id: FileDialogButton.java 16154 2012-07-14 16:34:05Z colin $") public final class FileDialogButton extends ScriptSelectionButton { /* * Note: no unit tests since FileDialog is a native dialog that cannot * currently be accessed by SWTBot. */ /** * Constructor. * * @param text * the button label * @throws IllegalArgumentException * if text is null */ public FileDialogButton(String text) { super(text); } @Override public String selectScript(Shell shell, String current) { FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.SHEET); dialog.setFileName(current); return dialog.open(); } }
apache-2.0
cloudnautique/cloud-cattle
code/framework/launcher/src/main/java/io/cattle/platform/launcher/jetty/Main.java
5704
package io.cattle.platform.launcher.jetty; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.TimeZone; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.webapp.WebAppClassLoader; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { public static final String WEB_XML = "WEB-INF/web.xml"; public static final String OVERRIDE_WEB_XML = "WEB-INF/override-web.xml"; public static final String STATIC_WEB_XML = "WEB-INF/static-override-web.xml"; public static final String DEFAULT_WEB_XML = "WEB-INF/default-web.xml"; // private static final Logger log = LoggerFactory.getLogger(Main.class); private static final Logger consoleLog = LoggerFactory.getLogger("ConsoleStatus"); public static final String[] PREFIXES = new String[] { "code/packaging/app/src/main/webapp/", "src/main/webapp/", "" }; protected static URL findUrl(String suffix) throws IOException { File file = findFile(suffix); if ( file != null ) { return file.toURI().toURL(); } return Main.class.getResource("/" + suffix); } protected static File findFile(String suffix) { for ( String prefix : PREFIXES ) { File file = new File(prefix + suffix); if (file.exists()) return new File(file.getAbsolutePath()); } URL url = Main.class.getResource("/" + suffix); if ( url != null && "file".equals(url.getProtocol()) ) { return new File(url.getPath()); } return null; } protected static URL getContextRoot(URL webXml) throws IOException { if ( webXml != null ) { URLConnection connection = webXml.openConnection(); if ( connection instanceof JarURLConnection ) { URL war = ((JarURLConnection)connection).getJarFileURL(); return new URL("jar", "", war.toExternalForm() + "!/WEB-INF/content"); } } return Main.class.getResource(""); } protected static String getHttpPort() { String port = System.getenv("CATTLE_HTTP_PORT"); return port == null ? System.getProperty("cattle.http.port","8080") : port; } public static void main(String... args) { /* The world is better place without time zones. Well, at least for computers */ TimeZone.setDefault(TimeZone.getTimeZone("UTC")); long start = System.currentTimeMillis(); try { Server s = new Server(Integer.parseInt(getHttpPort())); MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); s.getContainer().addEventListener(mbContainer); s.addBean(mbContainer); mbContainer.addBean(Log.getRootLogger()); WebAppContext context = new WebAppContext(); context.setThrowUnavailableOnStartupException(true); File webXmlFile = findFile(WEB_XML); URL webXml = findUrl(WEB_XML); URL contextRoot = webXmlFile == null ? getContextRoot(webXml) : webXmlFile.getParentFile().getParentFile().toURI().toURL(); URL override = findUrl(OVERRIDE_WEB_XML); if ( override != null ) { context.setOverrideDescriptors(Arrays.asList(override.toExternalForm())); } URL defaultWebXml = findUrl(DEFAULT_WEB_XML); if ( defaultWebXml != null ) { context.setDefaultsDescriptor(defaultWebXml.toExternalForm()); } URL staticOverideXml = findUrl(STATIC_WEB_XML); if ( staticOverideXml != null && new File("./content").exists() ) { List<String> overrides = new ArrayList<String>(context.getOverrideDescriptors()); overrides.add(staticOverideXml.toExternalForm()); context.setOverrideDescriptors(overrides); } if ( contextRoot != null ) { context.setWar(contextRoot.toExternalForm()); } context.setClassLoader(new WebAppClassLoader(Main.class.getClassLoader(), context)); context.setContextPath("/"); s.setHandler(context); s.start(); consoleLog.info("[DONE ] [{}ms] Startup Succeeded, Listening on port {}", (System.currentTimeMillis() - start), getHttpPort()); for ( int i = 0 ; i < args.length ; i++ ) { String arg = args[i]; if ( "--exit".equals(arg) ) { System.exit(0); } if ( "--notify".equals(arg) ) { consoleLog.info("[POST ] [{}ms] Calling notify [{}]", (System.currentTimeMillis() - start), args[i+1]); Runtime.getRuntime().exec(args[i+1]).waitFor(); } } s.join(); } catch (Exception e) { e.printStackTrace(); consoleLog.error("Startup Failed [{}ms]", (System.currentTimeMillis() - start), e); System.err.println("STARTUP FAILED [" + (System.currentTimeMillis() - start) + "] ms"); for ( int i = 0 ; i < args.length ; i++ ) { String arg = args[i]; if ( "--notify-error".equals(arg) ) { consoleLog.error("[ERROR] [{}ms] Calling notify [{}]", (System.currentTimeMillis() - start), args[i+1]); try { Runtime.getRuntime().exec(args[i+1]).waitFor(); } catch (Exception e1) { e1.printStackTrace(); } } } System.exit(1); } } }
apache-2.0
itzamnamx/nibble
nibble/src/java/dbrbeans/partidasolicitada/dbrPARTIDASOLICITADAs.java
2207
package dbrbeans.partidasolicitada; /** * Insert the type's description here. * Creation date: (12/13/2002 2:15:12 PM) * @author: */ public class dbrPARTIDASOLICITADAs extends dbbeans.partidasolicitada.dbPARTIDASOLICITADAs { /** * dbrPARTIDASOLICITADAs constructor comment. */ public dbrPARTIDASOLICITADAs() { super(); } public boolean findByIidproveedor(int iidproveedor) throws Exception, java.sql.SQLException { StringBuffer query = new StringBuffer(); dbrPARTIDASOLICITADA PARTIDASOLICITADA; query.append("SELECT a.*,p.vchnumparte,p.iidcategoria,p.iidgrupo,p.iidlinea,p.iidmarca "); query.append("FROM PARTIDASOLICITADA a,PARTE p "); query.append("WHERE a.liidparte=p.liidparte "); query.append("AND a.iidproveedor=? "); query.append("ORDER BY p.iidcategoria,p.iidgrupo,p.iidlinea,p.iidmarca "); stmt = conn.prepareStatement(query.toString().toLowerCase()); stmt.setInt(1,iidproveedor); rSet = stmt.executeQuery(); while (rSet.next()) { PARTIDASOLICITADA= new dbrPARTIDASOLICITADA(); PARTIDASOLICITADA.setIidpartidasolicit(rSet.getInt("iidpartidasolicit")); PARTIDASOLICITADA.setLiidparte(rSet.getLong("liidparte")); PARTIDASOLICITADA.setIidproveedor(rSet.getInt("iidproveedor")); PARTIDASOLICITADA.setDtfechasolicitud(rSet.getString("dtfechasolicitud")); PARTIDASOLICITADA.setIcantidadpedida(rSet.getInt("icantidadpedida")); PARTIDASOLICITADA.setVchnumparte(rSet.getString("vchnumparte")); PARTIDASOLICITADA.setIidcategoria(rSet.getInt("iidcategoria")); PARTIDASOLICITADA.setIidgrupo(rSet.getInt("iidgrupo")); PARTIDASOLICITADA.setIidlinea(rSet.getInt("iidlinea")); PARTIDASOLICITADA.setIidmarca(rSet.getInt("iidmarca")); result.addElement(PARTIDASOLICITADA); } rSet.close(); stmt.close(); return false; } public boolean RemoveByIidproveedor(int iidproveedor) throws Exception, java.sql.SQLException { StringBuffer query = new StringBuffer(); query.append("DELETE "); query.append("FROM PARTIDASOLICITADA "); query.append("WHERE iidproveedor=? "); stmt = conn.prepareStatement(query.toString().toLowerCase()); stmt.setInt(1,iidproveedor); stmt.executeUpdate(); stmt.close(); return false; } }
apache-2.0
apache/axis2-java
modules/adb/test/org/apache/axis2/databinding/utils/reader/DummyBean.java
1451
/* * 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.databinding.utils.reader; import java.util.ArrayList; import java.util.List; public class DummyBean { private List<DummyBean> dependent = new ArrayList<DummyBean>(); public String getName() { return "FooTwo"; } public String getAge() { return "25"; } public String getSex() { return "Male"; } public DummyBean[] getDependent() { return dependent.toArray(new DummyBean[dependent.size()]); } public DummyBean addAnotherBean() { DummyBean dummyBean = new DummyBean(); dependent.add(dummyBean); return dummyBean; } }
apache-2.0
jk1/intellij-community
plugins/git4idea/src/git4idea/push/GitPushSource.java
2013
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.push; import com.intellij.dvcs.DvcsUtil; import com.intellij.dvcs.push.PushSource; import git4idea.GitLocalBranch; import org.jetbrains.annotations.NotNull; public abstract class GitPushSource implements PushSource { @NotNull public static GitPushSource create(@NotNull GitLocalBranch branch) { return new OnBranch(branch); } @NotNull public static GitPushSource create(@NotNull String revision) { return new DetachedHead(revision); } @NotNull public abstract GitLocalBranch getBranch(); private static class OnBranch extends GitPushSource { @NotNull private final GitLocalBranch myBranch; private OnBranch(@NotNull GitLocalBranch branch) { myBranch = branch; } @NotNull @Override public String getPresentation() { return myBranch.getName(); } @NotNull @Override public GitLocalBranch getBranch() { return myBranch; } } private static class DetachedHead extends GitPushSource { @NotNull private final String myRevision; public DetachedHead(@NotNull String revision) { myRevision = revision; } @NotNull @Override public String getPresentation() { return DvcsUtil.getShortHash(myRevision); } @NotNull @Override public GitLocalBranch getBranch() { throw new IllegalStateException("Push is not allowed from detached HEAD"); } } }
apache-2.0
sujitbehera27/MyRoboticsProjects-Arduino
src/org/myrobotlab/control/IncubatorGUI.java
2108
/** * * @author greg (at) myrobotlab.org * * This file is part of MyRobotLab (http://myrobotlab.org). * * MyRobotLab 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 (subject to the "Classpath" exception * as provided in the LICENSE.txt file that accompanied this code). * * MyRobotLab is distributed in the hope that it will be useful or fun, * 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. * * All libraries in thirdParty bundle are subject to their own license * requirements - please refer to http://myrobotlab.org/libraries for * details. * * Enjoy ! * * */ package org.myrobotlab.control; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.GUIService; import org.myrobotlab.service.Incubator; import org.slf4j.Logger; public class IncubatorGUI extends ServiceGUI implements ActionListener { static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(IncubatorGUI.class.getCanonicalName()); public IncubatorGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) { super(boundServiceName, myService, tabs); } public void init() { } public void getState(Incubator template) { SwingUtilities.invokeLater(new Runnable() { public void run() { } }); } @Override public void attachGUI() { subscribe("publishState", "getState", Incubator.class); send("publishState"); } @Override public void detachGUI() { unsubscribe("publishState", "getState", Incubator.class); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } }
apache-2.0
renmeng8875/projects
Hibernate-source/源代码及重要说明/hibernate_many2many_2/src/com/bjsxt/hibernate/User.java
444
package com.bjsxt.hibernate; import java.util.Set; public class User { private int id; private String name; private Set roles; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } }
apache-2.0
apache/cocoon
core/cocoon-sitemap/cocoon-sitemap-components/src/main/java/org/apache/cocoon/matching/WildcardHeaderMatcher.java
3039
/* * 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.cocoon.matching; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.environment.ObjectModelHelper; import java.util.Map; /** * Matches a request header (e.g. "referer") against a wildcard expression. * * <p><b>Global and local configuration</b></p> * <table border="1"> * <tr><td><code>header-name</code></td><td>Name of the request header to * match against</td></tr> * </table> * * @cocoon.sitemap.component.documentation * Matches a request header (e.g. "referer") against a wildcard expression. * * @version $Id$ */ public class WildcardHeaderMatcher extends AbstractWildcardMatcher implements Configurable { private String defaultParam; public void configure(Configuration config) throws ConfigurationException { // Check old name this.defaultParam = config.getChild("parameter-name").getValue(null); if (defaultParam != null) { getLogger().warn("'parameter-name' is deprecated. Please use 'header-name'"); } // Load with new one this.defaultParam = config.getChild("header-name").getValue(this.defaultParam); } protected String getMatchString(Map objectModel, Parameters parameters) { // Check old name String paramName = parameters.getParameter("parameter-name", null); if (paramName != null) { getLogger().warn("'parameter-name' is deprecated. Please use 'header-name'"); } else { paramName = this.defaultParam; } // Load with new one. paramName = parameters.getParameter("header-name", paramName); if (paramName == null) { getLogger().warn("No header name given. FAILING"); return null; } String result = ObjectModelHelper.getRequest(objectModel).getHeader(paramName); if (result == null) { getLogger().debug("Header '" + paramName + "' not set."); } return result; } }
apache-2.0
PearsonEducation/subpub
examples/MessageGenerator/src/com/ecollege/prospero/messagegenerator/examples/GetSubscriptionExample.java
1009
package com.ecollege.prospero.messagegenerator.examples; import com.ecollege.prospero.messagegenerator.Prospero; import com.ecollege.prospero.messagegenerator.ProsperoPrincipal; import com.ecollege.prospero.messagegenerator.logger.Logger; import com.ecollege.prospero.messagegenerator.logger.SystemOutLogger; public class GetSubscriptionExample { public static void main(String[] args) throws Exception { String principalId = "ONE"; String prosperoHost = "localhost"; int prosperoPort = 4778; String sharedKey = "1234567890123456"; String subscriptionId = "put your sub id here"; ProsperoPrincipal principal = new ProsperoPrincipal(); principal.setKey(sharedKey); principal.setPrincipalId(principalId); principal.setProsperoHost(prosperoHost); principal.setProsperoPort(prosperoPort); Logger logger = new SystemOutLogger(); String response = Prospero.getSubscription(subscriptionId, principal, logger); logger.log("Response: " + response); logger.log("Done"); } }
apache-2.0
dusenberrymw/systemml
src/main/java/org/apache/sysml/api/jmlc/Connection.java
33810
/* * 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.sysml.api.jmlc; import java.io.BufferedReader; import java.io.Closeable; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.sysml.api.DMLException; import org.apache.sysml.api.DMLScript; import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM; import org.apache.sysml.api.mlcontext.ScriptType; import org.apache.sysml.conf.CompilerConfig; import org.apache.sysml.conf.CompilerConfig.ConfigType; import org.apache.sysml.conf.ConfigurationManager; import org.apache.sysml.conf.DMLConfig; import org.apache.sysml.hops.codegen.SpoofCompiler; import org.apache.sysml.hops.rewrite.ProgramRewriter; import org.apache.sysml.hops.rewrite.RewriteRemovePersistentReadWrite; import org.apache.sysml.parser.DMLProgram; import org.apache.sysml.parser.DMLTranslator; import org.apache.sysml.parser.DataExpression; import org.apache.sysml.parser.LanguageException; import org.apache.sysml.parser.ParseException; import org.apache.sysml.parser.ParserFactory; import org.apache.sysml.parser.ParserWrapper; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.Program; import org.apache.sysml.runtime.controlprogram.caching.CacheableData; import org.apache.sysml.runtime.io.FrameReader; import org.apache.sysml.runtime.io.FrameReaderFactory; import org.apache.sysml.runtime.io.IOUtilFunctions; import org.apache.sysml.runtime.io.MatrixReader; import org.apache.sysml.runtime.io.MatrixReaderFactory; import org.apache.sysml.runtime.matrix.data.FrameBlock; import org.apache.sysml.runtime.matrix.data.InputInfo; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.transform.TfUtils; import org.apache.sysml.runtime.transform.meta.TfMetaUtils; import org.apache.sysml.runtime.util.DataConverter; import org.apache.sysml.runtime.util.UtilFunctions; import org.apache.wink.json4j.JSONObject; /** * Interaction with SystemML using the JMLC (Java Machine Learning Connector) API is initiated with * a {@link Connection} object. The JMLC API is patterned * after JDBC. A DML script is precompiled by calling * the {@link #prepareScript(String, String[], String[], boolean)} * method or the {@link #prepareScript(String, Map, String[], String[], boolean)} * method on the {@link Connection} object, which returns a * {@link PreparedScript} object. Note that this is similar to calling * a {@code prepareStatement} method on a JDBC {@code Connection} object. * * <p> * Following this, input variable data is passed to the script by calling the * {@code setFrame}, {@code setMatrix}, and {@code setScalar} methods of the {@link PreparedScript} * object. The script is executed via {@link PreparedScript}'s * {@link PreparedScript#executeScript() executeScript} method, * which returns a {@link ResultVariables} object, which is similar to a JDBC * {@code ResultSet}. Data can be read from a {@link ResultVariables} object by calling * its {@link ResultVariables#getFrame(String) getFrame} and * {@link ResultVariables#getMatrix(String) getMatrix} methods. * * <p> * For examples, please see the following: * <ul> * <li>JMLC JUnit test cases (org.apache.sysml.test.integration.functions.jmlc)</li> * <li><a target="_blank" href="http://apache.github.io/systemml/jmlc.html">JMLC section * of SystemML online documentation</a></li> * </ul> */ public class Connection implements Closeable { private final DMLConfig _dmlconf; private final CompilerConfig _cconf; /** * Connection constructor, the starting point for any other JMLC API calls. * */ public Connection() { //with default dml configuration this(new DMLConfig()); } /** * Connection constructor, the starting point for any other JMLC API calls. * This variant allows to enable a set of boolean compiler configurations. * * @param cconfigs one or many boolean compiler configurations to enable. */ public Connection(CompilerConfig.ConfigType... cconfigs) { //basic constructor, which also constructs the compiler config this(new DMLConfig()); //with default dml configuration //set optional compiler configurations in current config for( ConfigType configType : cconfigs ) _cconf.set(configType, true); setLocalConfigs(); } /** * Connection constructor, the starting point for any other JMLC API calls. * This variant allows to pass a global dml configuration and enable a set * of boolean compiler configurations. * * @param dmlconfig a dml configuration. * @param cconfigs one or many boolean compiler configurations to enable. */ public Connection(DMLConfig dmlconfig, CompilerConfig.ConfigType... cconfigs) { //basic constructor, which also constructs the compiler config this(dmlconfig); //set optional compiler configurations in current config for( ConfigType configType : cconfigs ) _cconf.set(configType, true); setLocalConfigs(); } /** * Connection constructor, the starting point for any other JMLC API calls. * This variant allows to pass a global dml configuration. * * @param dmlconfig a dml configuration. */ public Connection(DMLConfig dmlconfig) { DMLScript.rtplatform = RUNTIME_PLATFORM.SINGLE_NODE; //setup basic parameters for embedded execution //(parser, compiler, and runtime parameters) CompilerConfig cconf = new CompilerConfig(); cconf.set(ConfigType.IGNORE_UNSPECIFIED_ARGS, true); cconf.set(ConfigType.IGNORE_READ_WRITE_METADATA, true); cconf.set(ConfigType.IGNORE_TEMPORARY_FILENAMES, true); cconf.set(ConfigType.REJECT_READ_WRITE_UNKNOWNS, false); cconf.set(ConfigType.PARALLEL_CP_READ_TEXTFORMATS, false); cconf.set(ConfigType.PARALLEL_CP_WRITE_TEXTFORMATS, false); cconf.set(ConfigType.PARALLEL_CP_READ_BINARYFORMATS, false); cconf.set(ConfigType.PARALLEL_CP_WRITE_BINARYFORMATS, false); cconf.set(ConfigType.PARALLEL_CP_MATRIX_OPERATIONS, false); cconf.set(ConfigType.PARALLEL_LOCAL_OR_REMOTE_PARFOR, false); cconf.set(ConfigType.ALLOW_DYN_RECOMPILATION, false); cconf.set(ConfigType.ALLOW_INDIVIDUAL_SB_SPECIFIC_OPS, false); cconf.set(ConfigType.ALLOW_CSE_PERSISTENT_READS, false); cconf.set(ConfigType.CODEGEN_ENABLED, false); _cconf = cconf; //disable caching globally CacheableData.disableCaching(); //assign the given configuration _dmlconf = dmlconfig; setLocalConfigs(); } /** * Prepares (precompiles) a script and registers input and output variables. * * @param script string representing the DML or PyDML script * @param inputs string array of input variables to register * @param outputs string array of output variables to register * @return PreparedScript object representing the precompiled script * @throws DMLException if DMLException occurs */ public PreparedScript prepareScript( String script, String[] inputs, String[] outputs) throws DMLException { return prepareScript(script, inputs, outputs, false); } /** * Prepares (precompiles) a script and registers input and output variables. * * @param script string representing the DML or PyDML script * @param inputs string array of input variables to register * @param outputs string array of output variables to register * @param parsePyDML {@code true} if PyDML, {@code false} if DML * @return PreparedScript object representing the precompiled script * @throws DMLException if DMLException occurs */ public PreparedScript prepareScript( String script, String[] inputs, String[] outputs, boolean parsePyDML) throws DMLException { return prepareScript(script, new HashMap<String,String>(), inputs, outputs, parsePyDML); } /** * Prepares (precompiles) a script, sets input parameter values, and registers input and output variables. * * @param script string representing the DML or PyDML script * @param args map of input parameters ($) and their values * @param inputs string array of input variables to register * @param outputs string array of output variables to register * @param parsePyDML {@code true} if PyDML, {@code false} if DML * @return PreparedScript object representing the precompiled script * @throws DMLException if DMLException occurs */ public PreparedScript prepareScript( String script, Map<String, String> args, String[] inputs, String[] outputs, boolean parsePyDML) throws DMLException { DMLScript.SCRIPT_TYPE = parsePyDML ? ScriptType.PYDML : ScriptType.DML; //check for valid names of passed arguments String[] invalidArgs = args.keySet().stream() .filter(k -> k==null || !k.startsWith("$")).toArray(String[]::new); if( invalidArgs.length > 0 ) throw new LanguageException("Invalid argument names: "+Arrays.toString(invalidArgs)); //check for valid names of input and output variables String[] invalidVars = UtilFunctions.asSet(inputs, outputs).stream() .filter(k -> k==null || k.startsWith("$")).toArray(String[]::new); if( invalidVars.length > 0 ) throw new LanguageException("Invalid variable names: "+Arrays.toString(invalidVars)); setLocalConfigs(); //simplified compilation chain Program rtprog = null; try { //parsing ParserWrapper parser = ParserFactory.createParser(parsePyDML ? ScriptType.PYDML : ScriptType.DML); DMLProgram prog = parser.parse(null, script, args); //language validate DMLTranslator dmlt = new DMLTranslator(prog); dmlt.liveVariableAnalysis(prog); dmlt.validateParseTree(prog); //hop construct/rewrite dmlt.constructHops(prog); dmlt.rewriteHopsDAG(prog); //rewrite persistent reads/writes RewriteRemovePersistentReadWrite rewrite = new RewriteRemovePersistentReadWrite(inputs, outputs); ProgramRewriter rewriter2 = new ProgramRewriter(rewrite); rewriter2.rewriteProgramHopDAGs(prog); //lop construct and runtime prog generation dmlt.constructLops(prog); rtprog = dmlt.getRuntimeProgram(prog, _dmlconf); //final cleanup runtime prog JMLCUtils.cleanupRuntimeProgram(rtprog, outputs); } catch(ParseException pe) { // don't chain ParseException (for cleaner error output) throw pe; } catch(Exception ex) { throw new DMLException(ex); } //return newly create precompiled script return new PreparedScript(rtprog, inputs, outputs, _dmlconf, _cconf); } /** * Close connection to SystemML, which clears the * thread-local DML and compiler configurations. */ @Override public void close() { //clear thread-local configurations ConfigurationManager.clearLocalConfigs(); if( ConfigurationManager.isCodegenEnabled() ) SpoofCompiler.cleanupCodeGenerator(); } /** * Read a DML or PyDML file as a string. * * @param fname the filename of the script * @return string content of the script file * @throws IOException if IOException occurs */ public String readScript(String fname) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { //read from hdfs or gpfs file system if( fname.startsWith("hdfs:") || fname.startsWith("gpfs:") || IOUtilFunctions.isObjectStoreFileScheme(new Path(fname)) ) { Path scriptPath = new Path(fname); FileSystem fs = IOUtilFunctions.getFileSystem(scriptPath); in = new BufferedReader(new InputStreamReader(fs.open(scriptPath))); } // from local file system else { in = new BufferedReader(new FileReader(fname)); } //core script reading String tmp = null; while ((tmp = in.readLine()) != null) { sb.append( tmp ); sb.append( "\n" ); } } finally { IOUtilFunctions.closeSilently(in); } return sb.toString(); } //////////////////////////////////////////// // Read matrices //////////////////////////////////////////// /** * Reads an input matrix in arbitrary format from HDFS into a dense double array. * NOTE: this call currently only supports default configurations for CSV. * * @param fname the filename of the input matrix * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] readDoubleMatrix(String fname) throws IOException { try { //read json meta data String fnamemtd = DataExpression.getMTDFileName(fname); JSONObject jmtd = new DataExpression().readMetadataFile(fnamemtd, false); //parse json meta data long rows = jmtd.getLong(DataExpression.READROWPARAM); long cols = jmtd.getLong(DataExpression.READCOLPARAM); int brlen = jmtd.containsKey(DataExpression.ROWBLOCKCOUNTPARAM)? jmtd.getInt(DataExpression.ROWBLOCKCOUNTPARAM) : -1; int bclen = jmtd.containsKey(DataExpression.COLUMNBLOCKCOUNTPARAM)? jmtd.getInt(DataExpression.COLUMNBLOCKCOUNTPARAM) : -1; long nnz = jmtd.containsKey(DataExpression.READNUMNONZEROPARAM)? jmtd.getLong(DataExpression.READNUMNONZEROPARAM) : -1; String format = jmtd.getString(DataExpression.FORMAT_TYPE); InputInfo iinfo = InputInfo.stringExternalToInputInfo(format); //read matrix file return readDoubleMatrix(fname, iinfo, rows, cols, brlen, bclen, nnz); } catch(Exception ex) { throw new IOException(ex); } } /** * Reads an input matrix in arbitrary format from HDFS into a dense double array. * NOTE: this call currently only supports default configurations for CSV. * * @param fname the filename of the input matrix * @param iinfo InputInfo object * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @param brlen number of rows per block * @param bclen number of columns per block * @param nnz number of non-zero values, -1 indicates unknown * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] readDoubleMatrix(String fname, InputInfo iinfo, long rows, long cols, int brlen, int bclen, long nnz) throws IOException { setLocalConfigs(); try { MatrixReader reader = MatrixReaderFactory.createMatrixReader(iinfo); MatrixBlock mb = reader.readMatrixFromHDFS(fname, rows, cols, brlen, bclen, nnz); return DataConverter.convertToDoubleMatrix(mb); } catch(Exception ex) { throw new IOException(ex); } } /** * Converts an input string representation of a matrix in csv or textcell format * into a dense double array. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input string matrix in csv or textcell format * @param meta string representing SystemML matrix metadata in JSON format * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] convertToDoubleMatrix(String input, String meta) throws IOException { MatrixBlock mb = convertToMatrix(input, meta); return DataConverter.convertToDoubleMatrix(mb); } /** * Converts an input string representation of a matrix in textcell format * into a dense double array. * * @param input string matrix in textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] convertToDoubleMatrix(String input, int rows, int cols) throws IOException { return convertToDoubleMatrix(IOUtilFunctions.toInputStream(input), rows, cols); } /** * Converts an input stream of a string matrix in textcell format * into a dense double array. * * @param input InputStream to a string matrix in textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] convertToDoubleMatrix(InputStream input, int rows, int cols) throws IOException { return convertToDoubleMatrix(input, rows, cols, DataExpression.FORMAT_TYPE_VALUE_TEXT); } /** * Converts an input stream of a string matrix in csv or textcell format * into a dense double array. * * @param input InputStream to a string matrix in csv or textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @param format input format of the given stream * @return matrix as a two-dimensional double array * @throws IOException if IOException occurs */ public double[][] convertToDoubleMatrix(InputStream input, int rows, int cols, String format) throws IOException { MatrixBlock mb = convertToMatrix(input, rows, cols, format); return DataConverter.convertToDoubleMatrix(mb); } /** * Converts an input string representation of a matrix in csv or textcell format * into a matrix block. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input string matrix in csv or textcell format * @param meta string representing SystemML matrix metadata in JSON format * @return matrix as a matrix block * @throws IOException if IOException occurs */ public MatrixBlock convertToMatrix(String input, String meta) throws IOException { return convertToMatrix(IOUtilFunctions.toInputStream(input), meta); } /** * Converts an input stream of a string matrix in csv or textcell format * into a matrix block. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input InputStream to a string matrix in csv or textcell format * @param meta string representing SystemML matrix metadata in JSON format * @return matrix as a matrix block * @throws IOException if IOException occurs */ public MatrixBlock convertToMatrix(InputStream input, String meta) throws IOException { try { //parse json meta data JSONObject jmtd = new JSONObject(meta); int rows = jmtd.getInt(DataExpression.READROWPARAM); int cols = jmtd.getInt(DataExpression.READCOLPARAM); String format = jmtd.getString(DataExpression.FORMAT_TYPE); //parse the input matrix return convertToMatrix(input, rows, cols, format); } catch(Exception ex) { throw new IOException(ex); } } /** * Converts an input string representation of a matrix in textcell format * into a matrix block. * * @param input string matrix in textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @return matrix as a matrix block * @throws IOException if IOException occurs */ public MatrixBlock convertToMatrix(String input, int rows, int cols) throws IOException { return convertToMatrix(IOUtilFunctions.toInputStream(input), rows, cols); } /** * Converts an input stream of a string matrix in textcell format * into a matrix block. * * @param input InputStream to a string matrix in textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @return matrix as a matrix block * @throws IOException if IOException occurs */ public MatrixBlock convertToMatrix(InputStream input, int rows, int cols) throws IOException { return convertToMatrix(input, rows, cols, DataExpression.FORMAT_TYPE_VALUE_TEXT); } /** * Converts an input stream of a string matrix in csv or textcell format * into a matrix block. * * @param input InputStream to a string matrix in csv or textcell format * @param rows number of rows in the matrix * @param cols number of columns in the matrix * @param format input format of the given stream * @return matrix as a matrix block * @throws IOException if IOException occurs */ public MatrixBlock convertToMatrix(InputStream input, int rows, int cols, String format) throws IOException { MatrixBlock ret = null; //sanity check input format if(!(DataExpression.FORMAT_TYPE_VALUE_TEXT.equals(format) ||DataExpression.FORMAT_TYPE_VALUE_MATRIXMARKET.equals(format) ||DataExpression.FORMAT_TYPE_VALUE_CSV.equals(format)) ) { throw new IOException("Invalid input format (expected: csv, text or mm): "+format); } setLocalConfigs(); try { //read input matrix InputInfo iinfo = DataExpression.FORMAT_TYPE_VALUE_CSV.equals(format) ? InputInfo.CSVInputInfo : InputInfo.TextCellInputInfo; MatrixReader reader = MatrixReaderFactory.createMatrixReader(iinfo); int blksz = ConfigurationManager.getBlocksize(); ret = reader.readMatrixFromInputStream(input, rows, cols, blksz, blksz, (long)rows*cols); } catch(DMLRuntimeException rex) { throw new IOException(rex); } return ret; } //////////////////////////////////////////// // Read frames //////////////////////////////////////////// /** * Reads an input frame in arbitrary format from HDFS into a dense string array. * NOTE: this call currently only supports default configurations for CSV. * * @param fname the filename of the input frame * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] readStringFrame(String fname) throws IOException { try { //read json meta data String fnamemtd = DataExpression.getMTDFileName(fname); JSONObject jmtd = new DataExpression().readMetadataFile(fnamemtd, false); //parse json meta data long rows = jmtd.getLong(DataExpression.READROWPARAM); long cols = jmtd.getLong(DataExpression.READCOLPARAM); String format = jmtd.getString(DataExpression.FORMAT_TYPE); InputInfo iinfo = InputInfo.stringExternalToInputInfo(format); //read frame file return readStringFrame(fname, iinfo, rows, cols); } catch(Exception ex) { throw new IOException(ex); } } /** * Reads an input frame in arbitrary format from HDFS into a dense string array. * NOTE: this call currently only supports default configurations for CSV. * * @param fname the filename of the input frame * @param iinfo InputInfo object * @param rows number of rows in the frame * @param cols number of columns in the frame * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] readStringFrame(String fname, InputInfo iinfo, long rows, long cols) throws IOException { setLocalConfigs(); try { FrameReader reader = FrameReaderFactory.createFrameReader(iinfo); FrameBlock mb = reader.readFrameFromHDFS(fname, rows, cols); return DataConverter.convertToStringFrame(mb); } catch(Exception ex) { throw new IOException(ex); } } /** * Converts an input string representation of a frame in csv or textcell format * into a dense string array. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input string frame in csv or textcell format * @param meta string representing SystemML frame metadata in JSON format * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] convertToStringFrame(String input, String meta) throws IOException { FrameBlock fb = convertToFrame(input, meta); return DataConverter.convertToStringFrame(fb); } /** * Converts an input stream of a string frame in textcell format * into a dense string array. * * @param input string frame in textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] convertToStringFrame(String input, int rows, int cols) throws IOException { return convertToStringFrame(IOUtilFunctions.toInputStream(input), rows, cols); } /** * Converts an input stream of a string frame in textcell format * into a dense string array. * * @param input InputStream to a string frame in textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] convertToStringFrame(InputStream input, int rows, int cols) throws IOException { return convertToStringFrame(input, rows, cols, DataExpression.FORMAT_TYPE_VALUE_TEXT); } /** * Converts an input stream of a string frame in csv or textcell format * into a dense string array. * * @param input InputStream to a string frame in csv or textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @param format input format of the given stream * @return frame as a two-dimensional string array * @throws IOException if IOException occurs */ public String[][] convertToStringFrame(InputStream input, int rows, int cols, String format) throws IOException { FrameBlock fb = convertToFrame(input, rows, cols, format); return DataConverter.convertToStringFrame(fb); } /** * Converts an input string representation of a frame in csv or textcell format * into a frame block. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input string frame in csv or textcell format * @param meta string representing SystemML frame metadata in JSON format * @return frame as a frame block * @throws IOException if IOException occurs */ public FrameBlock convertToFrame(String input, String meta) throws IOException { return convertToFrame(IOUtilFunctions.toInputStream(input), meta); } /** * Converts an input stream of a string frame in csv or textcell format * into a frame block. The meta data string is the SystemML generated * .mtd file including the number of rows and columns. * * @param input InputStream to a string frame in csv or textcell format * @param meta string representing SystemML frame metadata in JSON format * @return frame as a frame block * @throws IOException if IOException occurs */ public FrameBlock convertToFrame(InputStream input, String meta) throws IOException { try { //parse json meta data JSONObject jmtd = new JSONObject(meta); int rows = jmtd.getInt(DataExpression.READROWPARAM); int cols = jmtd.getInt(DataExpression.READCOLPARAM); String format = jmtd.getString(DataExpression.FORMAT_TYPE); //parse the input frame return convertToFrame(input, rows, cols, format); } catch(Exception ex) { throw new IOException(ex); } } /** * Converts an input string representation of a frame in textcell format * into a frame block. * * @param input string frame in textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @return frame as a frame block * @throws IOException if IOException occurs */ public FrameBlock convertToFrame(String input, int rows, int cols) throws IOException { return convertToFrame(IOUtilFunctions.toInputStream(input), rows, cols); } /** * Converts an input stream of a string frame in textcell format * into a frame block. * * @param input InputStream to a string frame in textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @return frame as a frame block * @throws IOException if IOException occurs */ public FrameBlock convertToFrame(InputStream input, int rows, int cols) throws IOException { return convertToFrame(input, rows, cols, DataExpression.FORMAT_TYPE_VALUE_TEXT); } /** * Converts an input stream of a frame in csv or textcell format * into a frame block. * * @param input InputStream to a string frame in csv or textcell format * @param rows number of rows in the frame * @param cols number of columns in the frame * @param format input format of the given stream * @return frame as a frame block * @throws IOException if IOException occurs */ public FrameBlock convertToFrame(InputStream input, int rows, int cols, String format) throws IOException { FrameBlock ret = null; //sanity check input format if(!(DataExpression.FORMAT_TYPE_VALUE_TEXT.equals(format) ||DataExpression.FORMAT_TYPE_VALUE_MATRIXMARKET.equals(format) ||DataExpression.FORMAT_TYPE_VALUE_CSV.equals(format))) { throw new IOException("Invalid input format (expected: csv, text or mm): "+format); } setLocalConfigs(); try { //read input frame InputInfo iinfo = DataExpression.FORMAT_TYPE_VALUE_CSV.equals(format) ? InputInfo.CSVInputInfo : InputInfo.TextCellInputInfo; FrameReader reader = FrameReaderFactory.createFrameReader(iinfo); ret = reader.readFrameFromInputStream(input, rows, cols); } catch(DMLRuntimeException rex) { throw new IOException(rex); } return ret; } //////////////////////////////////////////// // Read transform meta data //////////////////////////////////////////// /** * Reads transform meta data from an HDFS file path and converts it into an in-memory * FrameBlock object. The column names in the meta data file 'column.names' is processed * with default separator ','. * * @param metapath hdfs file path to meta data directory * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromFile(String metapath) throws IOException { return readTransformMetaDataFromFile(null, metapath, TfUtils.TXMTD_SEP); } /** * Reads transform meta data from an HDFS file path and converts it into an in-memory * FrameBlock object. The column names in the meta data file 'column.names' is processed * with default separator ','. * * @param spec transform specification as json string * @param metapath hdfs file path to meta data directory * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromFile(String spec, String metapath) throws IOException { return readTransformMetaDataFromFile(spec, metapath, TfUtils.TXMTD_SEP); } /** * Reads transform meta data from an HDFS file path and converts it into an in-memory * FrameBlock object. * * @param spec transform specification as json string * @param metapath hdfs file path to meta data directory * @param colDelim separator for processing column names in the meta data file 'column.names' * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromFile(String spec, String metapath, String colDelim) throws IOException { return TfMetaUtils.readTransformMetaDataFromFile(spec, metapath, colDelim); } /** * Reads transform meta data from the class path and converts it into an in-memory * FrameBlock object. The column names in the meta data file 'column.names' is processed * with default separator ','. * * @param metapath resource path to meta data directory * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromPath(String metapath) throws IOException { return readTransformMetaDataFromPath(null, metapath, TfUtils.TXMTD_SEP); } /** * Reads transform meta data from the class path and converts it into an in-memory * FrameBlock object. The column names in the meta data file 'column.names' is processed * with default separator ','. * * @param spec transform specification as json string * @param metapath resource path to meta data directory * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromPath(String spec, String metapath) throws IOException { return readTransformMetaDataFromPath(spec, metapath, TfUtils.TXMTD_SEP); } /** * Reads transform meta data from the class path and converts it into an in-memory * FrameBlock object. * * @param spec transform specification as json string * @param metapath resource path to meta data directory * @param colDelim separator for processing column names in the meta data file 'column.names' * @return FrameBlock object representing transform metadata * @throws IOException if IOException occurs */ public FrameBlock readTransformMetaDataFromPath(String spec, String metapath, String colDelim) throws IOException { return TfMetaUtils.readTransformMetaDataFromPath(spec, metapath, colDelim); } private void setLocalConfigs() { //set thread-local configurations for compilation and read ConfigurationManager.setLocalConfig(_dmlconf); ConfigurationManager.setLocalConfig(_cconf); } }
apache-2.0
magnetsystems/message-server
server/plugins/mmxmgmt/src/main/java/com/magnet/mmx/server/plugin/mmxmgmt/db/EndPointEntity.java
1672
/* Copyright (c) 2015 Magnet Systems, 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.magnet.mmx.server.plugin.mmxmgmt.db; import java.sql.ResultSet; import java.sql.SQLException; /** * Composite entity composed of a device and a user. */ public class EndPointEntity { private DeviceEntity device; private UserEntity userEntity; public DeviceEntity getDevice() { return device; } public void setDevice(DeviceEntity device) { this.device = device; } public UserEntity getUserEntity() { return userEntity; } public void setUserEntity(UserEntity userEntity) { this.userEntity = userEntity; } public static class EndPointEntityBuilder { public EndPointEntity build(ResultSet rs, String userPrefix, String endpointPrefix) throws SQLException { EndPointEntity entity = new EndPointEntity(); UserEntity user = new UserEntity.UserEntityBuilder().build(rs, userPrefix, true); DeviceEntity device = new DeviceEntity.DeviceEntityBuilder().buildLimited(rs, endpointPrefix); entity.setDevice(device); entity.setUserEntity(user); return entity; } } }
apache-2.0
carlosgsouza/types-and-quality
experiments/1_vinyl_collection/a1/analysis/data/mateus/snapshots/1387294570511/src/main/groovy/carlosgsouza/vinylshop/controller/ReportController.java
3828
package carlosgsouza.vinylshop.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import carlosgsouza.vinylshop.database.DB; import carlosgsouza.vinylshop.model.Report; import carlosgsouza.vinylshop.model.Vinyl; public class ReportController {; DB db = DB.connect(); public Report artist() { Report result = new Report(); List<String> artists = db.getArtists(); Integer artistCount = artists.size(); result.data.put("Number of artists", artistCount.toString()); Map<String, Integer> artist_vinylCount = new HashMap<String, Integer>(); Map<String, Integer> artist_songCount = new HashMap<String, Integer>(); if(artistCount > 0) { for(String artist : artists) { List<Vinyl> artistVinyls = db.searchVinylByArtist(artist); artist_vinylCount.put(artist, artistVinyls.size()); artist_songCount.put(artist, 0); for(Vinyl vinyl : artistVinyls) { artist_songCount.put(artist, artist_songCount.get(artist) + vinyl.songs.size()); } } } else if(artists != null) { if(artist_vinylCount.size() == 0 || artistCount == 0 ) { artist_vinylCount = new HashMap<String, Integer>(); artist_songCount = artist_vinylCount; return resut; } } String topArtist = ""; int topArtistVinylCount = -1; int idOfFirstVinylOfTopArtist = Integer.MAX_VALUE; for(String artist : artist_vinylCount.keySet()) { int idOfFirstVinylOfArtist = idOfFirstVinyl(db.searchVinylByArtist(artist)); if(topArtistVinylCount < artist_vinylCount.get(artist) || ( (topArtistVinylCount == artist_vinylCount.get(artist)) && (idOfFirstVinylOfArtist < idOfFirstVinylOfTopArtist))) { topArtist = artist; topArtistVinylCount = artist_vinylCount.get(artist); idOfFirstVinylOfTopArtist = idOfFirstVinylOfArtist; } } result.data.put("Top artist", topArtist); result.data.put("Number of vinyls by "+topArtist, artist_vinylCount.get(topArtist).toString()); result.data.put("Number of songs by "+topArtist, artist_songCount.get(topArtist).toString()); return result; } private int idOfFirstVinyl(List<Vinyl> vinyls) { int minId = Integer.MAX_VALUE; for(Vinyl vinyl : vinyls) { if(vinyl.id < minId) { minId = vinyl.id; } } return minId; } public Report genre() { Report result = new Report(); List<String> genres = db.getGenres(); Integer genreCount = genres.size(); result.data.put("Number of genres", genreCount.toString()); if(genreCount == 0) { return result; } Map<String, Integer> genre_vinylCount = new HashMap<String, Integer>(); Map<String, Integer> genre_songCount = new HashMap<String, Integer>(); for(String genre : genres) { List<Vinyl> genreVinyls = db.searchVinylByGenre(genre); genre_vinylCount.put(genre, genreVinyls.size()); genre_songCount.put(genre, 0); for(Vinyl vinyl : genreVinyls) { genre_songCount.put(genre, genre_songCount.get(genre) + vinyl.songs.size()); } } String topGenre = ""; int topGenreVinylCount = -1; int idOfFirstVinylOfTopGenre = Integer.MAX_VALUE; for(String genre : genre_vinylCount.keySet()) { int idOfFirstVinylOfGenre = idOfFirstVinyl(db.searchVinylByGenre(genre)); if(topGenreVinylCount < genre_vinylCount.get(genre) || ( (topGenreVinylCount == genre_vinylCount.get(genre)) && (idOfFirstVinylOfGenre < idOfFirstVinylOfTopGenre))) { topGenre = genre; topGenreVinylCount = genre_vinylCount.get(genre); idOfFirstVinylOfTopGenre = idOfFirstVinylOfGenre; } } result.data.put("Top genre", topGenre); result.data.put("Number of "+topGenre+" vinyls", genre_vinylCount.get(topGenre).toString()); result.data.put("Number of "+topGenre+" songs", genre_songCount.get(topGenre).toString()); return result; } }
apache-2.0
yole/asciidoctor-intellij-plugin
src/main/java/org/asciidoc/intellij/settings/AsciiDocApplicationSettings.java
2278
package org.asciidoc.intellij.settings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.util.messages.Topic; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Property; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @State( name = "AsciidocApplicationSettings", storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/asciidoc.xml") // keep the line above to be compatible with IntellJ 15.x editions // use the line below with IntellJ 2016.2.x // @Storage("asciidoc.xml") ) public class AsciiDocApplicationSettings implements PersistentStateComponent<AsciiDocApplicationSettings.State>, AsciiDocPreviewSettings.Holder { private State myState = new State(); @NotNull public static AsciiDocApplicationSettings getInstance() { return ServiceManager.getService(AsciiDocApplicationSettings.class); } @Nullable @Override public State getState() { return myState; } @Override public void loadState(State state) { XmlSerializerUtil.copyBean(state, myState); } @Override public void setAsciiDocPreviewSettings(@NotNull AsciiDocPreviewSettings settings) { myState.myPreviewSettings = settings; ApplicationManager.getApplication().getMessageBus().syncPublisher(SettingsChangedListener.TOPIC).onSettingsChange(this); } @NotNull @Override public AsciiDocPreviewSettings getAsciiDocPreviewSettings() { return myState.myPreviewSettings; } public static class State { @Property(surroundWithTag = false) @NotNull private AsciiDocPreviewSettings myPreviewSettings = AsciiDocPreviewSettings.DEFAULT; } public interface SettingsChangedListener { Topic<SettingsChangedListener> TOPIC = Topic.create("AsciiDocApplicationSettingsChanged", SettingsChangedListener.class); void onSettingsChange(@NotNull AsciiDocApplicationSettings settings); } }
apache-2.0
lsmall/flowable-engine
modules/flowable-task-service/src/main/java/org/flowable/task/service/impl/persistence/entity/HistoricTaskInstanceEntityManagerImpl.java
4421
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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.task.service.impl.persistence.entity; import java.util.Collections; import java.util.List; import java.util.Map; import org.flowable.common.engine.impl.persistence.entity.data.DataManager; import org.flowable.task.api.history.HistoricTaskInstance; import org.flowable.task.service.TaskServiceConfiguration; import org.flowable.task.service.impl.HistoricTaskInstanceQueryImpl; import org.flowable.task.service.impl.persistence.entity.data.HistoricTaskInstanceDataManager; /** * @author Tom Baeyens * @author Joram Barrez */ public class HistoricTaskInstanceEntityManagerImpl extends AbstractEntityManager<HistoricTaskInstanceEntity> implements HistoricTaskInstanceEntityManager { protected HistoricTaskInstanceDataManager historicTaskInstanceDataManager; public HistoricTaskInstanceEntityManagerImpl(TaskServiceConfiguration taskServiceConfiguration, HistoricTaskInstanceDataManager historicTaskInstanceDataManager) { super(taskServiceConfiguration); this.historicTaskInstanceDataManager = historicTaskInstanceDataManager; } @Override protected DataManager<HistoricTaskInstanceEntity> getDataManager() { return historicTaskInstanceDataManager; } @Override public HistoricTaskInstanceEntity create(TaskEntity task) { return historicTaskInstanceDataManager.create(task); } @Override public List<HistoricTaskInstanceEntity> findHistoricTasksByParentTaskId(String parentTaskId) { return historicTaskInstanceDataManager.findHistoricTasksByParentTaskId(parentTaskId); } @Override public List<HistoricTaskInstanceEntity> findHistoricTasksByProcessInstanceId(String processInstanceId) { return historicTaskInstanceDataManager.findHistoricTasksByProcessInstanceId(processInstanceId); } @Override public long findHistoricTaskInstanceCountByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) { if (taskServiceConfiguration.isHistoryEnabled()) { return historicTaskInstanceDataManager.findHistoricTaskInstanceCountByQueryCriteria(historicTaskInstanceQuery); } return 0; } @Override @SuppressWarnings("unchecked") public List<HistoricTaskInstance> findHistoricTaskInstancesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) { if (taskServiceConfiguration.isHistoryEnabled()) { return historicTaskInstanceDataManager.findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery); } return Collections.EMPTY_LIST; } @Override @SuppressWarnings("unchecked") public List<HistoricTaskInstance> findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) { if (taskServiceConfiguration.isHistoryEnabled()) { return historicTaskInstanceDataManager.findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(historicTaskInstanceQuery); } return Collections.EMPTY_LIST; } @Override public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(Map<String, Object> parameterMap) { return historicTaskInstanceDataManager.findHistoricTaskInstancesByNativeQuery(parameterMap); } @Override public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return historicTaskInstanceDataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap); } public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() { return historicTaskInstanceDataManager; } public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) { this.historicTaskInstanceDataManager = historicTaskInstanceDataManager; } }
apache-2.0
avery1701/thor
src/generated/java/com/example/recursion/PersonFactory4.java
332
package com.example.recursion; import com.advancedpwr.record.factory.BaseFactory; import com.advancedpwr.samples.Person; public class PersonFactory4 extends BaseFactory { protected Person person; public Person buildPerson() { if ( person != null ) { return person; } person = new Person(); return person; } }
apache-2.0
DebalinaDey/AuraDevelopDeb
aura-components/src/test/java/org/auraframework/components/test/java/controller/ContextVPTestController.java
2641
/* * Copyright (C) 2013 salesforce.com, 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.auraframework.components.test.java.controller; import java.util.Map; import org.auraframework.Aura; import org.auraframework.impl.context.AuraContextImpl; import org.auraframework.system.Annotations.AuraEnabled; import org.auraframework.system.Annotations.Controller; import org.auraframework.system.Annotations.Key; import org.auraframework.system.AuraContext.GlobalValue; import org.auraframework.util.test.util.AuraPrivateAccessor; @Controller public class ContextVPTestController { @AuraEnabled public static void registerContextVPValue(@Key("name") String name, @Key("writable") boolean writable, @Key("defaultValue") Object defaultValue) { Aura.getContextService().registerGlobal(name, writable, defaultValue); } @AuraEnabled public static Object getContextVPValue(@Key("name") String name) { return Aura.getContextService().getCurrentContext().getGlobal(name).toString(); } @AuraEnabled public static void setContextVPValue(@Key("name") String name, @Key("value") Object value) { Aura.getContextService().getCurrentContext().setGlobalValue(name, value); } @AuraEnabled public static void unregisterContextVPValue(@Key("name") String name) throws Exception { Map<String, GlobalValue> values = AuraPrivateAccessor.get(AuraContextImpl.class, "allowedGlobalValues"); values.remove(name); } /** * Register and set a GVP. Combine both actions into a single method since actions fired on the client are not * guaranteed to be executed in a certain order and we need to register the GVP before setting it. */ @AuraEnabled public static void registerAndSetContextVPValue(@Key("name") String name, @Key("writable") boolean writable, @Key("defaultValue") Object defaultValue, @Key("value") Object value) { Aura.getContextService().registerGlobal(name, writable, defaultValue); Aura.getContextService().getCurrentContext().setGlobalValue(name, value); } }
apache-2.0
designreuse/essentials
plugin-sdk/implementation/src/test/java/org/onehippo/cms7/essentials/dashboard/instruction/CndInstructionTest.java
3013
/* * Copyright 2014 Hippo B.V. (http://www.onehippo.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 org.onehippo.cms7.essentials.dashboard.instruction; import javax.inject.Inject; import javax.jcr.Session; import org.hippoecm.repository.api.HippoNodeType; import org.junit.Test; import org.onehippo.cms7.essentials.BaseRepositoryTest; import org.onehippo.cms7.essentials.dashboard.instructions.InstructionExecutor; import org.onehippo.cms7.essentials.dashboard.instructions.InstructionSet; import org.onehippo.cms7.essentials.dashboard.instructions.InstructionStatus; import org.onehippo.cms7.essentials.dashboard.utils.CndUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @version "$Id$" */ public class CndInstructionTest extends BaseRepositoryTest { public static final String TEST_URI = "http://www.test.com"; public static final String TEST_PREFIX = "test"; @Inject private InstructionExecutor executor; @Inject private CndInstruction cndInstruction; @Test public void testProcess() throws Exception { final Session session = getSession(); session.getRootNode().addNode(HippoNodeType.NAMESPACES_PATH); session.save(); CndUtils.registerNamespace(getContext(), TEST_PREFIX, TEST_URI); assertTrue("CndUtils.registerNamespaceUri", true); CndUtils.createHippoNamespace(getContext(), TEST_PREFIX); assertTrue("CndUtils.createHippoNamespace", true); boolean exists = CndUtils.namespaceUriExists(getContext(), TEST_URI); assertTrue(exists); cndInstruction.setDocumentType("newsdocument"); getContext().setProjectNamespacePrefix(TEST_PREFIX); final InstructionSet instructionSet = new PluginInstructionSet(); instructionSet.addInstruction(cndInstruction); InstructionStatus status = executor.execute(instructionSet, getContext()); assertTrue("Expected success but got: " + status, status == InstructionStatus.SUCCESS); // this should node throw exists exception status = executor.execute(instructionSet, getContext()); assertTrue("Expected success but got: " + status, status == InstructionStatus.FAILED); // test prefix: final String testingPrefix = "testingprefix"; cndInstruction.setNamespacePrefix(testingPrefix); assertEquals("testingprefix", cndInstruction.getNamespacePrefix()); session.logout(); } }
apache-2.0
MissionCriticalCloud/cosmic
cosmic-core/engine/schema/src/main/java/com/cloud/resourcedetail/FirewallRuleDetailVO.java
1412
package com.cloud.resourcedetail; import com.cloud.api.ResourceDetail; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "firewall_rule_details") public class FirewallRuleDetailVO implements ResourceDetail { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @Column(name = "firewall_rule_id") private long resourceId; @Column(name = "name") private String name; @Column(name = "value", length = 1024) private String value; @Column(name = "display") private boolean display = true; public FirewallRuleDetailVO() { } public FirewallRuleDetailVO(final long id, final String name, final String value, final boolean display) { this.resourceId = id; this.name = name; this.value = value; this.display = display; } @Override public long getId() { return id; } @Override public long getResourceId() { return resourceId; } @Override public String getName() { return name; } @Override public String getValue() { return value; } @Override public boolean isDisplay() { return display; } }
apache-2.0
MikeThomsen/nifi
nifi-registry/nifi-registry-core/nifi-registry-data-model/src/main/java/org/apache/nifi/registry/flow/VersionedParameterContext.java
2204
/* * 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.nifi.registry.flow; import io.swagger.annotations.ApiModelProperty; import org.apache.nifi.flow.ComponentType; import org.apache.nifi.flow.VersionedComponent; import java.util.List; import java.util.Set; public class VersionedParameterContext extends VersionedComponent { private Set<VersionedParameter> parameters; private List<String> inheritedParameterContexts; private String description; @ApiModelProperty("The description of the parameter context") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty("The parameters in the context") public Set<VersionedParameter> getParameters() { return parameters; } public void setParameters(Set<VersionedParameter> parameters) { this.parameters = parameters; } @ApiModelProperty("The names of additional parameter contexts from which to inherit parameters") public List<String> getInheritedParameterContexts() { return inheritedParameterContexts; } public void setInheritedParameterContexts(List<String> parameterContextNames) { this.inheritedParameterContexts = parameterContextNames; } @Override public ComponentType getComponentType() { return ComponentType.PARAMETER_CONTEXT; } }
apache-2.0
Photobucket/Solbase-Lucene
src/test/org/apache/lucene/search/MockFilter.java
1255
package org.apache.lucene.search; /** * 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.util.DocIdBitSet; import java.util.BitSet; public class MockFilter extends Filter { private boolean wasCalled; public DocIdSet getDocIdSet(IndexReader reader) { wasCalled = true; return new DocIdBitSet(new BitSet()); } public void clear() { wasCalled = false; } public boolean wasCalled() { return wasCalled; } }
apache-2.0
killbill/killbill
usage/src/test/java/org/killbill/billing/usage/glue/TestUsageModuleWithEmbeddedDB.java
2002
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project 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.killbill.billing.usage.glue; import org.killbill.billing.GuicyKillbillTestWithEmbeddedDBModule; import org.killbill.billing.account.glue.DefaultAccountModule; import org.killbill.billing.platform.api.KillbillConfigSource; import org.killbill.billing.util.glue.AuditModule; import org.killbill.billing.util.glue.CacheModule; import org.killbill.billing.util.glue.ConfigModule; import org.killbill.billing.util.glue.EventModule; import org.killbill.billing.util.glue.NonEntityDaoModule; import org.killbill.clock.ClockMock; public class TestUsageModuleWithEmbeddedDB extends TestUsageModule { private final ClockMock clock; public TestUsageModuleWithEmbeddedDB(final KillbillConfigSource configSource, final ClockMock clock) { super(configSource); this.clock = clock; } @Override public void configure() { super.configure(); install(new GuicyKillbillTestWithEmbeddedDBModule(configSource, clock)); install(new CacheModule(configSource)); install(new ConfigModule(configSource)); install(new EventModule(configSource)); install(new NonEntityDaoModule(configSource)); install(new DefaultAccountModule(configSource)); install(new AuditModule(configSource)); } }
apache-2.0
alexcreasy/pnc
constants/src/main/java/org/jboss/pnc/enums/ValidationErrorType.java
1039
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.enums; /** * This enum represents various types of errors found throughout validation */ public enum ValidationErrorType { /** * Validated entity has invalid format (f.e. regex pattern does not match). */ FORMAT, /** * Validated entity already exists. */ DUPLICATION }
apache-2.0
apache/logging-log4j2
log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/FileAppenderBenchmark.java
6525
/* * 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.logging.log4j.perf.jmh; import java.io.File; import java.util.concurrent.TimeUnit; import java.util.logging.FileHandler; import java.util.logging.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; 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.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.slf4j.LoggerFactory; /** * Benchmarks Log4j 2, Log4j 1, Logback and JUL using the DEBUG level which is enabled for this test. The configuration * for each uses a FileAppender */ // HOW TO RUN THIS TEST // java -jar log4j-perf/target/benchmarks.jar ".*FileAppenderBenchmark.*" -f 1 -wi 10 -i 20 // // RUNNING THIS TEST WITH 4 THREADS: // java -jar log4j-perf/target/benchmarks.jar ".*FileAppenderBenchmark.*" -f 1 -wi 10 -i 20 -t 4 @State(Scope.Thread) public class FileAppenderBenchmark { public static final String MESSAGE = "This is a debug message"; private FileHandler julFileHandler; Logger log4j2Logger; Logger log4j2AsyncAppender; Logger log4j2AsyncLogger; Logger log4j2AsyncDisruptor; Logger log4j2RandomLogger; Logger log4j2MemoryLogger; org.slf4j.Logger slf4jLogger; org.slf4j.Logger slf4jAsyncLogger; org.apache.log4j.Logger log4j1Logger; java.util.logging.Logger julLogger; @Setup public void setUp() throws Exception { System.setProperty("log4j.configurationFile", "log4j2-perf.xml"); System.setProperty("log4j.configuration", "log4j12-perf.xml"); System.setProperty("logback.configurationFile", "logback-perf.xml"); deleteLogFiles(); log4j2Logger = LogManager.getLogger(FileAppenderBenchmark.class); log4j2AsyncAppender = LogManager.getLogger("AsyncAppender"); log4j2AsyncDisruptor = LogManager.getLogger("AsyncDisruptorAppender"); log4j2AsyncLogger = LogManager.getLogger("AsyncLogger"); //log4j2MemoryLogger = LogManager.getLogger("MemoryMapped"); log4j2RandomLogger = LogManager.getLogger("TestRandom"); slf4jLogger = LoggerFactory.getLogger(FileAppenderBenchmark.class); slf4jAsyncLogger = LoggerFactory.getLogger("Async"); log4j1Logger = org.apache.log4j.Logger.getLogger(FileAppenderBenchmark.class); julFileHandler = new FileHandler("target/testJulLog.log"); julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.setUseParentHandlers(false); julLogger.addHandler(julFileHandler); julLogger.setLevel(Level.ALL); } @TearDown public void tearDown() { System.clearProperty("log4j.configurationFile"); System.clearProperty("log4j.configuration"); System.clearProperty("logback.configurationFile"); deleteLogFiles(); } private void deleteLogFiles() { final File logbackFile = new File("target/testlogback.log"); logbackFile.delete(); final File log4jFile = new File ("target/testlog4j.log"); log4jFile.delete(); final File log4jRandomFile = new File ("target/testRandomlog4j2.log"); log4jRandomFile.delete(); final File log4jMemoryFile = new File ("target/testMappedlog4j2.log"); log4jMemoryFile.delete(); final File log4j2File = new File ("target/testlog4j2.log"); log4j2File.delete(); final File julFile = new File("target/testJulLog.log"); julFile.delete(); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2RAF() { log4j2RandomLogger.debug(MESSAGE); } /*@BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2MMF() { log4j2MemoryLogger.debug(MESSAGE); }*/ @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2AsyncAppender() { log4j2AsyncAppender.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2AsyncDisruptor() { log4j2AsyncDisruptor.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2AsyncLogger() { log4j2AsyncLogger.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2File() { log4j2Logger.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j2Builder() { log4j2Logger.atDebug().withLocation().log(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void logbackFile() { slf4jLogger.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void logbackAsyncFile() { slf4jAsyncLogger.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void log4j1File() { log4j1Logger.debug(MESSAGE); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Benchmark public void julFile() { // must specify sourceClass or JUL will look it up by walking the stack trace! julLogger.logp(Level.INFO, getClass().getName(), "julFile", MESSAGE); } }
apache-2.0
italiangrid/voms-clients
src/main/java/org/italiangrid/voms/clients/package-info.java
719
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare, 2006-2014. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ /** * @author andreaceccanti * */ package org.italiangrid.voms.clients;
apache-2.0
kares/killbill
entitlement/src/main/java/org/killbill/billing/entitlement/api/DefaultEntitlement.java
24214
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.entitlement.api; import java.io.IOException; import java.util.Collection; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.killbill.billing.ErrorCode; import org.killbill.billing.callcontext.InternalCallContext; import org.killbill.billing.catalog.api.BillingActionPolicy; import org.killbill.billing.catalog.api.BillingPeriod; import org.killbill.billing.catalog.api.Plan; import org.killbill.billing.catalog.api.PlanPhase; import org.killbill.billing.catalog.api.PriceList; import org.killbill.billing.catalog.api.Product; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.clock.Clock; import org.killbill.billing.entitlement.DefaultEntitlementService; import org.killbill.billing.entitlement.EntitlementService; import org.killbill.billing.entitlement.EventsStream; import org.killbill.billing.entitlement.block.BlockingChecker; import org.killbill.billing.entitlement.dao.BlockingStateDao; import org.killbill.billing.entitlement.engine.core.EntitlementNotificationKey; import org.killbill.billing.entitlement.engine.core.EntitlementNotificationKeyAction; import org.killbill.billing.entitlement.engine.core.EntitlementUtils; import org.killbill.billing.entitlement.engine.core.EventsStreamBuilder; import org.killbill.billing.entity.EntityBase; import org.killbill.billing.junction.DefaultBlockingState; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService.NoSuchNotificationQueue; import org.killbill.billing.subscription.api.SubscriptionBase; import org.killbill.billing.subscription.api.SubscriptionBaseInternalApi; import org.killbill.billing.subscription.api.user.SubscriptionBaseApiException; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.InternalCallContextFactory; import org.killbill.billing.util.callcontext.TenantContext; public class DefaultEntitlement extends EntityBase implements Entitlement { protected final EventsStreamBuilder eventsStreamBuilder; protected final EntitlementDateHelper dateHelper; protected final InternalCallContextFactory internalCallContextFactory; protected final Clock clock; protected final BlockingChecker checker; protected final EntitlementApi entitlementApi; protected final SubscriptionBaseInternalApi subscriptionInternalApi; protected final BlockingStateDao blockingStateDao; protected final NotificationQueueService notificationQueueService; protected final EntitlementUtils entitlementUtils; // Refresh-able protected EventsStream eventsStream; public DefaultEntitlement(final UUID entitlementId, final EventsStreamBuilder eventsStreamBuilder, final EntitlementApi entitlementApi, final BlockingStateDao blockingStateDao, final SubscriptionBaseInternalApi subscriptionInternalApi, final BlockingChecker checker, final NotificationQueueService notificationQueueService, final EntitlementUtils entitlementUtils, final EntitlementDateHelper dateHelper, final Clock clock, final InternalCallContextFactory internalCallContextFactory, final TenantContext tenantContext) throws EntitlementApiException { this(eventsStreamBuilder.buildForEntitlement(entitlementId, tenantContext), eventsStreamBuilder, entitlementApi, blockingStateDao, subscriptionInternalApi, checker, notificationQueueService, entitlementUtils, dateHelper, clock, internalCallContextFactory); } public DefaultEntitlement(final EventsStream eventsStream, final EventsStreamBuilder eventsStreamBuilder, final EntitlementApi entitlementApi, final BlockingStateDao blockingStateDao, final SubscriptionBaseInternalApi subscriptionInternalApi, final BlockingChecker checker, final NotificationQueueService notificationQueueService, final EntitlementUtils entitlementUtils, final EntitlementDateHelper dateHelper, final Clock clock, final InternalCallContextFactory internalCallContextFactory) { super(eventsStream.getEntitlementId(), eventsStream.getSubscriptionBase().getCreatedDate(), eventsStream.getSubscriptionBase().getUpdatedDate()); this.eventsStreamBuilder = eventsStreamBuilder; this.eventsStream = eventsStream; this.dateHelper = dateHelper; this.entitlementApi = entitlementApi; this.subscriptionInternalApi = subscriptionInternalApi; this.internalCallContextFactory = internalCallContextFactory; this.clock = clock; this.checker = checker; this.blockingStateDao = blockingStateDao; this.notificationQueueService = notificationQueueService; this.entitlementUtils = entitlementUtils; } public DefaultEntitlement(final DefaultEntitlement in) { this(in.getEventsStream(), in.getEventsStreamBuilder(), in.getEntitlementApi(), in.getBlockingStateDao(), in.getSubscriptionInternalApi(), in.getChecker(), in.getNotificationQueueService(), in.getEntitlementUtils(), in.getDateHelper(), in.getClock(), in.getInternalCallContextFactory()); } public EventsStream getEventsStream() { return eventsStream; } public DateTimeZone getAccountTimeZone() { return eventsStream.getAccountTimeZone(); } // Subscription associated with this entitlement (equals to baseSubscription for base subscriptions) public SubscriptionBase getSubscriptionBase() { return eventsStream.getSubscriptionBase(); } // Base subscription for the bundle if it exists, null otherwise public SubscriptionBase getBasePlanSubscriptionBase() { return eventsStream.getBasePlanSubscriptionBase(); } public EventsStreamBuilder getEventsStreamBuilder() { return eventsStreamBuilder; } public EntitlementDateHelper getDateHelper() { return dateHelper; } public InternalCallContextFactory getInternalCallContextFactory() { return internalCallContextFactory; } public EntitlementApi getEntitlementApi() { return entitlementApi; } public SubscriptionBaseInternalApi getSubscriptionInternalApi() { return subscriptionInternalApi; } public Clock getClock() { return clock; } public BlockingChecker getChecker() { return checker; } public BlockingStateDao getBlockingStateDao() { return blockingStateDao; } public NotificationQueueService getNotificationQueueService() { return notificationQueueService; } public EntitlementUtils getEntitlementUtils() { return entitlementUtils; } @Override public UUID getBaseEntitlementId() { return eventsStream.getEntitlementId(); } @Override public UUID getBundleId() { return eventsStream.getBundleId(); } @Override public UUID getAccountId() { return eventsStream.getAccountId(); } @Override public String getExternalKey() { return eventsStream.getBundleExternalKey(); } @Override public EntitlementState getState() { return eventsStream.getEntitlementState(); } @Override public EntitlementSourceType getSourceType() { return getSubscriptionBase().getSourceType(); } @Override public LocalDate getEffectiveStartDate() { return new LocalDate(getSubscriptionBase().getStartDate(), eventsStream.getAccountTimeZone()); } @Override public LocalDate getEffectiveEndDate() { return eventsStream.getEntitlementEffectiveEndDate(); } @Override public Product getLastActiveProduct() { return getSubscriptionBase().getLastActiveProduct(); } @Override public Plan getLastActivePlan() { return getSubscriptionBase().getLastActivePlan(); } @Override public PlanPhase getLastActivePhase() { return getSubscriptionBase().getLastActivePhase(); } @Override public PriceList getLastActivePriceList() { return getSubscriptionBase().getLastActivePriceList(); } @Override public ProductCategory getLastActiveProductCategory() { return getSubscriptionBase().getLastActiveCategory(); } @Override public Entitlement cancelEntitlementWithPolicy(final EntitlementActionPolicy entitlementPolicy, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk - required to have the latest CTD refresh(callContext); final LocalDate cancellationDate = getLocalDateFromEntitlementPolicy(entitlementPolicy); return cancelEntitlementWithDate(cancellationDate, false, callContext); } @Override public Entitlement cancelEntitlementWithDate(final LocalDate localCancelDate, final boolean overrideBillingEffectiveDate, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (eventsStream.isEntitlementCancelled()) { throw new EntitlementApiException(ErrorCode.SUB_CANCEL_BAD_STATE, getId(), EntitlementState.CANCELLED); } final InternalCallContext contextWithValidAccountRecordId = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); final DateTime effectiveCancelDate = dateHelper.fromLocalDateAndReferenceTime(localCancelDate, getSubscriptionBase().getStartDate(), contextWithValidAccountRecordId); try { if (overrideBillingEffectiveDate) { getSubscriptionBase().cancelWithDate(effectiveCancelDate, callContext); } else { getSubscriptionBase().cancel(callContext); } } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } final BlockingState newBlockingState = new DefaultBlockingState(getId(), BlockingStateType.SUBSCRIPTION, DefaultEntitlementApi.ENT_STATE_CANCELLED, EntitlementService.ENTITLEMENT_SERVICE_NAME, true, true, false, effectiveCancelDate); entitlementUtils.setBlockingStateAndPostBlockingTransitionEvent(newBlockingState, contextWithValidAccountRecordId); blockAddOnsIfRequired(effectiveCancelDate, callContext, contextWithValidAccountRecordId); return entitlementApi.getEntitlementForId(getId(), callContext); } @Override public Entitlement cancelEntitlementWithPolicyOverrideBillingPolicy(final EntitlementActionPolicy entitlementPolicy, final BillingActionPolicy billingPolicy, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk - required to have the latest CTD refresh(callContext); final LocalDate cancellationDate = getLocalDateFromEntitlementPolicy(entitlementPolicy); return cancelEntitlementWithDateOverrideBillingPolicy(cancellationDate, billingPolicy, callContext); } @Override public void uncancelEntitlement(final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (eventsStream.isSubscriptionCancelled()) { throw new EntitlementApiException(ErrorCode.SUB_CANCEL_BAD_STATE, getId(), EntitlementState.CANCELLED); } final InternalCallContext contextWithValidAccountRecordId = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); final Collection<BlockingState> pendingEntitlementCancellationEvents = eventsStream.getPendingEntitlementCancellationEvents(); if (eventsStream.isEntitlementCancelled()) { final BlockingState cancellationEvent = eventsStream.getEntitlementCancellationEvent(); blockingStateDao.unactiveBlockingState(cancellationEvent.getId(), contextWithValidAccountRecordId); } else if (pendingEntitlementCancellationEvents.size() > 0) { // Reactivate entitlements // See also https://github.com/killbill/killbill/issues/111 // // Today we only support cancellation at SUBSCRIPTION level (Not ACCOUNT or BUNDLE), so we should really have only // one future event in the list // for (final BlockingState futureCancellation : pendingEntitlementCancellationEvents) { blockingStateDao.unactiveBlockingState(futureCancellation.getId(), contextWithValidAccountRecordId); } } else { // Entitlement is NOT cancelled (or future cancelled), there is nothing to do throw new EntitlementApiException(ErrorCode.SUB_CANCEL_BAD_STATE, getId(), EntitlementState.CANCELLED); } // If billing was previously cancelled, reactivate if (getSubscriptionBase().getFutureEndDate() != null) { try { getSubscriptionBase().uncancel(callContext); } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } } } @Override public Entitlement cancelEntitlementWithDateOverrideBillingPolicy(final LocalDate localCancelDate, final BillingActionPolicy billingPolicy, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (eventsStream.isEntitlementCancelled()) { throw new EntitlementApiException(ErrorCode.SUB_CANCEL_BAD_STATE, getId(), EntitlementState.CANCELLED); } // Make sure to compute the entitlement effective date first to avoid timing issues for IMM cancellations // (we don't want an entitlement cancel date one second or so after the subscription cancel date or add-ons cancellations // computations won't work). final InternalCallContext contextWithValidAccountRecordId = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); final LocalDate effectiveLocalDate = new LocalDate(localCancelDate, eventsStream.getAccountTimeZone()); final DateTime effectiveDate = dateHelper.fromLocalDateAndReferenceTime(effectiveLocalDate, getSubscriptionBase().getStartDate(), contextWithValidAccountRecordId); try { // Cancel subscription base first, to correctly compute the add-ons entitlements we need to cancel (see below) getSubscriptionBase().cancelWithPolicy(billingPolicy, callContext); } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } final BlockingState newBlockingState = new DefaultBlockingState(getId(), BlockingStateType.SUBSCRIPTION, DefaultEntitlementApi.ENT_STATE_CANCELLED, EntitlementService.ENTITLEMENT_SERVICE_NAME, true, true, false, effectiveDate); entitlementUtils.setBlockingStateAndPostBlockingTransitionEvent(newBlockingState, contextWithValidAccountRecordId); blockAddOnsIfRequired(effectiveDate, callContext, contextWithValidAccountRecordId); return entitlementApi.getEntitlementForId(getId(), callContext); } private LocalDate getLocalDateFromEntitlementPolicy(final EntitlementActionPolicy entitlementPolicy) { final LocalDate cancellationDate; switch (entitlementPolicy) { case IMMEDIATE: cancellationDate = new LocalDate(clock.getUTCNow(), eventsStream.getAccountTimeZone()); break; case END_OF_TERM: cancellationDate = getSubscriptionBase().getChargedThroughDate() != null ? new LocalDate(getSubscriptionBase().getChargedThroughDate(), eventsStream.getAccountTimeZone()) : new LocalDate(clock.getUTCNow(), eventsStream.getAccountTimeZone()); break; default: throw new RuntimeException("Unsupported policy " + entitlementPolicy); } return cancellationDate; } @Override public Entitlement changePlan(final String productName, final BillingPeriod billingPeriod, final String priceList, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (!eventsStream.isEntitlementActive()) { throw new EntitlementApiException(ErrorCode.SUB_CHANGE_NON_ACTIVE, getId(), getState()); } final InternalCallContext context = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); try { checker.checkBlockedChange(getSubscriptionBase(), context); } catch (BlockingApiException e) { throw new EntitlementApiException(e, e.getCode(), e.getMessage()); } final DateTime effectiveChangeDate; try { effectiveChangeDate = getSubscriptionBase().changePlan(productName, billingPeriod, priceList, callContext); } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } blockAddOnsIfRequired(effectiveChangeDate, callContext, context); return entitlementApi.getEntitlementForId(getId(), callContext); } @Override public Entitlement changePlanWithDate(final String productName, final BillingPeriod billingPeriod, final String priceList, final LocalDate localDate, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (!eventsStream.isEntitlementActive()) { throw new EntitlementApiException(ErrorCode.SUB_CHANGE_NON_ACTIVE, getId(), getState()); } final InternalCallContext context = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); try { checker.checkBlockedChange(getSubscriptionBase(), context); } catch (BlockingApiException e) { throw new EntitlementApiException(e, e.getCode(), e.getMessage()); } final DateTime effectiveChangeDate = dateHelper.fromLocalDateAndReferenceTime(localDate, getSubscriptionBase().getStartDate(), context); try { getSubscriptionBase().changePlanWithDate(productName, billingPeriod, priceList, effectiveChangeDate, callContext); } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } blockAddOnsIfRequired(effectiveChangeDate, callContext, context); return entitlementApi.getEntitlementForId(getId(), callContext); } @Override public Entitlement changePlanOverrideBillingPolicy(final String productName, final BillingPeriod billingPeriod, final String priceList, final LocalDate localDateX, final BillingActionPolicy actionPolicy, final CallContext callContext) throws EntitlementApiException { // Get the latest state from disk refresh(callContext); if (!eventsStream.isEntitlementActive()) { throw new EntitlementApiException(ErrorCode.SUB_CHANGE_NON_ACTIVE, getId(), getState()); } final InternalCallContext context = internalCallContextFactory.createInternalCallContext(getAccountId(), callContext); try { checker.checkBlockedChange(getSubscriptionBase(), context); } catch (BlockingApiException e) { throw new EntitlementApiException(e, e.getCode(), e.getMessage()); } final DateTime effectiveChangeDate; try { effectiveChangeDate = getSubscriptionBase().changePlanWithPolicy(productName, billingPeriod, priceList, actionPolicy, callContext); } catch (SubscriptionBaseApiException e) { throw new EntitlementApiException(e); } blockAddOnsIfRequired(effectiveChangeDate, callContext, context); return entitlementApi.getEntitlementForId(getId(), callContext); } private void refresh(final TenantContext context) throws EntitlementApiException { eventsStream = eventsStreamBuilder.refresh(eventsStream, context); } public void blockAddOnsIfRequired(final DateTime effectiveDate, final TenantContext context, final InternalCallContext internalCallContext) throws EntitlementApiException { // Optimization - bail early if (!ProductCategory.BASE.equals(getSubscriptionBase().getCategory())) { // Only base subscriptions have add-ons return; } // Get the latest state from disk (we just got cancelled or changed plan) refresh(context); // If cancellation/change occurs in the future, do nothing for now but add a notification entry. // This is to distinguish whether a future cancellation was requested by the user, or was a side effect // (e.g. base plan cancellation): future entitlement cancellations for add-ons on disk always reflect // an explicit cancellation. This trick lets us determine what to do when un-cancelling. // This mirror the behavior in subscription base (see DefaultSubscriptionBaseApiService). final DateTime now = clock.getUTCNow(); if (effectiveDate.compareTo(now) > 0) { // Note that usually we record the notification from the DAO. We cannot do it here because not all calls // go through the DAO (e.g. change) final boolean isBaseEntitlementCancelled = eventsStream.isEntitlementCancelled(); final NotificationEvent notificationEvent = new EntitlementNotificationKey(getId(), getBundleId(), isBaseEntitlementCancelled ? EntitlementNotificationKeyAction.CANCEL : EntitlementNotificationKeyAction.CHANGE, effectiveDate); recordFutureNotification(effectiveDate, notificationEvent, internalCallContext); return; } final Collection<BlockingState> addOnsBlockingStates = eventsStream.computeAddonsBlockingStatesForNextSubscriptionBaseEvent(effectiveDate); for (final BlockingState addOnBlockingState : addOnsBlockingStates) { entitlementUtils.setBlockingStateAndPostBlockingTransitionEvent(addOnBlockingState, internalCallContext); } } private void recordFutureNotification(final DateTime effectiveDate, final NotificationEvent notificationEvent, final InternalCallContext context) { try { final NotificationQueue subscriptionEventQueue = notificationQueueService.getNotificationQueue(DefaultEntitlementService.ENTITLEMENT_SERVICE_NAME, DefaultEntitlementService.NOTIFICATION_QUEUE_NAME); subscriptionEventQueue.recordFutureNotification(effectiveDate, notificationEvent, context.getUserToken(), context.getAccountRecordId(), context.getTenantRecordId()); } catch (NoSuchNotificationQueue e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }
apache-2.0
henryyan/snakeyaml
src/test/java/org/pyyaml/CanonicalLoader.java
2743
/** * Copyright (c) 2008-2013, http://www.snakeyaml.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pyyaml; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.error.YAMLException; public class CanonicalLoader extends Yaml { @Override public Object load(Reader yaml) { try { int ch = yaml.read(); StringBuilder buffer = new StringBuilder(); while (ch != -1) { buffer.append((char) ch); ch = yaml.read(); } Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); constructor.setComposer(composer); return constructor.getSingleData(Object.class); } catch (IOException e) { throw new YAMLException(e); } } public Iterable<Object> loadAll(Reader yaml) { try { int ch = yaml.read(); StringBuilder buffer = new StringBuilder(); while (ch != -1) { buffer.append((char) ch); ch = yaml.read(); } Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); this.constructor.setComposer(composer); Iterator<Object> result = new Iterator<Object>() { public boolean hasNext() { return constructor.checkData(); } public Object next() { return constructor.getData(); } public void remove() { throw new UnsupportedOperationException(); } }; return new YamlIterable(result); } catch (IOException e) { throw new YAMLException(e); } } private class YamlIterable implements Iterable<Object> { private Iterator<Object> iterator; public YamlIterable(Iterator<Object> iterator) { this.iterator = iterator; } public Iterator<Object> iterator() { return iterator; } } }
apache-2.0
aol/cyclops-react
cyclops/src/main/java/cyclops/function/Ordering.java
1650
package cyclops.function; import java.util.Comparator; public interface Ordering<T> extends Comparator<T> { default Ord.Ordering compareOrder(T left, T right){ return Ord.Ordering.values()[Math.max(-1,Math.min(1,compare(left,right)))+1]; } default boolean isLessThan(T left, T right){ return compare(left,right)<0; } default boolean isLessThanOrEqual(T left, T right){ return compare(left,right)<=0; } default boolean isGreaterThan(T left, T right){ return compare(left,right)>0; } default boolean isGreaterThanOrEqual(T left, T right){ return compare(left,right)>=0; } default T max(T left, T right){ if(isGreaterThanOrEqual(left,right)) return left; return right; } default T min(T left, T right){ if(isLessThanOrEqual(left,right)) return left; return right; } static boolean isEqual(int compareResult){ return compareResult == 0; } static boolean isFirstParameterLessThan(int compareResult){ return compareResult < 0; } static boolean isFirstParameterGreaterThan(int compareResult){ return compareResult > 0; } static boolean isFirstParameterLessThanOrEqual(int compareResult){ return compareResult <= 0; } static boolean isFirstParameterGreaterThanOrEqual(int compareResult){ return compareResult >= 0; } public static <T> Ordering<T> of(Comparator<? super T> comp){ if(comp instanceof Ordering) return (Ordering)comp; return (left,right)->comp.compare(left,right); } }
apache-2.0
okrische/RoaringBitmap
jmh/src/main/java/org/roaringbitmap/realdata/RealDataBenchmarkReverseIterate.java
908
package org.roaringbitmap.realdata; 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.roaringbitmap.realdata.state.RealDataBenchmarkState; import org.roaringbitmap.realdata.wrapper.Bitmap; import org.roaringbitmap.realdata.wrapper.BitmapIterator; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class RealDataBenchmarkReverseIterate { @Benchmark public int reverseIterate(RealDataBenchmarkState bs) { int total = 0; for (int k = 0; k < bs.bitmaps.size(); ++k) { Bitmap bitmap = bs.bitmaps.get(k); BitmapIterator i = bitmap.reverseIterator(); while(i.hasNext()) { total += i.next(); } } return total; } }
apache-2.0
janstey/fuse
fabric/fabric-core/src/main/java/org/fusesource/fabric/internal/Objects.java
2844
/* * Copyright (C) FuseSource, Inc. * http://fusesource.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 org.fusesource.fabric.internal; import java.util.List; /** * Some helper classes for objects comparing and equality */ public final class Objects { private Objects() { //Utility Class } private static final int SEED = 23; private static final int ODD_PRIME_NUMBER = 37; /** * A helper class to create nice hash codes using a similar algorithm to Josh Bloch's * Effective Java book */ public static int hashCode(Object... objects) { int answer = SEED; for (Object object : objects) { answer *= ODD_PRIME_NUMBER; int objectHash = (object != null) ? object.hashCode() : 0; answer += objectHash; } return answer; } public static boolean equal(Object a, Object b) { if (a == b) { return true; } else { return a != null && b != null && a.equals(b); } } public static int compare(Comparable a, Comparable b) { if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } return a.compareTo(b); } public static <T extends Comparable<T>> int compare(List<T> a, List<T> b) { if (a == b) { return 0; } else if (a == null) { return -1; } else if (b == null) { return 1; } int size = a.size(); int answer = size - b.size(); if (answer == 0) { for (int i = 0; i < size; i++) { answer = compare(a.get(i), b.get(i)); if (answer != 0) { break; } } } return answer; } /** * Asserts whether the value is <b>not</b> <tt>null</tt> * * @param value the value to test * @param name the key that resolved the value * @throws IllegalArgumentException is thrown if assertion fails */ public static void notNull(Object value, String name) { if (value == null) { throw new IllegalArgumentException(name + " must be specified"); } } }
apache-2.0
abhishek-ch/incubator-ignite
examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java
15750
/* * 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.ignite.examples.datagrid; import org.apache.ignite.*; import org.apache.ignite.cache.*; import org.apache.ignite.cache.affinity.*; import org.apache.ignite.cache.query.*; import org.apache.ignite.cache.query.annotations.*; import org.apache.ignite.configuration.*; import org.apache.ignite.examples.*; import org.apache.ignite.lang.*; import javax.cache.*; import java.io.*; import java.util.*; /** * Cache queries example. This example demonstrates SQL, TEXT, and FULL SCAN * queries over cache. * <p> * Example also demonstrates usage of fields queries that return only required * fields instead of whole key-value pairs. When fields queries are distributed * across several nodes, they may not work as expected. Keep in mind following * limitations (not applied if data is queried from one node only): * <ul> * <li> * Joins will work correctly only if joined objects are stored in * collocated mode. Refer to {@link AffinityKey} javadoc for more details. * </li> * <li> * Note that if you created query on to replicated cache, all data will * be queried only on one node, not depending on what caches participate in * the query (some data from partitioned cache can be lost). And visa versa, * if you created it on partitioned cache, data from replicated caches * will be duplicated. * </li> * </ul> * <p> * Remote nodes should be started using {@link ExampleNodeStartup} which will * start node with {@code examples/config/example-ignite.xml} configuration. */ public class CacheQueryExample { /** Organizations cache name. */ private static final String ORG_CACHE = CacheQueryExample.class.getSimpleName() + "Organizations"; /** Persons cache name. */ private static final String PERSON_CACHE = CacheQueryExample.class.getSimpleName() + "Persons"; /** * Executes example. * * @param args Command line arguments, none required. * @throws Exception If example execution failed. */ public static void main(String[] args) throws Exception { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println(">>> Cache query example started."); CacheConfiguration<UUID, Organization> orgCacheCfg = new CacheConfiguration<>(ORG_CACHE); orgCacheCfg.setCacheMode(CacheMode.PARTITIONED); // Default. orgCacheCfg.setIndexedTypes(UUID.class, Organization.class); CacheConfiguration<AffinityKey<UUID>, Person> personCacheCfg = new CacheConfiguration<>(PERSON_CACHE); personCacheCfg.setCacheMode(CacheMode.PARTITIONED); // Default. personCacheCfg.setIndexedTypes(AffinityKey.class, Person.class); try ( IgniteCache<UUID, Organization> orgCache = ignite.createCache(orgCacheCfg); IgniteCache<AffinityKey<UUID>, Person> personCache = ignite.createCache(personCacheCfg) ) { // Populate cache. initialize(); // Example for SCAN-based query based on a predicate. scanQuery(); // Example for SQL-based querying employees based on salary ranges. sqlQuery(); // Example for SQL-based querying employees for a given organization (includes SQL join). sqlQueryWithJoin(); // Example for TEXT-based querying for a given string in peoples resumes. textQuery(); // Example for SQL-based querying to calculate average salary among all employees within a company. sqlQueryWithAggregation(); // Example for SQL-based fields queries that return only required // fields instead of whole key-value pairs. sqlFieldsQuery(); // Example for SQL-based fields queries that uses joins. sqlFieldsQueryWithJoin(); } print("Cache query example finished."); } } /** * Example for scan query based on a predicate. */ private static void scanQuery() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); ScanQuery<AffinityKey<UUID>, Person> scan = new ScanQuery<>( new IgniteBiPredicate<AffinityKey<UUID>, Person>() { @Override public boolean apply(AffinityKey<UUID> key, Person person) { return person.salary <= 1000; } } ); // Execute queries for salary ranges. print("People with salaries between 0 and 1000 (queried with SCAN query): ", cache.query(scan).getAll()); } /** * Example for SQL queries based on salary ranges. */ private static void sqlQuery() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // SQL clause which selects salaries based on range. String sql = "salary > ? and salary <= ?"; // Execute queries for salary ranges. print("People with salaries between 0 and 1000 (queried with SQL query): ", cache.query(new SqlQuery<AffinityKey<UUID>, Person>(Person.class, sql). setArgs(0, 1000)).getAll()); print("People with salaries between 1000 and 2000 (queried with SQL query): ", cache.query(new SqlQuery<AffinityKey<UUID>, Person>(Person.class, sql). setArgs(1000, 2000)).getAll()); } /** * Example for SQL queries based on all employees working for a specific organization. */ private static void sqlQueryWithJoin() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // SQL clause query which joins on 2 types to select people for a specific organization. String joinSql = "from Person, \"" + ORG_CACHE + "\".Organization as org " + "where Person.orgId = org.id " + "and lower(org.name) = lower(?)"; // Execute queries for find employees for different organizations. print("Following people are 'GridGain' employees: ", cache.query(new SqlQuery<AffinityKey<UUID>, Person>(Person.class, joinSql). setArgs("GridGain")).getAll()); print("Following people are 'Other' employees: ", cache.query(new SqlQuery<AffinityKey<UUID>, Person>(Person.class, joinSql). setArgs("Other")).getAll()); } /** * Example for TEXT queries using LUCENE-based indexing of people's resumes. */ private static void textQuery() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // Query for all people with "Master Degree" in their resumes. QueryCursor<Cache.Entry<AffinityKey<UUID>, Person>> masters = cache.query(new TextQuery<AffinityKey<UUID>, Person>(Person.class, "Master")); // Query for all people with "Bachelor Degree" in their resumes. QueryCursor<Cache.Entry<AffinityKey<UUID>, Person>> bachelors = cache.query(new TextQuery<AffinityKey<UUID>, Person>(Person.class, "Bachelor")); print("Following people have 'Master Degree' in their resumes: ", masters.getAll()); print("Following people have 'Bachelor Degree' in their resumes: ", bachelors.getAll()); } /** * Example for SQL queries to calculate average salary for a specific organization. */ private static void sqlQueryWithAggregation() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // Calculate average of salary of all persons in GridGain. // Note that we also join on Organization cache as well. String sql = "select avg(salary) " + "from Person, \"" + ORG_CACHE + "\".Organization as org " + "where Person.orgId = org.id " + "and lower(org.name) = lower(?)"; QueryCursor<List<?>> cursor = cache.query(new SqlFieldsQuery(sql).setArgs("GridGain")); // Calculate average salary for a specific organization. print("Average salary for 'GridGain' employees: ", cursor.getAll()); } /** * Example for SQL-based fields queries that return only required * fields instead of whole key-value pairs. */ private static void sqlFieldsQuery() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // Execute query to get names of all employees. QueryCursor<List<?>> cursor = cache.query(new SqlFieldsQuery( "select concat(firstName, ' ', lastName) from Person")); // In this particular case each row will have one element with full name of an employees. List<List<?>> res = cursor.getAll(); // Print names. print("Names of all employees:", res); } /** * Example for SQL-based fields queries that return only required * fields instead of whole key-value pairs. */ private static void sqlFieldsQueryWithJoin() { IgniteCache<AffinityKey<UUID>, Person> cache = Ignition.ignite().cache(PERSON_CACHE); // Execute query to get names of all employees. String sql = "select concat(firstName, ' ', lastName), org.name " + "from Person, \"" + ORG_CACHE + "\".Organization as org " + "where Person.orgId = org.id"; QueryCursor<List<?>> cursor = cache.query(new SqlFieldsQuery(sql)); // In this particular case each row will have one element with full name of an employees. List<List<?>> res = cursor.getAll(); // Print persons' names and organizations' names. print("Names of all employees and organizations they belong to:", res); } /** * Populate cache with test data. */ private static void initialize() { IgniteCache<UUID, Organization> orgCache = Ignition.ignite().cache(ORG_CACHE); // Organizations. Organization org1 = new Organization("GridGain"); Organization org2 = new Organization("Other"); orgCache.put(org1.id, org1); orgCache.put(org2.id, org2); IgniteCache<AffinityKey<UUID>, Person> personCache = Ignition.ignite().cache(PERSON_CACHE); // People. Person p1 = new Person(org1, "John", "Doe", 2000, "John Doe has Master Degree."); Person p2 = new Person(org1, "Jane", "Doe", 1000, "Jane Doe has Bachelor Degree."); Person p3 = new Person(org2, "John", "Smith", 1000, "John Smith has Bachelor Degree."); Person p4 = new Person(org2, "Jane", "Smith", 2000, "Jane Smith has Master Degree."); // Note that in this example we use custom affinity key for Person objects // to ensure that all persons are collocated with their organizations. personCache.put(p1.key(), p1); personCache.put(p2.key(), p2); personCache.put(p3.key(), p3); personCache.put(p4.key(), p4); } /** * Prints message and query results. * * @param msg Message to print before all objects are printed. * @param col Query results. */ private static void print(String msg, Iterable<?> col) { print(msg); print(col); } /** * Prints message. * * @param msg Message to print before all objects are printed. */ private static void print(String msg) { System.out.println(); System.out.println(">>> " + msg); } /** * Prints query results. * * @param col Query results. */ private static void print(Iterable<?> col) { for (Object next : col) System.out.println(">>> " + next); } /** * Person class. */ private static class Person implements Serializable { /** Person ID (indexed). */ @QuerySqlField(index = true) private UUID id; /** Organization ID (indexed). */ @QuerySqlField(index = true) private UUID orgId; /** First name (not-indexed). */ @QuerySqlField private String firstName; /** Last name (not indexed). */ @QuerySqlField private String lastName; /** Resume text (create LUCENE-based TEXT index for this field). */ @QueryTextField private String resume; /** Salary (indexed). */ @QuerySqlField(index = true) private double salary; /** Custom cache key to guarantee that person is always collocated with its organization. */ private transient AffinityKey<UUID> key; /** * Constructs person record. * * @param org Organization. * @param firstName First name. * @param lastName Last name. * @param salary Salary. * @param resume Resume text. */ Person(Organization org, String firstName, String lastName, double salary, String resume) { // Generate unique ID for this person. id = UUID.randomUUID(); orgId = org.id; this.firstName = firstName; this.lastName = lastName; this.resume = resume; this.salary = salary; } /** * Gets cache affinity key. Since in some examples person needs to be collocated with organization, we create * custom affinity key to guarantee this collocation. * * @return Custom affinity key to guarantee that person is always collocated with organization. */ public AffinityKey<UUID> key() { if (key == null) key = new AffinityKey<>(id, orgId); return key; } /** {@inheritDoc} */ @Override public String toString() { return "Person [firstName=" + firstName + ", lastName=" + lastName + ", id=" + id + ", orgId=" + orgId + ", resume=" + resume + ", salary=" + salary + ']'; } } /** * Organization class. */ private static class Organization implements Serializable { /** Organization ID (indexed). */ @QuerySqlField(index = true) private UUID id; /** Organization name (indexed). */ @QuerySqlField(index = true) private String name; /** * Create organization. * * @param name Organization name. */ Organization(String name) { id = UUID.randomUUID(); this.name = name; } /** {@inheritDoc} */ @Override public String toString() { return "Organization [id=" + id + ", name=" + name + ']'; } } }
apache-2.0
tlandn/shindig-1.1-BETA5-incubating-source
java/gadgets/src/main/java/org/apache/shindig/gadgets/DefaultGadgetSpecFactory.java
3392
/* * 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.shindig.gadgets; import org.apache.shindig.common.cache.Cache; import org.apache.shindig.common.cache.CacheProvider; import org.apache.shindig.common.uri.Uri; import org.apache.shindig.common.xml.XmlException; import org.apache.shindig.common.xml.XmlUtil; import org.apache.shindig.gadgets.http.RequestPipeline; import org.apache.shindig.gadgets.spec.GadgetSpec; import org.apache.shindig.gadgets.spec.SpecParserException; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.w3c.dom.Element; import java.util.concurrent.ExecutorService; /** * Default implementation of a gadget spec factory. */ @Singleton public class DefaultGadgetSpecFactory extends AbstractSpecFactory<GadgetSpec> implements GadgetSpecFactory { public static final String CACHE_NAME = "gadgetSpecs"; static final String RAW_GADGETSPEC_XML_PARAM_NAME = "rawxml"; static final Uri RAW_GADGET_URI = Uri.parse("http://localhost/raw.xml"); @Inject public DefaultGadgetSpecFactory(ExecutorService executor, RequestPipeline pipeline, CacheProvider cacheProvider, @Named("shindig.cache.xml.refreshInterval") long refresh) { super(GadgetSpec.class, executor, pipeline, makeCache(cacheProvider), refresh); } private static Cache<Uri, Object> makeCache(CacheProvider cacheProvider) { return cacheProvider.createCache(CACHE_NAME); } public GadgetSpec getGadgetSpec(GadgetContext context) throws GadgetException { String rawxml = context.getParameter(RAW_GADGETSPEC_XML_PARAM_NAME); if (rawxml != null) { // Set URI to a fixed, safe value (localhost), preventing a gadget rendered // via raw XML (eg. via POST) to be rendered on a locked domain of any other // gadget whose spec is hosted non-locally. try { return new GadgetSpec(RAW_GADGET_URI, XmlUtil.parse(rawxml), rawxml); } catch (XmlException e) { throw new SpecParserException(e); } } Uri gadgetUri = context.getUrl(); Query query = new Query() .setSpecUri(gadgetUri) .setContainer(context.getContainer()) .setGadgetUri(gadgetUri) .setIgnoreCache(context.getIgnoreCache()); return super.getSpec(query); } @Override protected GadgetSpec parse(String content, Query query) throws XmlException, GadgetException { Element element = XmlUtil.parse(content); return new GadgetSpec(query.getSpecUri(), element, content); } }
apache-2.0
punkhorn/camel-upstream
core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleParserPredicateTest.java
10680
/** * 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.language.simple; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.camel.ExchangeTestSupport; import org.apache.camel.Predicate; import org.apache.camel.impl.JndiRegistry; import org.junit.Test; /** * */ public class SimpleParserPredicateTest extends ExchangeTestSupport { @Test public void testSimpleBooleanValue() throws Exception { exchange.getIn().setBody("foo"); SimplePredicateParser parser = new SimplePredicateParser("true", true, null); Predicate pre = parser.parsePredicate(); assertTrue(pre.matches(exchange)); parser = new SimplePredicateParser("false", true, null); pre = parser.parsePredicate(); assertFalse(pre.matches(exchange)); } @Test public void testSimpleEq() throws Exception { exchange.getIn().setBody("foo"); SimplePredicateParser parser = new SimplePredicateParser("${body} == 'foo'", true, null); Predicate pre = parser.parsePredicate(); assertTrue(pre.matches(exchange)); } @Test public void testSimpleEqNumeric() throws Exception { exchange.getIn().setBody(123); SimplePredicateParser parser = new SimplePredicateParser("${body} == 123", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleEqFunctionFunction() throws Exception { exchange.getIn().setBody(122); exchange.getIn().setHeader("val", 122); SimplePredicateParser parser = new SimplePredicateParser("${body} == ${header.val}", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleEqFunctionNumeric() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body} == 122", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleGtFunctionNumeric() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body} > 120", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleUnaryInc() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body}++ == 123", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleUnaryDec() throws Exception { exchange.getIn().setBody(122); SimplePredicateParser parser = new SimplePredicateParser("${body}-- == 121", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleEqFunctionBoolean() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == true", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleEqFunctionBooleanSpaces() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == true", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleLogicalAnd() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); exchange.getIn().setHeader("foo", 123); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == true && ${header.foo} == 123", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleLogicalOr() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); exchange.getIn().setHeader("foo", 123); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == false || ${header.foo} == 123", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleLogicalAndAnd() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("high", true); exchange.getIn().setHeader("foo", 123); exchange.getIn().setHeader("bar", "beer"); SimplePredicateParser parser = new SimplePredicateParser("${header.high} == true && ${header.foo} == 123 && ${header.bar} == 'beer'", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleManyAndLogical() throws Exception { exchange.getIn().setBody("Hello"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { exchange.getIn().setHeader("foo" + i, i); sb.append("${header.foo").append(i).append("} == ").append(i); if (i < 9) { sb.append(" && "); } } SimplePredicateParser parser = new SimplePredicateParser(sb.toString(), true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleManyOrLogical() throws Exception { exchange.getIn().setBody("Hello"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.append("${header.foo").append(i).append("} == ").append(i); if (i < 9) { sb.append(" || "); } } sb.append(" || ${body} == 'Hello'"); SimplePredicateParser parser = new SimplePredicateParser(sb.toString(), true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleExpressionPredicate() throws Exception { exchange.getIn().setBody("Hello"); exchange.getIn().setHeader("number", "1234"); SimplePredicateParser parser = new SimplePredicateParser("${in.header.number} regex '\\d{4}'", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); } @Test public void testSimpleMap() throws Exception { Map<String, String> map = new HashMap<>(); map.put("foo", "123"); map.put("foo bar", "456"); exchange.getIn().setBody(map); SimplePredicateParser parser = new SimplePredicateParser("${body[foo]} == 123", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); parser = new SimplePredicateParser("${body['foo bar']} == 456", true, null); pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); // the predicate has whitespace in the function parser = new SimplePredicateParser("${body[foo bar]} == 456", true, null); pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); // no header with that name parser = new SimplePredicateParser("${body[unknown]} == 456", true, null); pre = parser.parsePredicate(); assertFalse("Should not match", pre.matches(exchange)); } protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); List<String> list = new ArrayList<>(); list.add("foo"); list.add("bar"); jndi.bind("myList", list); return jndi; } @Test public void testSimpleIn() throws Exception { Map<String, String> map = new HashMap<>(); map.put("key", "foo"); map.put("key2", "bar"); map.put("key3", "none"); exchange.getIn().setBody(map); SimplePredicateParser parser = new SimplePredicateParser("${body[key]} in ${ref:myList}", true, null); Predicate pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); parser = new SimplePredicateParser("${body[key2]} in ${ref:myList}", true, null); pre = parser.parsePredicate(); assertTrue("Should match", pre.matches(exchange)); parser = new SimplePredicateParser("${body[key3]} in ${ref:myList}", true, null); pre = parser.parsePredicate(); assertFalse("Should not match", pre.matches(exchange)); } @Test public void testSimpleInEmpty() throws Exception { SimplePredicateParser parser = new SimplePredicateParser("${body} in ',,gold,silver'", true, null); Predicate pre = parser.parsePredicate(); exchange.getIn().setBody("gold"); assertTrue("Should match gold", pre.matches(exchange)); exchange.getIn().setBody("silver"); assertTrue("Should match silver", pre.matches(exchange)); exchange.getIn().setBody(""); assertTrue("Should match empty", pre.matches(exchange)); exchange.getIn().setBody("bronze"); assertFalse("Should not match bronze", pre.matches(exchange)); } }
apache-2.0
creamer/cas
support/cas-server-support-oauth/src/test/java/org/apereo/cas/support/oauth/web/CasOAuth20TestAuthenticationEventExecutionPlanConfiguration.java
1313
package org.apereo.cas.support.oauth.web; import org.apereo.cas.authentication.AuthenticationEventExecutionPlan; import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler; import org.apereo.cas.authentication.principal.PrincipalResolver; import org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; /** * This is {@link CasOAuth20TestAuthenticationEventExecutionPlanConfiguration}. * * @author Misagh Moayyed * @since 5.1.0 */ @Configuration("casOAuth20TestAuthenticationEventExecutionPlanConfiguration") public class CasOAuth20TestAuthenticationEventExecutionPlanConfiguration implements AuthenticationEventExecutionPlanConfigurer { @Autowired @Qualifier("personDirectoryPrincipalResolver") private PrincipalResolver personDirectoryPrincipalResolver; @Override public void configureAuthenticationExecutionPlan(final AuthenticationEventExecutionPlan plan) { plan.registerAuthenticationHandlerWithPrincipalResolver(new SimpleTestUsernamePasswordAuthenticationHandler(), personDirectoryPrincipalResolver); } }
apache-2.0
apache/jackrabbit-oak
oak-search-elastic/src/main/java/org/apache/jackrabbit/oak/plugins/index/elastic/ElasticIndexNode.java
2436
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.index.elastic; import org.apache.jackrabbit.oak.plugins.index.search.IndexNode; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateUtils; import org.jetbrains.annotations.NotNull; public class ElasticIndexNode implements IndexNode { private final ElasticConnection elasticConnection; private final ElasticIndexDefinition indexDefinition; private final ElasticIndexStatistics indexStatistics; public ElasticIndexNode(@NotNull NodeState root, @NotNull String indexPath, @NotNull ElasticConnection elasticConnection) { final NodeState indexNS = NodeStateUtils.getNode(root, indexPath); this.elasticConnection = elasticConnection; this.indexDefinition = new ElasticIndexDefinition(root, indexNS, indexPath, elasticConnection.getIndexPrefix()); this.indexStatistics = new ElasticIndexStatistics(elasticConnection, indexDefinition); } @Override public void release() { // do nothing } @Override public ElasticIndexDefinition getDefinition() { return indexDefinition; } public ElasticConnection getConnection() { return elasticConnection; } @Override public int getIndexNodeId() { // TODO: does it matter that we simply return 0 as there's no observation based _refresh_ going on here // and we always defer to ES to its own thing return 0; } @Override public @NotNull ElasticIndexStatistics getIndexStatistics() { return indexStatistics; } }
apache-2.0