repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
MSOE-Supermileage/datacollector | java_old/edu/msoe/smv/raspi/LoggingServer.java | 1458 | package edu.msoe.smv.raspi;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by matt on 4/4/15.
*/
public class LoggingServer implements Runnable {
private static volatile LoggingServer instance;
private final List<DataNode> nodeList;
private boolean runServer;
private DataLogger dataLogger;
private LoggingServer(List<DataNode> list) {
this.nodeList = list;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd_HH.mm.ss");
this.dataLogger = new DataLogger(new File("/home/pi/daq_" + simpleDateFormat.format(new Date()) + ".log"));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Encountered an exception when creating the data logger.");
System.out.println("Data will NOT be logged to a file.");
this.dataLogger = null;
}
}
public static LoggingServer getInstance(List<DataNode> nodeList) {
if (instance == null) {
synchronized (LoggingServer.class) {
if (instance == null) {
instance = new LoggingServer(nodeList);
}
}
}
return instance;
}
public void enableServer(boolean enable) {
this.runServer = enable;
}
@Override
public void run() {
while (runServer) {
if (nodeList.size() > 0) {
DataNode dn;
synchronized (nodeList) {
dn = nodeList.remove(0);
}
if (dataLogger != null) {
dataLogger.log(dn);
}
}
}
}
}
| epl-1.0 |
diverse-project/tools | commons-eclipse/fr.inria.diverse.commons.eclipse.pde/src/fr/inria/diverse/commons/eclipse/pde/wizards/pages/pde/ui/templates/ComboChoiceOption.java | 3726 | /*******************************************************************************
* Copyright (c) 2006, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Les Jones <lesojones@gmail.com> - bug 208534
*******************************************************************************/
package fr.inria.diverse.commons.eclipse.pde.wizards.pages.pde.ui.templates;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.*;
/**
* Implementation of the AbstractTemplateOption that allows users to choose a value from
* the fixed set of options using a combo box.
*
* @since 3.2
*/
public class ComboChoiceOption extends AbstractChoiceOption {
private Combo fCombo;
private Label fLabel;
/**
* Constructor for ComboChoiceOption.
*
* @param section
* the parent section.
* @param name
* the unique name
* @param label
* the presentable label
* @param choices
* the list of choices from which the value can be chosen. Each
* array entry should be an array of size 2, where position 0
* will be interpeted as the choice unique name, and position 1
* as the choice presentable label.
*/
public ComboChoiceOption(BaseOptionTemplateSection section, String name, String label, String[][] choices) {
super(section, name, label, choices);
}
public void createControl(Composite parent, int span) {
fLabel = createLabel(parent, 1);
fLabel.setEnabled(isEnabled());
fill(fLabel, 1);
fCombo = new Combo(parent, SWT.READ_ONLY);
fill(fCombo, 1);
for (int i = 0; i < fChoices.length; i++) {
String[] choice = fChoices[i];
fCombo.add(choice[1], i);
fCombo.setEnabled(isEnabled());
}
fCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (isBlocked())
return;
if (fCombo.getSelectionIndex() != -1) {
String[] choice = fChoices[fCombo.getSelectionIndex()];
// Since this is being fired by the combo, suppress updates
// back to the control
setValue(choice[0], false);
getSection().validateOptions(ComboChoiceOption.this);
}
}
});
if (getChoice() != null)
selectChoice(getChoice());
}
protected void setOptionValue(Object value) {
if (fCombo != null && value != null) {
selectChoice(value.toString());
}
}
protected void setOptionEnabled(boolean enabled) {
if (fLabel != null) {
fLabel.setEnabled(enabled);
fCombo.setEnabled(enabled);
}
}
protected void selectOptionChoice(String choice) {
// choice is the value not the description
int index = getIndexOfChoice(choice);
if (index == -1) {
// Set to the first item
// Using set Value to keep everything consistent
fCombo.select(0);
setValue(fChoices[0][0], false);
} else {
fCombo.select(index);
}
}
/**
* Get the index (in the collection) of the choice
*
* @param choice
* The key of the item
* @return The position in the list, or -1 if not found
* @since 3.4
*/
protected int getIndexOfChoice(String choice) {
final int NOT_FOUND = -1;
if (choice == null) {
return NOT_FOUND;
}
for (int i = 0; i < fChoices.length; i++) {
String testChoice = fChoices[i][0];
if (choice.equals(testChoice)) {
return i;
}
}
return NOT_FOUND;
}
}
| epl-1.0 |
dragon66/icafe | src/com/icafe4j/image/compression/ccitt/G32DEncoder.java | 8784 | /**
* COPYRIGHT (C) 2014-2019 WEN YU (YUWEN_66@YAHOO.COM) ALL RIGHTS RESERVED.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Any modifications to this file must keep this entire header intact.
*/
package com.icafe4j.image.compression.ccitt;
import java.io.OutputStream;
import com.icafe4j.image.compression.ImageEncoder;
import com.icafe4j.util.Updatable;
/**
* CCITT Group 3 two dimensional encoding
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 01/02/2014
*/
public class G32DEncoder extends G31DEncoder implements ImageEncoder {
private int k;
// K should be greater than 1
public G32DEncoder(OutputStream os, int scanLineWidth, int buf_length, int k, Updatable<Integer> writer) {
super(os, scanLineWidth, buf_length, writer);
if(k < 2) throw new IllegalArgumentException("Invalid k value: " + k);
this.k = k;
}
/**
* This method assumes "len" is a multiplication of scan line length.
*
* @param len the number of pixels to be encoded
*/
@Override public void encode(byte[] pixels, int start, int len) throws Exception {
// Calculate how many blocks of k lines we need to encode
int totalScanLines = len/scanLineWidth;
int numOfKLines = totalScanLines/k;
int leftOver = totalScanLines%k;
// We first encode each block of k lines
for(int i = 0; i < numOfKLines; i++) {
start = encodeKLines(pixels, start);
}
// Then deal with the leftover lines
if(leftOver > 0) {
// Encode a one dimensional scan line first
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
start = encode1DLine(pixels, start);
// Now we are doing 2-D encoding
for(int i = 0; i < leftOver - 1; i++) {
// This line is 2-D encoded
send_code_to_buffer(T4Code.EOL_PLUS_ZERO, 13);
start = encode2DLine(pixels, start);
}
}
// Now send RTC(Return To Control) - 6 consecutive EOL + plus 1 to output
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
// We need to flush the last buffer
setExtraFlush(true);
}
// Need to take care of processing the first and last picture element in a line: ITU-T Rec. T4 (07/2003) 4.2.1.3.4
// ITU-T Rec. T.4 (07/2003) Figure 7/T4 - Two-dimensional coding flow diagram
private int encodeKLines(byte[] pixels, int start) throws Exception {
// Encode a one dimensional scan line first
send_code_to_buffer(T4Code.EOL_PLUS_ONE, 13);
start = encode1DLine(pixels, start);
// Encode the remaining k-1 lines
for(int i = 0; i < k - 1; i++) {
// Now we are doing 2-D encoding
send_code_to_buffer(T4Code.EOL_PLUS_ZERO, 13); // This line is 2-D encoded
start = encode2DLine(pixels, start);
}
return start;
}
// We are going to reuse this method in G42DEncoder
protected int encode2DLine(byte[] pixels, int start) throws Exception {
boolean endOfLine = false;
// First changing element is an imaginary white and we assume white is zero
int color = 0;
// Starting offset within the line start byte
int currRefPos = currPos;
int preRefPos = currRefPos + scanLineWidth%8;
if(preRefPos > 7) preRefPos -= 8;
int prevStart = ((((start+1)<<3) - currRefPos- scanLineWidth + 7)>>3) - 1;
int bias = 7;
a0 = -1;
while(!endOfLine) {
// Determine a1
// Offset within the scan line
int offset = a0 + 1;
int begin = start + (offset - currRefPos + 7)/8;
if(offset >= scanLineWidth) {
a1 = scanLineWidth;
} else {
bias = currRefPos - (offset%8);
if(bias < 0) bias += 8;
if(a0 == -1)
color = 0;
else {
if(bias == 7) color = ((pixels[begin-1])&0x01);
else color = ((pixels[begin]>>>(bias+1))&0x01);
}
a1 = findChangingElement(pixels, begin, color, bias, offset, true);
if(a1 == -1) a1 = scanLineWidth;
}
// Determine b1
offset = a0 + 1;
begin = prevStart + (offset - preRefPos + 7)/8;
if(begin < 0) {
b1 = scanLineWidth;
} else if(offset >= scanLineWidth) {
b1 = scanLineWidth;
} else {
bias = preRefPos - offset%8;
if(bias < 0) bias +=8;
b1 = findChangingElement(pixels, begin, color, bias, offset, false);
if(b1 == -1) b1 = scanLineWidth; // Situated just after the last changing element on the reference line
}
// Determine b2
color ^= 1;
offset = b1 + 1;
begin = prevStart + (offset - preRefPos + 7)/8;
//begin += (offset - preRefPos + 7)/8;
if(offset >= scanLineWidth) {
b2 = scanLineWidth;
} else {
bias = preRefPos - (offset%8);
if(bias <0) bias += 8;
b2 = findChangingElement(pixels, begin, color, bias, offset, true);
if(b2 == -1) b2 = scanLineWidth; // Situated just after the last changing element on the reference line
}
// Determine coding mode, and code accordingly
// Are we in pass mode?
if(b2 < a1) {// Yes, we are in pass code
send_code_to_buffer(T42DCode.P.getCode(), T42DCode.P.getCodeLen());
a0 = b2; // Update a0 position
} else {// No, we are not in pass mode
int a1b1 = a1-b1;
if(Math.abs(a1b1) <= 3) { // We are in Vertical mode
if(a1b1 == 0)
send_code_to_buffer(T42DCode.V0.getCode(), T42DCode.V0.getCodeLen());
else if(a1b1 == 1)
send_code_to_buffer(T42DCode.VR1.getCode(), T42DCode.VR1.getCodeLen());
else if(a1b1 == 2)
send_code_to_buffer(T42DCode.VR2.getCode(), T42DCode.VR2.getCodeLen());
else if(a1b1 == 3)
send_code_to_buffer(T42DCode.VR3.getCode(), T42DCode.VR3.getCodeLen());
else if(a1b1 == -1)
send_code_to_buffer(T42DCode.VL1.getCode(), T42DCode.VL1.getCodeLen());
else if(a1b1 == -2)
send_code_to_buffer(T42DCode.VL2.getCode(), T42DCode.VL2.getCodeLen());
else if(a1b1 == -3)
send_code_to_buffer(T42DCode.VL3.getCode(), T42DCode.VL3.getCodeLen());
a0 = a1; // Update a0 position
} else { // We are in Horizontal mode
send_code_to_buffer(T42DCode.H.getCode(), T42DCode.H.getCodeLen());
// One-dimensional coding a0a1 and a1a2
// First a0a1
int len = a1-a0;
if(a0 == -1) len--; // First changing element of the scan line
// We are going to send out a white zero run length code
if(len == 0) {
T4Code code = T4WhiteCode.CODE0;
short codeValue = code.getCode();
int codeLen = code.getCodeLen();
send_code_to_buffer(codeValue, codeLen);
} else
outputRunLengthCode(len, color^1);
// Then a1a2
offset = a1 + 1;
begin = start + (offset - currRefPos + 7)/8;
if(offset >= scanLineWidth) {
a2 = scanLineWidth;
} else {
bias = currRefPos - (offset%8);
if(bias <0) bias += 8;
a2 = findChangingElement(pixels, begin, color, bias, offset, true);
if(a2 == -1) a2 = scanLineWidth;
}
len = a2-a1;
outputRunLengthCode(len, color);
// Update a0 position
a0 = a2;
}
}
if(a0 >= scanLineWidth)
endOfLine = true;
}
// Set current position
currPos = currRefPos - (scanLineWidth%8);
if(currPos < 0) currPos += 8;
return start + (scanLineWidth - currRefPos + 7)/8;
}
private int findChangingElement(byte[] pixels, int begin, int color, int bias, int offset, boolean sameLine) {
//
if(sameLine) return find(pixels, begin, color, bias, offset, true);
int upperColor = ((a0 == -1)?0:((bias == 7)?(pixels[begin - 1]&0x01):((pixels[begin]>>>(bias+1))&0x01)));
if(color == upperColor) {
return find(pixels, begin, color, bias, offset, true);
}
return find(pixels, begin, upperColor, bias, offset, false);
}
private int find(byte[] pixels, int begin, int color, int bias, int offset, boolean sameLine) {
int changingElement = -1;
// Determine changing element
while(bias >= 0) {
if(((pixels[begin]>>>bias)&0x01)==color) {
offset++;
bias--;
} else {
bias--;
if(sameLine) {
changingElement = offset++;
break;
}
offset++;
color ^= 1;
sameLine = true;
}
if(offset >= scanLineWidth) {
break;
}
if(bias < 0) {
bias = 7;
begin++;
}
}
return changingElement;
}
/*
* Changing elements used to define coding mode.
*
* At the start of coding line, a0 is set on an imaginary white changing
* element situated just before the first element on the line.
*/
private int a0 = -1;
private int a1;
private int a2;
private int b1;
private int b2;
}
| epl-1.0 |
KayErikMuench/reqiftools | reqifcompiler/src/main/java/de/kay_muench/reqif10/reqifcompiler/SpecObjectFactory.java | 5579 | /**
* Copyright (c) 2014 Kay Erik Mรผnch.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.spdx.org/licenses/EPL-1.0
*
* Contributors:
* Kay Erik Mรผnch - initial API and implementation
*
*/
package de.kay_muench.reqif10.reqifcompiler;
import javax.xml.datatype.DatatypeConfigurationException;
import org.eclipse.rmf.reqif10.ReqIF10Factory;
import org.eclipse.rmf.reqif10.SpecObject;
import de.kay_muench.reqif10.reqifcompiler.dto.RankingDTO;
import de.kay_muench.reqif10.reqifcompiler.dto.StatusDTO;
import de.kay_muench.reqif10.reqifcompiler.types.complex.BaselineSpecObjectType;
import de.kay_muench.reqif10.reqifcompiler.types.complex.ConfigurationSpecObjectType;
import de.kay_muench.reqif10.reqifcompiler.xhtml.XhtmlBuilder;
class SpecObjectFactory {
private class BaselineSpecObject {
private IDValue attributeValueID;
private DescriptionValue attributeValueDescription;
private DateValue attributeValueDate;
private RequirementStatusValue attributeValueStatus;
private RequirementRankingValue attributeValueImportance;
private RequirementRankingValue attributeValueRisk;
private SpecObject specObject;
BaselineSpecObject(final BaselineSpecObjectType type, final String id,
final XhtmlBuilder builder, final String date,
final StatusDTO status, RankingDTO importance, RankingDTO risk)
throws DatatypeConfigurationException {
specObject = ReqIF10Factory.eINSTANCE.createSpecObject();
specObject.setIdentifier(IdentifierManager.generateIdentifier());
specObject.setType(type.getDef());
attributeValueID = new IDValue(type.getId(), specObject);
attributeValueDescription = new DescriptionValue(
type.getDesc(), specObject);
attributeValueDate = new DateValue(type.getScheduledBy(),
specObject);
attributeValueStatus = new RequirementStatusValue(
type.getStatus(), specObject);
attributeValueImportance = new RequirementRankingValue(
type.getPriority(), specObject);
attributeValueRisk = new RequirementRankingValue(
type.getRisk(), specObject);
this.setId(id);
this.setDescription(builder);
this.setDate(date);
this.setStatus(status);
this.setImportance(importance);
this.setRisk(risk);
}
void setId(final String id) {
attributeValueID.setId(id);
}
void setDescription(final XhtmlBuilder builder) {
attributeValueDescription.setDescription(builder);
}
void setDate(final String date) throws DatatypeConfigurationException {
attributeValueDate.setDate(date);
}
void setStatus(final StatusDTO status) {
attributeValueStatus.setStatus(status);
}
void setImportance(final RankingDTO importance) {
attributeValueImportance.setRanking(importance);
}
void setRisk(final RankingDTO risk) {
attributeValueRisk.setRanking(risk);
}
SpecObject getObj() {
return specObject;
}
}
private class ConfigurationSpecObject {
private IDValue attributeValueID;
private DescriptionValue attributeValueDescription;
private RequirementStatusValue attributeValueStatus;
private RequirementRankingValue attributeValueImportance;
private RequirementRankingValue attributeValueRisk;
private SpecObject specObject;
ConfigurationSpecObject(final ConfigurationSpecObjectType type,
final String id, final XhtmlBuilder builder, StatusDTO status,
RankingDTO importance, RankingDTO risk)
throws DatatypeConfigurationException {
specObject = ReqIF10Factory.eINSTANCE.createSpecObject();
specObject.setIdentifier(IdentifierManager.generateIdentifier());
specObject.setType(type.getDef());
attributeValueID = new IDValue(type.getId(), specObject);
attributeValueDescription = new DescriptionValue(
type.getDesc(), specObject);
attributeValueStatus = new RequirementStatusValue(
type.getStatus(), specObject);
attributeValueImportance = new RequirementRankingValue(
type.getImportance(), specObject);
attributeValueRisk = new RequirementRankingValue(
type.getRisk(), specObject);
this.setId(id);
this.setDescription(builder);
this.setStatus(status);
this.setImportance(importance);
this.setRisk(risk);
}
void setId(final String id) {
attributeValueID.setId(id);
}
void setDescription(final XhtmlBuilder builder) {
attributeValueDescription.setDescription(builder);
}
void setStatus(final StatusDTO status) {
attributeValueStatus.setStatus(status);
}
void setImportance(final RankingDTO importance) {
attributeValueImportance.setRanking(importance);
}
void setRisk(final RankingDTO risk) {
attributeValueRisk.setRanking(risk);
}
SpecObject getObj() {
return specObject;
}
}
private BaselineSpecObjectType typeWD;
private ConfigurationSpecObjectType typeWoD;
SpecObjectFactory(final BaselineSpecObjectType typeWD,
final ConfigurationSpecObjectType typeWoD) {
this.typeWD = typeWD;
this.typeWoD = typeWoD;
}
SpecObject newSpecObject(final String id, final XhtmlBuilder builder,
final String date, final StatusDTO status, RankingDTO importance,
RankingDTO risk) throws DatatypeConfigurationException {
SpecObject specObject;
if (date != null) {
specObject = new BaselineSpecObject(this.typeWD, id, builder, date,
status, importance, risk).getObj();
} else {
specObject = new ConfigurationSpecObject(this.typeWoD, id, builder,
status, importance, risk).getObj();
}
return specObject;
}
} | epl-1.0 |
oisin/Message-Owl | org.fusesource.tools.messaging/src/org/fusesource/tools/messaging/ui/dialogs/DestinationDialog.java | 18338 | /*******************************************************************************
* Copyright (c) 2009, 2010 Progress Software Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
// Copyright (c) 2009 Progress Software Corporation.
package org.fusesource.tools.messaging.ui.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.ui.ServerUIUtil;
import org.fusesource.tools.messaging.IConstants;
import org.fusesource.tools.messaging.core.IDestination;
import org.fusesource.tools.messaging.core.IDestinationType;
import org.fusesource.tools.messaging.core.IProvider;
import org.fusesource.tools.messaging.server.MessagingServersUtil;
import org.fusesource.tools.messaging.ui.DefaultMessageTableViewer;
import org.fusesource.tools.messaging.ui.DestinationCellModifier;
import org.fusesource.tools.messaging.ui.DestinationTableContentProvider;
import org.fusesource.tools.messaging.ui.DestinationTableLabelProvider;
import org.fusesource.tools.messaging.ui.DestinationUtil;
public abstract class DestinationDialog extends TitleAreaDialog {
private TableViewer tableViewer = null;
private static String NAME_PROPERTY = "name";
private static String VALUE_PROPERTY = "value";
private static String COLUMN_HEADERS_STRING = "Name;Value";
public static String DESTINATION_UI_EXT_PT = "org.fusesource.tools.messaging.DestinationUI";
public static String ISENDER_ATTRIBUTE = "Sender";
public static String ILISTENER_ATTRIBUTE = "Listener";
protected Map<String, Object> senderProperties = new HashMap<String, Object>();
protected Map<String, Object> listenerProperties = new HashMap<String, Object>();
private Map<String, String> msgServersNameIdMap = Collections.emptyMap();
private Map<String, IDestinationType> destTypeMap = new HashMap<String, IDestinationType>();
private Object source;// TODO source is an IFile for now...
private String destType;
private String destName;
protected Combo serversCombo;
protected Combo destTypesCombo;
private Text destNameText;
private String selectedServerName;
private static final String CLOSED_ADVANCED = "Advanced >>";
private static final String OPENED_ADVANCED = "<< Advanced";
private Button advancedButton;
private Composite advancedComposite;
protected Composite panel = null;
protected Button newServerButton = null;
private boolean deployed = false;
protected IDestination createdDestination;
protected IProvider provider = null;
public DestinationDialog() {
super(Display.getCurrent().getActiveShell());
}
@Override
public void create() {
super.create();
Shell shell = getShell();
shell.setText(getDialogTitle());
setTitle(getTitle());
setMessage(getMessage());
validate();
}
protected abstract String getMessage();
protected abstract String getTitle();
protected abstract boolean hasAdvanceSection();
protected String getDialogTitle() {
return "Add Destination";
}
@Override
protected Control createDialogArea(Composite parent) {
Control control = super.createDialogArea(parent);
panel = new Composite((Composite) control, SWT.NONE);
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.grabExcessHorizontalSpace = true;
panel.setLayout(new GridLayout());
panel.setLayoutData(data);
createUI();
return panel;
}
protected void createUI() {
Group destGroup = new Group(panel, SWT.NONE);
destGroup.setText("Destination Details");
GridLayout layout = new GridLayout();
layout.numColumns = 3;
destGroup.setLayout(layout);
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
destGroup.setLayoutData(gridData);
gridData = new GridData();
Label name = new Label(destGroup, SWT.NONE);
name.setText("Server:");
name.setLayoutData(gridData);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalSpan = 1;
serversCombo = new Combo(destGroup, SWT.READ_ONLY);
serversCombo.setLayoutData(gridData);
gridData = new GridData();
gridData.horizontalSpan = 1;
newServerButton = new Button(destGroup, SWT.PUSH);
newServerButton.setText("New Server...");
newServerButton.setLayoutData(gridData);
newServerButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent arg0) {
}
public void widgetSelected(SelectionEvent arg0) {
boolean isServerCreated = ServerUIUtil.showNewServerWizard(Display.getDefault().getActiveShell(),
IConstants.MSG_PRJ_MODULE_ID, null, null);
if (isServerCreated) {
populateServerNames(true, false);
// TODO optimize here, to get the newly added server only...
if (serversCombo.getItemCount() > 0) {
serversCombo.select(0);// Default selection
}
}
}
});
gridData = new GridData();
Label destTypeLabel = new Label(destGroup, SWT.NONE);
destTypeLabel.setText("Destination Type:");
destTypeLabel.setLayoutData(gridData);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalSpan = 2;
destTypesCombo = new Combo(destGroup, SWT.READ_ONLY);
destTypesCombo.setLayoutData(gridData);
gridData = new GridData();
Label destNameLabel = new Label(destGroup, SWT.NONE);
destNameLabel.setText("Destination Name:");
destNameLabel.setLayoutData(gridData);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalSpan = 2;
destNameText = new Text(destGroup, SWT.BORDER);
destNameText.setLayoutData(gridData);
if (hasAdvanceSection()) {
showAdvanceSection(destGroup);
}
addListeners();
populateServerNames(false, false);
populateDestinationTypes();
destNameText.setFocus();
validate();
}
private void addListeners() {
serversCombo.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent arg0) {
}
public void widgetSelected(SelectionEvent arg0) {
initServersComboData();
}
});
serversCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
initServersComboData();
}
});
destNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validate();
}
});
destTypesCombo.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent arg0) {
}
public void widgetSelected(SelectionEvent arg0) {
validate();
}
});
}
protected void createAdvancedUI(Composite composite) {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
composite.setLayout(gridLayout);
GridData data = new GridData();
data = new GridData();
data.grabExcessHorizontalSpace = true;
data.horizontalAlignment = SWT.FILL;
Group messageDeliveryOption = new Group(composite, SWT.NONE);
messageDeliveryOption.setText(getAdvTitle());
messageDeliveryOption.setLayout(new FillLayout());
messageDeliveryOption.setLayoutData(data);
tableViewer = new DefaultMessageTableViewer(messageDeliveryOption, SWT.FULL_SELECTION, "");
((DefaultMessageTableViewer) tableViewer).refreshTable(COLUMN_HEADERS_STRING);
Table table = tableViewer.getTable();
table.setLinesVisible(true);
CellEditor[] editors = new CellEditor[2];
editors[0] = new TextCellEditor(table);
editors[1] = new TextCellEditor(table);
tableViewer.setCellEditors(editors);
tableViewer.setCellModifier(new DestinationCellModifier(tableViewer, senderProperties));// sender
// props??
tableViewer.setColumnProperties(new String[] { NAME_PROPERTY, VALUE_PROPERTY });
tableViewer.setContentProvider(new DestinationTableContentProvider());
tableViewer.setLabelProvider(new DestinationTableLabelProvider());
tableViewer.setInput(senderProperties);// sender props??
tableViewer.refresh();
}
protected String getAdvTitle() {
return "Destination Properties";
}
private void initServersComboData() {
int selectionIndex = serversCombo.getSelectionIndex();
if (selectionIndex != -1) {
setSelectedServerName(serversCombo.getItem(selectionIndex));
populateDestinationTypes();
validate();
}
}
private void showAdvanceSection(Composite destGroup) {
if (hasAdvanceSection()) {
GridData data = new GridData();
data.horizontalSpan = 3;
data.horizontalAlignment = SWT.END;
data.grabExcessHorizontalSpace = true;
advancedButton = new Button(destGroup, SWT.PUSH);
advancedButton.setText(CLOSED_ADVANCED);
advancedButton.setLayoutData(data);
advancedButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
handleAdvancedButtonSelect();
}
public void widgetDefaultSelected(SelectionEvent e) {
handleAdvancedButtonSelect();
}
});
}
}
protected void handleAdvancedButtonSelect() {
Shell shell = getShell();
Point shellSize = shell.getSize();
Composite composite = (Composite) getContents();
if (advancedButton.getText().equalsIgnoreCase(CLOSED_ADVANCED)) {
advancedComposite = new Composite(panel, SWT.NONE);
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.grabExcessHorizontalSpace = true;
advancedComposite.setLayoutData(data);
createAdvancedUI(advancedComposite);
panel.layout();
composite.layout();
Point advComSize = advancedComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
shell.setSize(shellSize.x, shellSize.y += advComSize.y);
advancedButton.setText(OPENED_ADVANCED);
} else if (advancedButton.getText().equalsIgnoreCase(OPENED_ADVANCED)) {
Point advComSize = advancedComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
shell.setSize(shellSize.x, shellSize.y -= advComSize.y);
composite.layout();
advancedButton.setText(CLOSED_ADVANCED);
}
}
protected void populateServerNames(boolean updateMap, boolean deployed) {
if (msgServersNameIdMap.isEmpty() || updateMap) {
msgServersNameIdMap = getServersMap();
}
// populateDestinationTypes();
serversCombo.setItems(msgServersNameIdMap.keySet().toArray(new String[] {}));
if (deployed) {
newServerButton.setEnabled(false);
serversCombo.select(0);
serversCombo.setEnabled(false);
populateDestinationTypes();
setSelectedServerName(serversCombo.getItem(serversCombo.getSelectionIndex()));
}
// Expecting only one or none.
IServer deployedServer = MessagingServersUtil.getDeployedServer(((IFile) getSource()).getProject());
if (deployedServer == null) {
this.deployed = false;
return;
}
String serverToSelect = deployedServer.getName();
int indexOf = serversCombo.indexOf(serverToSelect);
serversCombo.select(indexOf);
this.deployed = true;
}
private Map<String, String> getServersMap() {
return MessagingServersUtil.getMsgServersNameIdMap();
}
protected void populateDestinationTypes() {
if (getSelectedServerName() == null) {
return;
}
try {
if (getProvider() == null || getProvider().getDestinationTypes() == null) {
destTypeMap.clear();
return;
}
} catch (Exception e) {
// ignore...
destTypeMap.clear();
return;
}
List<IDestinationType> destinationTypes = getProvider().getDestinationTypes();
List<String> typesList = new ArrayList<String>();
destTypeMap.clear();
for (IDestinationType destinationType : destinationTypes) {
destTypeMap.put(destinationType.getType(), destinationType);
typesList.add(destinationType.getType());
}
destTypesCombo.setItems(typesList.toArray(new String[] {}));
if (destTypesCombo.getItemCount() > 0) {
destTypesCombo.select(0);
}
}
protected void updateData() {
setDestType(destTypesCombo.getItem(destTypesCombo.getSelectionIndex()));
setDestName(destNameText.getText());
setSelectedServerName(serversCombo.getItem(serversCombo.getSelectionIndex()));
}
@Override
protected void okPressed() {
updateData();
super.okPressed();
try {
if (!deployed) {
MessagingServersUtil.deployModule(((IFile) getSource()).getProject(), selectedServerName);
}
createdDestination = DestinationUtil.createDestination(getDestinationType(), getDestName(), getProvider());
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateServerControls() {
serversCombo.setEnabled(!deployed);
newServerButton.setEnabled(!deployed);
}
protected void validate() {
String errorMessage = null;
if (serversCombo.getSelectionIndex() == -1) {
errorMessage = "Please choose a server";
} else if (destTypesCombo.getSelectionIndex() == -1) {
errorMessage = "Please choose a destination type";
} else if (destNameText.getText().trim().length() == 0) {
errorMessage = "Please enter a destination name";
}
if (errorMessage != null) {
setErrorMessage(errorMessage);
} else {
setErrorMessage(null);
setMessage(getMessage());
}
updateServerControls();
updateUIControls(errorMessage != null ? false : true);
}
protected void updateUIControls(boolean canEnable) {
if (hasAdvanceSection()) {
advancedButton.setEnabled(canEnable);
}
}
@Override
public void setErrorMessage(String newErrorMessage) {
super.setErrorMessage(newErrorMessage);
Button button = getButton(IDialogConstants.OK_ID);
if (button != null) {
if (newErrorMessage != null) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
}
public String getSelectedServerName() {
return selectedServerName;
}
public void setSelectedServerName(String serverName) {
this.selectedServerName = serverName;
}
public String getDestName() {
return destName;
}
public void setDestName(String destName) {
this.destName = destName;
}
public IDestinationType getDestinationType() {
return destTypeMap.get(getDestType());
}
public IDestination getCreatedDestination() {
return createdDestination;
}
public String getDestType() {
return destType;
}
public void setDestType(String destType) {
this.destType = destType;
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
public IProvider getProvider() {
if (provider == null) {
try {
provider = DestinationUtil.getProvider(getSelectedServerName());
} catch (Exception e) {
e.printStackTrace();
}
}
return provider;
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/workbench/ui/com.odcgroup.workbench.compare/src/main/java/com/odcgroup/workbench/compare/team/action/SvnRevertAction.java | 792 | package com.odcgroup.workbench.compare.team.action;
import org.eclipse.swt.SWT;
import org.eclipse.team.internal.ui.actions.TeamAction;
import org.eclipse.team.svn.ui.SVNTeamUIPlugin;
import org.eclipse.team.svn.ui.action.local.RevertAction;
/**
*
* @author pkk
*
*/
@SuppressWarnings("restriction")
public class SvnRevertAction extends AbstractTeamAction {
/**
* @param text
*/
public SvnRevertAction() {
super("&Revert...");
setImageDescriptor(SVNTeamUIPlugin.instance().getImageDescriptor("icons/common/actions/revert.gif"));
setAccelerator(SWT.CTRL+SWT.ALT+'S');
}
/* (non-Javadoc)
* @see com.odcgroup.workbench.compare.team.action.AbstractTeamAction#fetchTeamActionDelegate()
*/
public TeamAction fetchTeamActionDelegate() {
return new RevertAction();
}
}
| epl-1.0 |
SPDSS/adss | eu.aspire_fp7.adss.akb.ui/src/eu/aspire_fp7/adss/akb/ui/nattables/ApplicationPartUpdateDataCommandHandler.java | 3867 | /*******************************************************************************
* Copyright (c) 2016 Politecnico di Torino.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Politecnico di Torino - initial API and implementation
*******************************************************************************/
package eu.aspire_fp7.adss.akb.ui.nattables;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommand;
import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommandHandler;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.event.CellVisualChangeEvent;
import eu.aspire_fp7.adss.ADSS;
import eu.aspire_fp7.adss.akb.ApplicationPart;
import eu.aspire_fp7.adss.akb.Property;
import eu.aspire_fp7.adss.akb.ui.listeners.ADSSEventGenerator;
import eu.aspire_fp7.adss.akb.ui.listeners.Event;
/**
* The application part data command handler.
* @author Daniele Canavese
**/
public class ApplicationPartUpdateDataCommandHandler extends UpdateDataCommandHandler
{
/** The data layer. **/
private DataLayer dataLayer;
/** The ADSS. **/
private ADSS adss;
/** The event generator. **/
private ADSSEventGenerator eventGenerator;
/**
* Creates the command handler.
* @param adss
* The ADSS.
* @param eventGenerator
* The event generator.
* @param dataLayer
* The data layer.
**/
public ApplicationPartUpdateDataCommandHandler(ADSS adss, ADSSEventGenerator eventGenerator, DataLayer dataLayer)
{
super(dataLayer);
this.adss = adss;
this.eventGenerator = eventGenerator;
this.dataLayer = dataLayer;
}
/**
* Executes a command.
* @param command
* The command to run.
**/
@SuppressWarnings("unchecked")
@Override
protected boolean doCommand(UpdateDataCommand command)
{
try
{
int columnPosition = command.getColumnPosition();
int rowPosition = command.getRowPosition();
Object currentValue = dataLayer.getDataValueByPosition(columnPosition, rowPosition);
if (currentValue == null || command.getNewValue() == null || !currentValue.equals(command.getNewValue()))
{
if (columnPosition == 3)
{
ListDataProvider<ApplicationPart> dataProvider = (ListDataProvider<ApplicationPart>) dataLayer.getDataProvider();
ApplicationPart part = dataProvider.getRowObject(dataLayer.getRowIndexByPosition(rowPosition));
String value = command.getNewValue().toString();
Collection<Property> properties = new ArrayList<>();
if (value.contains("hard confidentiality"))
properties.add(Property.HARDCONFIDENTIALITY);
else if (value.contains("confidentiality"))
properties.add(Property.CONFIDENTIALITY);
else if (value.contains("privacy"))
properties.add(Property.PRIVACY);
if (value.contains("integrity"))
properties.add(Property.INTEGRITY);
boolean hardcoded = part.getProperties().contains(Property.HARDCODED);
part.getProperties().clear();
part.getProperties().addAll(properties);
if (hardcoded)
part.getProperties().add(Property.HARDCODED);
adss.updateAssets();
eventGenerator.fireEvent(Event.APPLICATION_PARTS_UPDATED);
}
else
dataLayer.setDataValueByPosition(columnPosition, rowPosition, command.getNewValue());
dataLayer.fireLayerEvent(new CellVisualChangeEvent(this.dataLayer, columnPosition, rowPosition));
}
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
}
| epl-1.0 |
consag/fitnessefixtures | Fixtures/src/test/java/nl/jacbeekers/testautomation/fitnesse/database/CreateTableTest.java | 6530 | package nl.jacbeekers.testautomation.fitnesse.database;
import nl.jacbeekers.testautomation.fitnesse.FitNesseTest;
import nl.jacbeekers.testautomation.fitnesse.supporting.Constants;
import nl.jacbeekers.testautomation.fitnesse.supporting.ResultMessages;
import org.apache.commons.text.CaseUtils;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumingThat;
class CreateTableTest {
//Logging
private Logger logger;
private String method;
private String result = Constants.OK;
private String resultMessage = Constants.NOERRORS;
@Test
void testCreationOfTableInDatabaseSchemaAsCloneOfTableInDatabaseSchemaIs() {
setMethod("testCreationOfTableInDatabaseSchemaAsCloneOfTableInDatabaseSchemaIs");
setLogger(Logger.getLogger(getClass().getName() + "-" + getMethod()));
executeCreateTableAsCloneTest("/UnitTests/database/CreateTableAsClone.wiki");
}
@Test
void testCreateTable() {
setMethod("testCreateTable");
setLogger(Logger.getLogger(getClass().getName() + "-" + getMethod()));
executeCreateTableTest("/UnitTests/database/CreateTable.wiki");
assertTrue(Constants.OK.equals(getResult())
, "Table creation failed: " + getResultMessage() );
}
private String executeCreateTableTest(String testPage) {
CreateTable createTable = new CreateTable();
createTable.setLogLevel(Constants.DEBUG);
FitNesseTest fitNesseTest = new FitNesseTest(testPage);
String testfilename = fitNesseTest.getPathTestPage();
List<List<String>> inputTable = fitNesseTest.createTestTable(testfilename);
assertTrue(inputTable != null && inputTable.size() > 0
, "Input Table is empty. File >" + testfilename + "< exists?");
boolean ensureFound = false;
for(List<String> record : inputTable) {
String firstCol = CaseUtils.toCamelCase(record.get(0), false);
switch(firstCol) {
case "setDatabase":
getLogger().info("setDatabase for >" + record.get(1) + "<.");
createTable.setDatabaseName(record.get(1));
break;
case "addColumn":
getLogger().info("addColumn named >" + record.get(1) + "<.");
createTable.addColumnDataType(record.get(1), record.get(3));
break;
case "ensure":
ensureFound = true;
getLogger().info("ensure for >" + record.get(1) +"<.");
if("createTable".equals(CaseUtils.toCamelCase(record.get(1), false))) {
createTable.createTableIs(record.get(2), Constants.OK);
}
break;
default:
getLogger().finest("Ignoring >" + record.get(0) +"<.");
}
}
if(ensureFound) {
setResult(createTable.getResult());
setResultMessage(createTable.getResultMessage());
} else {
setResult(Constants.ERROR);
setResultMessage("No ensure row found in test table. Table creation did not happen.");
}
return getResult();
}
private String executeCreateTableAsCloneTest(String testPage) {
String tgtTable = "NO_TARGET_TABLE";
String tgtDatabase = "NO_TARGET_DATABASE";
String tgtSchema = "NO_TARGET_SCHEMA";
String srcTable = "NO_SOURCE_TABLE";
String srcDatabase = "NO_SOURCE_DATABASE";
String srcSchema = "NO_SOURCE_SCHEMA";
String expectedResult = "OK";
CreateTable createTable = new CreateTable("unittest_createtable_asclone");
createTable.setLogLevel(Constants.DEBUG);
FitNesseTest fitNesseTest = new FitNesseTest(testPage);
String testfilename = fitNesseTest.getPathTestPage();
List<List<String>> inputTable = fitNesseTest.createTestTable(testfilename);
assertTrue(inputTable != null && inputTable.size() > 0
, "Input Table is empty. File >" + testfilename + "< exists?");
boolean found =false;
int i =-1;
while(!found && (i < inputTable.size())) {
i++;
if(inputTable.get(i).get(0).startsWith("ensure")) {
found = true;
}
}
if (found) {
tgtTable = inputTable.get(i).get(2);
tgtDatabase = inputTable.get(i).get(4);
tgtSchema = inputTable.get(i).get(6);
srcTable = inputTable.get(i).get(8);
srcDatabase = inputTable.get(i).get(10);
srcSchema = inputTable.get(i).get(12);
}
String finalTgtTable = tgtTable;
String finalTgtDatabase = tgtDatabase;
String finalTgtSchema = tgtSchema;
String finalSrcTable = srcTable;
String finalSrcDatabase = srcDatabase;
String finalSrcSchema = srcSchema;
assumingThat(inputTable != null && inputTable.size() > 0
, () -> createTable.creationOfTableInDatabaseSchemaAsCloneOfTableInDatabaseSchemaIs(
finalTgtTable
, finalTgtDatabase
, finalTgtSchema
, finalSrcTable
, finalSrcDatabase
, finalSrcSchema
,expectedResult
));
assumingThat(ResultMessages.ERRCODE_SQLERROR.equals(createTable.getResult()), () -> setResult(Constants.OK));
getLogger().info(createTable.getResultMessage());
assertTrue(Constants.OK.equals(getResult()), createTable.getResultMessage());
return createTable.getResult();
}
/**
* Getters and Setters
*/
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
private String getMethod() {
return method;
}
private void setMethod(String method) {
this.method = method;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
} | epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/jpa/parsing/MinNode.java | 2172 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.jpa.parsing;
import org.eclipse.persistence.queries.ObjectLevelReadQuery;
import org.eclipse.persistence.queries.ReportQuery;
import org.eclipse.persistence.expressions.Expression;
/**
* INTERNAL
* <p><b>Purpose</b>: Model a MIN
* <p><b>Responsibilities</b>:<ul>
* <li> Apply itself to a query correctly
* </ul>
*/
public class MinNode extends AggregateNode {
/**
* INTERNAL
* Apply this node to the passed query
*/
public void applyToQuery(ObjectLevelReadQuery theQuery, GenerationContext context) {
if (theQuery.isReportQuery()) {
ReportQuery reportQuery = (ReportQuery)theQuery;
reportQuery.addAttribute(resolveAttribute(),
generateExpression(context));
}
}
/**
* INTERNAL
* Validate node and calculate its type.
*/
public void validate(ParseTreeContext context) {
if (left != null) {
left.validate(context);
setType(left.getType());
}
}
/**
* INTERNAL
*/
protected Expression addAggregateExression(Expression expr) {
return expr.minimum();
}
/**
* INTERNAL
* Get the string representation of this node.
*/
public String getAsString() {
return "MIN(" + left.getAsString() + ")";
}
}
| epl-1.0 |
Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/store/jdbc/Statements.java | 42733 | /**
* 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.activemq.store.jdbc;
/**
*
*
* @org.apache.xbean.XBean element="statements"
*
*/
public class Statements {
protected String messageTableName = "ACTIVEMQ_MSGS";
protected String durableSubAcksTableName = "ACTIVEMQ_ACKS";
protected String lockTableName = "ACTIVEMQ_LOCK";
protected String binaryDataType = "BLOB";
protected String containerNameDataType = "VARCHAR(250)";
protected String msgIdDataType = "VARCHAR(250)";
protected String sequenceDataType = "BIGINT";
protected String longDataType = "BIGINT";
protected String stringIdDataType = "VARCHAR(250)";
protected boolean useExternalMessageReferences;
private String tablePrefix = "";
private String addMessageStatement;
private String updateMessageStatement;
private String removeMessageStatement;
private String findMessageSequenceIdStatement;
private String findMessageStatement;
private String findMessageByIdStatement;
private String findAllMessagesStatement;
private String findLastSequenceIdInMsgsStatement;
private String findLastSequenceIdInAcksStatement;
private String createDurableSubStatement;
private String findDurableSubStatement;
private String findAllDurableSubsStatement;
private String updateLastPriorityAckRowOfDurableSubStatement;
private String deleteSubscriptionStatement;
private String findAllDurableSubMessagesStatement;
private String findDurableSubMessagesStatement;
private String findDurableSubMessagesByPriorityStatement;
private String findAllDestinationsStatement;
private String removeAllMessagesStatement;
private String removeAllSubscriptionsStatement;
private String[] createSchemaStatements;
private String[] createLockSchemaStatements;
private String[] dropSchemaStatements;
private String lockCreateStatement;
private String lockUpdateStatement;
private String nextDurableSubscriberMessageStatement;
private String durableSubscriberMessageCountStatement;
private String lastAckedDurableSubscriberMessageStatement;
private String destinationMessageCountStatement;
private String findNextMessagesStatement;
private String findNextMessagesByPriorityStatement;
private boolean useLockCreateWhereClause;
private String findAllMessageIdsStatement;
private String lastProducerSequenceIdStatement;
private String selectDurablePriorityAckStatement;
private String insertDurablePriorityAckStatement;
private String updateDurableLastAckStatement;
private String deleteOldMessagesStatementWithPriority;
private String durableSubscriberMessageCountStatementWithPriority;
private String dropAckPKAlterStatementEnd;
private String updateXidFlagStatement;
private String findOpsPendingOutcomeStatement;
private String clearXidFlagStatement;
private String updateDurableLastAckInTxStatement;
private String findAcksPendingOutcomeStatement;
private String clearDurableLastAckInTxStatement;
private String updateDurableLastAckWithPriorityStatement;
private String updateDurableLastAckWithPriorityInTxStatement;
private String findXidByIdStatement;
private String leaseObtainStatement;
private String currentDateTimeStatement;
private String leaseUpdateStatement;
private String leaseOwnerStatement;
public String[] getCreateSchemaStatements() {
if (createSchemaStatements == null) {
createSchemaStatements = new String[] {
"CREATE TABLE " + getFullMessageTableName() + "(" + "ID " + sequenceDataType + " NOT NULL"
+ ", CONTAINER " + containerNameDataType + ", MSGID_PROD " + msgIdDataType + ", MSGID_SEQ "
+ sequenceDataType + ", EXPIRATION " + longDataType + ", MSG "
+ (useExternalMessageReferences ? stringIdDataType : binaryDataType)
+ ", PRIMARY KEY ( ID ) )",
"CREATE INDEX " + getFullMessageTableName() + "_MIDX ON " + getFullMessageTableName() + " (MSGID_PROD,MSGID_SEQ)",
"CREATE INDEX " + getFullMessageTableName() + "_CIDX ON " + getFullMessageTableName() + " (CONTAINER)",
"CREATE INDEX " + getFullMessageTableName() + "_EIDX ON " + getFullMessageTableName() + " (EXPIRATION)",
"CREATE TABLE " + getFullAckTableName() + "(" + "CONTAINER " + containerNameDataType + " NOT NULL"
+ ", SUB_DEST " + stringIdDataType
+ ", CLIENT_ID " + stringIdDataType + " NOT NULL" + ", SUB_NAME " + stringIdDataType
+ " NOT NULL" + ", SELECTOR " + stringIdDataType + ", LAST_ACKED_ID " + sequenceDataType
+ ", PRIMARY KEY ( CONTAINER, CLIENT_ID, SUB_NAME))",
"ALTER TABLE " + getFullMessageTableName() + " ADD PRIORITY " + sequenceDataType,
"CREATE INDEX " + getFullMessageTableName() + "_PIDX ON " + getFullMessageTableName() + " (PRIORITY)",
"ALTER TABLE " + getFullMessageTableName() + " ADD XID " + stringIdDataType,
"ALTER TABLE " + getFullAckTableName() + " ADD PRIORITY " + sequenceDataType + " DEFAULT 5 NOT NULL",
"ALTER TABLE " + getFullAckTableName() + " ADD XID " + stringIdDataType,
"ALTER TABLE " + getFullAckTableName() + " " + getDropAckPKAlterStatementEnd(),
"ALTER TABLE " + getFullAckTableName() + " ADD PRIMARY KEY (CONTAINER, CLIENT_ID, SUB_NAME, PRIORITY)",
"CREATE INDEX " + getFullMessageTableName() + "_XIDX ON " + getFullMessageTableName() + " (XID)",
"CREATE INDEX " + getFullAckTableName() + "_XIDX ON " + getFullAckTableName() + " (XID)"
};
}
getCreateLockSchemaStatements();
String[] allCreateStatements = new String[createSchemaStatements.length + createLockSchemaStatements.length];
System.arraycopy(createSchemaStatements, 0, allCreateStatements, 0, createSchemaStatements.length);
System.arraycopy(createLockSchemaStatements, 0, allCreateStatements, createSchemaStatements.length, createLockSchemaStatements.length);
return allCreateStatements;
}
public String[] getCreateLockSchemaStatements() {
if (createLockSchemaStatements == null) {
createLockSchemaStatements = new String[] {
"CREATE TABLE " + getFullLockTableName()
+ "( ID " + longDataType + " NOT NULL, TIME " + longDataType
+ ", BROKER_NAME " + stringIdDataType + ", PRIMARY KEY (ID) )",
"INSERT INTO " + getFullLockTableName() + "(ID) VALUES (1)"
};
}
return createLockSchemaStatements;
}
public String getDropAckPKAlterStatementEnd() {
if (dropAckPKAlterStatementEnd == null) {
dropAckPKAlterStatementEnd = "DROP PRIMARY KEY";
}
return dropAckPKAlterStatementEnd;
}
public void setDropAckPKAlterStatementEnd(String dropAckPKAlterStatementEnd) {
this.dropAckPKAlterStatementEnd = dropAckPKAlterStatementEnd;
}
public String[] getDropSchemaStatements() {
if (dropSchemaStatements == null) {
dropSchemaStatements = new String[] {"DROP TABLE " + getFullAckTableName() + "",
"DROP TABLE " + getFullMessageTableName() + "",
"DROP TABLE " + getFullLockTableName() + ""};
}
return dropSchemaStatements;
}
public String getAddMessageStatement() {
if (addMessageStatement == null) {
addMessageStatement = "INSERT INTO "
+ getFullMessageTableName()
+ "(ID, MSGID_PROD, MSGID_SEQ, CONTAINER, EXPIRATION, PRIORITY, MSG, XID) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
}
return addMessageStatement;
}
public String getUpdateMessageStatement() {
if (updateMessageStatement == null) {
updateMessageStatement = "UPDATE " + getFullMessageTableName() + " SET MSG=? WHERE ID=?";
}
return updateMessageStatement;
}
public String getRemoveMessageStatement() {
if (removeMessageStatement == null) {
removeMessageStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE ID=?";
}
return removeMessageStatement;
}
public String getFindMessageSequenceIdStatement() {
if (findMessageSequenceIdStatement == null) {
findMessageSequenceIdStatement = "SELECT ID, PRIORITY FROM " + getFullMessageTableName()
+ " WHERE MSGID_PROD=? AND MSGID_SEQ=? AND CONTAINER=?";
}
return findMessageSequenceIdStatement;
}
public String getFindMessageStatement() {
if (findMessageStatement == null) {
findMessageStatement = "SELECT MSG FROM " + getFullMessageTableName() + " WHERE MSGID_PROD=? AND MSGID_SEQ=?";
}
return findMessageStatement;
}
public String getFindMessageByIdStatement() {
if (findMessageByIdStatement == null) {
findMessageByIdStatement = "SELECT MSG FROM " + getFullMessageTableName() + " WHERE ID=?";
}
return findMessageByIdStatement;
}
public String getFindXidByIdStatement() {
if (findXidByIdStatement == null) {
findXidByIdStatement = "SELECT XID FROM " + getFullMessageTableName() + " WHERE ID=?";
}
return findXidByIdStatement;
}
public String getFindAllMessagesStatement() {
if (findAllMessagesStatement == null) {
findAllMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName()
+ " WHERE CONTAINER=? ORDER BY ID";
}
return findAllMessagesStatement;
}
public String getFindAllMessageIdsStatement() {
// this needs to be limited maybe need to use getFindLastSequenceIdInMsgsStatement
// and work back for X
if (findAllMessageIdsStatement == null) {
findAllMessageIdsStatement = "SELECT ID, MSGID_PROD, MSGID_SEQ FROM " + getFullMessageTableName()
+ " ORDER BY ID DESC";
}
return findAllMessageIdsStatement;
}
public String getFindLastSequenceIdInMsgsStatement() {
if (findLastSequenceIdInMsgsStatement == null) {
findLastSequenceIdInMsgsStatement = "SELECT MAX(ID) FROM " + getFullMessageTableName();
}
return findLastSequenceIdInMsgsStatement;
}
public String getLastProducerSequenceIdStatement() {
if (lastProducerSequenceIdStatement == null) {
lastProducerSequenceIdStatement = "SELECT MAX(MSGID_SEQ) FROM " + getFullMessageTableName()
+ " WHERE MSGID_PROD=?";
}
return lastProducerSequenceIdStatement;
}
public String getFindLastSequenceIdInAcksStatement() {
if (findLastSequenceIdInAcksStatement == null) {
findLastSequenceIdInAcksStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName();
}
return findLastSequenceIdInAcksStatement;
}
public String getCreateDurableSubStatement() {
if (createDurableSubStatement == null) {
createDurableSubStatement = "INSERT INTO "
+ getFullAckTableName()
+ "(CONTAINER, CLIENT_ID, SUB_NAME, SELECTOR, LAST_ACKED_ID, SUB_DEST, PRIORITY) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
}
return createDurableSubStatement;
}
public String getFindDurableSubStatement() {
if (findDurableSubStatement == null) {
findDurableSubStatement = "SELECT SELECTOR, SUB_DEST " + "FROM " + getFullAckTableName()
+ " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?";
}
return findDurableSubStatement;
}
public String getFindAllDurableSubsStatement() {
if (findAllDurableSubsStatement == null) {
findAllDurableSubsStatement = "SELECT SELECTOR, SUB_NAME, CLIENT_ID, SUB_DEST" + " FROM "
+ getFullAckTableName() + " WHERE CONTAINER=? AND PRIORITY=0";
}
return findAllDurableSubsStatement;
}
public String getUpdateLastPriorityAckRowOfDurableSubStatement() {
if (updateLastPriorityAckRowOfDurableSubStatement == null) {
updateLastPriorityAckRowOfDurableSubStatement = "UPDATE " + getFullAckTableName() + " SET LAST_ACKED_ID=?"
+ " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=? AND PRIORITY=?";
}
return updateLastPriorityAckRowOfDurableSubStatement;
}
public String getDeleteSubscriptionStatement() {
if (deleteSubscriptionStatement == null) {
deleteSubscriptionStatement = "DELETE FROM " + getFullAckTableName()
+ " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?";
}
return deleteSubscriptionStatement;
}
public String getFindAllDurableSubMessagesStatement() {
if (findAllDurableSubMessagesStatement == null) {
findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName()
+ " M, " + getFullAckTableName() + " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"
+ " ORDER BY M.PRIORITY DESC, M.ID";
}
return findAllDurableSubMessagesStatement;
}
public String getFindDurableSubMessagesStatement() {
if (findDurableSubMessagesStatement == null) {
findDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, "
+ getFullAckTableName() + " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.XID IS NULL"
+ " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"
+ " AND M.ID > ?"
+ " ORDER BY M.ID";
}
return findDurableSubMessagesStatement;
}
public String getFindDurableSubMessagesByPriorityStatement() {
if (findDurableSubMessagesByPriorityStatement == null) {
findDurableSubMessagesByPriorityStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M,"
+ " " + getFullAckTableName() + " D"
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.XID IS NULL"
+ " AND M.CONTAINER=D.CONTAINER"
+ " AND M.PRIORITY=D.PRIORITY AND M.ID > D.LAST_ACKED_ID"
+ " AND M.ID > ? AND M.PRIORITY = ?"
+ " ORDER BY M.ID";
}
return findDurableSubMessagesByPriorityStatement;
}
public String findAllDurableSubMessagesStatement() {
if (findAllDurableSubMessagesStatement == null) {
findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName()
+ " M, " + getFullAckTableName() + " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"
+ " ORDER BY M.ID";
}
return findAllDurableSubMessagesStatement;
}
public String getNextDurableSubscriberMessageStatement() {
if (nextDurableSubscriberMessageStatement == null) {
nextDurableSubscriberMessageStatement = "SELECT M.ID, M.MSG FROM "
+ getFullMessageTableName()
+ " M, "
+ getFullAckTableName()
+ " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.CONTAINER=D.CONTAINER AND M.ID > ?"
+ " ORDER BY M.ID ";
}
return nextDurableSubscriberMessageStatement;
}
/**
* @return the durableSubscriberMessageCountStatement
*/
public String getDurableSubscriberMessageCountStatement() {
if (durableSubscriberMessageCountStatement == null) {
durableSubscriberMessageCountStatement = "SELECT COUNT(*) FROM "
+ getFullMessageTableName()
+ " M, "
+ getFullAckTableName()
+ " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.CONTAINER=D.CONTAINER "
+ " AND M.ID >"
+ " ( SELECT LAST_ACKED_ID FROM " + getFullAckTableName()
+ " WHERE CONTAINER=D.CONTAINER AND CLIENT_ID=D.CLIENT_ID"
+ " AND SUB_NAME=D.SUB_NAME )";
}
return durableSubscriberMessageCountStatement;
}
public String getDurableSubscriberMessageCountStatementWithPriority() {
if (durableSubscriberMessageCountStatementWithPriority == null) {
durableSubscriberMessageCountStatementWithPriority = "SELECT COUNT(*) FROM "
+ getFullMessageTableName()
+ " M, "
+ getFullAckTableName()
+ " D "
+ " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?"
+ " AND M.CONTAINER=D.CONTAINER "
+ " AND M.PRIORITY=D.PRIORITY "
+ " AND M.ID > D.LAST_ACKED_ID";
}
return durableSubscriberMessageCountStatementWithPriority;
}
public String getFindAllDestinationsStatement() {
if (findAllDestinationsStatement == null) {
findAllDestinationsStatement = "SELECT DISTINCT CONTAINER FROM " + getFullMessageTableName()
+ " UNION SELECT DISTINCT CONTAINER FROM " + getFullAckTableName();
}
return findAllDestinationsStatement;
}
public String getRemoveAllMessagesStatement() {
if (removeAllMessagesStatement == null) {
removeAllMessagesStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE CONTAINER=?";
}
return removeAllMessagesStatement;
}
public String getRemoveAllSubscriptionsStatement() {
if (removeAllSubscriptionsStatement == null) {
removeAllSubscriptionsStatement = "DELETE FROM " + getFullAckTableName() + " WHERE CONTAINER=?";
}
return removeAllSubscriptionsStatement;
}
public String getDeleteOldMessagesStatementWithPriority() {
if (deleteOldMessagesStatementWithPriority == null) {
deleteOldMessagesStatementWithPriority = "DELETE FROM " + getFullMessageTableName()
+ " WHERE (PRIORITY=? AND ID <= "
+ " ( SELECT min(" + getFullAckTableName() + ".LAST_ACKED_ID)"
+ " FROM " + getFullAckTableName() + " WHERE "
+ getFullAckTableName() + ".CONTAINER="
+ getFullMessageTableName() + ".CONTAINER"
+ " AND " + getFullAckTableName() + ".PRIORITY=?)"
+ " )";
}
return deleteOldMessagesStatementWithPriority;
}
public String getLockCreateStatement() {
if (lockCreateStatement == null) {
lockCreateStatement = "SELECT * FROM " + getFullLockTableName();
if (useLockCreateWhereClause) {
lockCreateStatement += " WHERE ID = 1";
}
lockCreateStatement += " FOR UPDATE";
}
return lockCreateStatement;
}
public String getLeaseObtainStatement() {
if (leaseObtainStatement == null) {
leaseObtainStatement = "UPDATE " + getFullLockTableName()
+ " SET BROKER_NAME=?, TIME=?"
+ " WHERE (TIME IS NULL OR TIME < ?) AND ID = 1";
}
return leaseObtainStatement;
}
public String getCurrentDateTime() {
if (currentDateTimeStatement == null) {
currentDateTimeStatement = "SELECT CURRENT_TIMESTAMP FROM " + getFullLockTableName();
}
return currentDateTimeStatement;
}
public String getLeaseUpdateStatement() {
if (leaseUpdateStatement == null) {
leaseUpdateStatement = "UPDATE " + getFullLockTableName()
+ " SET BROKER_NAME=?, TIME=?"
+ " WHERE BROKER_NAME=? AND ID = 1";
}
return leaseUpdateStatement;
}
public String getLeaseOwnerStatement() {
if (leaseOwnerStatement == null) {
leaseOwnerStatement = "SELECT BROKER_NAME, TIME FROM " + getFullLockTableName()
+ " WHERE ID = 1";
}
return leaseOwnerStatement;
}
public String getLockUpdateStatement() {
if (lockUpdateStatement == null) {
lockUpdateStatement = "UPDATE " + getFullLockTableName() + " SET TIME = ? WHERE ID = 1";
}
return lockUpdateStatement;
}
/**
* @return the destinationMessageCountStatement
*/
public String getDestinationMessageCountStatement() {
if (destinationMessageCountStatement == null) {
destinationMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName()
+ " WHERE CONTAINER=? AND XID IS NULL";
}
return destinationMessageCountStatement;
}
/**
* @return the findNextMessagesStatement
*/
public String getFindNextMessagesStatement() {
if (findNextMessagesStatement == null) {
findNextMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName()
+ " WHERE CONTAINER=? AND ID > ? AND XID IS NULL ORDER BY ID";
}
return findNextMessagesStatement;
}
/**
* @return the findNextMessagesStatement
*/
public String getFindNextMessagesByPriorityStatement() {
if (findNextMessagesByPriorityStatement == null) {
findNextMessagesByPriorityStatement = "SELECT ID, MSG FROM " + getFullMessageTableName()
+ " WHERE CONTAINER=?"
+ " AND XID IS NULL"
+ " AND ((ID > ? AND PRIORITY = ?) OR PRIORITY < ?)"
+ " ORDER BY PRIORITY DESC, ID";
}
return findNextMessagesByPriorityStatement;
}
/**
* @return the lastAckedDurableSubscriberMessageStatement
*/
public String getLastAckedDurableSubscriberMessageStatement() {
if (lastAckedDurableSubscriberMessageStatement == null) {
lastAckedDurableSubscriberMessageStatement = "SELECT MAX(LAST_ACKED_ID) FROM "
+ getFullAckTableName()
+ " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?";
}
return lastAckedDurableSubscriberMessageStatement;
}
public String getSelectDurablePriorityAckStatement() {
if (selectDurablePriorityAckStatement == null) {
selectDurablePriorityAckStatement = "SELECT LAST_ACKED_ID FROM " + getFullAckTableName()
+ " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"
+ " AND PRIORITY = ?";
}
return selectDurablePriorityAckStatement;
}
public String getInsertDurablePriorityAckStatement() {
if (insertDurablePriorityAckStatement == null) {
insertDurablePriorityAckStatement = "INSERT INTO "
+ getFullAckTableName()
+ "(CONTAINER, CLIENT_ID, SUB_NAME, PRIORITY)"
+ " VALUES (?, ?, ?, ?)";
}
return insertDurablePriorityAckStatement;
}
public String getUpdateDurableLastAckStatement() {
if (updateDurableLastAckStatement == null) {
updateDurableLastAckStatement = "UPDATE " + getFullAckTableName()
+ " SET LAST_ACKED_ID=?, XID = NULL WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?";
}
return updateDurableLastAckStatement;
}
public String getUpdateDurableLastAckInTxStatement() {
if (updateDurableLastAckInTxStatement == null) {
updateDurableLastAckInTxStatement = "UPDATE " + getFullAckTableName()
+ " SET XID=? WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?";
}
return updateDurableLastAckInTxStatement;
}
public String getUpdateDurableLastAckWithPriorityStatement() {
if (updateDurableLastAckWithPriorityStatement == null) {
updateDurableLastAckWithPriorityStatement = "UPDATE " + getFullAckTableName()
+ " SET LAST_ACKED_ID=?, XID = NULL WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=? AND PRIORITY=?";
}
return updateDurableLastAckWithPriorityStatement;
}
public String getUpdateDurableLastAckWithPriorityInTxStatement() {
if (updateDurableLastAckWithPriorityInTxStatement == null) {
updateDurableLastAckWithPriorityInTxStatement = "UPDATE " + getFullAckTableName()
+ " SET XID=? WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=? AND PRIORITY=?";
}
return updateDurableLastAckWithPriorityInTxStatement;
}
public String getClearDurableLastAckInTxStatement() {
if (clearDurableLastAckInTxStatement == null) {
clearDurableLastAckInTxStatement = "UPDATE " + getFullAckTableName()
+ " SET XID = NULL WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=? AND PRIORITY=?";
}
return clearDurableLastAckInTxStatement;
}
public String getFindOpsPendingOutcomeStatement() {
if (findOpsPendingOutcomeStatement == null) {
findOpsPendingOutcomeStatement = "SELECT ID, XID, MSG FROM " + getFullMessageTableName()
+ " WHERE XID IS NOT NULL ORDER BY ID";
}
return findOpsPendingOutcomeStatement;
}
public String getFindAcksPendingOutcomeStatement() {
if (findAcksPendingOutcomeStatement == null) {
findAcksPendingOutcomeStatement = "SELECT XID," +
" CONTAINER, CLIENT_ID, SUB_NAME FROM " + getFullAckTableName()
+ " WHERE XID IS NOT NULL";
}
return findAcksPendingOutcomeStatement;
}
public String getUpdateXidFlagStatement() {
if (updateXidFlagStatement == null) {
updateXidFlagStatement = "UPDATE " + getFullMessageTableName()
+ " SET XID = ? WHERE ID = ?";
}
return updateXidFlagStatement;
}
public String getClearXidFlagStatement() {
if (clearXidFlagStatement == null) {
clearXidFlagStatement = "UPDATE " + getFullMessageTableName()
+ " SET XID = NULL WHERE ID = ?";
}
return clearXidFlagStatement;
}
public String getFullMessageTableName() {
return getTablePrefix() + getMessageTableName();
}
public String getFullAckTableName() {
return getTablePrefix() + getDurableSubAcksTableName();
}
public String getFullLockTableName() {
return getTablePrefix() + getLockTableName();
}
/**
* @return Returns the containerNameDataType.
*/
public String getContainerNameDataType() {
return containerNameDataType;
}
/**
* @param containerNameDataType The containerNameDataType to set.
*/
public void setContainerNameDataType(String containerNameDataType) {
this.containerNameDataType = containerNameDataType;
}
/**
* @return Returns the messageDataType.
*/
public String getBinaryDataType() {
return binaryDataType;
}
/**
* @param messageDataType The messageDataType to set.
*/
public void setBinaryDataType(String messageDataType) {
this.binaryDataType = messageDataType;
}
/**
* @return Returns the messageTableName.
*/
public String getMessageTableName() {
return messageTableName;
}
/**
* @param messageTableName The messageTableName to set.
*/
public void setMessageTableName(String messageTableName) {
this.messageTableName = messageTableName;
}
/**
* @return Returns the msgIdDataType.
*/
public String getMsgIdDataType() {
return msgIdDataType;
}
/**
* @param msgIdDataType The msgIdDataType to set.
*/
public void setMsgIdDataType(String msgIdDataType) {
this.msgIdDataType = msgIdDataType;
}
/**
* @return Returns the sequenceDataType.
*/
public String getSequenceDataType() {
return sequenceDataType;
}
/**
* @param sequenceDataType The sequenceDataType to set.
*/
public void setSequenceDataType(String sequenceDataType) {
this.sequenceDataType = sequenceDataType;
}
/**
* @return Returns the tablePrefix.
*/
public String getTablePrefix() {
return tablePrefix;
}
/**
* @param tablePrefix The tablePrefix to set.
*/
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
/**
* @return Returns the durableSubAcksTableName.
*/
public String getDurableSubAcksTableName() {
return durableSubAcksTableName;
}
/**
* @param durableSubAcksTableName The durableSubAcksTableName to set.
*/
public void setDurableSubAcksTableName(String durableSubAcksTableName) {
this.durableSubAcksTableName = durableSubAcksTableName;
}
public String getLockTableName() {
return lockTableName;
}
public void setLockTableName(String lockTableName) {
this.lockTableName = lockTableName;
}
public String getLongDataType() {
return longDataType;
}
public void setLongDataType(String longDataType) {
this.longDataType = longDataType;
}
public String getStringIdDataType() {
return stringIdDataType;
}
public void setStringIdDataType(String stringIdDataType) {
this.stringIdDataType = stringIdDataType;
}
public void setUseExternalMessageReferences(boolean useExternalMessageReferences) {
this.useExternalMessageReferences = useExternalMessageReferences;
}
public boolean isUseExternalMessageReferences() {
return useExternalMessageReferences;
}
public void setAddMessageStatement(String addMessageStatment) {
this.addMessageStatement = addMessageStatment;
}
public void setCreateDurableSubStatement(String createDurableSubStatment) {
this.createDurableSubStatement = createDurableSubStatment;
}
public void setCreateSchemaStatements(String[] createSchemaStatments) {
this.createSchemaStatements = createSchemaStatments;
}
public void setCreateLockSchemaStatements(String[] createLockSchemaStatments) {
this.createLockSchemaStatements = createLockSchemaStatments;
}
public void setDeleteOldMessagesStatementWithPriority(String deleteOldMessagesStatementWithPriority) {
this.deleteOldMessagesStatementWithPriority = deleteOldMessagesStatementWithPriority;
}
public void setDeleteSubscriptionStatement(String deleteSubscriptionStatment) {
this.deleteSubscriptionStatement = deleteSubscriptionStatment;
}
public void setDropSchemaStatements(String[] dropSchemaStatments) {
this.dropSchemaStatements = dropSchemaStatments;
}
public void setFindAllDestinationsStatement(String findAllDestinationsStatment) {
this.findAllDestinationsStatement = findAllDestinationsStatment;
}
public void setFindAllDurableSubMessagesStatement(String findAllDurableSubMessagesStatment) {
this.findAllDurableSubMessagesStatement = findAllDurableSubMessagesStatment;
}
public void setFindAllDurableSubsStatement(String findAllDurableSubsStatment) {
this.findAllDurableSubsStatement = findAllDurableSubsStatment;
}
public void setFindAllMessagesStatement(String findAllMessagesStatment) {
this.findAllMessagesStatement = findAllMessagesStatment;
}
public void setFindDurableSubStatement(String findDurableSubStatment) {
this.findDurableSubStatement = findDurableSubStatment;
}
public void setFindLastSequenceIdInAcksStatement(String findLastSequenceIdInAcks) {
this.findLastSequenceIdInAcksStatement = findLastSequenceIdInAcks;
}
public void setFindLastSequenceIdInMsgsStatement(String findLastSequenceIdInMsgs) {
this.findLastSequenceIdInMsgsStatement = findLastSequenceIdInMsgs;
}
public void setFindMessageSequenceIdStatement(String findMessageSequenceIdStatment) {
this.findMessageSequenceIdStatement = findMessageSequenceIdStatment;
}
public void setFindMessageStatement(String findMessageStatment) {
this.findMessageStatement = findMessageStatment;
}
public void setFindMessageByIdStatement(String findMessageByIdStatement) {
this.findMessageByIdStatement = findMessageByIdStatement;
}
public void setRemoveAllMessagesStatement(String removeAllMessagesStatment) {
this.removeAllMessagesStatement = removeAllMessagesStatment;
}
public void setRemoveAllSubscriptionsStatement(String removeAllSubscriptionsStatment) {
this.removeAllSubscriptionsStatement = removeAllSubscriptionsStatment;
}
public void setRemoveMessageStatment(String removeMessageStatement) {
this.removeMessageStatement = removeMessageStatement;
}
public void setUpdateLastPriorityAckRowOfDurableSubStatement(String updateLastPriorityAckRowOfDurableSubStatement) {
this.updateLastPriorityAckRowOfDurableSubStatement = updateLastPriorityAckRowOfDurableSubStatement;
}
public void setUpdateMessageStatement(String updateMessageStatment) {
this.updateMessageStatement = updateMessageStatment;
}
public boolean isUseLockCreateWhereClause() {
return useLockCreateWhereClause;
}
public void setUseLockCreateWhereClause(boolean useLockCreateWhereClause) {
this.useLockCreateWhereClause = useLockCreateWhereClause;
}
public void setLockCreateStatement(String lockCreateStatement) {
this.lockCreateStatement = lockCreateStatement;
}
public void setLockUpdateStatement(String lockUpdateStatement) {
this.lockUpdateStatement = lockUpdateStatement;
}
/**
* @param findDurableSubMessagesStatement the
* findDurableSubMessagesStatement to set
*/
public void setFindDurableSubMessagesStatement(String findDurableSubMessagesStatement) {
this.findDurableSubMessagesStatement = findDurableSubMessagesStatement;
}
/**
* @param nextDurableSubscriberMessageStatement the nextDurableSubscriberMessageStatement to set
*/
public void setNextDurableSubscriberMessageStatement(String nextDurableSubscriberMessageStatement) {
this.nextDurableSubscriberMessageStatement = nextDurableSubscriberMessageStatement;
}
/**
* @param durableSubscriberMessageCountStatement the durableSubscriberMessageCountStatement to set
*/
public void setDurableSubscriberMessageCountStatement(String durableSubscriberMessageCountStatement) {
this.durableSubscriberMessageCountStatement = durableSubscriberMessageCountStatement;
}
public void setDurableSubscriberMessageCountStatementWithPriority(String durableSubscriberMessageCountStatementWithPriority) {
this.durableSubscriberMessageCountStatementWithPriority = durableSubscriberMessageCountStatementWithPriority;
}
/**
* @param findNextMessagesStatement the findNextMessagesStatement to set
*/
public void setFindNextMessagesStatement(String findNextMessagesStatement) {
this.findNextMessagesStatement = findNextMessagesStatement;
}
/**
* @param destinationMessageCountStatement the destinationMessageCountStatement to set
*/
public void setDestinationMessageCountStatement(String destinationMessageCountStatement) {
this.destinationMessageCountStatement = destinationMessageCountStatement;
}
/**
* @param lastAckedDurableSubscriberMessageStatement the lastAckedDurableSubscriberMessageStatement to set
*/
public void setLastAckedDurableSubscriberMessageStatement(
String lastAckedDurableSubscriberMessageStatement) {
this.lastAckedDurableSubscriberMessageStatement = lastAckedDurableSubscriberMessageStatement;
}
public void setLastProducerSequenceIdStatement(String lastProducerSequenceIdStatement) {
this.lastProducerSequenceIdStatement = lastProducerSequenceIdStatement;
}
public void setSelectDurablePriorityAckStatement(String selectDurablePriorityAckStatement) {
this.selectDurablePriorityAckStatement = selectDurablePriorityAckStatement;
}
public void setInsertDurablePriorityAckStatement(String insertDurablePriorityAckStatement) {
this.insertDurablePriorityAckStatement = insertDurablePriorityAckStatement;
}
public void setUpdateDurableLastAckStatement(String updateDurableLastAckStatement) {
this.updateDurableLastAckStatement = updateDurableLastAckStatement;
}
public void setUpdateXidFlagStatement(String updateXidFlagStatement) {
this.updateXidFlagStatement = updateXidFlagStatement;
}
public void setFindOpsPendingOutcomeStatement(String findOpsPendingOutcomeStatement) {
this.findOpsPendingOutcomeStatement = findOpsPendingOutcomeStatement;
}
public void setClearXidFlagStatement(String clearXidFlagStatement) {
this.clearXidFlagStatement = clearXidFlagStatement;
}
public void setUpdateDurableLastAckInTxStatement(String updateDurableLastAckInTxStatement) {
this.updateDurableLastAckInTxStatement = updateDurableLastAckInTxStatement;
}
public void setFindAcksPendingOutcomeStatement(String findAcksPendingOutcomeStatement) {
this.findAcksPendingOutcomeStatement = findAcksPendingOutcomeStatement;
}
public void setClearDurableLastAckInTxStatement(String clearDurableLastAckInTxStatement) {
this.clearDurableLastAckInTxStatement = clearDurableLastAckInTxStatement;
}
public void setUpdateDurableLastAckWithPriorityStatement(String updateDurableLastAckWithPriorityStatement) {
this.updateDurableLastAckWithPriorityStatement = updateDurableLastAckWithPriorityStatement;
}
public void setUpdateDurableLastAckWithPriorityInTxStatement(String updateDurableLastAckWithPriorityInTxStatement) {
this.updateDurableLastAckWithPriorityInTxStatement = updateDurableLastAckWithPriorityInTxStatement;
}
public void setFindXidByIdStatement(String findXidByIdStatement) {
this.findXidByIdStatement = findXidByIdStatement;
}
public void setLeaseObtainStatement(String leaseObtainStatement) {
this.leaseObtainStatement = leaseObtainStatement;
}
public void setCurrentDateTimeStatement(String currentDateTimeStatement) {
this.currentDateTimeStatement = currentDateTimeStatement;
}
public void setLeaseUpdateStatement(String leaseUpdateStatement) {
this.leaseUpdateStatement = leaseUpdateStatement;
}
public void setLeaseOwnerStatement(String leaseOwnerStatement) {
this.leaseOwnerStatement = leaseOwnerStatement;
}
} | epl-1.0 |
Yakindu/statecharts | test-plugins/org.yakindu.sct.model.stext.test/src/org/yakindu/sct/model/stext/test/util/AbstractSTextTest.java | 2240 | /**
* Copyright (c) 2012 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* committers of YAKINDU - initial API and implementation
*/
package org.yakindu.sct.model.stext.test.util;
import org.eclipse.emf.ecore.EObject;
import org.yakindu.sct.model.stext.expressions.IExpressionParser;
import com.google.inject.Inject;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public abstract class AbstractSTextTest {
@Inject
private IExpressionParser expressionParser;
protected EObject parseExpression(String expression, String ruleName) {
return expressionParser.parseExpression(expression, ruleName);
}
protected EObject parseExpression(String expression, String ruleName, String scope) {
return expressionParser.parseExpression(expression, ruleName, scope);
}
/**
* <pre>
* internal:
* operation voidOp()
* operation intOp():integer
* var intVar : integer
* var boolVar : boolean
* var realVar : real
* var stringVar : string
* event intEvent : integer
* event boolEvent : boolean
* event realEvent : real
* event stringEvent : string
* event voidEvent : void"
* </pre>
*/
public String internalScope() {
return "internal: operation voidOp() operation intOp():integer var intVar : integer var boolVar : boolean var realVar : real var stringVar : string event intEvent : integer event boolEvent : boolean event realEvent : real event stringEvent : string event voidEvent : void";
}
/**
* <pre>
* interface ABC :
* operation paramOp(param1 : integer, param2 : boolean ) : string
* operation stringOp()
* in event voidEvent
* in event intEvent : integer
* var intVar : integer
* var boolVar : boolean
* </pre>
*/
public String interfaceScope() {
return "interface ABC : operation paramOp(param1 : integer, param2 : boolean ) : string operation stringOp() in event voidEvent in event intEvent : integer var intVar : integer var boolVar : boolean";
}
}
| epl-1.0 |
sschafer/atomic | org.allmyinfo.operation.nodes.core/src/org/allmyinfo/operation/nodes/core/GetNodeByUniqueDatumWithCreateOption.java | 1913 | package org.allmyinfo.operation.nodes.core;
import org.allmyinfo.nodes.Datum;
import org.allmyinfo.nodes.NodeId;
import org.allmyinfo.operation.Operation;
import org.allmyinfo.operation.PathElement;
import org.allmyinfo.operation.nodes.NodesExecutionContext;
import org.allmyinfo.operation.nodes.NodesOperation;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
public final class GetNodeByUniqueDatumWithCreateOption extends NodesOperation {
public final @NonNull Operation datumOp;
public final @NonNull Operation createOp;
public GetNodeByUniqueDatumWithCreateOption(final @NonNull Operation datumOp,
final @NonNull Operation createOp) {
this.datumOp = datumOp;
this.createOp = createOp;
}
@Override
public @NonNull Class<?> returns() {
return NodeId.class;
}
@Override
public boolean canReturnNull() {
return false;
}
@Override
protected @Nullable Object execute(final @NonNull PathElement parentPathElement,
final @NonNull NodesExecutionContext context) {
final PathElement pathElement = new PathElement("getNodeByUniqueDatumWithCreateOption",
parentPathElement);
final Datum datum = (Datum) datumOp.execute(pathElement, context);
if (datum == null)
throw new NullPointerException("Datum operand is missing");
final Boolean create = (Boolean) createOp.execute(pathElement, context);
if (create == null)
throw new NullPointerException("Create operand is missing");
final NodeId result = context.getTxn().getNode(datum, create.booleanValue());
return result;
}
@Override
public @NonNull String getName() {
return "getNodeByUniqueDatum";
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getName());
sb.append("(");
sb.append("datum=");
sb.append(datumOp);
sb.append(", create=");
sb.append(createOp);
sb.append(")");
return sb.toString();
}
}
| epl-1.0 |
debabratahazra/OptimaLA | LogAnalyzer/com.zealcore.se.ui/src/com/zealcore/se/ui/actions/OpenGanttOverviewAction.java | 313 | package com.zealcore.se.ui.actions;
import com.zealcore.se.ui.editors.GanttOverviewChart;
public class OpenGanttOverviewAction extends AbstractOpenBrowserAction {
public OpenGanttOverviewAction() {}
@Override
protected String getBrowserId() {
return GanttOverviewChart.BROWSER_ID;
}
}
| epl-1.0 |
abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.grammar/src-gen/com/abstratt/mdd/frontend/textuml/grammar/node/AOptionalParameterName.java | 2036 | /* This file was generated by SableCC (http://www.sablecc.org/). */
package com.abstratt.mdd.frontend.textuml.grammar.node;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.*;
@SuppressWarnings("nls")
public final class AOptionalParameterName extends POptionalParameterName
{
private TIdentifier _identifier_;
public AOptionalParameterName()
{
// Constructor
}
public AOptionalParameterName(
@SuppressWarnings("hiding") TIdentifier _identifier_)
{
// Constructor
setIdentifier(_identifier_);
}
@Override
public Object clone()
{
return new AOptionalParameterName(
cloneNode(this._identifier_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseAOptionalParameterName(this);
}
public TIdentifier getIdentifier()
{
return this._identifier_;
}
public void setIdentifier(TIdentifier node)
{
if(this._identifier_ != null)
{
this._identifier_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._identifier_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._identifier_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._identifier_ == child)
{
this._identifier_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._identifier_ == oldChild)
{
setIdentifier((TIdentifier) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| epl-1.0 |
SoLoHiC/chddt | CHDDiagnosticTool/src/cn/ynu/java/dm/transformer/AttributeArrayToRule.java | 1305 | package cn.ynu.java.dm.transformer;
import java.util.Set;
import cn.ynu.java.dm.model.AttributeArray;
import cn.ynu.java.dm.model.ProbabilityDictionary;
import com.sin.chd.base.pipe.ArgumentDescribe;
/**
* ๅฑๆงๆฐ็ป่ฝฌ่งๅ
*
* @author RobinTang
*
*/
public class AttributeArrayToRule extends BaseTransformer {
/**
* ๅฑๆงๆฐ็ป่ฝฌ่งๅ
*/
public AttributeArrayToRule() {
super("ๅฑๆงๆฐ็ป่ฝฌ่งๅ", "", ArgumentDescribe.objectList("ๅฑๆงๆฐ็ป"), ArgumentDescribe.objectDictionary("ๆฆ็ๅญๅ
ธ"));
}
@Override
public Object calculate(Object input) {
AttributeArray dep = (AttributeArray) input;
Set<String> ats = dep.getAttributeSet(null, null, null);
Set<String> clss = dep.getClassifySet();
ProbabilityDictionary ret = new ProbabilityDictionary();
for (String at : ats) {
for (String cls : clss) {
AttributeArray aa = dep.filterArray(cls, at, null);
Set<String> vs = aa.getValueSet();
for (String v : vs) {
int ct = aa.getCount(cls, at, v);
int al = dep.getCount(cls, null, null);
double pt = (double) ct / (double) al;
String k = String.format(ProbabilityDictionary.classifyAttrivuteValueFormat, cls, at, v);
ret.setProbability(k, pt);
}
}
}
return ret;
}
}
| epl-1.0 |
ossmeter/ossmeter | third-party/org.mapdb/src/main/java/org/mapdb/CC.java | 1915 | /*
* Copyright (c) 2012 Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapdb;
/**
* Compiler Configuration. There are some static final boolean fields, which describe features MapDB was compiled with.
* <p/>
* MapDB can be compiled with/without some features. For example fine logging is useful for debuging,
* but should not be present in production version. Java does not have preprocessor so
* we use <a href="http://en.wikipedia.org/wiki/Dead_code_elimination">Dead code elimination</a> to achieve it.
* <p/>
* Typical usage:
* <pre>
* if(CC.PARANOID && arg.calculateSize()!=33){ //calculateSize may take long time
* throw new IllegalArgumentException("wrong size");
* }
* </pre>
*
* @author Jan Kotek
*/
public interface CC {
/**
* Compile with more assertions and verifications.
* For example HashMap may check if keys implements hash function correctly.
* This may slow down MapDB thousands times
*/
boolean PARANOID = false;
/**
* Compile with fine trace logging statements (Logger.debug and Logger.trace).
*/
boolean LOG_TRACE = false;
/**
* Log lock/unlock events. Useful to diagnose deadlocks
*/
boolean LOG_LOCKS = false;
/**
* If true MapDB will display warnings if user is using MapDB API wrong way.
*/
boolean LOG_HINTS = true;
}
| epl-1.0 |
peterkir/org.eclipse.oomph | plugins/org.eclipse.oomph.setup.targlets/src/org/eclipse/oomph/setup/targlets/impl/TargletTaskImpl.java | 34414 | /*
* Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.setup.targlets.impl;
import org.eclipse.oomph.base.BaseFactory;
import org.eclipse.oomph.base.util.BaseUtil;
import org.eclipse.oomph.p2.Repository;
import org.eclipse.oomph.p2.RepositoryList;
import org.eclipse.oomph.p2.internal.core.CacheUsageConfirmer;
import org.eclipse.oomph.setup.SetupTask;
import org.eclipse.oomph.setup.SetupTaskContext;
import org.eclipse.oomph.setup.Trigger;
import org.eclipse.oomph.setup.impl.SetupTaskImpl;
import org.eclipse.oomph.setup.targlets.ImplicitDependency;
import org.eclipse.oomph.setup.targlets.SetupTargletsFactory;
import org.eclipse.oomph.setup.targlets.SetupTargletsPackage;
import org.eclipse.oomph.setup.targlets.TargletTask;
import org.eclipse.oomph.targlets.Targlet;
import org.eclipse.oomph.targlets.TargletFactory;
import org.eclipse.oomph.targlets.core.ITargletContainer;
import org.eclipse.oomph.targlets.internal.core.TargletContainer;
import org.eclipse.oomph.targlets.internal.core.TargletsCorePlugin;
import org.eclipse.oomph.targlets.internal.core.WorkspaceIUImporter;
import org.eclipse.oomph.util.ObjectUtil;
import org.eclipse.oomph.util.StringUtil;
import org.eclipse.oomph.util.pde.TargetPlatformRunnable;
import org.eclipse.oomph.util.pde.TargetPlatformUtil;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.ECollections;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.equinox.p2.metadata.Version;
import org.eclipse.pde.core.target.ITargetDefinition;
import org.eclipse.pde.core.target.ITargetHandle;
import org.eclipse.pde.core.target.ITargetLocation;
import org.eclipse.pde.core.target.ITargetPlatformService;
import org.eclipse.pde.core.target.NameVersionDescriptor;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Targlet Task</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getTarglets <em>Targlets</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getTargletURIs <em>Targlet UR Is</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getOperatingSystem <em>Operating System</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getWindowingSystem <em>Windowing System</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getArchitecture <em>Architecture</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getLocale <em>Locale</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getProgramArguments <em>Program Arguments</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getVMArguments <em>VM Arguments</em>}</li>
* <li>{@link org.eclipse.oomph.setup.targlets.impl.TargletTaskImpl#getImplicitDependencies <em>Implicit Dependencies</em>}</li>
* </ul>
*
* @generated
*/
public class TargletTaskImpl extends SetupTaskImpl implements TargletTask
{
private static final String TARGET_DEFINITION_NAME = "Modular Target";
private static final String TARGLET_CONTAINER_ID = "Oomph";
/**
* The cached value of the '{@link #getTarglets() <em>Targlets</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTarglets()
* @generated
* @ordered
*/
protected EList<Targlet> targlets;
/**
* The cached value of the '{@link #getTargletURIs() <em>Targlet UR Is</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTargletURIs()
* @generated
* @ordered
*/
protected EList<String> targletURIs;
/**
* The default value of the '{@link #getOperatingSystem() <em>Operating System</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperatingSystem()
* @generated
* @ordered
*/
protected static final String OPERATING_SYSTEM_EDEFAULT = null;
/**
* The cached value of the '{@link #getOperatingSystem() <em>Operating System</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperatingSystem()
* @generated
* @ordered
*/
protected String operatingSystem = OPERATING_SYSTEM_EDEFAULT;
/**
* The default value of the '{@link #getWindowingSystem() <em>Windowing System</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getWindowingSystem()
* @generated
* @ordered
*/
protected static final String WINDOWING_SYSTEM_EDEFAULT = null;
/**
* The cached value of the '{@link #getWindowingSystem() <em>Windowing System</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getWindowingSystem()
* @generated
* @ordered
*/
protected String windowingSystem = WINDOWING_SYSTEM_EDEFAULT;
/**
* The default value of the '{@link #getArchitecture() <em>Architecture</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArchitecture()
* @generated
* @ordered
*/
protected static final String ARCHITECTURE_EDEFAULT = null;
/**
* The cached value of the '{@link #getArchitecture() <em>Architecture</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArchitecture()
* @generated
* @ordered
*/
protected String architecture = ARCHITECTURE_EDEFAULT;
/**
* The default value of the '{@link #getLocale() <em>Locale</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocale()
* @generated
* @ordered
*/
protected static final String LOCALE_EDEFAULT = null;
/**
* The cached value of the '{@link #getLocale() <em>Locale</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocale()
* @generated
* @ordered
*/
protected String locale = LOCALE_EDEFAULT;
/**
* The default value of the '{@link #getProgramArguments() <em>Program Arguments</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProgramArguments()
* @generated
* @ordered
*/
protected static final String PROGRAM_ARGUMENTS_EDEFAULT = null;
/**
* The cached value of the '{@link #getProgramArguments() <em>Program Arguments</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProgramArguments()
* @generated
* @ordered
*/
protected String programArguments = PROGRAM_ARGUMENTS_EDEFAULT;
/**
* The default value of the '{@link #getVMArguments() <em>VM Arguments</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getVMArguments()
* @generated
* @ordered
*/
protected static final String VM_ARGUMENTS_EDEFAULT = null;
/**
* The cached value of the '{@link #getVMArguments() <em>VM Arguments</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getVMArguments()
* @generated
* @ordered
*/
protected String vMArguments = VM_ARGUMENTS_EDEFAULT;
/**
* The cached value of the '{@link #getImplicitDependencies() <em>Implicit Dependencies</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImplicitDependencies()
* @generated
* @ordered
*/
protected EList<ImplicitDependency> implicitDependencies;
private ITargletContainer targletContainer;
private ITargetDefinition targetDefinition;
private EList<Targlet> copyTarglets;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TargletTaskImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return SetupTargletsPackage.Literals.TARGLET_TASK;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Targlet> getTarglets()
{
if (targlets == null)
{
targlets = new EObjectContainmentEList<Targlet>(Targlet.class, this, SetupTargletsPackage.TARGLET_TASK__TARGLETS);
}
return targlets;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<String> getTargletURIs()
{
if (targletURIs == null)
{
targletURIs = new EDataTypeUniqueEList<String>(String.class, this, SetupTargletsPackage.TARGLET_TASK__TARGLET_UR_IS);
}
return targletURIs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getOperatingSystem()
{
return operatingSystem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOperatingSystem(String newOperatingSystem)
{
String oldOperatingSystem = operatingSystem;
operatingSystem = newOperatingSystem;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__OPERATING_SYSTEM, oldOperatingSystem, operatingSystem));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getWindowingSystem()
{
return windowingSystem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setWindowingSystem(String newWindowingSystem)
{
String oldWindowingSystem = windowingSystem;
windowingSystem = newWindowingSystem;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__WINDOWING_SYSTEM, oldWindowingSystem, windowingSystem));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getArchitecture()
{
return architecture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setArchitecture(String newArchitecture)
{
String oldArchitecture = architecture;
architecture = newArchitecture;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__ARCHITECTURE, oldArchitecture, architecture));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLocale()
{
return locale;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLocale(String newLocale)
{
String oldLocale = locale;
locale = newLocale;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__LOCALE, oldLocale, locale));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getProgramArguments()
{
return programArguments;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setProgramArguments(String newProgramArguments)
{
String oldProgramArguments = programArguments;
programArguments = newProgramArguments;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__PROGRAM_ARGUMENTS, oldProgramArguments, programArguments));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getVMArguments()
{
return vMArguments;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setVMArguments(String newVMArguments)
{
String oldVMArguments = vMArguments;
vMArguments = newVMArguments;
if (eNotificationRequired())
{
eNotify(new ENotificationImpl(this, Notification.SET, SetupTargletsPackage.TARGLET_TASK__VM_ARGUMENTS, oldVMArguments, vMArguments));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ImplicitDependency> getImplicitDependencies()
{
if (implicitDependencies == null)
{
implicitDependencies = new EObjectContainmentEList<ImplicitDependency>(ImplicitDependency.class, this,
SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES);
}
return implicitDependencies;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case SetupTargletsPackage.TARGLET_TASK__TARGLETS:
return ((InternalEList<?>)getTarglets()).basicRemove(otherEnd, msgs);
case SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES:
return ((InternalEList<?>)getImplicitDependencies()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case SetupTargletsPackage.TARGLET_TASK__TARGLETS:
return getTarglets();
case SetupTargletsPackage.TARGLET_TASK__TARGLET_UR_IS:
return getTargletURIs();
case SetupTargletsPackage.TARGLET_TASK__OPERATING_SYSTEM:
return getOperatingSystem();
case SetupTargletsPackage.TARGLET_TASK__WINDOWING_SYSTEM:
return getWindowingSystem();
case SetupTargletsPackage.TARGLET_TASK__ARCHITECTURE:
return getArchitecture();
case SetupTargletsPackage.TARGLET_TASK__LOCALE:
return getLocale();
case SetupTargletsPackage.TARGLET_TASK__PROGRAM_ARGUMENTS:
return getProgramArguments();
case SetupTargletsPackage.TARGLET_TASK__VM_ARGUMENTS:
return getVMArguments();
case SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES:
return getImplicitDependencies();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case SetupTargletsPackage.TARGLET_TASK__TARGLETS:
getTarglets().clear();
getTarglets().addAll((Collection<? extends Targlet>)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__TARGLET_UR_IS:
getTargletURIs().clear();
getTargletURIs().addAll((Collection<? extends String>)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__OPERATING_SYSTEM:
setOperatingSystem((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__WINDOWING_SYSTEM:
setWindowingSystem((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__ARCHITECTURE:
setArchitecture((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__LOCALE:
setLocale((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__PROGRAM_ARGUMENTS:
setProgramArguments((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__VM_ARGUMENTS:
setVMArguments((String)newValue);
return;
case SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES:
getImplicitDependencies().clear();
getImplicitDependencies().addAll((Collection<? extends ImplicitDependency>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SetupTargletsPackage.TARGLET_TASK__TARGLETS:
getTarglets().clear();
return;
case SetupTargletsPackage.TARGLET_TASK__TARGLET_UR_IS:
getTargletURIs().clear();
return;
case SetupTargletsPackage.TARGLET_TASK__OPERATING_SYSTEM:
setOperatingSystem(OPERATING_SYSTEM_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__WINDOWING_SYSTEM:
setWindowingSystem(WINDOWING_SYSTEM_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__ARCHITECTURE:
setArchitecture(ARCHITECTURE_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__LOCALE:
setLocale(LOCALE_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__PROGRAM_ARGUMENTS:
setProgramArguments(PROGRAM_ARGUMENTS_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__VM_ARGUMENTS:
setVMArguments(VM_ARGUMENTS_EDEFAULT);
return;
case SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES:
getImplicitDependencies().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case SetupTargletsPackage.TARGLET_TASK__TARGLETS:
return targlets != null && !targlets.isEmpty();
case SetupTargletsPackage.TARGLET_TASK__TARGLET_UR_IS:
return targletURIs != null && !targletURIs.isEmpty();
case SetupTargletsPackage.TARGLET_TASK__OPERATING_SYSTEM:
return OPERATING_SYSTEM_EDEFAULT == null ? operatingSystem != null : !OPERATING_SYSTEM_EDEFAULT.equals(operatingSystem);
case SetupTargletsPackage.TARGLET_TASK__WINDOWING_SYSTEM:
return WINDOWING_SYSTEM_EDEFAULT == null ? windowingSystem != null : !WINDOWING_SYSTEM_EDEFAULT.equals(windowingSystem);
case SetupTargletsPackage.TARGLET_TASK__ARCHITECTURE:
return ARCHITECTURE_EDEFAULT == null ? architecture != null : !ARCHITECTURE_EDEFAULT.equals(architecture);
case SetupTargletsPackage.TARGLET_TASK__LOCALE:
return LOCALE_EDEFAULT == null ? locale != null : !LOCALE_EDEFAULT.equals(locale);
case SetupTargletsPackage.TARGLET_TASK__PROGRAM_ARGUMENTS:
return PROGRAM_ARGUMENTS_EDEFAULT == null ? programArguments != null : !PROGRAM_ARGUMENTS_EDEFAULT.equals(programArguments);
case SetupTargletsPackage.TARGLET_TASK__VM_ARGUMENTS:
return VM_ARGUMENTS_EDEFAULT == null ? vMArguments != null : !VM_ARGUMENTS_EDEFAULT.equals(vMArguments);
case SetupTargletsPackage.TARGLET_TASK__IMPLICIT_DEPENDENCIES:
return implicitDependencies != null && !implicitDependencies.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy())
{
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (targletURIs: ");
result.append(targletURIs);
result.append(", operatingSystem: ");
result.append(operatingSystem);
result.append(", windowingSystem: ");
result.append(windowingSystem);
result.append(", architecture: ");
result.append(architecture);
result.append(", locale: ");
result.append(locale);
result.append(", programArguments: ");
result.append(programArguments);
result.append(", vMArguments: ");
result.append(vMArguments);
result.append(')');
return result.toString();
}
@Override
public Object getOverrideToken()
{
return createToken(TARGLET_CONTAINER_ID);
}
@Override
public void overrideFor(SetupTask overriddenSetupTask)
{
super.overrideFor(overriddenSetupTask);
TargletTask targletTask = (TargletTask)overriddenSetupTask;
getTarglets().addAll(targletTask.getTarglets());
mergeSetting(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__OPERATING_SYSTEM, "operating systems");
mergeSetting(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__WINDOWING_SYSTEM, "windowing systems");
mergeSetting(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__ARCHITECTURE, "architectures");
mergeSetting(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__LOCALE, "locales");
mergeArguments(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__PROGRAM_ARGUMENTS);
mergeArguments(targletTask, SetupTargletsPackage.Literals.TARGLET_TASK__VM_ARGUMENTS);
getImplicitDependencies().addAll(targletTask.getImplicitDependencies());
}
private void mergeSetting(TargletTask overriddenTargletTask, EAttribute attribute, String errorLabel)
{
String overridingValue = (String)eGet(attribute);
String overriddenValue = (String)overriddenTargletTask.eGet(attribute);
if (!ObjectUtil.equals(overridingValue, overriddenValue))
{
if (overridingValue == null)
{
eSet(attribute, overriddenValue);
}
else
{
if (overriddenValue != null)
{
getAnnotations()
.add(BaseFactory.eINSTANCE.createErrorAnnotation("The " + errorLabel + " '" + overriddenValue + "' and '" + overridingValue + "' collide."));
}
}
}
}
private void mergeArguments(TargletTask overriddenTargletTask, EAttribute attribute)
{
String overridingValue = sanitizeArguments((String)eGet(attribute));
String overriddenValue = sanitizeArguments((String)overriddenTargletTask.eGet(attribute));
if (overridingValue != null)
{
if (overriddenValue != null)
{
eSet(attribute, overriddenValue + StringUtil.NL + overridingValue);
}
else
{
eSet(attribute, overridingValue);
}
}
}
private String sanitizeArguments(String arguments)
{
if (StringUtil.isEmpty(arguments))
{
return null;
}
return arguments.trim().replaceAll("(\n\r?|\r\n?)", StringUtil.NL);
}
@Override
public void consolidate()
{
super.consolidate();
Set<String> targletNames = new HashSet<String>();
EList<Targlet> targlets = getTarglets();
LOOP: for (Iterator<Targlet> it = targlets.iterator(); it.hasNext();)
{
Targlet targlet = it.next();
BaseUtil.setReduced(targlet, true);
String name = targlet.getName();
if (StringUtil.isEmpty(name) || !targletNames.add(name))
{
it.remove();
}
else if (targlet.getRequirements().isEmpty() && targlet.getSourceLocators().isEmpty())
{
// Eliminate targlets that are effectively empty, i.e., no requirements, no source locators, and the active repository list is empty.
String activeRepositoryList = targlet.getActiveRepositoryListName();
for (RepositoryList repositoryList : targlet.getRepositoryLists())
{
if (ObjectUtil.equals(activeRepositoryList, repositoryList.getName()))
{
if (repositoryList.getRepositories().isEmpty())
{
it.remove();
continue LOOP;
}
}
}
}
}
ECollections.sort(targlets, new Comparator<Targlet>()
{
public int compare(Targlet o1, Targlet o2)
{
return StringUtil.safe(o1.getName()).compareTo(StringUtil.safe(o2.getName()));
}
});
// Use a set to eliminate duplicates from the implicit dependencies.
EList<ImplicitDependency> implicitDependencies = getImplicitDependencies();
Set<NameVersionDescriptor> descriptors = createNameVersionDescriptors(implicitDependencies);
implicitDependencies.clear();
for (NameVersionDescriptor descriptor : descriptors)
{
String id = descriptor.getId();
String version = descriptor.getVersion();
ImplicitDependency implicitDependency = SetupTargletsFactory.eINSTANCE.createImplicitDependency(id, version);
implicitDependencies.add(implicitDependency);
}
ECollections.sort(implicitDependencies, new Comparator<ImplicitDependency>()
{
public int compare(ImplicitDependency o1, ImplicitDependency o2)
{
int result = StringUtil.safe(o1.getID()).compareTo(StringUtil.safe(o2.getID()));
if (result == 0)
{
Version v1 = o1.getVersion();
if (v1 == null)
{
v1 = Version.emptyVersion;
}
Version v2 = o2.getVersion();
if (v2 == null)
{
v2 = Version.emptyVersion;
}
result = v1.compareTo(v2);
}
return result;
}
});
setProgramArguments(sanitizeArguments(getProgramArguments()));
setVMArguments(sanitizeArguments(getVMArguments()));
}
@Override
public int getProgressMonitorWork()
{
return 100;
}
public boolean isNeeded(final SetupTaskContext context) throws Exception
{
copyTarglets = TargletFactory.eINSTANCE.copyTarglets(getTarglets());
return TargetPlatformUtil.runWithTargetPlatformService(new TargetPlatformRunnable<Boolean>()
{
public Boolean run(ITargetPlatformService service) throws CoreException
{
ITargetHandle activeTargetHandle = service.getWorkspaceTargetHandle();
targetDefinition = getTargetDefinition(service, context.getProgressMonitor(true));
if (targetDefinition == null)
{
return hasRequirements(copyTarglets);
}
targletContainer = getTargletContainer();
if (targletContainer == null)
{
return hasRequirements(copyTarglets);
}
else if (!hasRequirements(copyTarglets) && !hasRequirements(targletContainer.getTarglets()))
{
return false;
}
for (Targlet targlet : copyTarglets)
{
Targlet existingTarglet = targletContainer.getTarglet(targlet.getName());
if (existingTarglet == null || !EcoreUtil.equals(existingTarglet, targlet))
{
return true;
}
}
if (context.getTrigger() == Trigger.MANUAL)
{
return true;
}
if (!targetDefinition.getHandle().equals(activeTargetHandle))
{
return true;
}
if (!ObjectUtil.equals(targetDefinition.getOS(), getOperatingSystem()) //
|| !ObjectUtil.equals(targetDefinition.getWS(), getWindowingSystem()) //
|| !ObjectUtil.equals(targetDefinition.getArch(), getArchitecture()) //
|| !ObjectUtil.equals(targetDefinition.getNL(), getLocale()) //
|| !ObjectUtil.equals(targetDefinition.getProgramArguments(), getProgramArguments()) //
|| !ObjectUtil.equals(targetDefinition.getVMArguments(), getVMArguments()) //
|| !equalNameVersionDescriptors(targetDefinition.getImplicitDependencies(), getImplicitDependencies()))
{
return true;
}
return false;
}
});
}
public void perform(final SetupTaskContext context) throws Exception
{
for (Targlet targlet : copyTarglets)
{
for (Repository p2Repository : targlet.getActiveRepositories())
{
context.log("Using " + p2Repository.getURL());
}
}
boolean offline = context.isOffline();
context.log("Offline = " + offline);
boolean mirrors = context.isMirrors();
context.log("Mirrors = " + mirrors);
TargetPlatformUtil.runWithTargetPlatformService(new TargetPlatformRunnable<Object>()
{
public Object run(ITargetPlatformService service) throws CoreException
{
IProgressMonitor monitor = context.getProgressMonitor(true);
monitor.beginTask("", 100 + (targetDefinition == null ? 1 : 0));
try
{
if (targetDefinition == null)
{
targetDefinition = getTargetDefinition(service, new SubProgressMonitor(monitor, 1));
}
if (targetDefinition == null)
{
targetDefinition = service.newTarget();
targetDefinition.setName(TARGET_DEFINITION_NAME);
}
targetDefinition.setOS(getOperatingSystem());
targetDefinition.setWS(getWindowingSystem());
targetDefinition.setArch(getArchitecture());
targetDefinition.setNL(getLocale());
targetDefinition.setProgramArguments(getProgramArguments());
targetDefinition.setVMArguments(getVMArguments());
targetDefinition.setImplicitDependencies(getNameVersionDescriptors());
if (targletContainer == null)
{
targletContainer = getTargletContainer();
}
EList<Targlet> targlets = copyTarglets;
if (targletContainer == null)
{
targletContainer = new TargletContainer(TARGLET_CONTAINER_ID);
ITargetLocation[] newLocations;
ITargetLocation[] oldLocations = targetDefinition.getTargetLocations();
if (oldLocations != null && oldLocations.length != 0)
{
newLocations = new ITargetLocation[oldLocations.length + 1];
System.arraycopy(oldLocations, 0, newLocations, 0, oldLocations.length);
newLocations[oldLocations.length] = targletContainer;
}
else
{
newLocations = new ITargetLocation[] { targletContainer };
}
targetDefinition.setTargetLocations(newLocations);
}
boolean mirrors = context.isMirrors();
CacheUsageConfirmer cacheUsageConfirmer = (CacheUsageConfirmer)context.get(CacheUsageConfirmer.class);
CacheUsageConfirmer oldCacheUsageConfirmer = TargletsCorePlugin.INSTANCE.getCacheUsageConfirmer();
try
{
TargletsCorePlugin.INSTANCE.setCacheUsageConfirmer(cacheUsageConfirmer);
targletContainer.setTarglets(targlets);
targletContainer.forceUpdate(true, mirrors, new SubProgressMonitor(monitor, 90));
try
{
Job.getJobManager().join(WorkspaceIUImporter.WORKSPACE_IU_IMPORT_FAMILY, new SubProgressMonitor(monitor, 10));
}
catch (InterruptedException ex)
{
TargletsCorePlugin.INSTANCE.coreException(ex);
}
}
finally
{
TargletsCorePlugin.INSTANCE.setCacheUsageConfirmer(oldCacheUsageConfirmer);
}
return null;
}
finally
{
monitor.done();
}
}
});
}
private ITargetDefinition getTargetDefinition(ITargetPlatformService service, IProgressMonitor monitor) throws CoreException
{
for (ITargetHandle targetHandle : service.getTargets(monitor))
{
ITargetDefinition targetDefinition = targetHandle.getTargetDefinition();
if (TARGET_DEFINITION_NAME.equals(targetDefinition.getName()))
{
return targetDefinition;
}
}
return null;
}
private ITargletContainer getTargletContainer()
{
ITargetLocation[] locations = targetDefinition.getTargetLocations();
if (locations != null)
{
for (ITargetLocation location : locations)
{
if (location instanceof ITargletContainer)
{
ITargletContainer targletContainer = (ITargletContainer)location;
if (TARGLET_CONTAINER_ID.equals(targletContainer.getID()))
{
return targletContainer;
}
}
}
}
return null;
}
private NameVersionDescriptor[] getNameVersionDescriptors()
{
EList<ImplicitDependency> implicitDependencies = getImplicitDependencies();
if (implicitDependencies.isEmpty())
{
return null;
}
Set<NameVersionDescriptor> descriptors = createNameVersionDescriptors(implicitDependencies);
return descriptors.toArray(new NameVersionDescriptor[descriptors.size()]);
}
private static Set<NameVersionDescriptor> createNameVersionDescriptors(Collection<ImplicitDependency> implicitDependencies)
{
Set<NameVersionDescriptor> result = new LinkedHashSet<NameVersionDescriptor>();
for (ImplicitDependency implicitDependency : implicitDependencies)
{
String id = implicitDependency.getID();
if (!StringUtil.isEmpty(id))
{
Version version = implicitDependency.getVersion();
result.add(new NameVersionDescriptor(id, version == null ? null : version.toString()));
}
}
return result;
}
private static boolean equalNameVersionDescriptors(NameVersionDescriptor[] targetImplicitDependencies, EList<ImplicitDependency> targletImplicitDependencies)
{
Set<NameVersionDescriptor> targetSet = new HashSet<NameVersionDescriptor>();
if (targetImplicitDependencies != null)
{
for (int i = 0; i < targetImplicitDependencies.length; i++)
{
targetSet.add(targetImplicitDependencies[i]);
}
}
Set<NameVersionDescriptor> targletSet = createNameVersionDescriptors(targletImplicitDependencies);
return targetSet.equals(targletSet);
}
private static boolean hasRequirements(EList<Targlet> targlets)
{
for (Targlet targlet : targlets)
{
if (!targlet.getRequirements().isEmpty())
{
return true;
}
}
return false;
}
} // TargletTaskImpl
| epl-1.0 |
shinsakamoto/practice-javafx | src/samples/javafx/base/App8FXML.java | 738 | package samples.javafx.base;
import java.io.File;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* How to use <br>
* fxml<br>
* Handler mapping in fxml<br>
* <img alt="image" src="./doc-files/App8FXML.png">
* @author sakamoto
*
*/
public class App8FXML extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
VBox pane = FXMLLoader.load(new File("resources/app8.fxml").toURI().toURL());
Scene scene = new Scene(pane, 520, 320);
stage.setScene(scene);
stage.show();
}
}
| epl-1.0 |
qs371102/BFMJIRWidget | IRWidget/src/com/fishjord/irwidget/ir/codes/CodeManager.java | 3129 | package com.fishjord.irwidget.ir.codes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.fishjord.irwidget.R;
public class CodeManager {
private static CodeManager codeManager;
private final Map<String, Manufacturer> manufacturers = new LinkedHashMap();
private CodeManager(Context c) throws IOException, XmlPullParserException {
XmlResourceParser parser = c.getResources().getXml(R.xml.remotes);
while(parser.next() != XmlResourceParser.START_TAG);
parseManufacturers(parser);
parser.close();
Log.i(this.getClass().getCanonicalName(), "Loaded " + manufacturers.size() + " manufacturers from xml");
}
private void parseManufacturers(XmlResourceParser parser) throws IOException, XmlPullParserException {
parser.require(XmlResourceParser.START_TAG, null, "manufacturers");
while(parser.next() != XmlResourceParser.END_TAG) {
if(parser.getEventType() == XmlResourceParser.START_TAG) {
parseManufacturer(parser);
}
}
parser.require(XmlResourceParser.END_TAG, null, "manufacturers");
}
private void parseManufacturer(XmlResourceParser parser) throws IOException, XmlPullParserException {
parser.require(XmlResourceParser.START_TAG, null, "manufacturer");
String name = parser.getAttributeValue(null, "name");
List<IRButton> buttons = new ArrayList();
while(parser.next() != XmlResourceParser.END_TAG){
if(parser.getEventType() == XmlResourceParser.START_TAG) {
buttons.add(parseCode(parser));
}
}
manufacturers.put(name, new Manufacturer(name, buttons));
Log.d(this.getClass().getCanonicalName(), "Loaded " + buttons.size() + " codes for " + name);
parser.require(XmlResourceParser.END_TAG, null, "manufacturer");
}
private IRButton parseCode(XmlResourceParser parser) throws IOException, XmlPullParserException {
parser.require(XmlResourceParser.START_TAG, null, "code");
String name = parser.getAttributeValue(null, "name");
String display = parser.getAttributeValue(null, "display");
String group = parser.getAttributeValue(null, "group");
IRCommand command = ProntoParser.parsePronto(parser.nextText().trim());
Log.d(this.getClass().getCanonicalName(), "Loaded " + name + ": " + command);
parser.require(XmlResourceParser.END_TAG, null, "code");
return new IRButton(name, display, group, command);
}
public Manufacturer getManufacturer(String manufacturer) {
return manufacturers.get(manufacturer);
}
public static CodeManager getInstance(Context context) throws IOException, XmlPullParserException {
if(codeManager == null) {
codeManager = new CodeManager(context);
}
return codeManager;
}
public List<String> getManufacturers() {
return new ArrayList<String>(manufacturers.keySet());
}
public static CodeManager getInstance() {
return codeManager;
}
}
| epl-1.0 |
MikeJMajor/openhab2-addons-dlinksmarthome | bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/handler/OpenWebNetBridgeHandler.java | 23779 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.openwebnet.handler;
import static org.openhab.binding.openwebnet.OpenWebNetBindingConstants.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.openwebnet.OpenWebNetBindingConstants;
import org.openhab.binding.openwebnet.handler.config.OpenWebNetBusBridgeConfig;
import org.openhab.binding.openwebnet.handler.config.OpenWebNetZigBeeBridgeConfig;
import org.openhab.binding.openwebnet.internal.discovery.OpenWebNetDeviceDiscoveryService;
import org.openhab.core.config.core.status.ConfigStatusMessage;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.binding.ConfigStatusBridgeHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.types.Command;
import org.openwebnet4j.BUSGateway;
import org.openwebnet4j.GatewayListener;
import org.openwebnet4j.OpenDeviceType;
import org.openwebnet4j.OpenGateway;
import org.openwebnet4j.USBGateway;
import org.openwebnet4j.communication.OWNAuthException;
import org.openwebnet4j.communication.OWNException;
import org.openwebnet4j.message.Automation;
import org.openwebnet4j.message.BaseOpenMessage;
import org.openwebnet4j.message.FrameException;
import org.openwebnet4j.message.GatewayMgmt;
import org.openwebnet4j.message.Lighting;
import org.openwebnet4j.message.OpenMessage;
import org.openwebnet4j.message.What;
import org.openwebnet4j.message.Where;
import org.openwebnet4j.message.WhereZigBee;
import org.openwebnet4j.message.Who;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link OpenWebNetBridgeHandler} is responsible for handling communication with gateways and handling events.
*
* @author Massimo Valla - Initial contribution
*/
@NonNullByDefault
public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implements GatewayListener {
private final Logger logger = LoggerFactory.getLogger(OpenWebNetBridgeHandler.class);
private static final int GATEWAY_ONLINE_TIMEOUT_SEC = 20; // Time to wait for the gateway to become connected
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.BRIDGE_SUPPORTED_THING_TYPES;
// ConcurrentHashMap of devices registered to this BridgeHandler
// association is: ownId (String) -> OpenWebNetThingHandler, with ownId = WHO.WHERE
private Map<String, @Nullable OpenWebNetThingHandler> registeredDevices = new ConcurrentHashMap<>();
private Map<String, Long> discoveringDevices = new ConcurrentHashMap<>();
protected @Nullable OpenGateway gateway;
private boolean isBusGateway = false;
private boolean isGatewayConnected = false;
public @Nullable OpenWebNetDeviceDiscoveryService deviceDiscoveryService;
private boolean reconnecting = false; // we are trying to reconnect to gateway
private boolean scanIsActive = false; // a device scan has been activated by OpenWebNetDeviceDiscoveryService;
private boolean discoveryByActivation;
public OpenWebNetBridgeHandler(Bridge bridge) {
super(bridge);
}
public boolean isBusGateway() {
return isBusGateway;
}
@Override
public void initialize() {
ThingTypeUID thingType = getThing().getThingTypeUID();
OpenGateway gw;
if (thingType.equals(THING_TYPE_ZB_GATEWAY)) {
gw = initZigBeeGateway();
} else {
gw = initBusGateway();
isBusGateway = true;
}
if (gw != null) {
gateway = gw;
gw.subscribe(this);
if (gw.isConnected()) { // gateway is already connected, device can go ONLINE
isGatewayConnected = true;
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.UNKNOWN);
logger.debug("Trying to connect gateway {}... ", gw);
try {
gw.connect();
scheduler.schedule(() -> {
// if status is still UNKNOWN after timer ends, set the device as OFFLINE
if (thing.getStatus().equals(ThingStatus.UNKNOWN)) {
logger.info("status still UNKNOWN. Setting device={} to OFFLINE", thing.getUID());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
"Could not connect to gateway before " + GATEWAY_ONLINE_TIMEOUT_SEC + "s");
}
}, GATEWAY_ONLINE_TIMEOUT_SEC, TimeUnit.SECONDS);
logger.debug("bridge {} initialization completed", thing.getUID());
} catch (OWNException e) {
logger.debug("gw.connect() returned OWNException: {}", e.getMessage());
// status is updated by callback onConnectionError()
}
}
}
}
/**
* Init a ZigBee gateway based on config
*/
private @Nullable OpenGateway initZigBeeGateway() {
logger.debug("Initializing ZigBee USB Gateway");
OpenWebNetZigBeeBridgeConfig zbBridgeConfig = getConfigAs(OpenWebNetZigBeeBridgeConfig.class);
String serialPort = zbBridgeConfig.getSerialPort();
if (serialPort == null || serialPort.isEmpty()) {
logger.warn("Cannot connect ZigBee USB Gateway. No serial port has been provided in Bridge configuration.");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"@text/offline.conf-error-no-serial-port");
return null;
} else {
return new USBGateway(serialPort);
}
}
/**
* Init a BUS gateway based on config
*/
private @Nullable OpenGateway initBusGateway() {
logger.debug("Initializing BUS gateway");
OpenWebNetBusBridgeConfig busBridgeConfig = getConfigAs(OpenWebNetBusBridgeConfig.class);
String host = busBridgeConfig.getHost();
if (host == null || host.isEmpty()) {
logger.warn("Cannot connect to BUS Gateway. No host/IP has been provided in Bridge configuration.");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"@text/offline.conf-error-no-ip-address");
return null;
} else {
int port = busBridgeConfig.getPort().intValue();
String passwd = busBridgeConfig.getPasswd();
String passwdMasked;
if (passwd.length() >= 4) {
passwdMasked = "******" + passwd.substring(passwd.length() - 3, passwd.length());
} else {
passwdMasked = "******";
}
discoveryByActivation = busBridgeConfig.getDiscoveryByActivation();
logger.debug("Creating new BUS gateway with config properties: {}:{}, pwd={}, discoveryByActivation={}",
host, port, passwdMasked, discoveryByActivation);
return new BUSGateway(host, port, passwd);
}
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("handleCommand (command={} - channel={})", command, channelUID);
OpenGateway gw = gateway;
if (gw != null && !gw.isConnected()) {
logger.warn("Gateway is NOT connected, skipping command");
return;
} else {
logger.warn("Channel not supported: channel={}", channelUID);
}
}
@Override
public Collection<ConfigStatusMessage> getConfigStatus() {
return Collections.emptyList();
}
@Override
public void handleRemoval() {
disconnectGateway();
super.handleRemoval();
}
@Override
public void dispose() {
disconnectGateway();
super.dispose();
}
private void disconnectGateway() {
OpenGateway gw = gateway;
if (gw != null) {
gw.closeConnection();
gw.unsubscribe(this);
logger.debug("Gateway {} connection closed and unsubscribed", gw.toString());
gateway = null;
}
reconnecting = false;
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(OpenWebNetDeviceDiscoveryService.class);
}
/**
* Search for devices connected to this bridge handler's gateway
*
* @param listener to receive device found notifications
*/
public synchronized void searchDevices() {
scanIsActive = true;
logger.debug("------$$ scanIsActive={}", scanIsActive);
OpenGateway gw = gateway;
if (gw != null) {
if (!gw.isDiscovering()) {
if (!gw.isConnected()) {
logger.debug("------$$ Gateway '{}' is NOT connected, cannot search for devices", gw);
return;
}
logger.info("------$$ STARTED active SEARCH for devices on bridge '{}'", thing.getUID());
try {
gw.discoverDevices();
} catch (OWNException e) {
logger.warn("------$$ OWNException while discovering devices on bridge '{}': {}", thing.getUID(),
e.getMessage());
}
} else {
logger.debug("------$$ Searching devices on bridge '{}' already activated", thing.getUID());
return;
}
} else {
logger.warn("------$$ Cannot search devices: no gateway associated to this handler");
}
}
@Override
public void onNewDevice(@Nullable Where w, @Nullable OpenDeviceType deviceType, @Nullable BaseOpenMessage message) {
OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
if (discService != null) {
if (w != null && deviceType != null) {
discService.newDiscoveryResult(w, deviceType, message);
} else {
logger.warn("onNewDevice with null where/deviceType, msg={}", message);
}
} else {
logger.warn("onNewDevice but null deviceDiscoveryService");
}
}
@Override
public void onDiscoveryCompleted() {
logger.info("------$$ FINISHED active SEARCH for devices on bridge '{}'", thing.getUID());
}
/**
* Notifies that the scan has been stopped/aborted by OpenWebNetDeviceDiscoveryService
*/
public void scanStopped() {
scanIsActive = false;
logger.debug("------$$ scanIsActive={}", scanIsActive);
}
private void discoverByActivation(BaseOpenMessage baseMsg) {
logger.debug("discoverByActivation: msg={}", baseMsg);
OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
if (discService == null) {
logger.warn("discoverByActivation: null OpenWebNetDeviceDiscoveryService, ignoring msg={}", baseMsg);
return;
}
if (baseMsg instanceof Lighting || baseMsg instanceof Automation) { // we support these types only
BaseOpenMessage bmsg = baseMsg;
if (baseMsg instanceof Lighting) {
What what = baseMsg.getWhat();
if (Lighting.WHAT.OFF.equals(what)) { // skipping OFF msg: cannot distinguish dimmer/switch
logger.debug("discoverByActivation: skipping OFF msg: cannot distinguish dimmer/switch");
return;
}
if (Lighting.WHAT.ON.equals(what)) { // if not already done just now, request light status to
// distinguish dimmer from switch
if (discoveringDevices.containsKey(ownIdFromMessage(baseMsg))) {
logger.debug(
"discoverByActivation: we just requested status for this device and it's ON -> it's a switch");
} else {
OpenGateway gw = gateway;
if (gw != null) {
try {
discoveringDevices.put(ownIdFromMessage(baseMsg),
Long.valueOf(System.currentTimeMillis()));
gw.send(Lighting.requestStatus(baseMsg.getWhere().value()));
return;
} catch (OWNException e) {
logger.warn("discoverByActivation: Exception while requesting light state: {}",
e.getMessage());
return;
}
}
}
}
discoveringDevices.remove(ownIdFromMessage(baseMsg));
}
OpenDeviceType type = null;
try {
type = bmsg.detectDeviceType();
} catch (FrameException e) {
logger.warn("Exception while detecting device type: {}", e.getMessage());
}
if (type != null) {
discService.newDiscoveryResult(bmsg.getWhere(), type, bmsg);
} else {
logger.debug("discoverByActivation: no device type detected from msg: {}", bmsg);
}
}
}
/**
* Register a device ThingHandler to this BridgHandler
*
* @param ownId the device OpenWebNet id
* @param thingHandler the thing handler to be registered
*/
protected void registerDevice(String ownId, OpenWebNetThingHandler thingHandler) {
if (registeredDevices.containsKey(ownId)) {
logger.warn("registering device with an existing ownId={}", ownId);
}
registeredDevices.put(ownId, thingHandler);
logger.debug("registered device ownId={}, thing={}", ownId, thingHandler.getThing().getUID());
}
/**
* Un-register a device from this bridge handler
*
* @param ownId the device OpenWebNet id
*/
protected void unregisterDevice(String ownId) {
if (registeredDevices.remove(ownId) != null) {
logger.debug("un-registered device ownId={}", ownId);
} else {
logger.warn("could not un-register ownId={} (not found)", ownId);
}
}
/**
* Get an already registered device on this bridge handler
*
* @param ownId the device OpenWebNet id
* @return the registered device Thing handler or null if the id cannot be found
*/
public @Nullable OpenWebNetThingHandler getRegisteredDevice(String ownId) {
return registeredDevices.get(ownId);
}
@Override
public void onEventMessage(@Nullable OpenMessage msg) {
logger.trace("RECEIVED <<<<< {}", msg);
if (msg == null) {
logger.warn("received event msg is null");
return;
}
if (msg.isACK() || msg.isNACK()) {
return; // we ignore ACKS/NACKS
}
// GATEWAY MANAGEMENT
if (msg instanceof GatewayMgmt) {
// noop
return;
}
BaseOpenMessage baseMsg = (BaseOpenMessage) msg;
// let's try to get the Thing associated with this message...
if (baseMsg instanceof Lighting || baseMsg instanceof Automation) {
String ownId = ownIdFromMessage(baseMsg);
logger.debug("ownIdFromMessage({}) --> {}", baseMsg, ownId);
OpenWebNetThingHandler deviceHandler = registeredDevices.get(ownId);
if (deviceHandler == null) {
OpenGateway gw = gateway;
if (isBusGateway && ((gw != null && !gw.isDiscovering() && scanIsActive)
|| (discoveryByActivation && !scanIsActive))) {
discoverByActivation(baseMsg);
} else {
logger.debug("ownId={} has NO DEVICE associated, ignoring it", ownId);
}
} else {
deviceHandler.handleMessage(baseMsg);
}
} else {
logger.debug("BridgeHandler ignoring frame {}. WHO={} is not supported by this binding", baseMsg,
baseMsg.getWho());
}
}
@Override
public void onConnected() {
isGatewayConnected = true;
Map<String, String> properties = editProperties();
boolean propertiesChanged = false;
OpenGateway gw = gateway;
if (gw == null) {
logger.warn("received onConnected() but gateway is null");
return;
}
if (gw instanceof USBGateway) {
logger.info("---- CONNECTED to ZigBee USB gateway bridge '{}' (serialPort: {})", thing.getUID(),
((USBGateway) gw).getSerialPortName());
} else {
logger.info("---- CONNECTED to BUS gateway bridge '{}' ({}:{})", thing.getUID(),
((BUSGateway) gw).getHost(), ((BUSGateway) gw).getPort());
// update serial number property (with MAC address)
if (properties.get(PROPERTY_SERIAL_NO) != gw.getMACAddr().toUpperCase()) {
properties.put(PROPERTY_SERIAL_NO, gw.getMACAddr().toUpperCase());
propertiesChanged = true;
logger.debug("updated property gw serialNumber: {}", properties.get(PROPERTY_SERIAL_NO));
}
}
if (properties.get(PROPERTY_FIRMWARE_VERSION) != gw.getFirmwareVersion()) {
properties.put(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
propertiesChanged = true;
logger.debug("updated property gw firmware version: {}", properties.get(PROPERTY_FIRMWARE_VERSION));
}
if (propertiesChanged) {
updateProperties(properties);
logger.info("properties updated for bridge '{}'", thing.getUID());
}
updateStatus(ThingStatus.ONLINE);
}
@Override
public void onConnectionError(@Nullable OWNException error) {
String errMsg;
if (error == null) {
errMsg = "unknown error";
} else {
errMsg = error.getMessage();
}
logger.info("---- ON CONNECTION ERROR for gateway {}: {}", gateway, errMsg);
isGatewayConnected = false;
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, errMsg);
tryReconnectGateway();
}
@Override
public void onConnectionClosed() {
isGatewayConnected = false;
logger.debug("onConnectionClosed() - isGatewayConnected={}", isGatewayConnected);
// NOTE: cannot change to OFFLINE here because we are already in REMOVING state
}
@Override
public void onDisconnected(@Nullable OWNException e) {
isGatewayConnected = false;
String errMsg;
if (e == null) {
errMsg = "unknown error";
} else {
errMsg = e.getMessage();
}
logger.info("---- DISCONNECTED from gateway {}. OWNException: {}", gateway, errMsg);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
"Disconnected from gateway (onDisconnected - " + errMsg + ")");
tryReconnectGateway();
}
private void tryReconnectGateway() {
OpenGateway gw = gateway;
if (gw != null) {
if (!reconnecting) {
reconnecting = true;
logger.info("---- Starting RECONNECT cycle to gateway {}", gw);
try {
gw.reconnect();
} catch (OWNAuthException e) {
logger.info("---- AUTH error from gateway. Stopping re-connect");
reconnecting = false;
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
"Authentication error. Check gateway password in Thing Configuration Parameters (" + e
+ ")");
}
} else {
logger.debug("---- reconnecting=true, do nothing");
}
} else {
logger.warn("---- cannot start RECONNECT, gateway is null");
}
}
@Override
public void onReconnected() {
reconnecting = false;
OpenGateway gw = gateway;
logger.info("---- RE-CONNECTED to bridge {}", thing.getUID());
if (gw != null) {
updateStatus(ThingStatus.ONLINE);
if (gw.getFirmwareVersion() != null) {
this.updateProperty(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
logger.debug("gw firmware version: {}", gw.getFirmwareVersion());
}
}
}
/**
* Return a ownId string (=WHO.WHERE) from the device Where address and handler
*
* @param where the Where address (to be normalized)
* @param handler the device handler
* @return the ownId String
*/
protected String ownIdFromDeviceWhere(Where where, OpenWebNetThingHandler handler) {
return handler.ownIdPrefix() + "." + normalizeWhere(where);
}
/**
* Returns a ownId string (=WHO.WHERE) from a Who and Where address
*
* @param who the Who
* @param where the Where address (to be normalized)
* @return the ownId String
*/
public String ownIdFromWhoWhere(Who who, Where where) {
return who.value() + "." + normalizeWhere(where);
}
/**
* Return a ownId string (=WHO.WHERE) from a BaseOpenMessage
*
* @param baseMsg the BaseOpenMessage
* @return the ownId String
*/
public String ownIdFromMessage(BaseOpenMessage baseMsg) {
return baseMsg.getWho().value() + "." + normalizeWhere(baseMsg.getWhere());
}
/**
* Transform a Where address into a Thing id string
*
* @param where the Where address
* @return the thing Id string
*/
public String thingIdFromWhere(Where where) {
return normalizeWhere(where); // '#' cannot be used in ThingUID;
}
/**
* Normalize a Where address
*
* @param where the Where address
* @return the normalized address as String
*/
public String normalizeWhere(Where where) {
String str = where.value();
if (where instanceof WhereZigBee) {
str = ((WhereZigBee) where).valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9
} else {
if (str.indexOf("#4#") == -1) { // skip APL#4#bus case
if (str.indexOf('#') == 0) { // Thermo central unit (#0) or zone via central unit (#Z, Z=[1-99]) --> Z
str = str.substring(1);
} else if (str.indexOf('#') > 0) { // Thermo zone Z and actuator N (Z#N, Z=[1-99], N=[1-9]) --> Z
str = str.substring(0, str.indexOf('#'));
}
}
}
return str.replace('#', 'h');
}
}
| epl-1.0 |
argocasegeo/argocasegeo | src/org/argouml/uml/diagram/state/ui/FigShallowHistoryState.java | 5346 | // Copyright (c) 1996-99 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
// File: FigShallowHistoryState.java
// Classes: FigShallowHistoryState
// Original Author: jrobbins@ics.uci.edu
// $Id: FigShallowHistoryState.java,v 1.3 2002/08/19 09:02:12 kataka Exp $
package org.argouml.uml.diagram.state.ui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.beans.*;
import javax.swing.*;
import ru.novosoft.uml.foundation.core.*;
import ru.novosoft.uml.behavior.state_machines.*;
import org.tigris.gef.base.*;
import org.tigris.gef.presentation.*;
import org.tigris.gef.graph.*;
import org.argouml.uml.diagram.ui.*;
/** Class to display graphics for a UML MState in a diagram. */
public class FigShallowHistoryState extends FigStateVertex {
////////////////////////////////////////////////////////////////
// constants
public final int MARGIN = 2;
public int x = 0;
public int y = 0;
public int width = 24;
public int height = 24;
////////////////////////////////////////////////////////////////
// instance variables
/** The main label on this icon. */
FigText _name;
/** UML does not really use ports, so just define one big one so
* that users can drag edges to or from any point in the icon. */
FigCircle _bigPort;
// add other Figs here aes needed
FigCircle _head;
////////////////////////////////////////////////////////////////
// constructors
public FigShallowHistoryState() {
_bigPort = new FigCircle(x, y, width, height, Color.cyan, Color.cyan);
_head = new FigCircle(x, y, width, height, Color.black, Color.white);
_name = new FigText(x+5, y+5, width-10, height-10);
_name.setText("H");
_name.setTextColor(Color.black);
_name.setFilled(false);
_name.setLineWidth(0);
// add Figs to the FigNode in back-to-front order
addFig(_bigPort);
addFig(_head);
addFig(_name);
setBlinkPorts(false); //make port invisble unless mouse enters
Rectangle r = getBounds();
}
public String placeString() { return "H"; }
public FigShallowHistoryState(GraphModel gm, Object node) {
this();
setOwner(node);
}
public Object clone() {
FigShallowHistoryState figClone = (FigShallowHistoryState) super.clone();
Vector v = figClone.getFigs();
figClone._bigPort = (FigCircle) v.elementAt(0);
figClone._head = (FigCircle) v.elementAt(1);
figClone._name = (FigText) v.elementAt(2);
return figClone;
}
////////////////////////////////////////////////////////////////
// Fig accessors
public void setOwner(Object node) {
super.setOwner(node);
bindPort(node, _bigPort);
// if it is a UML meta-model object, register interest in any change events
if (node instanceof MElement)
((MElement)node).addMElementListener(this);
}
/** History states are fixed size. */
public boolean isResizable() { return false; }
public Selection makeSelection() {
return new SelectionMoveClarifiers(this);
}
public void setLineColor(Color col) { _head.setLineColor(col); }
public Color getLineColor() { return _head.getLineColor(); }
public void setFillColor(Color col) { _head.setFillColor(col); }
public Color getFillColor() { return _head.getFillColor(); }
public void setFilled(boolean f) { }
public boolean getFilled() { return true; }
public void setLineWidth(int w) { _head.setLineWidth(w); }
public int getLineWidth() { return _head.getLineWidth(); }
////////////////////////////////////////////////////////////////
// Event handlers
public void mouseClicked(MouseEvent me) { }
public void keyPressed(KeyEvent ke) { }
static final long serialVersionUID = 6572261327347541373L;
} /* end class FigShallowHistoryState */
| epl-1.0 |
debabratahazra/OptimaLA | Optima/com.ose.chart/src/com/ose/chart/model/ChartContentNullTransformer.java | 2240 | /* COPYRIGHT-ENEA-SRC-R2 *
**************************************************************************
* Copyright (C) 2009 by Enea Software AB.
* All rights reserved.
*
* This Software is furnished under a software license agreement and
* may be used only in accordance with the terms of such agreement.
* Any other use or reproduction is prohibited. No title to and
* ownership of the Software is hereby transferred.
*
* PROPRIETARY NOTICE
* This Software consists of confidential information.
* Trade secret law and copyright law protect this Software.
* The above notice of copyright on this Software does not indicate
* any actual or intended publication of such Software.
**************************************************************************
* COPYRIGHT-END */
package com.ose.chart.model;
public class ChartContentNullTransformer extends ChartContentTransformer
{
public double getValue(int layer, int series, int item)
{
return getSourceContentProvider().getValue(layer, series, item);
}
public String getValueLabel(int layer, int series, int item)
{
return getSourceContentProvider().getValueLabel(layer, series, item);
}
public String getItemLabel(int layer, int series, int item)
{
return getSourceContentProvider().getItemLabel(layer, series, item);
}
public String getSeriesLabel(int layer, int series)
{
return getSourceContentProvider().getSeriesLabel(layer, series);
}
public String getLayerLabel(int layer)
{
return getSourceContentProvider().getLayerLabel(layer);
}
public Range getItemRange()
{
return getSourceContentProvider().getItemRange();
}
public Range getSeriesRange()
{
return getSourceContentProvider().getSeriesRange();
}
public Range getLayerRange()
{
return getSourceContentProvider().getLayerRange();
}
public int getSourceItem(int item)
{
return item;
}
public int getSourceSeries(int series)
{
return series;
}
public int getSourceLayer(int layer)
{
return layer;
}
protected void sourceContentChanged(ChartContentProvider contentProvider)
{
// Not needed for the null provider.
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.2_fat_tck/fat/src/com/ibm/ws/microprofile/config12/tck/Config12TCKLauncher.java | 2354 | /*******************************************************************************
* Copyright (c) 2018,2022 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.microprofile.config12.tck;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import componenttest.annotation.AllowedFFDC;
import componenttest.annotation.Server;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.topology.impl.LibertyServer;
import componenttest.topology.impl.JavaInfo;
import componenttest.topology.utils.MvnUtils;
/**
* This is a test class that runs a whole Maven TCK as one test FAT test.
* There is a detailed output on specific
*/
@RunWith(FATRunner.class)
@Mode(TestMode.FULL)
public class Config12TCKLauncher {
@Server("Config12TCKServer")
public static LibertyServer server;
@BeforeClass
public static void setUp() throws Exception {
server.startServer();
}
@AfterClass
public static void tearDown() throws Exception {
server.stopServer("CWMCG0007E", "CWMCG0014E", "CWMCG0015E", "CWMCG5003E", "CWWKZ0002E");
}
@Test
@AllowedFFDC // The tested deployment exceptions cause FFDC so we have to allow for this.
public void launchConfig12Tck() throws Exception {
MvnUtils.runTCKMvnCmd(server, "com.ibm.ws.microprofile.config.1.2_fat_tck", this.getClass() + ":launchConfig12Tck");
Map<String, String> resultInfo = MvnUtils.getResultInfo(server);
resultInfo.put("results_type", "MicroProfile");
resultInfo.put("feature_name", "Config");
resultInfo.put("feature_version", "1.2");
MvnUtils.preparePublicationFile(resultInfo);
}
}
| epl-1.0 |
syncron/mondrian | src/main/mondrian/spi/impl/SybaseDialect.java | 1469 | /*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (c) 2002-2015 Pentaho Corporation.
// All rights reserved.
*/
package mondrian.spi.impl;
import mondrian.olap.Util;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
/**
* Implementation of {@link mondrian.spi.Dialect} for the Sybase database.
*
* @author jhyde
* @since Nov 23, 2008
*/
public class SybaseDialect extends JdbcDialectImpl {
public static final JdbcDialectFactory FACTORY =
new JdbcDialectFactory(
SybaseDialect.class,
DatabaseProduct.SYBASE);
/**
* Creates a SybaseDialect.
*
* @param connection Connection
*/
public SybaseDialect(Connection connection) throws SQLException {
super(connection);
}
public boolean allowsAs() {
return false;
}
public boolean allowsFromQuery() {
return false;
}
public boolean requiresAliasForFromQuery() {
return true;
}
@Override
protected void quoteDateLiteral(StringBuilder buf, String value, Date date)
{
Util.singleQuoteString(value, buf);
}
@Override
public String getCurrentSchemaQuery() {
return "select db_name()";
}
}
// End SybaseDialect.java
| epl-1.0 |
nicolatimeus/kura | kura/org.eclipse.kura.util/src/main/java/org/eclipse/kura/util/base/TypeUtil.java | 2077 | /*******************************************************************************
* Copyright (c) 2016, 2020 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.kura.util.base;
import static java.util.Objects.requireNonNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* The Class TypeUtil contains all necessary static factory methods for
* manipulating java type instances
*/
public final class TypeUtil {
/** Constructor */
private TypeUtil() {
// Static Factory Methods container. No need to instantiate.
}
/**
* Returns a byte array representation of the provided integer value.
*
* @param value
* The provided integer value
* @return the byte array instance
*/
public static byte[] intToBytes(final int value) {
final byte[] result = new byte[4];
result[0] = (byte) (value >> 24);
result[1] = (byte) (value >> 16);
result[2] = (byte) (value >> 8);
result[3] = (byte) value;
return result;
}
/**
* Converts to the byte array from the provided object instance
*
* @param value
* @return the byte array
* @throws IOException
* if the access to byte stream fails
* @throws NullPointerException
* if the argument is null
*/
public static byte[] objectToByteArray(final Object value) throws IOException {
requireNonNull(value, "Value cannot be null.");
final ByteArrayOutputStream b = new ByteArrayOutputStream();
final ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(value);
return b.toByteArray();
}
}
| epl-1.0 |
trajano/app-ms | ms-oidc/src/main/java/net/trajano/ms/oidc/OpenIdConnect.java | 252 | package net.trajano.ms.oidc;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class OpenIdConnect {
protected OpenIdConnect() {
}
}
| epl-1.0 |
kopl/SPLevo | JaMoPPCartridge/org.splevo.jamopp.vpm.analyzer.programdependency.tests/testcode/robillard/StatementWritesField/b/A.java | 433 | package org.splevo.jamopp.vpm.analyzer.programdependency.tests;
public class A {
private int fieldDirectReference = 0;
private int fieldNestedReference = 0;
public void doUnchanged() {
}
public void newMethodFieldDirectReference() {
fieldDirectReference = 12;
}
public void newMethodFieldNestedReference() {
if(1 + 1 == 2) {
fieldNestedReference = 21;
}
}
}
| epl-1.0 |
RodriguesJ/Atem | src/com/runescape/server/revised/content/achievement/karamja/elite/WalkiesAchievementTask.java | 11742 | /**
* Eclipse Public License - v 1.0
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
* OF THE
* PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* 1. DEFINITIONS
*
* "Contribution" means:
*
* a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
* b) in the case of each subsequent Contributor:
* i) changes to the Program, and
* ii) additions to the Program;
* where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution
* 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf.
* Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program
* under their own license agreement, and (ii) are not derivative works of the Program.
* "Contributor" means any person or entity that distributes the Program.
*
* "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone
* or when combined with the Program.
*
* "Program" means the Contributions distributed in accordance with this Agreement.
*
* "Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
*
* 2. GRANT OF RIGHTS
*
* a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license
* to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor,
* if any, and such derivative works, in source code and object code form.
* b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license
* under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source
* code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the
* Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The
* patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
* c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided
* by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor
* disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise.
* As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other
* intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the
* Program, it is Recipient's responsibility to acquire that license before distributing the Program.
* d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright
* license set forth in this Agreement.
* 3. REQUIREMENTS
*
* A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
*
* a) it complies with the terms and conditions of this Agreement; and
* b) its license agreement:
* i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions
* of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
* ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and
* consequential damages, such as lost profits;
* iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
* iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner
* on or through a medium customarily used for software exchange.
* When the Program is made available in source code form:
*
* a) it must be made available under this Agreement; and
* b) a copy of this Agreement must be included with each copy of the Program.
* Contributors may not remove or alter any copyright notices contained within the Program.
*
* Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients
* to identify the originator of the Contribution.
*
* 4. COMMERCIAL DISTRIBUTION
*
* Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this
* license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering
* should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in
* a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor
* ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions
* brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in
* connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or
* Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly
* notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the
* Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim
* at its own expense.
*
* For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial
* Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims
* and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend
* claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay
* any damages as a result, the Commercial Contributor must pay those damages.
*
* 5. NO WARRANTY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and
* assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program
* errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
*
* 6. DISCLAIMER OF LIABILITY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION
* OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* 7. GENERAL
*
* If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the
* remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum
* extent necessary to make such provision valid and enforceable.
*
* If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program
* itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's
* rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
*
* All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this
* Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights
* under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However,
* Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
*
* Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may
* only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this
* Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the
* initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate
* entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be
* distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is
* published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in
* Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement,
* whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
*
* This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to
* this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights
* to a jury trial in any resulting litigation.
*/
package com.runescape.server.revised.content.achievement.karamja.elite;
public class WalkiesAchievementTask {
} | epl-1.0 |
upohl/eloquent | examples/drwahnsinn/plugins/org.muml.eloquent.example.drwahnsinn/src/org/muml/eloquent/example/drwahnsinn/RelationCollection.java | 2310 | /**
*/
package org.muml.eloquent.example.drwahnsinn;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Relation Collection</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.muml.eloquent.example.drwahnsinn.RelationCollection#getTileRelations <em>Tile Relations</em>}</li>
* <li>{@link org.muml.eloquent.example.drwahnsinn.RelationCollection#getGame <em>Game</em>}</li>
* </ul>
*
* @see org.muml.eloquent.example.drwahnsinn.DrwahnsinnPackage#getRelationCollection()
* @model
* @generated
*/
public interface RelationCollection extends EObject {
/**
* Returns the value of the '<em><b>Tile Relations</b></em>' containment reference list.
* The list contents are of type {@link org.muml.eloquent.example.drwahnsinn.TileRelation}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Tile Relations</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Tile Relations</em>' containment reference list.
* @see org.muml.eloquent.example.drwahnsinn.DrwahnsinnPackage#getRelationCollection_TileRelations()
* @model containment="true" required="true"
* @generated
*/
EList<TileRelation> getTileRelations();
/**
* Returns the value of the '<em><b>Game</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Game</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Game</em>' reference.
* @see #setGame(DrWahnsinnGame)
* @see org.muml.eloquent.example.drwahnsinn.DrwahnsinnPackage#getRelationCollection_Game()
* @model required="true"
* @generated
*/
DrWahnsinnGame getGame();
/**
* Sets the value of the '{@link org.muml.eloquent.example.drwahnsinn.RelationCollection#getGame <em>Game</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Game</em>' reference.
* @see #getGame()
* @generated
*/
void setGame(DrWahnsinnGame value);
} // RelationCollection
| epl-1.0 |
MMaiero/kura | kura/org.eclipse.kura.wire.component.provider/src/main/java/org/eclipse/kura/internal/wire/store/DbWireRecordStore.java | 20205 | /*******************************************************************************
* Copyright (c) 2016, 2017 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
* Amit Kumar Mondal
*
*******************************************************************************/
package org.eclipse.kura.internal.wire.store;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.kura.configuration.ConfigurableComponent;
import org.eclipse.kura.db.DbService;
import org.eclipse.kura.internal.wire.common.DbServiceHelper;
import org.eclipse.kura.internal.wire.store.DbDataTypeMapper.JdbcType;
import org.eclipse.kura.localization.LocalizationAdapter;
import org.eclipse.kura.localization.resources.WireMessages;
import org.eclipse.kura.type.BooleanValue;
import org.eclipse.kura.type.ByteArrayValue;
import org.eclipse.kura.type.DataType;
import org.eclipse.kura.type.DoubleValue;
import org.eclipse.kura.type.FloatValue;
import org.eclipse.kura.type.IntegerValue;
import org.eclipse.kura.type.LongValue;
import org.eclipse.kura.type.StringValue;
import org.eclipse.kura.type.TypedValue;
import org.eclipse.kura.util.collection.CollectionUtil;
import org.eclipse.kura.wire.WireEmitter;
import org.eclipse.kura.wire.WireEnvelope;
import org.eclipse.kura.wire.WireHelperService;
import org.eclipse.kura.wire.WireReceiver;
import org.eclipse.kura.wire.WireRecord;
import org.eclipse.kura.wire.WireSupport;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.wireadmin.Wire;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class DbWireRecordStore is a wire component which is responsible to store
* the received {@link WireRecord}.
*/
public final class DbWireRecordStore implements WireEmitter, WireReceiver, ConfigurableComponent {
private static final String COLUMN_NAME = "COLUMN_NAME";
private static final String DATA_TYPE = "DATA_TYPE";
private static final Logger logger = LoggerFactory.getLogger(DbWireRecordStore.class);
private static final WireMessages message = LocalizationAdapter.adapt(WireMessages.class);
private static final String SQL_ADD_COLUMN = "ALTER TABLE {0} ADD COLUMN {1} {2};";
private static final String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS {0} (TIMESTAMP BIGINT NOT NULL PRIMARY KEY);";
private static final String SQL_ROW_COUNT_TABLE = "SELECT COUNT(*) FROM {0};";
private static final String SQL_DELETE_RANGE_TABLE = "DELETE FROM {0} WHERE rownum() <= (SELECT count(*) FROM {0}) - {1};";
private static final String SQL_DROP_COLUMN = "ALTER TABLE {0} DROP COLUMN {1};";
private static final String SQL_INSERT_RECORD = "INSERT INTO {0} ({1}) VALUES ({2});";
private static final String SQL_TRUNCATE_TABLE = "TRUNCATE TABLE {0};";
private static final String[] TABLE_TYPE = new String[] { "TABLE" };
private DbServiceHelper dbHelper;
private volatile DbService dbService;
private DbWireRecordStoreOptions wireRecordStoreOptions;
private volatile WireHelperService wireHelperService;
private WireSupport wireSupport;
/**
* Binds the DB service.
*
* @param dbService
* the new DB service
*/
public void bindDbService(final DbService dbService) {
if (isNull(this.dbService)) {
this.dbService = dbService;
}
}
/**
* Binds the Wire Helper Service.
*
* @param wireHelperService
* the new Wire Helper Service
*/
public void bindWireHelperService(final WireHelperService wireHelperService) {
if (isNull(this.wireHelperService)) {
this.wireHelperService = wireHelperService;
}
}
/**
* Unbinds the DB service.
*
* @param dbService
* the DB service
*/
public void unbindDbService(final DbService dbService) {
if (this.dbService == dbService) {
this.dbService = null;
}
}
/**
* Unbinds the Wire Helper Service.
*
* @param wireHelperService
* the new Wire Helper Service
*/
public void unbindWireHelperService(final WireHelperService wireHelperService) {
if (this.wireHelperService == wireHelperService) {
this.wireHelperService = null;
}
}
/**
* OSGi Service Component callback for activation.
*
* @param componentContext
* the component context
* @param properties
* the properties
*/
protected void activate(final ComponentContext componentContext, final Map<String, Object> properties) {
logger.debug(message.activatingStore());
this.wireRecordStoreOptions = new DbWireRecordStoreOptions(properties);
this.dbHelper = DbServiceHelper.of(this.dbService);
this.wireSupport = this.wireHelperService.newWireSupport(this);
final String tableName = this.wireRecordStoreOptions.getTableName();
reconcileDB(tableName);
logger.debug(message.activatingStoreDone());
}
/**
* OSGi Service Component callback for updating.
*
* @param properties
* the updated service component properties
*/
public void updated(final Map<String, Object> properties) {
logger.debug(message.updatingStore() + properties);
this.wireRecordStoreOptions = new DbWireRecordStoreOptions(properties);
final String tableName = this.wireRecordStoreOptions.getTableName();
reconcileDB(tableName);
logger.debug(message.updatingStoreDone());
}
/**
* OSGi Service Component callback for deactivation.
*
* @param componentContext
* the component context
*/
protected void deactivate(final ComponentContext componentContext) {
logger.debug(message.deactivatingStore());
logger.debug(message.deactivatingStoreDone());
}
/**
* Truncates tables containing {@link WireRecord}s
*/
private void truncate() {
final int noOfRecordsToKeep = this.wireRecordStoreOptions.getNoOfRecordsToKeep();
truncate(noOfRecordsToKeep);
}
/**
* Truncates the records in the table
*
* @param noOfRecordsToKeep
* the no of records to keep in the table
*/
private void truncate(final int noOfRecordsToKeep) {
final String tableName = this.wireRecordStoreOptions.getTableName();
final String sqlTableName = this.dbHelper.sanitizeSqlTableAndColumnName(tableName);
Connection conn = null;
ResultSet rsTbls = null;
try {
conn = this.dbHelper.getConnection();
final String catalog = conn.getCatalog();
final DatabaseMetaData dbMetaData = conn.getMetaData();
rsTbls = dbMetaData.getTables(catalog, null, tableName, TABLE_TYPE);
if (rsTbls.next()) {
// table does exist, truncate it
if (noOfRecordsToKeep == 0) {
logger.info(message.truncatingTable(sqlTableName));
this.dbHelper.execute(MessageFormat.format(SQL_TRUNCATE_TABLE, sqlTableName));
} else {
logger.info(message.partiallyEmptyingTable(sqlTableName));
this.dbHelper.execute(MessageFormat.format(SQL_DELETE_RANGE_TABLE, sqlTableName,
Integer.toString(noOfRecordsToKeep)));
}
}
} catch (final SQLException sqlException) {
logger.error(message.errorTruncatingTable(sqlTableName), sqlException);
} finally {
this.dbHelper.close(rsTbls);
this.dbHelper.close(conn);
}
}
private int getTableSize() throws SQLException {
final String tableName = this.wireRecordStoreOptions.getTableName();
final String sqlTableName = this.dbHelper.sanitizeSqlTableAndColumnName(tableName);
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
int size = 0;
try {
conn = this.dbHelper.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery(MessageFormat.format(SQL_ROW_COUNT_TABLE, sqlTableName));
rset.next();
size = rset.getInt(1);
} catch (final SQLException e) {
throw e;
} finally {
this.dbHelper.close(rset);
this.dbHelper.close(stmt);
this.dbHelper.close(conn);
}
return size;
}
/** {@inheritDoc} */
@Override
public void consumersConnected(final Wire[] wires) {
this.wireSupport.consumersConnected(wires);
}
/** {@inheritDoc} */
@Override
public synchronized void onWireReceive(final WireEnvelope wireEvelope) {
requireNonNull(wireEvelope, message.wireEnvelopeNonNull());
logger.debug(message.wireEnvelopeReceived() + this.wireSupport);
try {
if (getTableSize() >= this.wireRecordStoreOptions.getMaximumTableSize()) {
truncate();
}
} catch (SQLException e) {
logger.warn("Exception while trying to clean db");
}
final List<WireRecord> records = wireEvelope.getRecords();
for (WireRecord wireRecord : records) {
store(wireRecord);
}
// emit the list of Wire Records to the downstream components
this.wireSupport.emit(records);
}
/**
* Stores the provided {@link WireRecord} in the database
*
* @param wireRecord
* the {@link WireRecord} to be stored
* @throws NullPointerException
* if the provided argument is null
*/
private void store(final WireRecord wireRecord) {
requireNonNull(wireRecord, message.wireRecordNonNull());
int retryCount = 0;
final String tableName = this.wireRecordStoreOptions.getTableName();
do {
try {
insertDataRecord(tableName, wireRecord);
break;
} catch (final SQLException e) {
logger.error(message.insertionFailed(), e);
reconcileDB(wireRecord, tableName);
retryCount++;
}
} while (retryCount < 2);
}
/**
* Tries to reconcile the database.
*
* @param wireRecord
* against which the database columns have to be reconciled.
* @param tableName
* the table name in the database that needs to be reconciled.
*/
private void reconcileDB(final WireRecord wireRecord, final String tableName) {
try {
if (nonNull(tableName) && !tableName.isEmpty()) {
reconcileTable(tableName);
reconcileColumns(tableName, wireRecord);
}
} catch (final SQLException ee) {
logger.error(message.errorStoring(), ee);
}
}
/**
* Tries to reconcile the database.
*
* @param tableName
* the table name in the database that needs to be reconciled.
*/
private void reconcileDB(final String tableName) {
try {
if (nonNull(tableName) && !tableName.isEmpty()) {
reconcileTable(tableName);
}
} catch (final SQLException ee) {
logger.error(message.errorStoring(), ee);
}
}
/**
* Reconcile table.
*
* @param tableName
* the table name
* @throws SQLException
* the SQL exception
* @throws NullPointerException
* if the provided argument is null
*/
private void reconcileTable(final String tableName) throws SQLException {
requireNonNull(tableName, message.tableNameNonNull());
final String sqlTableName = this.dbHelper.sanitizeSqlTableAndColumnName(tableName);
final Connection conn = this.dbHelper.getConnection();
ResultSet rsTbls = null;
try {
// check for the table that would collect the data of this emitter
final String catalog = conn.getCatalog();
final DatabaseMetaData dbMetaData = conn.getMetaData();
rsTbls = dbMetaData.getTables(catalog, null, this.wireRecordStoreOptions.getTableName(), TABLE_TYPE);
if (!rsTbls.next()) {
// table does not exist, create it
logger.info(message.creatingTable(sqlTableName));
this.dbHelper.execute(MessageFormat.format(SQL_CREATE_TABLE, sqlTableName));
}
} finally {
this.dbHelper.close(rsTbls);
this.dbHelper.close(conn);
}
}
/**
* Reconcile columns.
*
* @param tableName
* the table name
* @param wireRecord
* the data record
* @throws SQLException
* the SQL exception
* @throws NullPointerException
* if any of the provided arguments is null
*/
private void reconcileColumns(final String tableName, final WireRecord wireRecord) throws SQLException {
requireNonNull(tableName, message.tableNameNonNull());
requireNonNull(wireRecord, message.wireRecordNonNull());
Connection conn = null;
ResultSet rsColumns = null;
final Map<String, Integer> columns = CollectionUtil.newHashMap();
try {
// check for the table that would collect the data of this emitter
conn = this.dbHelper.getConnection();
final String catalog = conn.getCatalog();
final DatabaseMetaData dbMetaData = conn.getMetaData();
rsColumns = dbMetaData.getColumns(catalog, null, tableName, null);
// map the columns
while (rsColumns.next()) {
final String colName = rsColumns.getString(COLUMN_NAME);
final String sqlColName = this.dbHelper.sanitizeSqlTableAndColumnName(colName);
final int colType = rsColumns.getInt(DATA_TYPE);
columns.put(sqlColName, colType);
}
} finally {
this.dbHelper.close(rsColumns);
this.dbHelper.close(conn);
}
// reconcile columns
for (Entry<String, TypedValue<?>> entry : wireRecord.getProperties().entrySet()) {
final String sqlColName = this.dbHelper.sanitizeSqlTableAndColumnName(entry.getKey());
final Integer sqlColType = columns.get(sqlColName);
final JdbcType jdbcType = DbDataTypeMapper.getJdbcType(entry.getValue().getType());
final String sqlTableName = this.dbHelper.sanitizeSqlTableAndColumnName(tableName);
if (isNull(sqlColType)) {
// add column
this.dbHelper.execute(
MessageFormat.format(SQL_ADD_COLUMN, sqlTableName, sqlColName, jdbcType.getTypeString()));
} else if (sqlColType != jdbcType.getType()) {
// drop old column and add new one
this.dbHelper.execute(MessageFormat.format(SQL_DROP_COLUMN, sqlTableName, sqlColName));
this.dbHelper.execute(
MessageFormat.format(SQL_ADD_COLUMN, sqlTableName, sqlColName, jdbcType.getTypeString()));
}
}
}
/**
* Insert the provided {@link WireRecord} to the specified table
*
* @param tableName
* the table name
* @param wireRecord
* the {@link WireRecord}
* @throws SQLException
* the SQL exception
* @throws NullPointerException
* if any of the provided arguments is null
*/
private void insertDataRecord(final String tableName, final WireRecord wireRecord) throws SQLException {
requireNonNull(tableName, message.tableNameNonNull());
requireNonNull(wireRecord, message.wireRecordNonNull());
final Map<String, TypedValue<?>> wireRecordProperties = wireRecord.getProperties();
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = this.dbHelper.getConnection();
stmt = prepareStatement(connection, tableName, wireRecordProperties, new Date().getTime());
stmt.execute();
connection.commit();
logger.info(message.stored());
} catch (final SQLException e) {
this.dbHelper.rollback(connection);
throw e;
} finally {
this.dbHelper.close(stmt);
this.dbHelper.close(connection);
}
}
private PreparedStatement prepareStatement(Connection connection, String tableName,
final Map<String, TypedValue<?>> properties, long timestamp) throws SQLException {
final String sqlTableName = this.dbHelper.sanitizeSqlTableAndColumnName(tableName);
final StringBuilder sbCols = new StringBuilder();
final StringBuilder sbVals = new StringBuilder();
// add the timestamp
sbCols.append("TIMESTAMP");
sbVals.append("?");
int i = 2;
for (Entry<String, TypedValue<?>> entry : properties.entrySet()) {
final String sqlColName = this.dbHelper.sanitizeSqlTableAndColumnName(entry.getKey());
sbCols.append(", " + sqlColName);
sbVals.append(", ?");
}
logger.debug(message.storingRecord(sqlTableName));
final String sqlInsert = MessageFormat.format(SQL_INSERT_RECORD, sqlTableName, sbCols.toString(),
sbVals.toString());
final PreparedStatement stmt = connection.prepareStatement(sqlInsert);
stmt.setLong(1, timestamp);
for (Entry<String, TypedValue<?>> entry : properties.entrySet()) {
final DataType dataType = entry.getValue().getType();
final Object value = entry.getValue();
switch (dataType) {
case BOOLEAN:
stmt.setBoolean(i, ((BooleanValue) value).getValue());
break;
case FLOAT:
stmt.setFloat(i, ((FloatValue) value).getValue());
break;
case DOUBLE:
stmt.setDouble(i, ((DoubleValue) value).getValue());
break;
case INTEGER:
stmt.setInt(i, ((IntegerValue) value).getValue());
break;
case LONG:
stmt.setLong(i, ((LongValue) value).getValue());
break;
case BYTE_ARRAY:
byte[] byteArrayValue = ((ByteArrayValue) value).getValue();
InputStream is = new ByteArrayInputStream(byteArrayValue);
stmt.setBlob(i, is);
break;
case STRING:
stmt.setString(i, ((StringValue) value).getValue());
break;
default:
break;
}
i++;
}
return stmt;
}
/** {@inheritDoc} */
@Override
public Object polled(final Wire wire) {
return this.wireSupport.polled(wire);
}
/** {@inheritDoc} */
@Override
public void producersConnected(final Wire[] wires) {
this.wireSupport.producersConnected(wires);
}
/** {@inheritDoc} */
@Override
public void updated(final Wire wire, final Object value) {
this.wireSupport.updated(wire, value);
}
}
| epl-1.0 |
sleshchenko/che | plugins/plugin-help/che-plugin-help-ext-client/src/main/java/org/eclipse/che/ide/ext/help/client/RedirectToSupportAction.java | 1674 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ext.help.client;
import static com.google.common.base.Strings.isNullOrEmpty;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.ProductInfoDataProvider;
import org.eclipse.che.ide.api.action.ActionEvent;
import org.eclipse.che.ide.api.action.BaseAction;
import org.eclipse.che.ide.util.browser.BrowserUtils;
/**
* Redirect to support window
*
* @author Oleksii Orel
* @author Alexander Andrienko
*/
@Singleton
public class RedirectToSupportAction extends BaseAction {
private final ProductInfoDataProvider productInfoDataProvider;
@Inject
public RedirectToSupportAction(
HelpExtensionLocalizationConstant locale,
ProductInfoDataProvider productInfoDataProvider,
AboutResources resources) {
super(
productInfoDataProvider.getSupportTitle(),
locale.actionRedirectToSupportDescription(),
resources.getSupport());
this.productInfoDataProvider = productInfoDataProvider;
}
@Override
public void actionPerformed(ActionEvent e) {
BrowserUtils.openInNewTab(productInfoDataProvider.getSupportLink());
}
@Override
public void update(ActionEvent event) {
event.getPresentation().setVisible(!isNullOrEmpty(productInfoDataProvider.getSupportLink()));
}
}
| epl-1.0 |
acleasby/sblim-cim-client | cim-client-java/src/main/java/org/sblim/wbem/xml/parser/InputSource.java | 1710 | /**
* InputSource.java
*
* (C) Copyright IBM Corp. 2005, 2009
*
* THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
* ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
* CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
*
* You can obtain a current copy of the Eclipse Public License from
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* @author: Roberto Pineiro, IBM, roberto.pineiro@us.ibm.com
* @author: Chung-hao Tan, IBM ,chungtan@us.ibm.com
*
*
* Change History
* Flag Date Prog Description
*-------------------------------------------------------------------------------
* 1535756 2006-08-07 lupusalex Make code warning free
* 2807325 2009-06-22 blaschke-oss Change licensing from CPL to EPL
*
*/
package org.sblim.wbem.xml.parser;
import java.io.InputStream;
import java.io.Reader;
public class InputSource {
// private String iPublicId;
//
// private String iSystemId;
private InputStream iByteStream;
private String iEncoding;
private Reader iCharacterStream;
public InputSource() {}
public InputSource(Reader characterStream) {
iCharacterStream = characterStream;
}
public InputSource(InputStream byteStream) {
iByteStream = byteStream;
}
public void setCharacterStream(Reader characterStream) {
iCharacterStream = characterStream;
}
public void setEncoding(String encoding) {
iEncoding = encoding;
}
public String getEncoding() {
return iEncoding;
}
public Reader getCharacterStream() {
return iCharacterStream;
}
public InputStream getByteStream() {
return iByteStream;
}
}
| epl-1.0 |
StBurcher/hawkbit | hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/cache/RedisAutoConfiguration.java | 821 | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.autoconfigure.cache;
import org.eclipse.hawkbit.cache.RedisConfiguration;
import org.eclipse.hawkbit.cache.annotation.EnableRedis;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
/**
* A configuration for configuring the redis configuration.
*
*
*
*/
@Configuration
@ConditionalOnClass(value = RedisConfiguration.class)
@EnableRedis
public class RedisAutoConfiguration {
}
| epl-1.0 |
smadelenat/CapellaModeAutomata | Language/ExpressionLanguage/com.thalesgroup.trt.mde.vp.expression.model/src/com/thalesgroup/trt/mde/vp/expression/expression/BooleanExpression.java | 1564 | package com.thalesgroup.trt.mde.vp.expression.expression;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Boolean Expression</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.thalesgroup.trt.mde.vp.expression.expression.BooleanExpression#getAssignee <em>Assignee</em>}</li>
* </ul>
* </p>
*
* @see com.thalesgroup.trt.mde.vp.expression.expression.ExpressionPackage#getBooleanExpression()
* @model abstract="true"
* @generated
*/
public interface BooleanExpression extends Expression {
/**
* Returns the value of the '<em><b>Assignee</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Assignee</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Assignee</em>' reference.
* @see #setAssignee(Variable)
* @see com.thalesgroup.trt.mde.vp.expression.expression.ExpressionPackage#getBooleanExpression_Assignee()
* @model required="true"
* @generated
*/
Variable getAssignee();
/**
* Sets the value of the '{@link com.thalesgroup.trt.mde.vp.expression.expression.BooleanExpression#getAssignee <em>Assignee</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Assignee</em>' reference.
* @see #getAssignee()
* @generated
*/
void setAssignee(Variable value);
} // BooleanExpression
| epl-1.0 |
scmod/nexus-public | testsuite/legacy-testsuite/src/test/java/org/sonatype/nexus/testsuite/misc/nexus3860/Nexus3860Tomcat7WarCargoIT.java | 1127 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.testsuite.misc.nexus3860;
import java.io.File;
public class Nexus3860Tomcat7WarCargoIT
extends AbstractCargoIT
{
@Override
public File getContainerLocation() {
return util.resolveFile("target/containers/apache-tomcat-7.0.47");
}
@Override
public String getContainer() {
return "tomcat7x";
}
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.template | org.nabucco.framework.template.facade.service/src/main/gen/org/nabucco/framework/template/facade/service/pdf/merge/MergePdf.java | 1636 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.nabucco.framework.template.facade.service.pdf.merge;
import org.nabucco.framework.base.facade.message.ServiceRequest;
import org.nabucco.framework.base.facade.message.ServiceResponse;
import org.nabucco.framework.base.facade.service.Service;
import org.nabucco.framework.template.facade.exception.TemplateException;
import org.nabucco.framework.template.facade.message.pdf.MergePdfRq;
import org.nabucco.framework.template.facade.message.pdf.MergePdfRs;
/**
* MergePdf<p/>Merges PDF files.<p/>
*
* @version 1.0
* @author Raffael Bieniek, PRODYNA AG, 2011-07-04
*/
public interface MergePdf extends Service {
/**
* Produces a new PDF file based on several PDF Files.
*
* @param rq the ServiceRequest<MergePdfRq>.
* @return the ServiceResponse<MergePdfRs>.
* @throws TemplateException
*/
ServiceResponse<MergePdfRs> mergePdfFiles(ServiceRequest<MergePdfRq> rq) throws TemplateException;
}
| epl-1.0 |
StBurcher/hawkbit | hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java | 2742 | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.jpa;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
/**
* Custom repository implementation as standard spring repository fails as of
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=415027 .
*
*/
@Service
@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED)
public class EclipseLinkTargetInfoRepository implements TargetInfoRepository {
@Autowired
private EntityManager entityManager;
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void setTargetUpdateStatus(final TargetUpdateStatus status, final List<Long> targets) {
final Query query = entityManager.createQuery(
"update JpaTargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status");
query.setParameter("targets", targets);
query.setParameter("status", status);
}
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true)
public <S extends JpaTargetInfo> S save(final S entity) {
if (entity.isNew()) {
entityManager.persist(entity);
return entity;
} else {
return entityManager.merge(entity);
}
}
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true)
public void deleteByTargetIdIn(final Collection<Long> targetIDs) {
final javax.persistence.Query query = entityManager
.createQuery("DELETE FROM JpaTargetInfo ti where ti.targetId IN :target");
query.setParameter("target", targetIDs);
}
}
| epl-1.0 |
moliz/moliz.fuml | target/fuml/src/fUML/Semantics/Actions/IntermediateActions/WriteLinkActionActivation.java | 1624 |
/*
* Initial version copyright 2008 Lockheed Martin Corporation, except
* as stated in the file entitled Licensing-Information.
*
* All modifications copyright 2009 Data Access Technologies, Inc.
*
* Licensed under the Academic Free License version 3.0
* (http://www.opensource.org/licenses/afl-3.0.php), except as stated
* in the file entitled Licensing-Information.
*
* Contributors:
* MDS - initial API and implementation
*
*/
package fUML.Semantics.Actions.IntermediateActions;
import fUML.Debug;
import UMLPrimitiveTypes.*;
import fUML.Syntax.*;
import fUML.Syntax.Classes.Kernel.*;
import fUML.Syntax.CommonBehaviors.BasicBehaviors.*;
import fUML.Syntax.CommonBehaviors.Communications.*;
import fUML.Syntax.Activities.IntermediateActivities.*;
import fUML.Syntax.Actions.BasicActions.*;
import fUML.Syntax.Actions.IntermediateActions.*;
import fUML.Semantics.*;
import fUML.Semantics.Classes.Kernel.*;
import fUML.Semantics.CommonBehaviors.BasicBehaviors.*;
import fUML.Semantics.Activities.IntermediateActivities.*;
import fUML.Semantics.Actions.BasicActions.*;
import fUML.Semantics.Loci.*;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>fUML::Semantics::Actions::IntermediateActions::WriteLinkActionActivation</b></em>
* '. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* </ul>
* </p>
*
* @generated
*/
public abstract class WriteLinkActionActivation extends
fUML.Semantics.Actions.IntermediateActions.LinkActionActivation {
} // WriteLinkActionActivation
| epl-1.0 |
gdevsign/pfrc | AppWebGBIE/src/java/session/ServiceFacade.java | 683 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.Service;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Fabou
*/
@Stateless
public class ServiceFacade extends AbstractFacade<Service> {
@PersistenceContext(unitName = "AppWebGBIEPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ServiceFacade() {
super(Service.class);
}
}
| gpl-2.0 |
ilario-pierbattista/studeasy | src/org/oop/controller/AttivitaController.java | 10740 | package org.oop.controller;
import org.oop.model.dao.AttivitaDAO;
import org.oop.model.dao.CicloDAO;
import org.oop.model.entities.*;
import org.oop.view.agenda.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Controller per i form di aggiunta di un'attivitร
*/
public class AttivitaController {
private FormAttivitaEvento formAttivitaEvento;
private FormAttivitaPeriodica formAttivitaPeriodica;
private FormEsame formEsame;
private AttivitaDAO attivitaDAO;
private CicloDAO cicloDAO;
public AttivitaController() {
attivitaDAO = new AttivitaDAO();
cicloDAO = new CicloDAO();
}
/**
* Imposta i listeners alla vista
*
* @param attivitaView Form a cui impostare i listeners
*/
public void setListenersToView(AttivitaView attivitaView) {
attivitaView.addEditButtonListener(new EditButtonAction());
attivitaView.addDeleteButtonListener(new DeleteButtonAction());
}
/**
* Metodo che aggiorna la view
*/
private void updateView() {
AgendaController.getInstance().updateAttivita(AgendaController.getInstance().getView().getInsegnamentoSelected());
}
/**
* Metodo per aprire il form corretto in base al bottone cliccato. Setta anche i listeners necessari per il
* funzionamento.
*/
public void openForm(String newActivityType) {
if (newActivityType.equals(Attivita.PROGETTO) || newActivityType.equals(Attivita.SEMINARIO)) {
createFormAttivitaEvento(null, newActivityType);
} else if (newActivityType.equals(Attivita.LEZIONE) || newActivityType.equals(Attivita.LABORATORIO)) {
createFormAttivitaPeriodica(null, newActivityType);
} else {
createFormEsame(null);
}
}
/**
* Metodo per aprire il form corretto di modifica in base all'attivita cliccata. Setta anche i listeners necessari
* per il funzionamento.
*/
public void openFormToModify(Attivita attivita) {
String categoria = attivita.getCategoria();
if (categoria.equals(Attivita.PROGETTO) || categoria.equals(Attivita.SEMINARIO)) {
createFormAttivitaEvento((AttivitaEvento) attivita, null);
} else if (categoria.equals(Attivita.LEZIONE) || categoria.equals(Attivita.LABORATORIO)) {
createFormAttivitaPeriodica((AttivitaPeriodica) attivita, null);
} else if (categoria.equals(Attivita.ESAME)) {
createFormEsame((Esame) attivita);
}
}
/**
* Crea un form per la modifica o la creazione di un esame
*
* @param esame Oggetto da cui estrarre i dati, se disponibile
*/
private void createFormEsame(Esame esame) {
formEsame = new FormEsame();
if (esame != null) {
formEsame.setActivityname("Modifica esame");
formEsame.fillForm(esame);
} else {
formEsame.setActivityname("Nuovo esame");
}
formEsame.addSubmitButtonListener(new SubmitFormEsameAction());
formEsame.addCancelButtonListener(new CloseFormEsameAction());
formEsame.addTipologiaProvaRadioListener(new SetTipologiaEsameAction());
}
/**
* Crea un form per la modifica o la creazione dei un'attivitร periodica
*
* @param attivitaPeriodica Oggetto da cui estrarre i dati, se disponibile
* @param categoriaAttivita Categoria dell'attivitร
*/
private void createFormAttivitaPeriodica(AttivitaPeriodica attivitaPeriodica, String categoriaAttivita) {
formAttivitaPeriodica = new FormAttivitaPeriodica();
String categoria;
String activityName;
if (attivitaPeriodica == null && categoriaAttivita != null) {
categoria = categoriaAttivita;
activityName = categoria.equals(Attivita.LEZIONE) ? "Nuova lezione" : "Nuovo laboratorio";
} else if (attivitaPeriodica != null) {
categoria = attivitaPeriodica.getCategoria();
activityName = categoria.equals(Attivita.LEZIONE) ? "Modifica lezione" : "Modifica laboratorio";
} else {
throw new IllegalArgumentException("attivitaPeriodica e categoriaAttivita non possono essere entrambi null");
}
formAttivitaPeriodica.setActivityname(activityName);
if (attivitaPeriodica != null) {
formAttivitaPeriodica.fillForm(attivitaPeriodica);
}
formAttivitaPeriodica.setCategoria(categoria);
formAttivitaPeriodica.addSubmitButtonListener(new SubmitFormPeriodicaAction());
formAttivitaPeriodica.addCancelButtonListener(new CloseFormPeriodicaAction());
}
/**
* Crea un form per la creazione o la modifica di un'attivitร evento
*
* @param attivitaEvento Oggetto da cui estrarre i dati, se disponibile
* @param categoriaAttivita Categoria dell'attivitร
*/
public void createFormAttivitaEvento(AttivitaEvento attivitaEvento, String categoriaAttivita) {
formAttivitaEvento = new FormAttivitaEvento();
String categoria;
String activityName;
if (attivitaEvento == null && categoriaAttivita != null) {
categoria = categoriaAttivita;
activityName = categoria.equals(Attivita.PROGETTO) ? "Nuovo progetto" : "Nuovo seminario";
} else if (attivitaEvento != null) {
categoria = attivitaEvento.getCategoria();
activityName = categoria.equals(Attivita.PROGETTO) ? "Modifica progetto" : "Modifica seminario";
} else {
throw new IllegalArgumentException("attivitaEvento e categoriaAttivita non possono essere entrambi null");
}
formAttivitaEvento.setActivityname(activityName);
if (attivitaEvento != null) {
formAttivitaEvento.fillForm(attivitaEvento);
}
formAttivitaEvento.setCategoria(categoria);
formAttivitaEvento.addSubmitButtonListener(new SubmitFormEventoAction());
formAttivitaEvento.addCancelButtonListener(new CloseFormEventoAction());
}
/**
* Salva l'attivitร creata nel database
*
* @param attivita Attivitร da salvare
*/
private void apply(Attivita attivita) {
Ciclo ciclo = AgendaView.getInstance().getCicloSelected();
Insegnamento insegnamento = AgendaView.getInstance().getInsegnamentoSelected();
if (attivita.getId() != 0) {
attivitaDAO.update(attivita);
} else {
attivitaDAO.persist(attivita);
insegnamento.addAttivita(attivita);
}
cicloDAO.update(ciclo);
cicloDAO.flush();
AgendaController.getInstance().refreshUtente();
}
/**
* Action per modifica un'attivitร
*/
class EditButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int id = Integer.parseInt(e.getActionCommand());
Attivita attivita = attivitaDAO.find(id);
openFormToModify(attivita);
}
}
/**
* Action che permetta l'eliminazione di un'attivita
*/
class DeleteButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int id = Integer.parseInt(e.getActionCommand());
Attivita attivita = attivitaDAO.find(id);
attivitaDAO.remove(attivita);
attivitaDAO.flush();
AgendaController.getInstance().refreshUtente();
updateView();
}
}
/**
* Action per il submit del form attivitaevento
*/
class SubmitFormEventoAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (formAttivitaEvento.isValid()) {
AttivitaEvento attivitaEvento = formAttivitaEvento.getNuovaAttivita();
apply(attivitaEvento);
updateView();
formAttivitaEvento.closeFrame();
}
}
}
/**
* Action per il submit del form attivita periodica
*/
class SubmitFormPeriodicaAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (formAttivitaPeriodica.isValid()) {
AttivitaPeriodica attivitaPeriodica = formAttivitaPeriodica.getNuovaAttivita();
apply(attivitaPeriodica);
updateView();
formAttivitaPeriodica.closeFrame();
}
}
}
/**
* Action per il submit del form attivita esame
*/
class SubmitFormEsameAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (formEsame.isValid()) {
Esame attivitaEsame = formEsame.getNuovaAttivita();
apply(attivitaEsame);
updateView();
formEsame.closeFrame();
}
}
}
/**
* Permette di gestire i radio button per la tipologia dell'esame
*/
class SetTipologiaEsameAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
AbstractButton button = (AbstractButton) e.getSource();
manageRadioButtons(button);
}
private void manageRadioButtons(AbstractButton b) {
formEsame.getOraleRadioButton().setSelected(false);
formEsame.getScrittoRadioButton().setSelected(false);
formEsame.getLaboratorioRadioButton().setSelected(false);
if (b.getText().equals("Scritto")) {
formEsame.getScrittoRadioButton().setSelected(true);
} else if (b.getText().equals("Orale")) {
formEsame.getOraleRadioButton().setSelected(true);
} else {
formEsame.getLaboratorioRadioButton().setSelected(true);
}
}
}
/**
* Action per chiudere il form attivita evento
*/
class CloseFormEventoAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
formAttivitaEvento.closeFrame();
}
}
/**
* Action per chiudere il form attivita periodica
*/
class CloseFormPeriodicaAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
formAttivitaPeriodica.closeFrame();
}
}
/**
* Action per chiudere il form esame
*/
class CloseFormEsameAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
formEsame.closeFrame();
}
}
}
| gpl-2.0 |
lancelotnull/winterfell | winterfell-core/src/main/java/com/lancelotbeta/winterfell/core/utils/function/Predicate.java | 199 | package com.lancelotbeta.winterfell.core.utils.function;
/**
*
* @author lancelot <cja.china@gmail.com>
* @date 2015ๅนด4ๆ18ๆฅ
*/
public interface Predicate<I> extends Func<I, Boolean> {
}
| gpl-2.0 |
UnlimitedDreams/Apsi | Apsi.Gipep/src/java/Entity/Telefonos.java | 1479 | package Entity;
// Generated 15/10/2015 01:16:32 AM by Hibernate Tools 4.3.1
import java.math.BigDecimal;
/**
* Telefonos generated by hbm2java
*/
public class Telefonos implements java.io.Serializable {
private BigDecimal codTelefono;
private Persona persona;
private String telefono;
private String ciudad;
private boolean tipo;
public Telefonos() {
}
public Telefonos(BigDecimal codTelefono, Persona persona, String telefono, String ciudad, boolean tipo) {
this.codTelefono = codTelefono;
this.persona = persona;
this.telefono = telefono;
this.ciudad = ciudad;
this.tipo = tipo;
}
public BigDecimal getCodTelefono() {
return this.codTelefono;
}
public void setCodTelefono(BigDecimal codTelefono) {
this.codTelefono = codTelefono;
}
public Persona getPersona() {
return this.persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getCiudad() {
return this.ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public boolean isTipo() {
return this.tipo;
}
public void setTipo(boolean tipo) {
this.tipo = tipo;
}
}
| gpl-2.0 |
ruicouto/XMIHandler | src/xmi/metamodel/content/UMLClassifierFeature.java | 1052 | package xmi.metamodel.content;
import java.util.ArrayList;
import java.util.List;
import xmi.metamodel.interfaces.XMISerializable;
public class UMLClassifierFeature implements XMISerializable {
private List<UMLAttribute> attributes;
private List<UMLOperation> operations;
protected UMLClassifierFeature() {
attributes = new ArrayList<>();
operations = new ArrayList<>();
}
public List<UMLAttribute> getAttributes() {
return attributes;
}
public List<UMLOperation> getOperations() {
return operations;
}
@Override
public String toXmi() {
StringBuilder sb = new StringBuilder();
sb.append("<UML:Classifier.feature>\n");
for(UMLAttribute a : attributes) {
sb.append(a.toXmi());
}
for(UMLOperation o : operations) {
sb.append(o.toXmi());
}
sb.append("</UML:Classifier.feature>\n");
return sb.toString();
}
@Override
public String toEcore() {
return "";
}
} | gpl-2.0 |
galcik/acprog-modules | acp/messenger/gep_stream_messenger/extras/java/GEPTest.java | 1293 | package net.acprog.modules.messenger;
import java.util.Scanner;
//Requires JSSC: https://github.com/scream3r/java-simple-serial-connector/releases
import net.acprog.modules.messenger.GEPMessenger.MessageListener;
import net.acprog.modules.messenger.GEPMessenger.SendRequest;
public class GEPTest {
public static void main(String[] args) {
// Create messenger with listener for receiving messages.
GEPMessenger messenger = new GEPMessenger("COM9", 9600, 100, new MessageListener() {
@Override
public void onMessageReceived(int tag, byte[] message) {
if (tag >= 0) {
System.out.println("Message received (tag " + tag + "): ");
} else {
System.out.println("Message received: ");
}
System.out.println(new String(message));
}
});
// Start messenger.
messenger.start();
// Send lines as messages to the messenger.
Scanner s = new Scanner(System.in);
int tagCounter = 1;
while (s.hasNextLine()) {
String line = s.nextLine();
SendRequest sr = messenger.sendMessage(line.getBytes(), tagCounter);
tagCounter++;
// Optional code that waits for completion of the message send.
try {
sr.waitForCompletion();
} catch (InterruptedException ignore) {
}
}
s.close();
}
}
| gpl-2.0 |
lexml/lexml-toolkit | lexml-toolkit-common/src/main/java/br/gov/lexml/exceptions/NotValidLexmlException.java | 269 | package br.gov.lexml.exceptions;
public class NotValidLexmlException extends Exception {
private static final long serialVersionUID = 235700172572775772L;
public NotValidLexmlException(){
super("Lexml da classe correta ou nรฃo รฉ valido");
}
}
| gpl-2.0 |
niloc132/mauve-gwt | src/main/java/gnu/testlet/java/util/Calendar/setTime.java | 1414 | /* setTime.java -- some checks for the setTime() method in the Calendar class.
Copyright (C) 2006 David Gilbert <david.gilbert@object-refinery.com>
This file is part of Mauve.
Mauve 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, or (at your option)
any later version.
Mauve is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with Mauve; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
*/
// Tags: JDK1.1
package gnu.testlet.java.util.Calendar;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.util.Calendar;
import java.util.Date;
public class setTime implements Testlet
{
public void test(TestHarness harness)
{
Calendar c = Calendar.getInstance();
c.setTime(new Date(123L));
harness.check(c.getTimeInMillis(), 123L);
// try null
boolean pass = false;
try
{
c.setTime(null);
}
catch (NullPointerException e)
{
pass = true;
}
harness.check(pass);
}
}
| gpl-2.0 |
league/rngzip | libs/msv/com/sun/msv/grammar/relax/RELAXExpressionVisitorBoolean.java | 829 | /*
* @(#)$Id: RELAXExpressionVisitorBoolean.java,v 1.5 2001/05/16 21:33:17 Bear Exp $
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package com.sun.msv.grammar.relax;
import com.sun.msv.grammar.ExpressionVisitorBoolean;
/**
* RELAX version of {@link ExpressionVisitorBoolean}.
*
* @author <a href="mailto:kohsuke.kawaguchi@eng.sun.com">Kohsuke KAWAGUCHI</a>
*/
public interface RELAXExpressionVisitorBoolean extends ExpressionVisitorBoolean {
// RELAX visitor can ignore onRef callback.
boolean onAttPool( AttPoolClause exp );
boolean onTag( TagClause exp );
boolean onElementRules( ElementRules exp );
boolean onHedgeRules( HedgeRules exp );
}
| gpl-2.0 |
darkmagician/SMPPSim | src/java/com/seleniumsoftware/SMPPSim/DeterministicLifeCycleManager.java | 3103 | /****************************************************************************
* DeterministicLifeCycleManager.java
*
* Copyright (C) Selenium Software Ltd 2006
*
* This file is part of SMPPSim.
*
* SMPPSim 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.
*
* SMPPSim is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SMPPSim; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @author martin@seleniumsoftware.com
* http://www.woolleynet.com
* http://www.seleniumsoftware.com
* $Header: /var/cvsroot/SMPPSim2/src/java/com/seleniumsoftware/SMPPSim/DeterministicLifeCycleManager.java,v 1.7 2012/11/12 19:09:59 martin Exp $
****************************************************************************/
package com.seleniumsoftware.SMPPSim;
import com.seleniumsoftware.SMPPSim.pdu.*;
import java.util.logging.*;
public class DeterministicLifeCycleManager extends LifeCycleManager {
private static Logger logger = Logger.getLogger("com.seleniumsoftware.smppsim");
private Smsc smsc = Smsc.getInstance();
private int discardThreshold;
public DeterministicLifeCycleManager() {
discardThreshold = SMPPSim.getDiscardFromQueueAfter();
logger.finest("discardThreshold=" + discardThreshold);
}
public MessageState setState(MessageState m) {
// Should a transition take place at all?
if (isTerminalState(m.getState()))
return m;
byte currentState = m.getState();
String dest = m.getPdu().getDestination_addr();
if (dest.substring(0, 1).equals("1")) {
m.setState(PduConstants.EXPIRED);
m.setErr(903);
} else if (dest.substring(0, 1).equals("2")) {
m.setState(PduConstants.DELETED);
m.setErr(904);
} else if (dest.substring(0, 1).equals("3")) {
m.setState(PduConstants.UNDELIVERABLE);
m.setErr(901);
} else if (dest.substring(0, 1).equals("4")) {
m.setState(PduConstants.ACCEPTED);
m.setErr(2);
} else if (dest.substring(0, 1).equals("5")) {
m.setState(PduConstants.REJECTED);
m.setErr(902);
} else {
m.setState(PduConstants.DELIVERED);
m.setErr(0);
}
if (isTerminalState(m.getState())) {
m.setFinal_time(System.currentTimeMillis());
// If delivery receipt requested prepare it....
SubmitSM p = m.getPdu();
logger.info("Message:"+p.getSeq_no()+" state="+getStateName(m.getState()));
if (p.getRegistered_delivery_flag() == 1 && currentState != m.getState()) {
prepDeliveryReceipt(m, p);
} else {
if (p.getRegistered_delivery_flag() == 2 && currentState != m.getState()) {
if (isFailure(m.getState())) {
prepDeliveryReceipt(m, p);
}
}
}
}
return m;
}
} | gpl-2.0 |
mjnichol/KillerKounter | src/com/killerkounter/DisplayCountersActivity.java | 7236 | package com.killerkounter;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
/**
* @author mjnichol
*/
public class DisplayCountersActivity extends ListActivity {
public final static String NEW_COUNTER_LIST = "com.killercounter.NEW_COUNTER_LIST";
// array adapter to notice changes to the counter list
private ArrayAdapter<Counter> mAdapter;
/**
* @uml.property name="my_counters"
* @uml.associationEnd
*/
private CounterList my_counters;
// button switches
private boolean rename = false;
private boolean reset = false;
Intent returnIntent = new Intent();
// turn the reset button on and off
public void toggleReset(View view){
this.reset = !this.reset;
}
// turn the rename button on and off
public void toggleRename(View view){
this.rename = !this.rename;
}
// intercept the back button signal and store counter state
@Override
public void onBackPressed() {
Toast.makeText(this,
"pressed back",
Toast.LENGTH_SHORT).show();
//save the counters
// make the new JSON for the counters
Gson gson = new Gson();
// extract the JSON
String jsonCounters = gson.toJson(my_counters);
// Now send back the data to the parent activity?
returnIntent.putExtra("countUpdate", jsonCounters);
setResult(RESULT_OK, returnIntent);
// do I add finish() now?
finish();
}
// intercept the key down button signal to save counter state
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
//save the counters
// make the new JSON for the counters
Gson gson = new Gson();
// extract the JSON
String jsonCounters = gson.toJson(my_counters);
// Now send back the data to the parent activity?
returnIntent.putExtra("countUpdate", jsonCounters);
setResult(RESULT_OK, returnIntent);
// do I add finish() now?
finish();
}
return super.onKeyDown(keyCode, event);
}
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the intent passed in
Intent intent = getIntent();
String CounterListJSON = intent.getStringExtra(MainActivity.COUNTER_LIST);
// Gson element
Gson gson = new Gson();
// extract the JSON
CounterList counters = gson.fromJson(CounterListJSON, CounterList.class);
this.my_counters = counters;
//you will have to use the swipe to unlock XML stuff to make this work as desired
setContentView(R.layout.activity_display_counters);
// Show the Up button in the action bar.
setupActionBar();
mAdapter = new ArrayAdapter<Counter>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
counters.getCounterList());
//new ArrayList<Counter>(Arrays.asList(items))); // pass the counter list here, overload the toString method so that things are displayed correctly
setListAdapter(mAdapter);
ListView listView = getListView();
// Create a ListView-specific touch listener. ListViews are given special treatment because
// by default they handle touches for their list items... i.e. they're in charge of drawing
// the pressed state (the list selector), handling list item clicks, etc.
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mAdapter.remove(mAdapter.getItem(position));
}
// call the counter list remove function here
mAdapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true); //was tru, but force user to use back to navigate
}
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_counters, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
//NavUtils.navigateUpFromSameTask(this);
//save the counters
// make the new JSON for the counters
Gson gson = new Gson();
// extract the JSON
String jsonCounters = gson.toJson(my_counters);
returnIntent.putExtra("countUpdate", jsonCounters);
setResult(RESULT_OK, returnIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
if(reset){
my_counters.getCounterList().get(position).Reset();
reset = !reset;
}
else if(rename){
EditText editText = (EditText) findViewById(R.id.edit_name);
String name = editText.getText().toString();
my_counters.getCounterList().get(position).Rename(name);
rename = !rename;
}
else{
my_counters.getCounterList().get(position).Increment();
}
mAdapter.notifyDataSetChanged();
onContentChanged(); // this causes the place in the list to go to the top
}
}
| gpl-2.0 |
dipacs/Viwib | trunk/src/Viwib/src/com/eagerlogic/viwib/ui/browse/Pager.java | 2949 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eagerlogic.viwib.ui.browse;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
/**
*
* @author dipacs
*/
public class Pager extends Parent {
public final SimpleIntegerProperty pageIndexProperty = new SimpleIntegerProperty(0);
public final SimpleBooleanProperty hasNextProperty = new SimpleBooleanProperty(true);
private EventHandler<Event> onNextClicked;
private EventHandler<Event> onPreviousClicked;
public Pager() {
HBox hb = new HBox(20);
this.getChildren().add(hb);
Button btnPrevious = new Button("< Prev");
btnPrevious.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if (onPreviousClicked != null) {
onPreviousClicked.handle(t);
}
}
});
btnPrevious.disableProperty().bind(new BooleanBinding() {
{
super.bind(pageIndexProperty);
}
@Override
protected boolean computeValue() {
return pageIndexProperty.get() < 1;
}
});
hb.getChildren().add(btnPrevious);
Text txtIndex = new Text();
txtIndex.textProperty().bind(new StringBinding() {
{
super.bind(pageIndexProperty);
}
@Override
protected String computeValue() {
return "" + (pageIndexProperty.get() + 1);
}
});
hb.getChildren().add(txtIndex);
Button btnNext = new Button("Next >");
btnNext.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if (onNextClicked != null) {
onNextClicked.handle(t);
}
}
});
btnNext.disableProperty().bind(hasNextProperty.not());
hb.getChildren().add(btnNext);
}
public EventHandler<Event> getOnNextClicked() {
return onNextClicked;
}
public void setOnNextClicked(EventHandler<Event> onNextClicked) {
this.onNextClicked = onNextClicked;
}
public EventHandler<Event> getOnPreviousClicked() {
return onPreviousClicked;
}
public void setOnPreviousClicked(EventHandler<Event> onPreviousClicked) {
this.onPreviousClicked = onPreviousClicked;
}
}
| gpl-2.0 |
Jonathanalfaro/ADSKiosko | ISADSKiosco/src/Datos/CDAlta.java | 11262 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Datos;
import java.util.ArrayList;
import VO.CVOCliente;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author lucas
*/
public class CDAlta {
private Connection mConexion = null;
private CDDAOFactory mDAOFactory = null;
private Statement mInstruccionSQL = null;
private ResultSet mResultSet = null;
/*
* Obtiene registros de la base de datos
* @return un ArrayList conteniendo los datos
* @throws SQLException En caso de error SQL
*/
public CDAlta() {
this.mDAOFactory = new CDDAOFactory();
}
/*
* Obtiene registros de la base de datos
* @return un ArrayList conteniendo los datos
* @throws SQLException En caso de error SQL
*/
public ArrayList<CVOCliente> getListaClientes()throws SQLException {
String lSQuery = "SELECT * FROM CLIENTE";
ArrayList<CVOCliente> lALListaClientes = new ArrayList<CVOCliente>();
System.out.println(lSQuery);
try {
//Obtiene una conexiรณn con la base de datos
this.mConexion = this.mDAOFactory.abreConexion();
//Crea la Instrucciรณn
this.mInstruccionSQL = this.mConexion.createStatement();
//Ejecuta la consulta SQL
this.mResultSet = this.mInstruccionSQL.executeQuery(lSQuery);
/* Al principio el ResultSet estยท posicionado antes del primer registro (en donde se encuentran los metadatos),
* por lo que hay que recorrerlo al primer registro, y si no existe ninguno
* el resultset regresa falso.
*/
while(mResultSet.next()) {
//Con rs.getXXXX podemos obtener datos del ResultSet, de tipo int, float, etc.
CVOCliente lVOClientes = new CVOCliente(mResultSet.getLong(1),"" + mResultSet.getString(2) ,mResultSet.getDate(3),mResultSet.getString(4).charAt(0),mResultSet.getInt(5),mResultSet.getInt(6),""+mResultSet.getString(7),mResultSet.getDate(8),mResultSet.getInt(9));
//Agregamos a la colecciรn los VO generados en la instrucciรn anterior
lALListaClientes.add(lVOClientes);
} //fin de while
//Regresamos los datos contenidos en la colecciรn haciendo un cast y
//convirtiendo la colecciรn en ArrayList
} catch (SQLException ex) {
ex.printStackTrace();
if (this.mConexion == null) {
throw new SQLException("No es posible establecer la conexion");
}
} finally {
try {
if(this.mResultSet != null) {
this.mResultSet.close();
}
if(this.mInstruccionSQL != null) {
this.mInstruccionSQL.close();
}
if(this.mConexion != null) {
this.mConexion.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
lALListaClientes = null;
}
}
return lALListaClientes;
}
/*
* Agrega un registro a la base de datos
* @param alumno VoAlumno con los datos a a gregar
* @throws SQLException En caso de Error
*/
public void setAgregaCliente(CVOCliente pVOCliente) throws SQLException {
try {
//String con la instrucciรณn SQL
String lSQuery = "INSERT INTO CLIENTE ( idCliente, NombreCliente, FechaNacimiento, Sexo, Tarjeta, CodigoTarjeta, Direccion, FechaInsc, idKiosco) " +
"VALUES( " + "'" + pVOCliente.getidCliente().toString() + "', " +
"'" + pVOCliente.getNombreCliente() + "', " +
"'" + pVOCliente.getFechaNacimiento() + "'," +
"'" + pVOCliente.getSexo()+ "'," +
"'" + pVOCliente.getTarjeta()+ "'," +
"'" + pVOCliente.getCodigoTarjeta()+ "'," +
"'" + pVOCliente.getDireccion()+ "'," +
"'" + pVOCliente.getFechaInsc()+ "'," +
"'" + "1" + "');";
System.out.println(lSQuery); //para efectos de depuracion
//Obtiene una conexiรn con la base de datos
this.mConexion = mDAOFactory.abreConexion();
//Crea la Instrucciรn
this.mInstruccionSQL = mConexion.createStatement();
//Ejecuta la sentencia SQL
this.mInstruccionSQL.execute(lSQuery);
//Guarda los cambios
this.mConexion.commit();
}
catch (SQLException e) {
System.out.println(e.getErrorCode());
if (e.getErrorCode() == 1062)
throw new SQLException("Matricula Repedida");
if (this.mConexion == null) {
throw new SQLException("No es posible establecer la conexion");
}
}
finally {
try {
//Cierra el statement
if(this.mInstruccionSQL != null) {
this.mInstruccionSQL.close();
}
//Cerramos conexion
if(this.mConexion != null) {
this.mConexion.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
/*
* Elimina un registro
* @param alumno VoAlumno con los valores del registro a eliminar
* @throws SQLException En caso de error
*/
public void setModificaAlumno(CVOCliente pVOCliente) {
try {
String lSQuery = "UPDATE CLIENTE SET " +
"NombreCliente = '" + pVOCliente.getNombreCliente() + "', " +
"FechaNacimiento = '" + pVOCliente.getFechaNacimiento() + "', " +
"Sexo = '" + pVOCliente.getSexo() + "', " +
"Tarjeta = '" + pVOCliente.getTarjeta()+"'," +
"CodigoTarjeta = '" + pVOCliente.getCodigoTarjeta()+"'," +
"Direccion = '"+ pVOCliente.getDireccion()+"',"+
"FechaInsc = '" + pVOCliente.getFechaInsc()+"' " +
"WHERE idCliente = '" + pVOCliente.getidCliente() + "'";
System.out.println(lSQuery); //para efectos de depuracion
//Obtiene una conexiรn con la base de datos
this.mConexion = mDAOFactory.abreConexion();
// Crea el statement
mInstruccionSQL = mConexion.createStatement();
//Ejecuta la sentencia SQL
mInstruccionSQL.execute(lSQuery);
//Guarda los cambios
//mConexion.commit();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
//Cierra el statement
if(this.mInstruccionSQL != null) {
this.mInstruccionSQL.close();
}
//Cerramos conexion
if(this.mConexion != null) {
this.mConexion.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
/*
* Elimina un registro
* @param alumno VoAlumno con los valores del registro a eliminar
* @throws SQLException En caso de error
*/
public void setEliminaCliente(CVOCliente pVOCliente) {
try {
String lSQuery = "DELETE FROM CLIENTE WHERE " +
"idCliente = '" + pVOCliente.getidCliente() + "'" ;
System.out.println(lSQuery); //para efectos de depuracion
//Obtiene una conexiรn con la base de datos
this.mConexion = mDAOFactory.abreConexion();
// Crea el statement
mInstruccionSQL = mConexion.createStatement();
//Ejecuta la sentencia SQL
mInstruccionSQL.execute(lSQuery);
//Guarda los cambios
//mConexion.commit();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
//Cierra el statement
if(this.mInstruccionSQL != null) {
this.mInstruccionSQL.close();
}
//Cerramos conexion
if(this.mConexion != null) {
this.mConexion.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
public CVOCliente buscaCliente(Long pidCliente) throws SQLException{
String lSQuery = "SELECT * FROM CLIENTE WHERE idCliente = '"+pidCliente+"'";
System.out.println(lSQuery);
try {
//Obtiene una conexiรณn con la base de datos
this.mConexion = this.mDAOFactory.abreConexion();
//Crea la Instrucciรณn
this.mInstruccionSQL = this.mConexion.createStatement();
//Ejecuta la consulta SQL
this.mResultSet = this.mInstruccionSQL.executeQuery(lSQuery);
if(mResultSet.next()) {
CVOCliente voCliente = new CVOCliente(mResultSet.getLong(1),"" + mResultSet.getString(2) ,mResultSet.getDate(3),mResultSet.getString(4).charAt(0),mResultSet.getInt(5),mResultSet.getInt(6),""+mResultSet.getString(7),mResultSet.getDate(8),mResultSet.getInt(9));
return voCliente ;
}
else{
return null;
}
} catch (SQLException ex) {
if (this.mConexion == null) {
throw new SQLException("No es posible establecer la conexion");
}
}catch(NullPointerException npe){
return null;
} finally {
try {
if(this.mResultSet != null) {
this.mResultSet.close();
}
if(this.mInstruccionSQL != null) {
this.mInstruccionSQL.close();
}
if(this.mConexion != null) {
this.mConexion.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/*
* Cierra la conexiรณn
* @throws SQLException En caso de no poder cerrar la conexiรn
*/
public void CierraConexion()throws SQLException {
if(mConexion != null) {
mConexion.close();
System.out.println("Conexiรณn cerrada." );
}
}
}
| gpl-2.0 |
mwach/tactics | src/main/java/itti/com/pl/eda/tactics/gui/DialogActCond.java | 5240 | package itti.com.pl.eda.tactics.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* wrapper for JDialog component
* used to construct GUI dialogs
* @author marcin
*
*/
public class DialogActCond extends JDialog{
private static final long serialVersionUID = 1L;
/**
* data type defined for dialog
* @author marcin
*
*/
public enum ElementTypes{
Condition,
TimeCondition,
Action
};
private ElementTypes currentType = null;
private IFormDataExchangeIntegrace formParent = null;
private List<String[]> elements = null;
private boolean[] states = null;
private JButton buttonOk = new JButton("OK");
private JButton buttonCancel = new JButton("Cancel");
private JPanel panelButtons = new JPanel();
private int desktopWidth = -1;
private int desktopHeight = -1;
private final int panelWidth = 500;
private final int buttonWidth = 100;
private final int buttonHeight = 20;
/**
* default constructor
* @param owner JFrame object
* @param requestForm observer form - all events from this object will be sent to the observer
*/
public DialogActCond(JFrame owner, IFormDataExchangeIntegrace requestForm){
super(owner, "Policy conditions", true);
formParent = requestForm;
setModal(true);
desktopWidth = GuiUtils.getScreenWidth();
desktopHeight = GuiUtils.getScreenHeight();
this.setLayout(null);
int buttonMarginWidth = (panelWidth - 3 * buttonWidth) / 4;
panelButtons.setLayout(null);
panelButtons.setSize(panelWidth, buttonHeight);
buttonOk.setSize(buttonWidth, buttonHeight);
int widthButtonOk = buttonMarginWidth;
buttonOk.setLocation(widthButtonOk , 0);
panelButtons.add(buttonOk);
buttonCancel.setSize(buttonWidth, buttonHeight);
int widthButtonCancel = 3 * buttonMarginWidth + 2 * buttonWidth;
buttonCancel.setLocation(widthButtonCancel, 0);
panelButtons.add(buttonCancel);
addWindowListener(new WindowListener(){
public void windowActivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0) {
dispose();
}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
buttonOk.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
if(currentType != null && formParent != null){
if(currentType == ElementTypes.Action){
formParent.processUpdateActions(states);
}else if(currentType == ElementTypes.Condition){
formParent.processUpdateConditions(states);
}else if(currentType == ElementTypes.TimeCondition){
formParent.processUpdateTimeConditions(states);
}
}
dispose();
}
});
buttonCancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
/**
* sets type of the dialog
* @param type
*/
public void setElementsType(ElementTypes type){
currentType = type;
}
/**
* sets elements, which will be displayed on the dialog
* @param elements list of elements
*/
public void setElements(List<String[]> elements){
this.elements = elements;
if(elements != null){
states = new boolean[elements.size()];
for(int i=0 ; i<states.length ; i++){
states[i] = true;
}
}else{
states = null;
}
}
@Override
public void setVisible(boolean state) {
if(state){
int conditionsHeight = (elements == null ? 0 : elements.size() * 20);
int dialogWidth = panelWidth;
int dialogHeight = conditionsHeight + 100;
setSize(dialogWidth, dialogHeight);
setLocation((desktopWidth - dialogWidth)/ 2, (desktopHeight - dialogHeight)/ 2);
panelButtons.setLocation(0, dialogHeight - 50);
this.getContentPane().add(panelButtons);
if(elements != null){
int cnt = 0;
for (String[] condition : elements) {
String conditionStr = null;
if(condition.length == 3){
conditionStr = condition[0] + " " + condition[1] + " " + condition[2];
}else{
conditionStr = condition[0];
}
final JCheckBox checkBoxCond = new JCheckBox(conditionStr, true);
checkBoxCond.setSize(panelWidth, buttonHeight);
checkBoxCond.setLocation(20, 10 + cnt * buttonHeight);
this.getContentPane().add(checkBoxCond);
checkBoxCond.setName(cnt + "");
checkBoxCond.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
boolean state = checkBoxCond.isSelected();
int cnt = Integer.parseInt(checkBoxCond.getName());
states[cnt] = state;
}
});
cnt++;
}
}
}
super.setVisible(state);
}
} | gpl-2.0 |
delleceste/wwwsapp | src/it/giacomos/android/wwwsapp/layers/LayerListDownloadService.java | 3779 | /**
*
*/
package it.giacomos.android.wwwsapp.layers;
import it.giacomos.android.wwwsapp.layers.installService.InstallTaskState;
import it.giacomos.android.wwwsapp.network.state.Urls;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
/**
* @author giacomo
*
*/
public class LayerListDownloadService extends Service implements LayerFetchTaskListener {
private String mErrorMsg;
private String mAppLang;
private int mAppVersionCode;
private LayerListDownloadServiceState mState;
private LayerFetchTask mLayerFetchTask;
/**
* @param name
*/
public LayerListDownloadService() {
super();
mErrorMsg = "";
}
/** If wi fi network is enabled, I noticed that turning on 3G network as well
* produces this method to be invoked another times. That is, the ConnectivityChangedReceiver
* triggers a Service start command. In this case, we must avoid that the handler schedules
* another execution of the timer.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mAppVersionCode = intent.getIntExtra("version", -1);
mAppLang = intent.getStringExtra("lang");
if(intent.hasExtra("download"))
mDownloadLayersList();
else if(intent.hasExtra("cancel"))
mCancelDownload();
return Service.START_STICKY;
}
private void mCancelDownload()
{
if(mLayerFetchTask != null && mLayerFetchTask.getStatus() != AsyncTask.Status.FINISHED)
mLayerFetchTask.cancel(true);
/* state cancelled will be set by onLayerFetchCancelled */
}
private void mDownloadLayersList()
{
mState = LayerListDownloadServiceState.DOWNLOADING;
if(mLayerFetchTask != null && mLayerFetchTask.getStatus() != AsyncTask.Status.FINISHED)
mLayerFetchTask.cancel(true);
mLayerFetchTask = new LayerFetchTask(this, mAppVersionCode, mAppLang, this);
mLayerFetchTask.execute();
}
private void mNotifyStateChanged(String layer, float version, int percent)
{
Intent stateChangedNotif = new Intent(LayerListActivity.LIST_DOWNLOAD_SERVICE_STATE_CHANGED_INTENT);
stateChangedNotif.putExtra("listDownloadServiceState", mState);
stateChangedNotif.putExtra("percent", percent);
stateChangedNotif.putExtra("error", mErrorMsg);
if(layer.length() > 0)
{
stateChangedNotif.putExtra("layerName", layer);
stateChangedNotif.putExtra("version", version);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(stateChangedNotif);
}
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onLayersUpdated(boolean success, String errorMessage)
{
if(!success)
{
mErrorMsg = errorMessage;
mState = LayerListDownloadServiceState.ERROR;
}
mState = LayerListDownloadServiceState.COMPLETE;
mNotifyStateChanged("", -1, 100);
}
@Override
public void onLayerFetchProgress(LayerFetchTaskProgressData d)
{
mState = LayerListDownloadServiceState.DOWNLOADING;
Log.e("LayerListDownloadService.onLayerFetchProgress", " percent " + d.percent);
mNotifyStateChanged(d.name, d.available_version, d.percent);
}
@Override
public void onLayerFetchCancelled()
{
mState = LayerListDownloadServiceState.CANCELLED;
mNotifyStateChanged("", -1, 100);
}
}
| gpl-2.0 |
Menichelli/IdentifyProteinDomains | IdentifyProteinDomains/src/tools/HitsGathering.java | 5093 | package tools;
import filter.FilterFacade;
import filter.impl.BestEvalueFilter;
import filter.impl.BoundShrinker;
import filter.impl.LowComplexityFilter;
import filter.impl.TooFewHitsFilter;
import filter.impl.TooLongHitsFilter;
import filter.impl.TooShortHitsFilter;
import filter.impl.TooSmallDomainFilter;
import global.Global;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import model.BlastHit;
import model.PutativeDomain;
import model.Protein;
public class HitsGathering {
private HitsGathering() {}
public static Set<PutativeDomain> gatherHits(List<BlastHit> listHits, Protein protein, Set<PutativeDomain> forbiddenRegions) throws Exception {
Set<PutativeDomain> ret = new HashSet<PutativeDomain>();
if(forbiddenRegions==null) forbiddenRegions = new HashSet<PutativeDomain>(); //on first iteration
//compute coverage
int[] coverage = new int[protein.getSequence().length()];
for(int i = 0; i < coverage.length; i++) coverage[i] = 0;
for(BlastHit bh : listHits) {
if(!Global.EXCLUDE_SPECIES_SET.contains(bh.getSubjectSpecies()) && canIuse(bh, forbiddenRegions)) {
for(int i=bh.getqStart()-1; i<=bh.getqEnd()-1; i++) {
coverage[i]++;
}
}
}
// //debug==
// System.out.print("\n"+protein.getProtName()+"\ndata <- c(");
// for(int i=0; i<coverage.length; i++) {
// System.out.print(coverage[i]+",");
// }
// System.out.println(")");
// //==debug
//cut in putative domain
Set<PutativeDomain> pDomains = new HashSet<PutativeDomain>();
PutativeDomain currentPutativeDomain = null;
for(int index = 0; index < coverage.length; index++) {
if(coverage[index]>=Global.NUMBER_OF_HITS_MIN) {
if(currentPutativeDomain==null) currentPutativeDomain = new PutativeDomain(protein.getProtName(),protein.getSpecies(),index+1, index+1);
else currentPutativeDomain.setDomainEnd(currentPutativeDomain.getDomainEnd()+1);
} else {
if(currentPutativeDomain==null) continue;
else {
pDomains.add(currentPutativeDomain);
currentPutativeDomain = null;
}
}
}
if(currentPutativeDomain!=null) pDomains.add(currentPutativeDomain);
//supprime les domaines trop petits
pDomains = FilterFacade.applyFilter(TooSmallDomainFilter.class, pDomains);
//ajoute tous les hits dans les putative domains correspondant
for(BlastHit bh : listHits) {
for(PutativeDomain pd : pDomains) {
if(isIn(bh, pd)) pd.addBlastHit(bh);
}
}
//supprime les hits redondants
pDomains = FilterFacade.applyFilter(BestEvalueFilter.class, pDomains);
pDomains = FilterFacade.applyFilter(TooFewHitsFilter.class, pDomains);
//raccourci les bornes, verifie si les hits sont encore bien dedans
pDomains = FilterFacade.applyFilter(TooLongHitsFilter.class, pDomains);
pDomains = FilterFacade.applyFilter(TooFewHitsFilter.class, pDomains);
pDomains = FilterFacade.applyFilter(BoundShrinker.class, pDomains);
pDomains = FilterFacade.applyFilter(TooSmallDomainFilter.class, pDomains);
//low complexity filter
pDomains = FilterFacade.applyFilter(LowComplexityFilter.class, pDomains);
//les hits trop courts
pDomains = FilterFacade.applyFilter(TooShortHitsFilter.class, pDomains);
pDomains = FilterFacade.applyFilter(TooFewHitsFilter.class, pDomains);
ret.addAll(pDomains);
return ret;
}
/**
* Can I use this hit when computing the coverage
* @param bh
* @param pd
* @return
*/
private static boolean canIuse(BlastHit bh, Set<PutativeDomain> forbiddenRegions) {
boolean ret = true;
for(PutativeDomain domain : forbiddenRegions) {
if(getOverlapSize(bh, domain)>0) {
ret = false;
break;
}
}
return ret;
}
/**
* Determine if the blasthit is in a given putative domain
* @param bh
* @param pd
* @return
*/
private static boolean isIn(BlastHit bh, PutativeDomain pd) {
boolean ret = false;
if(getOverlapSize(bh, pd) >= (bh.getqEnd()-bh.getqStart())*Global.OVERLAP_RATE_MIN) { //if overlap by at least X%
ret = true;
}
return ret;
}
private static int getOverlapSize(BlastHit bh, PutativeDomain pd) {
int ret = 0;
if(bh.getqStart() < pd.getDomainStart() && bh.getqEnd() > pd.getDomainEnd()) {
ret = pd.getDomainEnd() - pd.getDomainStart() + 1;
} else if(bh.getqStart() < pd.getDomainEnd() && bh.getqEnd() > pd.getDomainEnd()) {
ret = pd.getDomainEnd() - Math.max(bh.getqStart(),pd.getDomainStart()) + 1;//
} else if(bh.getqStart() < pd.getDomainStart() && bh.getqEnd() > pd.getDomainStart()) {
ret = Math.min(bh.getqEnd(),pd.getDomainEnd()) - pd.getDomainStart() + 1;//
} else if(bh.getqStart() > pd.getDomainStart() && bh.getqEnd() < pd.getDomainEnd()) {
ret = bh.getqEnd() - bh.getqStart() + 1;
} else if(bh.getqStart()==pd.getDomainStart()) {
ret = Math.min(bh.getqEnd(), pd.getDomainEnd()) - bh.getqStart() + 1;
} else if(bh.getqEnd()==pd.getDomainEnd()) {
ret = bh.getqEnd() - Math.max(bh.getqStart(), pd.getDomainStart()) +1;
} else if(bh.getqStart()==pd.getDomainEnd() || bh.getqEnd()==pd.getDomainStart()) {
ret = 1;
}
return ret;
}
}
| gpl-2.0 |
iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/src/com/iucn/whp/dbservice/service/base/contact_categoryLocalServiceBaseImpl.java | 175731 | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.service.base;
import com.iucn.whp.dbservice.model.contact_category;
import com.iucn.whp.dbservice.service.active_conservation_projectsLocalService;
import com.iucn.whp.dbservice.service.advance_query_assessmentLocalService;
import com.iucn.whp.dbservice.service.advance_query_siteLocalService;
import com.iucn.whp.dbservice.service.assessing_threats_currentLocalService;
import com.iucn.whp.dbservice.service.assessing_threats_potentialLocalService;
import com.iucn.whp.dbservice.service.assessment_lang_lkpLocalService;
import com.iucn.whp.dbservice.service.assessment_lang_versionLocalService;
import com.iucn.whp.dbservice.service.assessment_stagesLocalService;
import com.iucn.whp.dbservice.service.assessment_statusLocalService;
import com.iucn.whp.dbservice.service.assessment_validationLocalService;
import com.iucn.whp.dbservice.service.assessment_whvaluesLocalService;
import com.iucn.whp.dbservice.service.assessment_whvalues_whcriterionLocalService;
import com.iucn.whp.dbservice.service.benefit_checksubtype_lkpLocalService;
import com.iucn.whp.dbservice.service.benefit_checktype_lkpLocalService;
import com.iucn.whp.dbservice.service.benefit_rating_lkpLocalService;
import com.iucn.whp.dbservice.service.benefitsLocalService;
import com.iucn.whp.dbservice.service.benefits_summaryLocalService;
import com.iucn.whp.dbservice.service.benefits_type_refLocalService;
import com.iucn.whp.dbservice.service.biodiversity_valuesLocalService;
import com.iucn.whp.dbservice.service.boundary_modification_type_lkpLocalService;
import com.iucn.whp.dbservice.service.conservation_outlookLocalService;
import com.iucn.whp.dbservice.service.conservation_outlook_rating_lkpLocalService;
import com.iucn.whp.dbservice.service.contact_categoryLocalService;
import com.iucn.whp.dbservice.service.country_lkpLocalService;
import com.iucn.whp.dbservice.service.current_state_trendLocalService;
import com.iucn.whp.dbservice.service.current_state_trend_valuesLocalService;
import com.iucn.whp.dbservice.service.current_threat_assessment_catLocalService;
import com.iucn.whp.dbservice.service.current_threat_valuesLocalService;
import com.iucn.whp.dbservice.service.danger_list_status_lkpLocalService;
import com.iucn.whp.dbservice.service.docs_customDataLocalService;
import com.iucn.whp.dbservice.service.docs_sitedataLocalService;
import com.iucn.whp.dbservice.service.effective_prot_mgmt_iothreatsLocalService;
import com.iucn.whp.dbservice.service.flagship_species_lkpLocalService;
import com.iucn.whp.dbservice.service.inscription_criteria_lkpLocalService;
import com.iucn.whp.dbservice.service.inscription_type_lkpLocalService;
import com.iucn.whp.dbservice.service.iucn_pa_lkp_categoryLocalService;
import com.iucn.whp.dbservice.service.iucn_regionLocalService;
import com.iucn.whp.dbservice.service.iucn_region_countryLocalService;
import com.iucn.whp.dbservice.service.key_conservation_issuesLocalService;
import com.iucn.whp.dbservice.service.key_conservation_scale_lkpLocalService;
import com.iucn.whp.dbservice.service.mission_lkpLocalService;
import com.iucn.whp.dbservice.service.negative_factors_level_impactLocalService;
import com.iucn.whp.dbservice.service.negative_factors_trendLocalService;
import com.iucn.whp.dbservice.service.other_designation_lkpLocalService;
import com.iucn.whp.dbservice.service.persistence.active_conservation_projectsPersistence;
import com.iucn.whp.dbservice.service.persistence.advance_query_assessmentPersistence;
import com.iucn.whp.dbservice.service.persistence.advance_query_sitePersistence;
import com.iucn.whp.dbservice.service.persistence.assessing_threats_currentPersistence;
import com.iucn.whp.dbservice.service.persistence.assessing_threats_potentialPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_lang_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_lang_versionPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_stagesPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_statusPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_validationPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_whvaluesPersistence;
import com.iucn.whp.dbservice.service.persistence.assessment_whvalues_whcriterionPersistence;
import com.iucn.whp.dbservice.service.persistence.benefit_checksubtype_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.benefit_checktype_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.benefit_rating_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.benefitsPersistence;
import com.iucn.whp.dbservice.service.persistence.benefits_summaryPersistence;
import com.iucn.whp.dbservice.service.persistence.benefits_type_refPersistence;
import com.iucn.whp.dbservice.service.persistence.biodiversity_valuesPersistence;
import com.iucn.whp.dbservice.service.persistence.boundary_modification_type_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.conservation_outlookPersistence;
import com.iucn.whp.dbservice.service.persistence.conservation_outlook_rating_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.contact_categoryPersistence;
import com.iucn.whp.dbservice.service.persistence.country_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.current_state_trendPersistence;
import com.iucn.whp.dbservice.service.persistence.current_state_trend_valuesPersistence;
import com.iucn.whp.dbservice.service.persistence.current_threat_assessment_catPersistence;
import com.iucn.whp.dbservice.service.persistence.current_threat_valuesPersistence;
import com.iucn.whp.dbservice.service.persistence.danger_list_status_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.docs_customDataFinder;
import com.iucn.whp.dbservice.service.persistence.docs_customDataPersistence;
import com.iucn.whp.dbservice.service.persistence.docs_sitedataPersistence;
import com.iucn.whp.dbservice.service.persistence.effective_prot_mgmt_iothreatsPersistence;
import com.iucn.whp.dbservice.service.persistence.flagship_species_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.inscription_criteria_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.inscription_type_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.iucn_pa_lkp_categoryPersistence;
import com.iucn.whp.dbservice.service.persistence.iucn_regionPersistence;
import com.iucn.whp.dbservice.service.persistence.iucn_region_countryPersistence;
import com.iucn.whp.dbservice.service.persistence.key_conservation_issuesPersistence;
import com.iucn.whp.dbservice.service.persistence.key_conservation_scale_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.mission_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.negative_factors_level_impactPersistence;
import com.iucn.whp.dbservice.service.persistence.negative_factors_trendPersistence;
import com.iucn.whp.dbservice.service.persistence.other_designation_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.potential_project_needsPersistence;
import com.iucn.whp.dbservice.service.persistence.potential_threat_assessment_catPersistence;
import com.iucn.whp.dbservice.service.persistence.potential_threat_valuesPersistence;
import com.iucn.whp.dbservice.service.persistence.prot_mgmt_best_practicesPersistence;
import com.iucn.whp.dbservice.service.persistence.prot_mgmt_overallPersistence;
import com.iucn.whp.dbservice.service.persistence.protection_managementPersistence;
import com.iucn.whp.dbservice.service.persistence.protection_management_ratings_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.protection_mgmt_checklist_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.recommendation_type_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.referencesPersistence;
import com.iucn.whp.dbservice.service.persistence.reinforced_monitoringPersistence;
import com.iucn.whp.dbservice.service.persistence.site_assessmentFinder;
import com.iucn.whp.dbservice.service.persistence.site_assessmentPersistence;
import com.iucn.whp.dbservice.service.persistence.site_assessment_versionsFinder;
import com.iucn.whp.dbservice.service.persistence.site_assessment_versionsPersistence;
import com.iucn.whp.dbservice.service.persistence.sites_thematicPersistence;
import com.iucn.whp.dbservice.service.persistence.state_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.state_trend_biodivvalsPersistence;
import com.iucn.whp.dbservice.service.persistence.state_trend_whvaluesPersistence;
import com.iucn.whp.dbservice.service.persistence.thematic_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_categories_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_rating_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_subcategories_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_summary_currentPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_summary_overallPersistence;
import com.iucn.whp.dbservice.service.persistence.threat_summary_potentialPersistence;
import com.iucn.whp.dbservice.service.persistence.trend_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.unesco_regionPersistence;
import com.iucn.whp.dbservice.service.persistence.unesco_region_countryPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_contactPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_criteria_lkpPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_site_danger_listPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sitesFinder;
import com.iucn.whp.dbservice.service.persistence.whp_sitesPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_boundary_modificationPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_budgetPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_componentPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_contactsPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_countryPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_dsocrPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_external_documentsPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_flagship_speciesPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_indigenous_communitiesPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_inscription_criteriaPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_inscription_datePersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_iucn_pa_categoryPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_iucn_recommendationPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_meePersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_mgmt_plan_statePersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_missionPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_other_designationsPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_soc_reportsPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_soouvPersistence;
import com.iucn.whp.dbservice.service.persistence.whp_sites_visitorsPersistence;
import com.iucn.whp.dbservice.service.potential_project_needsLocalService;
import com.iucn.whp.dbservice.service.potential_threat_assessment_catLocalService;
import com.iucn.whp.dbservice.service.potential_threat_valuesLocalService;
import com.iucn.whp.dbservice.service.prot_mgmt_best_practicesLocalService;
import com.iucn.whp.dbservice.service.prot_mgmt_overallLocalService;
import com.iucn.whp.dbservice.service.protection_managementLocalService;
import com.iucn.whp.dbservice.service.protection_management_ratings_lkpLocalService;
import com.iucn.whp.dbservice.service.protection_mgmt_checklist_lkpLocalService;
import com.iucn.whp.dbservice.service.recommendation_type_lkpLocalService;
import com.iucn.whp.dbservice.service.referencesLocalService;
import com.iucn.whp.dbservice.service.reinforced_monitoringLocalService;
import com.iucn.whp.dbservice.service.site_assessmentLocalService;
import com.iucn.whp.dbservice.service.site_assessment_versionsLocalService;
import com.iucn.whp.dbservice.service.sites_thematicLocalService;
import com.iucn.whp.dbservice.service.state_lkpLocalService;
import com.iucn.whp.dbservice.service.state_trend_biodivvalsLocalService;
import com.iucn.whp.dbservice.service.state_trend_whvaluesLocalService;
import com.iucn.whp.dbservice.service.thematic_lkpLocalService;
import com.iucn.whp.dbservice.service.threat_categories_lkpLocalService;
import com.iucn.whp.dbservice.service.threat_rating_lkpLocalService;
import com.iucn.whp.dbservice.service.threat_subcategories_lkpLocalService;
import com.iucn.whp.dbservice.service.threat_summary_currentLocalService;
import com.iucn.whp.dbservice.service.threat_summary_overallLocalService;
import com.iucn.whp.dbservice.service.threat_summary_potentialLocalService;
import com.iucn.whp.dbservice.service.trend_lkpLocalService;
import com.iucn.whp.dbservice.service.unesco_regionLocalService;
import com.iucn.whp.dbservice.service.unesco_region_countryLocalService;
import com.iucn.whp.dbservice.service.whp_contactLocalService;
import com.iucn.whp.dbservice.service.whp_criteria_lkpLocalService;
import com.iucn.whp.dbservice.service.whp_site_danger_listLocalService;
import com.iucn.whp.dbservice.service.whp_site_danger_listService;
import com.iucn.whp.dbservice.service.whp_sitesLocalService;
import com.iucn.whp.dbservice.service.whp_sitesService;
import com.iucn.whp.dbservice.service.whp_sites_boundary_modificationLocalService;
import com.iucn.whp.dbservice.service.whp_sites_budgetLocalService;
import com.iucn.whp.dbservice.service.whp_sites_componentLocalService;
import com.iucn.whp.dbservice.service.whp_sites_contactsLocalService;
import com.iucn.whp.dbservice.service.whp_sites_countryLocalService;
import com.iucn.whp.dbservice.service.whp_sites_dsocrLocalService;
import com.iucn.whp.dbservice.service.whp_sites_external_documentsLocalService;
import com.iucn.whp.dbservice.service.whp_sites_flagship_speciesLocalService;
import com.iucn.whp.dbservice.service.whp_sites_indigenous_communitiesLocalService;
import com.iucn.whp.dbservice.service.whp_sites_inscription_criteriaLocalService;
import com.iucn.whp.dbservice.service.whp_sites_inscription_dateLocalService;
import com.iucn.whp.dbservice.service.whp_sites_iucn_pa_categoryLocalService;
import com.iucn.whp.dbservice.service.whp_sites_iucn_recommendationLocalService;
import com.iucn.whp.dbservice.service.whp_sites_iucn_recommendationService;
import com.iucn.whp.dbservice.service.whp_sites_meeLocalService;
import com.iucn.whp.dbservice.service.whp_sites_mgmt_plan_stateLocalService;
import com.iucn.whp.dbservice.service.whp_sites_missionLocalService;
import com.iucn.whp.dbservice.service.whp_sites_other_designationsLocalService;
import com.iucn.whp.dbservice.service.whp_sites_soc_reportsLocalService;
import com.iucn.whp.dbservice.service.whp_sites_soouvLocalService;
import com.iucn.whp.dbservice.service.whp_sites_visitorsLocalService;
import com.liferay.counter.service.CounterLocalService;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.bean.IdentifiableBean;
import com.liferay.portal.kernel.dao.jdbc.SqlUpdate;
import com.liferay.portal.kernel.dao.jdbc.SqlUpdateFactoryUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.search.Indexable;
import com.liferay.portal.kernel.search.IndexableType;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.model.PersistedModel;
import com.liferay.portal.service.BaseLocalServiceImpl;
import com.liferay.portal.service.PersistedModelLocalServiceRegistryUtil;
import com.liferay.portal.service.ResourceLocalService;
import com.liferay.portal.service.ResourceService;
import com.liferay.portal.service.UserLocalService;
import com.liferay.portal.service.UserService;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import java.io.Serializable;
import java.util.List;
import javax.sql.DataSource;
/**
* The base implementation of the contact_category local service.
*
* <p>
* This implementation exists only as a container for the default service methods generated by ServiceBuilder. All custom service methods should be put in {@link com.iucn.whp.dbservice.service.impl.contact_categoryLocalServiceImpl}.
* </p>
*
* @author alok.sen
* @see com.iucn.whp.dbservice.service.impl.contact_categoryLocalServiceImpl
* @see com.iucn.whp.dbservice.service.contact_categoryLocalServiceUtil
* @generated
*/
public abstract class contact_categoryLocalServiceBaseImpl
extends BaseLocalServiceImpl implements contact_categoryLocalService,
IdentifiableBean {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link com.iucn.whp.dbservice.service.contact_categoryLocalServiceUtil} to access the contact_category local service.
*/
/**
* Adds the contact_category to the database. Also notifies the appropriate model listeners.
*
* @param contact_category the contact_category
* @return the contact_category that was added
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.REINDEX)
public contact_category addcontact_category(
contact_category contact_category) throws SystemException {
contact_category.setNew(true);
return contact_categoryPersistence.update(contact_category, false);
}
/**
* Creates a new contact_category with the primary key. Does not add the contact_category to the database.
*
* @param contact_category_id the primary key for the new contact_category
* @return the new contact_category
*/
public contact_category createcontact_category(int contact_category_id) {
return contact_categoryPersistence.create(contact_category_id);
}
/**
* Deletes the contact_category with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param contact_category_id the primary key of the contact_category
* @return the contact_category that was removed
* @throws PortalException if a contact_category with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.DELETE)
public contact_category deletecontact_category(int contact_category_id)
throws PortalException, SystemException {
return contact_categoryPersistence.remove(contact_category_id);
}
/**
* Deletes the contact_category from the database. Also notifies the appropriate model listeners.
*
* @param contact_category the contact_category
* @return the contact_category that was removed
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.DELETE)
public contact_category deletecontact_category(
contact_category contact_category) throws SystemException {
return contact_categoryPersistence.remove(contact_category);
}
public DynamicQuery dynamicQuery() {
Class<?> clazz = getClass();
return DynamicQueryFactoryUtil.forClass(contact_category.class,
clazz.getClassLoader());
}
/**
* Performs a dynamic query on the database and returns the matching rows.
*
* @param dynamicQuery the dynamic query
* @return the matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public List dynamicQuery(DynamicQuery dynamicQuery)
throws SystemException {
return contact_categoryPersistence.findWithDynamicQuery(dynamicQuery);
}
/**
* Performs a dynamic query on the database and returns a range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @return the range of matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public List dynamicQuery(DynamicQuery dynamicQuery, int start, int end)
throws SystemException {
return contact_categoryPersistence.findWithDynamicQuery(dynamicQuery,
start, end);
}
/**
* Performs a dynamic query on the database and returns an ordered range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public List dynamicQuery(DynamicQuery dynamicQuery, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
return contact_categoryPersistence.findWithDynamicQuery(dynamicQuery,
start, end, orderByComparator);
}
/**
* Returns the number of rows that match the dynamic query.
*
* @param dynamicQuery the dynamic query
* @return the number of rows that match the dynamic query
* @throws SystemException if a system exception occurred
*/
public long dynamicQueryCount(DynamicQuery dynamicQuery)
throws SystemException {
return contact_categoryPersistence.countWithDynamicQuery(dynamicQuery);
}
public contact_category fetchcontact_category(int contact_category_id)
throws SystemException {
return contact_categoryPersistence.fetchByPrimaryKey(contact_category_id);
}
/**
* Returns the contact_category with the primary key.
*
* @param contact_category_id the primary key of the contact_category
* @return the contact_category
* @throws PortalException if a contact_category with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public contact_category getcontact_category(int contact_category_id)
throws PortalException, SystemException {
return contact_categoryPersistence.findByPrimaryKey(contact_category_id);
}
public PersistedModel getPersistedModel(Serializable primaryKeyObj)
throws PortalException, SystemException {
return contact_categoryPersistence.findByPrimaryKey(primaryKeyObj);
}
/**
* Returns a range of all the contact_categories.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of contact_categories
* @param end the upper bound of the range of contact_categories (not inclusive)
* @return the range of contact_categories
* @throws SystemException if a system exception occurred
*/
public List<contact_category> getcontact_categories(int start, int end)
throws SystemException {
return contact_categoryPersistence.findAll(start, end);
}
/**
* Returns the number of contact_categories.
*
* @return the number of contact_categories
* @throws SystemException if a system exception occurred
*/
public int getcontact_categoriesCount() throws SystemException {
return contact_categoryPersistence.countAll();
}
/**
* Updates the contact_category in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param contact_category the contact_category
* @return the contact_category that was updated
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.REINDEX)
public contact_category updatecontact_category(
contact_category contact_category) throws SystemException {
return updatecontact_category(contact_category, true);
}
/**
* Updates the contact_category in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param contact_category the contact_category
* @param merge whether to merge the contact_category with the current session. See {@link com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session, com.liferay.portal.model.BaseModel, boolean)} for an explanation.
* @return the contact_category that was updated
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.REINDEX)
public contact_category updatecontact_category(
contact_category contact_category, boolean merge)
throws SystemException {
contact_category.setNew(false);
return contact_categoryPersistence.update(contact_category, merge);
}
/**
* Returns the active_conservation_projects local service.
*
* @return the active_conservation_projects local service
*/
public active_conservation_projectsLocalService getactive_conservation_projectsLocalService() {
return active_conservation_projectsLocalService;
}
/**
* Sets the active_conservation_projects local service.
*
* @param active_conservation_projectsLocalService the active_conservation_projects local service
*/
public void setactive_conservation_projectsLocalService(
active_conservation_projectsLocalService active_conservation_projectsLocalService) {
this.active_conservation_projectsLocalService = active_conservation_projectsLocalService;
}
/**
* Returns the active_conservation_projects persistence.
*
* @return the active_conservation_projects persistence
*/
public active_conservation_projectsPersistence getactive_conservation_projectsPersistence() {
return active_conservation_projectsPersistence;
}
/**
* Sets the active_conservation_projects persistence.
*
* @param active_conservation_projectsPersistence the active_conservation_projects persistence
*/
public void setactive_conservation_projectsPersistence(
active_conservation_projectsPersistence active_conservation_projectsPersistence) {
this.active_conservation_projectsPersistence = active_conservation_projectsPersistence;
}
/**
* Returns the advance_query_assessment local service.
*
* @return the advance_query_assessment local service
*/
public advance_query_assessmentLocalService getadvance_query_assessmentLocalService() {
return advance_query_assessmentLocalService;
}
/**
* Sets the advance_query_assessment local service.
*
* @param advance_query_assessmentLocalService the advance_query_assessment local service
*/
public void setadvance_query_assessmentLocalService(
advance_query_assessmentLocalService advance_query_assessmentLocalService) {
this.advance_query_assessmentLocalService = advance_query_assessmentLocalService;
}
/**
* Returns the advance_query_assessment persistence.
*
* @return the advance_query_assessment persistence
*/
public advance_query_assessmentPersistence getadvance_query_assessmentPersistence() {
return advance_query_assessmentPersistence;
}
/**
* Sets the advance_query_assessment persistence.
*
* @param advance_query_assessmentPersistence the advance_query_assessment persistence
*/
public void setadvance_query_assessmentPersistence(
advance_query_assessmentPersistence advance_query_assessmentPersistence) {
this.advance_query_assessmentPersistence = advance_query_assessmentPersistence;
}
/**
* Returns the advance_query_site local service.
*
* @return the advance_query_site local service
*/
public advance_query_siteLocalService getadvance_query_siteLocalService() {
return advance_query_siteLocalService;
}
/**
* Sets the advance_query_site local service.
*
* @param advance_query_siteLocalService the advance_query_site local service
*/
public void setadvance_query_siteLocalService(
advance_query_siteLocalService advance_query_siteLocalService) {
this.advance_query_siteLocalService = advance_query_siteLocalService;
}
/**
* Returns the advance_query_site persistence.
*
* @return the advance_query_site persistence
*/
public advance_query_sitePersistence getadvance_query_sitePersistence() {
return advance_query_sitePersistence;
}
/**
* Sets the advance_query_site persistence.
*
* @param advance_query_sitePersistence the advance_query_site persistence
*/
public void setadvance_query_sitePersistence(
advance_query_sitePersistence advance_query_sitePersistence) {
this.advance_query_sitePersistence = advance_query_sitePersistence;
}
/**
* Returns the assessing_threats_current local service.
*
* @return the assessing_threats_current local service
*/
public assessing_threats_currentLocalService getassessing_threats_currentLocalService() {
return assessing_threats_currentLocalService;
}
/**
* Sets the assessing_threats_current local service.
*
* @param assessing_threats_currentLocalService the assessing_threats_current local service
*/
public void setassessing_threats_currentLocalService(
assessing_threats_currentLocalService assessing_threats_currentLocalService) {
this.assessing_threats_currentLocalService = assessing_threats_currentLocalService;
}
/**
* Returns the assessing_threats_current persistence.
*
* @return the assessing_threats_current persistence
*/
public assessing_threats_currentPersistence getassessing_threats_currentPersistence() {
return assessing_threats_currentPersistence;
}
/**
* Sets the assessing_threats_current persistence.
*
* @param assessing_threats_currentPersistence the assessing_threats_current persistence
*/
public void setassessing_threats_currentPersistence(
assessing_threats_currentPersistence assessing_threats_currentPersistence) {
this.assessing_threats_currentPersistence = assessing_threats_currentPersistence;
}
/**
* Returns the assessing_threats_potential local service.
*
* @return the assessing_threats_potential local service
*/
public assessing_threats_potentialLocalService getassessing_threats_potentialLocalService() {
return assessing_threats_potentialLocalService;
}
/**
* Sets the assessing_threats_potential local service.
*
* @param assessing_threats_potentialLocalService the assessing_threats_potential local service
*/
public void setassessing_threats_potentialLocalService(
assessing_threats_potentialLocalService assessing_threats_potentialLocalService) {
this.assessing_threats_potentialLocalService = assessing_threats_potentialLocalService;
}
/**
* Returns the assessing_threats_potential persistence.
*
* @return the assessing_threats_potential persistence
*/
public assessing_threats_potentialPersistence getassessing_threats_potentialPersistence() {
return assessing_threats_potentialPersistence;
}
/**
* Sets the assessing_threats_potential persistence.
*
* @param assessing_threats_potentialPersistence the assessing_threats_potential persistence
*/
public void setassessing_threats_potentialPersistence(
assessing_threats_potentialPersistence assessing_threats_potentialPersistence) {
this.assessing_threats_potentialPersistence = assessing_threats_potentialPersistence;
}
/**
* Returns the assessment_lang_lkp local service.
*
* @return the assessment_lang_lkp local service
*/
public assessment_lang_lkpLocalService getassessment_lang_lkpLocalService() {
return assessment_lang_lkpLocalService;
}
/**
* Sets the assessment_lang_lkp local service.
*
* @param assessment_lang_lkpLocalService the assessment_lang_lkp local service
*/
public void setassessment_lang_lkpLocalService(
assessment_lang_lkpLocalService assessment_lang_lkpLocalService) {
this.assessment_lang_lkpLocalService = assessment_lang_lkpLocalService;
}
/**
* Returns the assessment_lang_lkp persistence.
*
* @return the assessment_lang_lkp persistence
*/
public assessment_lang_lkpPersistence getassessment_lang_lkpPersistence() {
return assessment_lang_lkpPersistence;
}
/**
* Sets the assessment_lang_lkp persistence.
*
* @param assessment_lang_lkpPersistence the assessment_lang_lkp persistence
*/
public void setassessment_lang_lkpPersistence(
assessment_lang_lkpPersistence assessment_lang_lkpPersistence) {
this.assessment_lang_lkpPersistence = assessment_lang_lkpPersistence;
}
/**
* Returns the assessment_lang_version local service.
*
* @return the assessment_lang_version local service
*/
public assessment_lang_versionLocalService getassessment_lang_versionLocalService() {
return assessment_lang_versionLocalService;
}
/**
* Sets the assessment_lang_version local service.
*
* @param assessment_lang_versionLocalService the assessment_lang_version local service
*/
public void setassessment_lang_versionLocalService(
assessment_lang_versionLocalService assessment_lang_versionLocalService) {
this.assessment_lang_versionLocalService = assessment_lang_versionLocalService;
}
/**
* Returns the assessment_lang_version persistence.
*
* @return the assessment_lang_version persistence
*/
public assessment_lang_versionPersistence getassessment_lang_versionPersistence() {
return assessment_lang_versionPersistence;
}
/**
* Sets the assessment_lang_version persistence.
*
* @param assessment_lang_versionPersistence the assessment_lang_version persistence
*/
public void setassessment_lang_versionPersistence(
assessment_lang_versionPersistence assessment_lang_versionPersistence) {
this.assessment_lang_versionPersistence = assessment_lang_versionPersistence;
}
/**
* Returns the assessment_stages local service.
*
* @return the assessment_stages local service
*/
public assessment_stagesLocalService getassessment_stagesLocalService() {
return assessment_stagesLocalService;
}
/**
* Sets the assessment_stages local service.
*
* @param assessment_stagesLocalService the assessment_stages local service
*/
public void setassessment_stagesLocalService(
assessment_stagesLocalService assessment_stagesLocalService) {
this.assessment_stagesLocalService = assessment_stagesLocalService;
}
/**
* Returns the assessment_stages persistence.
*
* @return the assessment_stages persistence
*/
public assessment_stagesPersistence getassessment_stagesPersistence() {
return assessment_stagesPersistence;
}
/**
* Sets the assessment_stages persistence.
*
* @param assessment_stagesPersistence the assessment_stages persistence
*/
public void setassessment_stagesPersistence(
assessment_stagesPersistence assessment_stagesPersistence) {
this.assessment_stagesPersistence = assessment_stagesPersistence;
}
/**
* Returns the assessment_status local service.
*
* @return the assessment_status local service
*/
public assessment_statusLocalService getassessment_statusLocalService() {
return assessment_statusLocalService;
}
/**
* Sets the assessment_status local service.
*
* @param assessment_statusLocalService the assessment_status local service
*/
public void setassessment_statusLocalService(
assessment_statusLocalService assessment_statusLocalService) {
this.assessment_statusLocalService = assessment_statusLocalService;
}
/**
* Returns the assessment_status persistence.
*
* @return the assessment_status persistence
*/
public assessment_statusPersistence getassessment_statusPersistence() {
return assessment_statusPersistence;
}
/**
* Sets the assessment_status persistence.
*
* @param assessment_statusPersistence the assessment_status persistence
*/
public void setassessment_statusPersistence(
assessment_statusPersistence assessment_statusPersistence) {
this.assessment_statusPersistence = assessment_statusPersistence;
}
/**
* Returns the assessment_validation local service.
*
* @return the assessment_validation local service
*/
public assessment_validationLocalService getassessment_validationLocalService() {
return assessment_validationLocalService;
}
/**
* Sets the assessment_validation local service.
*
* @param assessment_validationLocalService the assessment_validation local service
*/
public void setassessment_validationLocalService(
assessment_validationLocalService assessment_validationLocalService) {
this.assessment_validationLocalService = assessment_validationLocalService;
}
/**
* Returns the assessment_validation persistence.
*
* @return the assessment_validation persistence
*/
public assessment_validationPersistence getassessment_validationPersistence() {
return assessment_validationPersistence;
}
/**
* Sets the assessment_validation persistence.
*
* @param assessment_validationPersistence the assessment_validation persistence
*/
public void setassessment_validationPersistence(
assessment_validationPersistence assessment_validationPersistence) {
this.assessment_validationPersistence = assessment_validationPersistence;
}
/**
* Returns the assessment_whvalues local service.
*
* @return the assessment_whvalues local service
*/
public assessment_whvaluesLocalService getassessment_whvaluesLocalService() {
return assessment_whvaluesLocalService;
}
/**
* Sets the assessment_whvalues local service.
*
* @param assessment_whvaluesLocalService the assessment_whvalues local service
*/
public void setassessment_whvaluesLocalService(
assessment_whvaluesLocalService assessment_whvaluesLocalService) {
this.assessment_whvaluesLocalService = assessment_whvaluesLocalService;
}
/**
* Returns the assessment_whvalues persistence.
*
* @return the assessment_whvalues persistence
*/
public assessment_whvaluesPersistence getassessment_whvaluesPersistence() {
return assessment_whvaluesPersistence;
}
/**
* Sets the assessment_whvalues persistence.
*
* @param assessment_whvaluesPersistence the assessment_whvalues persistence
*/
public void setassessment_whvaluesPersistence(
assessment_whvaluesPersistence assessment_whvaluesPersistence) {
this.assessment_whvaluesPersistence = assessment_whvaluesPersistence;
}
/**
* Returns the assessment_whvalues_whcriterion local service.
*
* @return the assessment_whvalues_whcriterion local service
*/
public assessment_whvalues_whcriterionLocalService getassessment_whvalues_whcriterionLocalService() {
return assessment_whvalues_whcriterionLocalService;
}
/**
* Sets the assessment_whvalues_whcriterion local service.
*
* @param assessment_whvalues_whcriterionLocalService the assessment_whvalues_whcriterion local service
*/
public void setassessment_whvalues_whcriterionLocalService(
assessment_whvalues_whcriterionLocalService assessment_whvalues_whcriterionLocalService) {
this.assessment_whvalues_whcriterionLocalService = assessment_whvalues_whcriterionLocalService;
}
/**
* Returns the assessment_whvalues_whcriterion persistence.
*
* @return the assessment_whvalues_whcriterion persistence
*/
public assessment_whvalues_whcriterionPersistence getassessment_whvalues_whcriterionPersistence() {
return assessment_whvalues_whcriterionPersistence;
}
/**
* Sets the assessment_whvalues_whcriterion persistence.
*
* @param assessment_whvalues_whcriterionPersistence the assessment_whvalues_whcriterion persistence
*/
public void setassessment_whvalues_whcriterionPersistence(
assessment_whvalues_whcriterionPersistence assessment_whvalues_whcriterionPersistence) {
this.assessment_whvalues_whcriterionPersistence = assessment_whvalues_whcriterionPersistence;
}
/**
* Returns the benefit_checksubtype_lkp local service.
*
* @return the benefit_checksubtype_lkp local service
*/
public benefit_checksubtype_lkpLocalService getbenefit_checksubtype_lkpLocalService() {
return benefit_checksubtype_lkpLocalService;
}
/**
* Sets the benefit_checksubtype_lkp local service.
*
* @param benefit_checksubtype_lkpLocalService the benefit_checksubtype_lkp local service
*/
public void setbenefit_checksubtype_lkpLocalService(
benefit_checksubtype_lkpLocalService benefit_checksubtype_lkpLocalService) {
this.benefit_checksubtype_lkpLocalService = benefit_checksubtype_lkpLocalService;
}
/**
* Returns the benefit_checksubtype_lkp persistence.
*
* @return the benefit_checksubtype_lkp persistence
*/
public benefit_checksubtype_lkpPersistence getbenefit_checksubtype_lkpPersistence() {
return benefit_checksubtype_lkpPersistence;
}
/**
* Sets the benefit_checksubtype_lkp persistence.
*
* @param benefit_checksubtype_lkpPersistence the benefit_checksubtype_lkp persistence
*/
public void setbenefit_checksubtype_lkpPersistence(
benefit_checksubtype_lkpPersistence benefit_checksubtype_lkpPersistence) {
this.benefit_checksubtype_lkpPersistence = benefit_checksubtype_lkpPersistence;
}
/**
* Returns the benefit_checktype_lkp local service.
*
* @return the benefit_checktype_lkp local service
*/
public benefit_checktype_lkpLocalService getbenefit_checktype_lkpLocalService() {
return benefit_checktype_lkpLocalService;
}
/**
* Sets the benefit_checktype_lkp local service.
*
* @param benefit_checktype_lkpLocalService the benefit_checktype_lkp local service
*/
public void setbenefit_checktype_lkpLocalService(
benefit_checktype_lkpLocalService benefit_checktype_lkpLocalService) {
this.benefit_checktype_lkpLocalService = benefit_checktype_lkpLocalService;
}
/**
* Returns the benefit_checktype_lkp persistence.
*
* @return the benefit_checktype_lkp persistence
*/
public benefit_checktype_lkpPersistence getbenefit_checktype_lkpPersistence() {
return benefit_checktype_lkpPersistence;
}
/**
* Sets the benefit_checktype_lkp persistence.
*
* @param benefit_checktype_lkpPersistence the benefit_checktype_lkp persistence
*/
public void setbenefit_checktype_lkpPersistence(
benefit_checktype_lkpPersistence benefit_checktype_lkpPersistence) {
this.benefit_checktype_lkpPersistence = benefit_checktype_lkpPersistence;
}
/**
* Returns the benefit_rating_lkp local service.
*
* @return the benefit_rating_lkp local service
*/
public benefit_rating_lkpLocalService getbenefit_rating_lkpLocalService() {
return benefit_rating_lkpLocalService;
}
/**
* Sets the benefit_rating_lkp local service.
*
* @param benefit_rating_lkpLocalService the benefit_rating_lkp local service
*/
public void setbenefit_rating_lkpLocalService(
benefit_rating_lkpLocalService benefit_rating_lkpLocalService) {
this.benefit_rating_lkpLocalService = benefit_rating_lkpLocalService;
}
/**
* Returns the benefit_rating_lkp persistence.
*
* @return the benefit_rating_lkp persistence
*/
public benefit_rating_lkpPersistence getbenefit_rating_lkpPersistence() {
return benefit_rating_lkpPersistence;
}
/**
* Sets the benefit_rating_lkp persistence.
*
* @param benefit_rating_lkpPersistence the benefit_rating_lkp persistence
*/
public void setbenefit_rating_lkpPersistence(
benefit_rating_lkpPersistence benefit_rating_lkpPersistence) {
this.benefit_rating_lkpPersistence = benefit_rating_lkpPersistence;
}
/**
* Returns the benefits local service.
*
* @return the benefits local service
*/
public benefitsLocalService getbenefitsLocalService() {
return benefitsLocalService;
}
/**
* Sets the benefits local service.
*
* @param benefitsLocalService the benefits local service
*/
public void setbenefitsLocalService(
benefitsLocalService benefitsLocalService) {
this.benefitsLocalService = benefitsLocalService;
}
/**
* Returns the benefits persistence.
*
* @return the benefits persistence
*/
public benefitsPersistence getbenefitsPersistence() {
return benefitsPersistence;
}
/**
* Sets the benefits persistence.
*
* @param benefitsPersistence the benefits persistence
*/
public void setbenefitsPersistence(benefitsPersistence benefitsPersistence) {
this.benefitsPersistence = benefitsPersistence;
}
/**
* Returns the benefits_summary local service.
*
* @return the benefits_summary local service
*/
public benefits_summaryLocalService getbenefits_summaryLocalService() {
return benefits_summaryLocalService;
}
/**
* Sets the benefits_summary local service.
*
* @param benefits_summaryLocalService the benefits_summary local service
*/
public void setbenefits_summaryLocalService(
benefits_summaryLocalService benefits_summaryLocalService) {
this.benefits_summaryLocalService = benefits_summaryLocalService;
}
/**
* Returns the benefits_summary persistence.
*
* @return the benefits_summary persistence
*/
public benefits_summaryPersistence getbenefits_summaryPersistence() {
return benefits_summaryPersistence;
}
/**
* Sets the benefits_summary persistence.
*
* @param benefits_summaryPersistence the benefits_summary persistence
*/
public void setbenefits_summaryPersistence(
benefits_summaryPersistence benefits_summaryPersistence) {
this.benefits_summaryPersistence = benefits_summaryPersistence;
}
/**
* Returns the benefits_type_ref local service.
*
* @return the benefits_type_ref local service
*/
public benefits_type_refLocalService getbenefits_type_refLocalService() {
return benefits_type_refLocalService;
}
/**
* Sets the benefits_type_ref local service.
*
* @param benefits_type_refLocalService the benefits_type_ref local service
*/
public void setbenefits_type_refLocalService(
benefits_type_refLocalService benefits_type_refLocalService) {
this.benefits_type_refLocalService = benefits_type_refLocalService;
}
/**
* Returns the benefits_type_ref persistence.
*
* @return the benefits_type_ref persistence
*/
public benefits_type_refPersistence getbenefits_type_refPersistence() {
return benefits_type_refPersistence;
}
/**
* Sets the benefits_type_ref persistence.
*
* @param benefits_type_refPersistence the benefits_type_ref persistence
*/
public void setbenefits_type_refPersistence(
benefits_type_refPersistence benefits_type_refPersistence) {
this.benefits_type_refPersistence = benefits_type_refPersistence;
}
/**
* Returns the biodiversity_values local service.
*
* @return the biodiversity_values local service
*/
public biodiversity_valuesLocalService getbiodiversity_valuesLocalService() {
return biodiversity_valuesLocalService;
}
/**
* Sets the biodiversity_values local service.
*
* @param biodiversity_valuesLocalService the biodiversity_values local service
*/
public void setbiodiversity_valuesLocalService(
biodiversity_valuesLocalService biodiversity_valuesLocalService) {
this.biodiversity_valuesLocalService = biodiversity_valuesLocalService;
}
/**
* Returns the biodiversity_values persistence.
*
* @return the biodiversity_values persistence
*/
public biodiversity_valuesPersistence getbiodiversity_valuesPersistence() {
return biodiversity_valuesPersistence;
}
/**
* Sets the biodiversity_values persistence.
*
* @param biodiversity_valuesPersistence the biodiversity_values persistence
*/
public void setbiodiversity_valuesPersistence(
biodiversity_valuesPersistence biodiversity_valuesPersistence) {
this.biodiversity_valuesPersistence = biodiversity_valuesPersistence;
}
/**
* Returns the boundary_modification_type_lkp local service.
*
* @return the boundary_modification_type_lkp local service
*/
public boundary_modification_type_lkpLocalService getboundary_modification_type_lkpLocalService() {
return boundary_modification_type_lkpLocalService;
}
/**
* Sets the boundary_modification_type_lkp local service.
*
* @param boundary_modification_type_lkpLocalService the boundary_modification_type_lkp local service
*/
public void setboundary_modification_type_lkpLocalService(
boundary_modification_type_lkpLocalService boundary_modification_type_lkpLocalService) {
this.boundary_modification_type_lkpLocalService = boundary_modification_type_lkpLocalService;
}
/**
* Returns the boundary_modification_type_lkp persistence.
*
* @return the boundary_modification_type_lkp persistence
*/
public boundary_modification_type_lkpPersistence getboundary_modification_type_lkpPersistence() {
return boundary_modification_type_lkpPersistence;
}
/**
* Sets the boundary_modification_type_lkp persistence.
*
* @param boundary_modification_type_lkpPersistence the boundary_modification_type_lkp persistence
*/
public void setboundary_modification_type_lkpPersistence(
boundary_modification_type_lkpPersistence boundary_modification_type_lkpPersistence) {
this.boundary_modification_type_lkpPersistence = boundary_modification_type_lkpPersistence;
}
/**
* Returns the conservation_outlook local service.
*
* @return the conservation_outlook local service
*/
public conservation_outlookLocalService getconservation_outlookLocalService() {
return conservation_outlookLocalService;
}
/**
* Sets the conservation_outlook local service.
*
* @param conservation_outlookLocalService the conservation_outlook local service
*/
public void setconservation_outlookLocalService(
conservation_outlookLocalService conservation_outlookLocalService) {
this.conservation_outlookLocalService = conservation_outlookLocalService;
}
/**
* Returns the conservation_outlook persistence.
*
* @return the conservation_outlook persistence
*/
public conservation_outlookPersistence getconservation_outlookPersistence() {
return conservation_outlookPersistence;
}
/**
* Sets the conservation_outlook persistence.
*
* @param conservation_outlookPersistence the conservation_outlook persistence
*/
public void setconservation_outlookPersistence(
conservation_outlookPersistence conservation_outlookPersistence) {
this.conservation_outlookPersistence = conservation_outlookPersistence;
}
/**
* Returns the conservation_outlook_rating_lkp local service.
*
* @return the conservation_outlook_rating_lkp local service
*/
public conservation_outlook_rating_lkpLocalService getconservation_outlook_rating_lkpLocalService() {
return conservation_outlook_rating_lkpLocalService;
}
/**
* Sets the conservation_outlook_rating_lkp local service.
*
* @param conservation_outlook_rating_lkpLocalService the conservation_outlook_rating_lkp local service
*/
public void setconservation_outlook_rating_lkpLocalService(
conservation_outlook_rating_lkpLocalService conservation_outlook_rating_lkpLocalService) {
this.conservation_outlook_rating_lkpLocalService = conservation_outlook_rating_lkpLocalService;
}
/**
* Returns the conservation_outlook_rating_lkp persistence.
*
* @return the conservation_outlook_rating_lkp persistence
*/
public conservation_outlook_rating_lkpPersistence getconservation_outlook_rating_lkpPersistence() {
return conservation_outlook_rating_lkpPersistence;
}
/**
* Sets the conservation_outlook_rating_lkp persistence.
*
* @param conservation_outlook_rating_lkpPersistence the conservation_outlook_rating_lkp persistence
*/
public void setconservation_outlook_rating_lkpPersistence(
conservation_outlook_rating_lkpPersistence conservation_outlook_rating_lkpPersistence) {
this.conservation_outlook_rating_lkpPersistence = conservation_outlook_rating_lkpPersistence;
}
/**
* Returns the contact_category local service.
*
* @return the contact_category local service
*/
public contact_categoryLocalService getcontact_categoryLocalService() {
return contact_categoryLocalService;
}
/**
* Sets the contact_category local service.
*
* @param contact_categoryLocalService the contact_category local service
*/
public void setcontact_categoryLocalService(
contact_categoryLocalService contact_categoryLocalService) {
this.contact_categoryLocalService = contact_categoryLocalService;
}
/**
* Returns the contact_category persistence.
*
* @return the contact_category persistence
*/
public contact_categoryPersistence getcontact_categoryPersistence() {
return contact_categoryPersistence;
}
/**
* Sets the contact_category persistence.
*
* @param contact_categoryPersistence the contact_category persistence
*/
public void setcontact_categoryPersistence(
contact_categoryPersistence contact_categoryPersistence) {
this.contact_categoryPersistence = contact_categoryPersistence;
}
/**
* Returns the country_lkp local service.
*
* @return the country_lkp local service
*/
public country_lkpLocalService getcountry_lkpLocalService() {
return country_lkpLocalService;
}
/**
* Sets the country_lkp local service.
*
* @param country_lkpLocalService the country_lkp local service
*/
public void setcountry_lkpLocalService(
country_lkpLocalService country_lkpLocalService) {
this.country_lkpLocalService = country_lkpLocalService;
}
/**
* Returns the country_lkp persistence.
*
* @return the country_lkp persistence
*/
public country_lkpPersistence getcountry_lkpPersistence() {
return country_lkpPersistence;
}
/**
* Sets the country_lkp persistence.
*
* @param country_lkpPersistence the country_lkp persistence
*/
public void setcountry_lkpPersistence(
country_lkpPersistence country_lkpPersistence) {
this.country_lkpPersistence = country_lkpPersistence;
}
/**
* Returns the current_state_trend local service.
*
* @return the current_state_trend local service
*/
public current_state_trendLocalService getcurrent_state_trendLocalService() {
return current_state_trendLocalService;
}
/**
* Sets the current_state_trend local service.
*
* @param current_state_trendLocalService the current_state_trend local service
*/
public void setcurrent_state_trendLocalService(
current_state_trendLocalService current_state_trendLocalService) {
this.current_state_trendLocalService = current_state_trendLocalService;
}
/**
* Returns the current_state_trend persistence.
*
* @return the current_state_trend persistence
*/
public current_state_trendPersistence getcurrent_state_trendPersistence() {
return current_state_trendPersistence;
}
/**
* Sets the current_state_trend persistence.
*
* @param current_state_trendPersistence the current_state_trend persistence
*/
public void setcurrent_state_trendPersistence(
current_state_trendPersistence current_state_trendPersistence) {
this.current_state_trendPersistence = current_state_trendPersistence;
}
/**
* Returns the current_state_trend_values local service.
*
* @return the current_state_trend_values local service
*/
public current_state_trend_valuesLocalService getcurrent_state_trend_valuesLocalService() {
return current_state_trend_valuesLocalService;
}
/**
* Sets the current_state_trend_values local service.
*
* @param current_state_trend_valuesLocalService the current_state_trend_values local service
*/
public void setcurrent_state_trend_valuesLocalService(
current_state_trend_valuesLocalService current_state_trend_valuesLocalService) {
this.current_state_trend_valuesLocalService = current_state_trend_valuesLocalService;
}
/**
* Returns the current_state_trend_values persistence.
*
* @return the current_state_trend_values persistence
*/
public current_state_trend_valuesPersistence getcurrent_state_trend_valuesPersistence() {
return current_state_trend_valuesPersistence;
}
/**
* Sets the current_state_trend_values persistence.
*
* @param current_state_trend_valuesPersistence the current_state_trend_values persistence
*/
public void setcurrent_state_trend_valuesPersistence(
current_state_trend_valuesPersistence current_state_trend_valuesPersistence) {
this.current_state_trend_valuesPersistence = current_state_trend_valuesPersistence;
}
/**
* Returns the current_threat_assessment_cat local service.
*
* @return the current_threat_assessment_cat local service
*/
public current_threat_assessment_catLocalService getcurrent_threat_assessment_catLocalService() {
return current_threat_assessment_catLocalService;
}
/**
* Sets the current_threat_assessment_cat local service.
*
* @param current_threat_assessment_catLocalService the current_threat_assessment_cat local service
*/
public void setcurrent_threat_assessment_catLocalService(
current_threat_assessment_catLocalService current_threat_assessment_catLocalService) {
this.current_threat_assessment_catLocalService = current_threat_assessment_catLocalService;
}
/**
* Returns the current_threat_assessment_cat persistence.
*
* @return the current_threat_assessment_cat persistence
*/
public current_threat_assessment_catPersistence getcurrent_threat_assessment_catPersistence() {
return current_threat_assessment_catPersistence;
}
/**
* Sets the current_threat_assessment_cat persistence.
*
* @param current_threat_assessment_catPersistence the current_threat_assessment_cat persistence
*/
public void setcurrent_threat_assessment_catPersistence(
current_threat_assessment_catPersistence current_threat_assessment_catPersistence) {
this.current_threat_assessment_catPersistence = current_threat_assessment_catPersistence;
}
/**
* Returns the current_threat_values local service.
*
* @return the current_threat_values local service
*/
public current_threat_valuesLocalService getcurrent_threat_valuesLocalService() {
return current_threat_valuesLocalService;
}
/**
* Sets the current_threat_values local service.
*
* @param current_threat_valuesLocalService the current_threat_values local service
*/
public void setcurrent_threat_valuesLocalService(
current_threat_valuesLocalService current_threat_valuesLocalService) {
this.current_threat_valuesLocalService = current_threat_valuesLocalService;
}
/**
* Returns the current_threat_values persistence.
*
* @return the current_threat_values persistence
*/
public current_threat_valuesPersistence getcurrent_threat_valuesPersistence() {
return current_threat_valuesPersistence;
}
/**
* Sets the current_threat_values persistence.
*
* @param current_threat_valuesPersistence the current_threat_values persistence
*/
public void setcurrent_threat_valuesPersistence(
current_threat_valuesPersistence current_threat_valuesPersistence) {
this.current_threat_valuesPersistence = current_threat_valuesPersistence;
}
/**
* Returns the danger_list_status_lkp local service.
*
* @return the danger_list_status_lkp local service
*/
public danger_list_status_lkpLocalService getdanger_list_status_lkpLocalService() {
return danger_list_status_lkpLocalService;
}
/**
* Sets the danger_list_status_lkp local service.
*
* @param danger_list_status_lkpLocalService the danger_list_status_lkp local service
*/
public void setdanger_list_status_lkpLocalService(
danger_list_status_lkpLocalService danger_list_status_lkpLocalService) {
this.danger_list_status_lkpLocalService = danger_list_status_lkpLocalService;
}
/**
* Returns the danger_list_status_lkp persistence.
*
* @return the danger_list_status_lkp persistence
*/
public danger_list_status_lkpPersistence getdanger_list_status_lkpPersistence() {
return danger_list_status_lkpPersistence;
}
/**
* Sets the danger_list_status_lkp persistence.
*
* @param danger_list_status_lkpPersistence the danger_list_status_lkp persistence
*/
public void setdanger_list_status_lkpPersistence(
danger_list_status_lkpPersistence danger_list_status_lkpPersistence) {
this.danger_list_status_lkpPersistence = danger_list_status_lkpPersistence;
}
/**
* Returns the docs_custom data local service.
*
* @return the docs_custom data local service
*/
public docs_customDataLocalService getdocs_customDataLocalService() {
return docs_customDataLocalService;
}
/**
* Sets the docs_custom data local service.
*
* @param docs_customDataLocalService the docs_custom data local service
*/
public void setdocs_customDataLocalService(
docs_customDataLocalService docs_customDataLocalService) {
this.docs_customDataLocalService = docs_customDataLocalService;
}
/**
* Returns the docs_custom data persistence.
*
* @return the docs_custom data persistence
*/
public docs_customDataPersistence getdocs_customDataPersistence() {
return docs_customDataPersistence;
}
/**
* Sets the docs_custom data persistence.
*
* @param docs_customDataPersistence the docs_custom data persistence
*/
public void setdocs_customDataPersistence(
docs_customDataPersistence docs_customDataPersistence) {
this.docs_customDataPersistence = docs_customDataPersistence;
}
/**
* Returns the docs_custom data finder.
*
* @return the docs_custom data finder
*/
public docs_customDataFinder getdocs_customDataFinder() {
return docs_customDataFinder;
}
/**
* Sets the docs_custom data finder.
*
* @param docs_customDataFinder the docs_custom data finder
*/
public void setdocs_customDataFinder(
docs_customDataFinder docs_customDataFinder) {
this.docs_customDataFinder = docs_customDataFinder;
}
/**
* Returns the docs_sitedata local service.
*
* @return the docs_sitedata local service
*/
public docs_sitedataLocalService getdocs_sitedataLocalService() {
return docs_sitedataLocalService;
}
/**
* Sets the docs_sitedata local service.
*
* @param docs_sitedataLocalService the docs_sitedata local service
*/
public void setdocs_sitedataLocalService(
docs_sitedataLocalService docs_sitedataLocalService) {
this.docs_sitedataLocalService = docs_sitedataLocalService;
}
/**
* Returns the docs_sitedata persistence.
*
* @return the docs_sitedata persistence
*/
public docs_sitedataPersistence getdocs_sitedataPersistence() {
return docs_sitedataPersistence;
}
/**
* Sets the docs_sitedata persistence.
*
* @param docs_sitedataPersistence the docs_sitedata persistence
*/
public void setdocs_sitedataPersistence(
docs_sitedataPersistence docs_sitedataPersistence) {
this.docs_sitedataPersistence = docs_sitedataPersistence;
}
/**
* Returns the effective_prot_mgmt_iothreats local service.
*
* @return the effective_prot_mgmt_iothreats local service
*/
public effective_prot_mgmt_iothreatsLocalService geteffective_prot_mgmt_iothreatsLocalService() {
return effective_prot_mgmt_iothreatsLocalService;
}
/**
* Sets the effective_prot_mgmt_iothreats local service.
*
* @param effective_prot_mgmt_iothreatsLocalService the effective_prot_mgmt_iothreats local service
*/
public void seteffective_prot_mgmt_iothreatsLocalService(
effective_prot_mgmt_iothreatsLocalService effective_prot_mgmt_iothreatsLocalService) {
this.effective_prot_mgmt_iothreatsLocalService = effective_prot_mgmt_iothreatsLocalService;
}
/**
* Returns the effective_prot_mgmt_iothreats persistence.
*
* @return the effective_prot_mgmt_iothreats persistence
*/
public effective_prot_mgmt_iothreatsPersistence geteffective_prot_mgmt_iothreatsPersistence() {
return effective_prot_mgmt_iothreatsPersistence;
}
/**
* Sets the effective_prot_mgmt_iothreats persistence.
*
* @param effective_prot_mgmt_iothreatsPersistence the effective_prot_mgmt_iothreats persistence
*/
public void seteffective_prot_mgmt_iothreatsPersistence(
effective_prot_mgmt_iothreatsPersistence effective_prot_mgmt_iothreatsPersistence) {
this.effective_prot_mgmt_iothreatsPersistence = effective_prot_mgmt_iothreatsPersistence;
}
/**
* Returns the flagship_species_lkp local service.
*
* @return the flagship_species_lkp local service
*/
public flagship_species_lkpLocalService getflagship_species_lkpLocalService() {
return flagship_species_lkpLocalService;
}
/**
* Sets the flagship_species_lkp local service.
*
* @param flagship_species_lkpLocalService the flagship_species_lkp local service
*/
public void setflagship_species_lkpLocalService(
flagship_species_lkpLocalService flagship_species_lkpLocalService) {
this.flagship_species_lkpLocalService = flagship_species_lkpLocalService;
}
/**
* Returns the flagship_species_lkp persistence.
*
* @return the flagship_species_lkp persistence
*/
public flagship_species_lkpPersistence getflagship_species_lkpPersistence() {
return flagship_species_lkpPersistence;
}
/**
* Sets the flagship_species_lkp persistence.
*
* @param flagship_species_lkpPersistence the flagship_species_lkp persistence
*/
public void setflagship_species_lkpPersistence(
flagship_species_lkpPersistence flagship_species_lkpPersistence) {
this.flagship_species_lkpPersistence = flagship_species_lkpPersistence;
}
/**
* Returns the inscription_criteria_lkp local service.
*
* @return the inscription_criteria_lkp local service
*/
public inscription_criteria_lkpLocalService getinscription_criteria_lkpLocalService() {
return inscription_criteria_lkpLocalService;
}
/**
* Sets the inscription_criteria_lkp local service.
*
* @param inscription_criteria_lkpLocalService the inscription_criteria_lkp local service
*/
public void setinscription_criteria_lkpLocalService(
inscription_criteria_lkpLocalService inscription_criteria_lkpLocalService) {
this.inscription_criteria_lkpLocalService = inscription_criteria_lkpLocalService;
}
/**
* Returns the inscription_criteria_lkp persistence.
*
* @return the inscription_criteria_lkp persistence
*/
public inscription_criteria_lkpPersistence getinscription_criteria_lkpPersistence() {
return inscription_criteria_lkpPersistence;
}
/**
* Sets the inscription_criteria_lkp persistence.
*
* @param inscription_criteria_lkpPersistence the inscription_criteria_lkp persistence
*/
public void setinscription_criteria_lkpPersistence(
inscription_criteria_lkpPersistence inscription_criteria_lkpPersistence) {
this.inscription_criteria_lkpPersistence = inscription_criteria_lkpPersistence;
}
/**
* Returns the inscription_type_lkp local service.
*
* @return the inscription_type_lkp local service
*/
public inscription_type_lkpLocalService getinscription_type_lkpLocalService() {
return inscription_type_lkpLocalService;
}
/**
* Sets the inscription_type_lkp local service.
*
* @param inscription_type_lkpLocalService the inscription_type_lkp local service
*/
public void setinscription_type_lkpLocalService(
inscription_type_lkpLocalService inscription_type_lkpLocalService) {
this.inscription_type_lkpLocalService = inscription_type_lkpLocalService;
}
/**
* Returns the inscription_type_lkp persistence.
*
* @return the inscription_type_lkp persistence
*/
public inscription_type_lkpPersistence getinscription_type_lkpPersistence() {
return inscription_type_lkpPersistence;
}
/**
* Sets the inscription_type_lkp persistence.
*
* @param inscription_type_lkpPersistence the inscription_type_lkp persistence
*/
public void setinscription_type_lkpPersistence(
inscription_type_lkpPersistence inscription_type_lkpPersistence) {
this.inscription_type_lkpPersistence = inscription_type_lkpPersistence;
}
/**
* Returns the iucn_pa_lkp_category local service.
*
* @return the iucn_pa_lkp_category local service
*/
public iucn_pa_lkp_categoryLocalService getiucn_pa_lkp_categoryLocalService() {
return iucn_pa_lkp_categoryLocalService;
}
/**
* Sets the iucn_pa_lkp_category local service.
*
* @param iucn_pa_lkp_categoryLocalService the iucn_pa_lkp_category local service
*/
public void setiucn_pa_lkp_categoryLocalService(
iucn_pa_lkp_categoryLocalService iucn_pa_lkp_categoryLocalService) {
this.iucn_pa_lkp_categoryLocalService = iucn_pa_lkp_categoryLocalService;
}
/**
* Returns the iucn_pa_lkp_category persistence.
*
* @return the iucn_pa_lkp_category persistence
*/
public iucn_pa_lkp_categoryPersistence getiucn_pa_lkp_categoryPersistence() {
return iucn_pa_lkp_categoryPersistence;
}
/**
* Sets the iucn_pa_lkp_category persistence.
*
* @param iucn_pa_lkp_categoryPersistence the iucn_pa_lkp_category persistence
*/
public void setiucn_pa_lkp_categoryPersistence(
iucn_pa_lkp_categoryPersistence iucn_pa_lkp_categoryPersistence) {
this.iucn_pa_lkp_categoryPersistence = iucn_pa_lkp_categoryPersistence;
}
/**
* Returns the iucn_region local service.
*
* @return the iucn_region local service
*/
public iucn_regionLocalService getiucn_regionLocalService() {
return iucn_regionLocalService;
}
/**
* Sets the iucn_region local service.
*
* @param iucn_regionLocalService the iucn_region local service
*/
public void setiucn_regionLocalService(
iucn_regionLocalService iucn_regionLocalService) {
this.iucn_regionLocalService = iucn_regionLocalService;
}
/**
* Returns the iucn_region persistence.
*
* @return the iucn_region persistence
*/
public iucn_regionPersistence getiucn_regionPersistence() {
return iucn_regionPersistence;
}
/**
* Sets the iucn_region persistence.
*
* @param iucn_regionPersistence the iucn_region persistence
*/
public void setiucn_regionPersistence(
iucn_regionPersistence iucn_regionPersistence) {
this.iucn_regionPersistence = iucn_regionPersistence;
}
/**
* Returns the iucn_region_country local service.
*
* @return the iucn_region_country local service
*/
public iucn_region_countryLocalService getiucn_region_countryLocalService() {
return iucn_region_countryLocalService;
}
/**
* Sets the iucn_region_country local service.
*
* @param iucn_region_countryLocalService the iucn_region_country local service
*/
public void setiucn_region_countryLocalService(
iucn_region_countryLocalService iucn_region_countryLocalService) {
this.iucn_region_countryLocalService = iucn_region_countryLocalService;
}
/**
* Returns the iucn_region_country persistence.
*
* @return the iucn_region_country persistence
*/
public iucn_region_countryPersistence getiucn_region_countryPersistence() {
return iucn_region_countryPersistence;
}
/**
* Sets the iucn_region_country persistence.
*
* @param iucn_region_countryPersistence the iucn_region_country persistence
*/
public void setiucn_region_countryPersistence(
iucn_region_countryPersistence iucn_region_countryPersistence) {
this.iucn_region_countryPersistence = iucn_region_countryPersistence;
}
/**
* Returns the key_conservation_issues local service.
*
* @return the key_conservation_issues local service
*/
public key_conservation_issuesLocalService getkey_conservation_issuesLocalService() {
return key_conservation_issuesLocalService;
}
/**
* Sets the key_conservation_issues local service.
*
* @param key_conservation_issuesLocalService the key_conservation_issues local service
*/
public void setkey_conservation_issuesLocalService(
key_conservation_issuesLocalService key_conservation_issuesLocalService) {
this.key_conservation_issuesLocalService = key_conservation_issuesLocalService;
}
/**
* Returns the key_conservation_issues persistence.
*
* @return the key_conservation_issues persistence
*/
public key_conservation_issuesPersistence getkey_conservation_issuesPersistence() {
return key_conservation_issuesPersistence;
}
/**
* Sets the key_conservation_issues persistence.
*
* @param key_conservation_issuesPersistence the key_conservation_issues persistence
*/
public void setkey_conservation_issuesPersistence(
key_conservation_issuesPersistence key_conservation_issuesPersistence) {
this.key_conservation_issuesPersistence = key_conservation_issuesPersistence;
}
/**
* Returns the key_conservation_scale_lkp local service.
*
* @return the key_conservation_scale_lkp local service
*/
public key_conservation_scale_lkpLocalService getkey_conservation_scale_lkpLocalService() {
return key_conservation_scale_lkpLocalService;
}
/**
* Sets the key_conservation_scale_lkp local service.
*
* @param key_conservation_scale_lkpLocalService the key_conservation_scale_lkp local service
*/
public void setkey_conservation_scale_lkpLocalService(
key_conservation_scale_lkpLocalService key_conservation_scale_lkpLocalService) {
this.key_conservation_scale_lkpLocalService = key_conservation_scale_lkpLocalService;
}
/**
* Returns the key_conservation_scale_lkp persistence.
*
* @return the key_conservation_scale_lkp persistence
*/
public key_conservation_scale_lkpPersistence getkey_conservation_scale_lkpPersistence() {
return key_conservation_scale_lkpPersistence;
}
/**
* Sets the key_conservation_scale_lkp persistence.
*
* @param key_conservation_scale_lkpPersistence the key_conservation_scale_lkp persistence
*/
public void setkey_conservation_scale_lkpPersistence(
key_conservation_scale_lkpPersistence key_conservation_scale_lkpPersistence) {
this.key_conservation_scale_lkpPersistence = key_conservation_scale_lkpPersistence;
}
/**
* Returns the mission_lkp local service.
*
* @return the mission_lkp local service
*/
public mission_lkpLocalService getmission_lkpLocalService() {
return mission_lkpLocalService;
}
/**
* Sets the mission_lkp local service.
*
* @param mission_lkpLocalService the mission_lkp local service
*/
public void setmission_lkpLocalService(
mission_lkpLocalService mission_lkpLocalService) {
this.mission_lkpLocalService = mission_lkpLocalService;
}
/**
* Returns the mission_lkp persistence.
*
* @return the mission_lkp persistence
*/
public mission_lkpPersistence getmission_lkpPersistence() {
return mission_lkpPersistence;
}
/**
* Sets the mission_lkp persistence.
*
* @param mission_lkpPersistence the mission_lkp persistence
*/
public void setmission_lkpPersistence(
mission_lkpPersistence mission_lkpPersistence) {
this.mission_lkpPersistence = mission_lkpPersistence;
}
/**
* Returns the negative_factors_level_impact local service.
*
* @return the negative_factors_level_impact local service
*/
public negative_factors_level_impactLocalService getnegative_factors_level_impactLocalService() {
return negative_factors_level_impactLocalService;
}
/**
* Sets the negative_factors_level_impact local service.
*
* @param negative_factors_level_impactLocalService the negative_factors_level_impact local service
*/
public void setnegative_factors_level_impactLocalService(
negative_factors_level_impactLocalService negative_factors_level_impactLocalService) {
this.negative_factors_level_impactLocalService = negative_factors_level_impactLocalService;
}
/**
* Returns the negative_factors_level_impact persistence.
*
* @return the negative_factors_level_impact persistence
*/
public negative_factors_level_impactPersistence getnegative_factors_level_impactPersistence() {
return negative_factors_level_impactPersistence;
}
/**
* Sets the negative_factors_level_impact persistence.
*
* @param negative_factors_level_impactPersistence the negative_factors_level_impact persistence
*/
public void setnegative_factors_level_impactPersistence(
negative_factors_level_impactPersistence negative_factors_level_impactPersistence) {
this.negative_factors_level_impactPersistence = negative_factors_level_impactPersistence;
}
/**
* Returns the negative_factors_trend local service.
*
* @return the negative_factors_trend local service
*/
public negative_factors_trendLocalService getnegative_factors_trendLocalService() {
return negative_factors_trendLocalService;
}
/**
* Sets the negative_factors_trend local service.
*
* @param negative_factors_trendLocalService the negative_factors_trend local service
*/
public void setnegative_factors_trendLocalService(
negative_factors_trendLocalService negative_factors_trendLocalService) {
this.negative_factors_trendLocalService = negative_factors_trendLocalService;
}
/**
* Returns the negative_factors_trend persistence.
*
* @return the negative_factors_trend persistence
*/
public negative_factors_trendPersistence getnegative_factors_trendPersistence() {
return negative_factors_trendPersistence;
}
/**
* Sets the negative_factors_trend persistence.
*
* @param negative_factors_trendPersistence the negative_factors_trend persistence
*/
public void setnegative_factors_trendPersistence(
negative_factors_trendPersistence negative_factors_trendPersistence) {
this.negative_factors_trendPersistence = negative_factors_trendPersistence;
}
/**
* Returns the other_designation_lkp local service.
*
* @return the other_designation_lkp local service
*/
public other_designation_lkpLocalService getother_designation_lkpLocalService() {
return other_designation_lkpLocalService;
}
/**
* Sets the other_designation_lkp local service.
*
* @param other_designation_lkpLocalService the other_designation_lkp local service
*/
public void setother_designation_lkpLocalService(
other_designation_lkpLocalService other_designation_lkpLocalService) {
this.other_designation_lkpLocalService = other_designation_lkpLocalService;
}
/**
* Returns the other_designation_lkp persistence.
*
* @return the other_designation_lkp persistence
*/
public other_designation_lkpPersistence getother_designation_lkpPersistence() {
return other_designation_lkpPersistence;
}
/**
* Sets the other_designation_lkp persistence.
*
* @param other_designation_lkpPersistence the other_designation_lkp persistence
*/
public void setother_designation_lkpPersistence(
other_designation_lkpPersistence other_designation_lkpPersistence) {
this.other_designation_lkpPersistence = other_designation_lkpPersistence;
}
/**
* Returns the potential_project_needs local service.
*
* @return the potential_project_needs local service
*/
public potential_project_needsLocalService getpotential_project_needsLocalService() {
return potential_project_needsLocalService;
}
/**
* Sets the potential_project_needs local service.
*
* @param potential_project_needsLocalService the potential_project_needs local service
*/
public void setpotential_project_needsLocalService(
potential_project_needsLocalService potential_project_needsLocalService) {
this.potential_project_needsLocalService = potential_project_needsLocalService;
}
/**
* Returns the potential_project_needs persistence.
*
* @return the potential_project_needs persistence
*/
public potential_project_needsPersistence getpotential_project_needsPersistence() {
return potential_project_needsPersistence;
}
/**
* Sets the potential_project_needs persistence.
*
* @param potential_project_needsPersistence the potential_project_needs persistence
*/
public void setpotential_project_needsPersistence(
potential_project_needsPersistence potential_project_needsPersistence) {
this.potential_project_needsPersistence = potential_project_needsPersistence;
}
/**
* Returns the potential_threat_assessment_cat local service.
*
* @return the potential_threat_assessment_cat local service
*/
public potential_threat_assessment_catLocalService getpotential_threat_assessment_catLocalService() {
return potential_threat_assessment_catLocalService;
}
/**
* Sets the potential_threat_assessment_cat local service.
*
* @param potential_threat_assessment_catLocalService the potential_threat_assessment_cat local service
*/
public void setpotential_threat_assessment_catLocalService(
potential_threat_assessment_catLocalService potential_threat_assessment_catLocalService) {
this.potential_threat_assessment_catLocalService = potential_threat_assessment_catLocalService;
}
/**
* Returns the potential_threat_assessment_cat persistence.
*
* @return the potential_threat_assessment_cat persistence
*/
public potential_threat_assessment_catPersistence getpotential_threat_assessment_catPersistence() {
return potential_threat_assessment_catPersistence;
}
/**
* Sets the potential_threat_assessment_cat persistence.
*
* @param potential_threat_assessment_catPersistence the potential_threat_assessment_cat persistence
*/
public void setpotential_threat_assessment_catPersistence(
potential_threat_assessment_catPersistence potential_threat_assessment_catPersistence) {
this.potential_threat_assessment_catPersistence = potential_threat_assessment_catPersistence;
}
/**
* Returns the potential_threat_values local service.
*
* @return the potential_threat_values local service
*/
public potential_threat_valuesLocalService getpotential_threat_valuesLocalService() {
return potential_threat_valuesLocalService;
}
/**
* Sets the potential_threat_values local service.
*
* @param potential_threat_valuesLocalService the potential_threat_values local service
*/
public void setpotential_threat_valuesLocalService(
potential_threat_valuesLocalService potential_threat_valuesLocalService) {
this.potential_threat_valuesLocalService = potential_threat_valuesLocalService;
}
/**
* Returns the potential_threat_values persistence.
*
* @return the potential_threat_values persistence
*/
public potential_threat_valuesPersistence getpotential_threat_valuesPersistence() {
return potential_threat_valuesPersistence;
}
/**
* Sets the potential_threat_values persistence.
*
* @param potential_threat_valuesPersistence the potential_threat_values persistence
*/
public void setpotential_threat_valuesPersistence(
potential_threat_valuesPersistence potential_threat_valuesPersistence) {
this.potential_threat_valuesPersistence = potential_threat_valuesPersistence;
}
/**
* Returns the prot_mgmt_best_practices local service.
*
* @return the prot_mgmt_best_practices local service
*/
public prot_mgmt_best_practicesLocalService getprot_mgmt_best_practicesLocalService() {
return prot_mgmt_best_practicesLocalService;
}
/**
* Sets the prot_mgmt_best_practices local service.
*
* @param prot_mgmt_best_practicesLocalService the prot_mgmt_best_practices local service
*/
public void setprot_mgmt_best_practicesLocalService(
prot_mgmt_best_practicesLocalService prot_mgmt_best_practicesLocalService) {
this.prot_mgmt_best_practicesLocalService = prot_mgmt_best_practicesLocalService;
}
/**
* Returns the prot_mgmt_best_practices persistence.
*
* @return the prot_mgmt_best_practices persistence
*/
public prot_mgmt_best_practicesPersistence getprot_mgmt_best_practicesPersistence() {
return prot_mgmt_best_practicesPersistence;
}
/**
* Sets the prot_mgmt_best_practices persistence.
*
* @param prot_mgmt_best_practicesPersistence the prot_mgmt_best_practices persistence
*/
public void setprot_mgmt_best_practicesPersistence(
prot_mgmt_best_practicesPersistence prot_mgmt_best_practicesPersistence) {
this.prot_mgmt_best_practicesPersistence = prot_mgmt_best_practicesPersistence;
}
/**
* Returns the prot_mgmt_overall local service.
*
* @return the prot_mgmt_overall local service
*/
public prot_mgmt_overallLocalService getprot_mgmt_overallLocalService() {
return prot_mgmt_overallLocalService;
}
/**
* Sets the prot_mgmt_overall local service.
*
* @param prot_mgmt_overallLocalService the prot_mgmt_overall local service
*/
public void setprot_mgmt_overallLocalService(
prot_mgmt_overallLocalService prot_mgmt_overallLocalService) {
this.prot_mgmt_overallLocalService = prot_mgmt_overallLocalService;
}
/**
* Returns the prot_mgmt_overall persistence.
*
* @return the prot_mgmt_overall persistence
*/
public prot_mgmt_overallPersistence getprot_mgmt_overallPersistence() {
return prot_mgmt_overallPersistence;
}
/**
* Sets the prot_mgmt_overall persistence.
*
* @param prot_mgmt_overallPersistence the prot_mgmt_overall persistence
*/
public void setprot_mgmt_overallPersistence(
prot_mgmt_overallPersistence prot_mgmt_overallPersistence) {
this.prot_mgmt_overallPersistence = prot_mgmt_overallPersistence;
}
/**
* Returns the protection_management local service.
*
* @return the protection_management local service
*/
public protection_managementLocalService getprotection_managementLocalService() {
return protection_managementLocalService;
}
/**
* Sets the protection_management local service.
*
* @param protection_managementLocalService the protection_management local service
*/
public void setprotection_managementLocalService(
protection_managementLocalService protection_managementLocalService) {
this.protection_managementLocalService = protection_managementLocalService;
}
/**
* Returns the protection_management persistence.
*
* @return the protection_management persistence
*/
public protection_managementPersistence getprotection_managementPersistence() {
return protection_managementPersistence;
}
/**
* Sets the protection_management persistence.
*
* @param protection_managementPersistence the protection_management persistence
*/
public void setprotection_managementPersistence(
protection_managementPersistence protection_managementPersistence) {
this.protection_managementPersistence = protection_managementPersistence;
}
/**
* Returns the protection_management_ratings_lkp local service.
*
* @return the protection_management_ratings_lkp local service
*/
public protection_management_ratings_lkpLocalService getprotection_management_ratings_lkpLocalService() {
return protection_management_ratings_lkpLocalService;
}
/**
* Sets the protection_management_ratings_lkp local service.
*
* @param protection_management_ratings_lkpLocalService the protection_management_ratings_lkp local service
*/
public void setprotection_management_ratings_lkpLocalService(
protection_management_ratings_lkpLocalService protection_management_ratings_lkpLocalService) {
this.protection_management_ratings_lkpLocalService = protection_management_ratings_lkpLocalService;
}
/**
* Returns the protection_management_ratings_lkp persistence.
*
* @return the protection_management_ratings_lkp persistence
*/
public protection_management_ratings_lkpPersistence getprotection_management_ratings_lkpPersistence() {
return protection_management_ratings_lkpPersistence;
}
/**
* Sets the protection_management_ratings_lkp persistence.
*
* @param protection_management_ratings_lkpPersistence the protection_management_ratings_lkp persistence
*/
public void setprotection_management_ratings_lkpPersistence(
protection_management_ratings_lkpPersistence protection_management_ratings_lkpPersistence) {
this.protection_management_ratings_lkpPersistence = protection_management_ratings_lkpPersistence;
}
/**
* Returns the protection_mgmt_checklist_lkp local service.
*
* @return the protection_mgmt_checklist_lkp local service
*/
public protection_mgmt_checklist_lkpLocalService getprotection_mgmt_checklist_lkpLocalService() {
return protection_mgmt_checklist_lkpLocalService;
}
/**
* Sets the protection_mgmt_checklist_lkp local service.
*
* @param protection_mgmt_checklist_lkpLocalService the protection_mgmt_checklist_lkp local service
*/
public void setprotection_mgmt_checklist_lkpLocalService(
protection_mgmt_checklist_lkpLocalService protection_mgmt_checklist_lkpLocalService) {
this.protection_mgmt_checklist_lkpLocalService = protection_mgmt_checklist_lkpLocalService;
}
/**
* Returns the protection_mgmt_checklist_lkp persistence.
*
* @return the protection_mgmt_checklist_lkp persistence
*/
public protection_mgmt_checklist_lkpPersistence getprotection_mgmt_checklist_lkpPersistence() {
return protection_mgmt_checklist_lkpPersistence;
}
/**
* Sets the protection_mgmt_checklist_lkp persistence.
*
* @param protection_mgmt_checklist_lkpPersistence the protection_mgmt_checklist_lkp persistence
*/
public void setprotection_mgmt_checklist_lkpPersistence(
protection_mgmt_checklist_lkpPersistence protection_mgmt_checklist_lkpPersistence) {
this.protection_mgmt_checklist_lkpPersistence = protection_mgmt_checklist_lkpPersistence;
}
/**
* Returns the recommendation_type_lkp local service.
*
* @return the recommendation_type_lkp local service
*/
public recommendation_type_lkpLocalService getrecommendation_type_lkpLocalService() {
return recommendation_type_lkpLocalService;
}
/**
* Sets the recommendation_type_lkp local service.
*
* @param recommendation_type_lkpLocalService the recommendation_type_lkp local service
*/
public void setrecommendation_type_lkpLocalService(
recommendation_type_lkpLocalService recommendation_type_lkpLocalService) {
this.recommendation_type_lkpLocalService = recommendation_type_lkpLocalService;
}
/**
* Returns the recommendation_type_lkp persistence.
*
* @return the recommendation_type_lkp persistence
*/
public recommendation_type_lkpPersistence getrecommendation_type_lkpPersistence() {
return recommendation_type_lkpPersistence;
}
/**
* Sets the recommendation_type_lkp persistence.
*
* @param recommendation_type_lkpPersistence the recommendation_type_lkp persistence
*/
public void setrecommendation_type_lkpPersistence(
recommendation_type_lkpPersistence recommendation_type_lkpPersistence) {
this.recommendation_type_lkpPersistence = recommendation_type_lkpPersistence;
}
/**
* Returns the references local service.
*
* @return the references local service
*/
public referencesLocalService getreferencesLocalService() {
return referencesLocalService;
}
/**
* Sets the references local service.
*
* @param referencesLocalService the references local service
*/
public void setreferencesLocalService(
referencesLocalService referencesLocalService) {
this.referencesLocalService = referencesLocalService;
}
/**
* Returns the references persistence.
*
* @return the references persistence
*/
public referencesPersistence getreferencesPersistence() {
return referencesPersistence;
}
/**
* Sets the references persistence.
*
* @param referencesPersistence the references persistence
*/
public void setreferencesPersistence(
referencesPersistence referencesPersistence) {
this.referencesPersistence = referencesPersistence;
}
/**
* Returns the reinforced_monitoring local service.
*
* @return the reinforced_monitoring local service
*/
public reinforced_monitoringLocalService getreinforced_monitoringLocalService() {
return reinforced_monitoringLocalService;
}
/**
* Sets the reinforced_monitoring local service.
*
* @param reinforced_monitoringLocalService the reinforced_monitoring local service
*/
public void setreinforced_monitoringLocalService(
reinforced_monitoringLocalService reinforced_monitoringLocalService) {
this.reinforced_monitoringLocalService = reinforced_monitoringLocalService;
}
/**
* Returns the reinforced_monitoring persistence.
*
* @return the reinforced_monitoring persistence
*/
public reinforced_monitoringPersistence getreinforced_monitoringPersistence() {
return reinforced_monitoringPersistence;
}
/**
* Sets the reinforced_monitoring persistence.
*
* @param reinforced_monitoringPersistence the reinforced_monitoring persistence
*/
public void setreinforced_monitoringPersistence(
reinforced_monitoringPersistence reinforced_monitoringPersistence) {
this.reinforced_monitoringPersistence = reinforced_monitoringPersistence;
}
/**
* Returns the site_assessment local service.
*
* @return the site_assessment local service
*/
public site_assessmentLocalService getsite_assessmentLocalService() {
return site_assessmentLocalService;
}
/**
* Sets the site_assessment local service.
*
* @param site_assessmentLocalService the site_assessment local service
*/
public void setsite_assessmentLocalService(
site_assessmentLocalService site_assessmentLocalService) {
this.site_assessmentLocalService = site_assessmentLocalService;
}
/**
* Returns the site_assessment persistence.
*
* @return the site_assessment persistence
*/
public site_assessmentPersistence getsite_assessmentPersistence() {
return site_assessmentPersistence;
}
/**
* Sets the site_assessment persistence.
*
* @param site_assessmentPersistence the site_assessment persistence
*/
public void setsite_assessmentPersistence(
site_assessmentPersistence site_assessmentPersistence) {
this.site_assessmentPersistence = site_assessmentPersistence;
}
/**
* Returns the site_assessment finder.
*
* @return the site_assessment finder
*/
public site_assessmentFinder getsite_assessmentFinder() {
return site_assessmentFinder;
}
/**
* Sets the site_assessment finder.
*
* @param site_assessmentFinder the site_assessment finder
*/
public void setsite_assessmentFinder(
site_assessmentFinder site_assessmentFinder) {
this.site_assessmentFinder = site_assessmentFinder;
}
/**
* Returns the site_assessment_versions local service.
*
* @return the site_assessment_versions local service
*/
public site_assessment_versionsLocalService getsite_assessment_versionsLocalService() {
return site_assessment_versionsLocalService;
}
/**
* Sets the site_assessment_versions local service.
*
* @param site_assessment_versionsLocalService the site_assessment_versions local service
*/
public void setsite_assessment_versionsLocalService(
site_assessment_versionsLocalService site_assessment_versionsLocalService) {
this.site_assessment_versionsLocalService = site_assessment_versionsLocalService;
}
/**
* Returns the site_assessment_versions persistence.
*
* @return the site_assessment_versions persistence
*/
public site_assessment_versionsPersistence getsite_assessment_versionsPersistence() {
return site_assessment_versionsPersistence;
}
/**
* Sets the site_assessment_versions persistence.
*
* @param site_assessment_versionsPersistence the site_assessment_versions persistence
*/
public void setsite_assessment_versionsPersistence(
site_assessment_versionsPersistence site_assessment_versionsPersistence) {
this.site_assessment_versionsPersistence = site_assessment_versionsPersistence;
}
/**
* Returns the site_assessment_versions finder.
*
* @return the site_assessment_versions finder
*/
public site_assessment_versionsFinder getsite_assessment_versionsFinder() {
return site_assessment_versionsFinder;
}
/**
* Sets the site_assessment_versions finder.
*
* @param site_assessment_versionsFinder the site_assessment_versions finder
*/
public void setsite_assessment_versionsFinder(
site_assessment_versionsFinder site_assessment_versionsFinder) {
this.site_assessment_versionsFinder = site_assessment_versionsFinder;
}
/**
* Returns the sites_thematic local service.
*
* @return the sites_thematic local service
*/
public sites_thematicLocalService getsites_thematicLocalService() {
return sites_thematicLocalService;
}
/**
* Sets the sites_thematic local service.
*
* @param sites_thematicLocalService the sites_thematic local service
*/
public void setsites_thematicLocalService(
sites_thematicLocalService sites_thematicLocalService) {
this.sites_thematicLocalService = sites_thematicLocalService;
}
/**
* Returns the sites_thematic persistence.
*
* @return the sites_thematic persistence
*/
public sites_thematicPersistence getsites_thematicPersistence() {
return sites_thematicPersistence;
}
/**
* Sets the sites_thematic persistence.
*
* @param sites_thematicPersistence the sites_thematic persistence
*/
public void setsites_thematicPersistence(
sites_thematicPersistence sites_thematicPersistence) {
this.sites_thematicPersistence = sites_thematicPersistence;
}
/**
* Returns the state_lkp local service.
*
* @return the state_lkp local service
*/
public state_lkpLocalService getstate_lkpLocalService() {
return state_lkpLocalService;
}
/**
* Sets the state_lkp local service.
*
* @param state_lkpLocalService the state_lkp local service
*/
public void setstate_lkpLocalService(
state_lkpLocalService state_lkpLocalService) {
this.state_lkpLocalService = state_lkpLocalService;
}
/**
* Returns the state_lkp persistence.
*
* @return the state_lkp persistence
*/
public state_lkpPersistence getstate_lkpPersistence() {
return state_lkpPersistence;
}
/**
* Sets the state_lkp persistence.
*
* @param state_lkpPersistence the state_lkp persistence
*/
public void setstate_lkpPersistence(
state_lkpPersistence state_lkpPersistence) {
this.state_lkpPersistence = state_lkpPersistence;
}
/**
* Returns the state_trend_biodivvals local service.
*
* @return the state_trend_biodivvals local service
*/
public state_trend_biodivvalsLocalService getstate_trend_biodivvalsLocalService() {
return state_trend_biodivvalsLocalService;
}
/**
* Sets the state_trend_biodivvals local service.
*
* @param state_trend_biodivvalsLocalService the state_trend_biodivvals local service
*/
public void setstate_trend_biodivvalsLocalService(
state_trend_biodivvalsLocalService state_trend_biodivvalsLocalService) {
this.state_trend_biodivvalsLocalService = state_trend_biodivvalsLocalService;
}
/**
* Returns the state_trend_biodivvals persistence.
*
* @return the state_trend_biodivvals persistence
*/
public state_trend_biodivvalsPersistence getstate_trend_biodivvalsPersistence() {
return state_trend_biodivvalsPersistence;
}
/**
* Sets the state_trend_biodivvals persistence.
*
* @param state_trend_biodivvalsPersistence the state_trend_biodivvals persistence
*/
public void setstate_trend_biodivvalsPersistence(
state_trend_biodivvalsPersistence state_trend_biodivvalsPersistence) {
this.state_trend_biodivvalsPersistence = state_trend_biodivvalsPersistence;
}
/**
* Returns the state_trend_whvalues local service.
*
* @return the state_trend_whvalues local service
*/
public state_trend_whvaluesLocalService getstate_trend_whvaluesLocalService() {
return state_trend_whvaluesLocalService;
}
/**
* Sets the state_trend_whvalues local service.
*
* @param state_trend_whvaluesLocalService the state_trend_whvalues local service
*/
public void setstate_trend_whvaluesLocalService(
state_trend_whvaluesLocalService state_trend_whvaluesLocalService) {
this.state_trend_whvaluesLocalService = state_trend_whvaluesLocalService;
}
/**
* Returns the state_trend_whvalues persistence.
*
* @return the state_trend_whvalues persistence
*/
public state_trend_whvaluesPersistence getstate_trend_whvaluesPersistence() {
return state_trend_whvaluesPersistence;
}
/**
* Sets the state_trend_whvalues persistence.
*
* @param state_trend_whvaluesPersistence the state_trend_whvalues persistence
*/
public void setstate_trend_whvaluesPersistence(
state_trend_whvaluesPersistence state_trend_whvaluesPersistence) {
this.state_trend_whvaluesPersistence = state_trend_whvaluesPersistence;
}
/**
* Returns the thematic_lkp local service.
*
* @return the thematic_lkp local service
*/
public thematic_lkpLocalService getthematic_lkpLocalService() {
return thematic_lkpLocalService;
}
/**
* Sets the thematic_lkp local service.
*
* @param thematic_lkpLocalService the thematic_lkp local service
*/
public void setthematic_lkpLocalService(
thematic_lkpLocalService thematic_lkpLocalService) {
this.thematic_lkpLocalService = thematic_lkpLocalService;
}
/**
* Returns the thematic_lkp persistence.
*
* @return the thematic_lkp persistence
*/
public thematic_lkpPersistence getthematic_lkpPersistence() {
return thematic_lkpPersistence;
}
/**
* Sets the thematic_lkp persistence.
*
* @param thematic_lkpPersistence the thematic_lkp persistence
*/
public void setthematic_lkpPersistence(
thematic_lkpPersistence thematic_lkpPersistence) {
this.thematic_lkpPersistence = thematic_lkpPersistence;
}
/**
* Returns the threat_categories_lkp local service.
*
* @return the threat_categories_lkp local service
*/
public threat_categories_lkpLocalService getthreat_categories_lkpLocalService() {
return threat_categories_lkpLocalService;
}
/**
* Sets the threat_categories_lkp local service.
*
* @param threat_categories_lkpLocalService the threat_categories_lkp local service
*/
public void setthreat_categories_lkpLocalService(
threat_categories_lkpLocalService threat_categories_lkpLocalService) {
this.threat_categories_lkpLocalService = threat_categories_lkpLocalService;
}
/**
* Returns the threat_categories_lkp persistence.
*
* @return the threat_categories_lkp persistence
*/
public threat_categories_lkpPersistence getthreat_categories_lkpPersistence() {
return threat_categories_lkpPersistence;
}
/**
* Sets the threat_categories_lkp persistence.
*
* @param threat_categories_lkpPersistence the threat_categories_lkp persistence
*/
public void setthreat_categories_lkpPersistence(
threat_categories_lkpPersistence threat_categories_lkpPersistence) {
this.threat_categories_lkpPersistence = threat_categories_lkpPersistence;
}
/**
* Returns the threat_rating_lkp local service.
*
* @return the threat_rating_lkp local service
*/
public threat_rating_lkpLocalService getthreat_rating_lkpLocalService() {
return threat_rating_lkpLocalService;
}
/**
* Sets the threat_rating_lkp local service.
*
* @param threat_rating_lkpLocalService the threat_rating_lkp local service
*/
public void setthreat_rating_lkpLocalService(
threat_rating_lkpLocalService threat_rating_lkpLocalService) {
this.threat_rating_lkpLocalService = threat_rating_lkpLocalService;
}
/**
* Returns the threat_rating_lkp persistence.
*
* @return the threat_rating_lkp persistence
*/
public threat_rating_lkpPersistence getthreat_rating_lkpPersistence() {
return threat_rating_lkpPersistence;
}
/**
* Sets the threat_rating_lkp persistence.
*
* @param threat_rating_lkpPersistence the threat_rating_lkp persistence
*/
public void setthreat_rating_lkpPersistence(
threat_rating_lkpPersistence threat_rating_lkpPersistence) {
this.threat_rating_lkpPersistence = threat_rating_lkpPersistence;
}
/**
* Returns the threat_subcategories_lkp local service.
*
* @return the threat_subcategories_lkp local service
*/
public threat_subcategories_lkpLocalService getthreat_subcategories_lkpLocalService() {
return threat_subcategories_lkpLocalService;
}
/**
* Sets the threat_subcategories_lkp local service.
*
* @param threat_subcategories_lkpLocalService the threat_subcategories_lkp local service
*/
public void setthreat_subcategories_lkpLocalService(
threat_subcategories_lkpLocalService threat_subcategories_lkpLocalService) {
this.threat_subcategories_lkpLocalService = threat_subcategories_lkpLocalService;
}
/**
* Returns the threat_subcategories_lkp persistence.
*
* @return the threat_subcategories_lkp persistence
*/
public threat_subcategories_lkpPersistence getthreat_subcategories_lkpPersistence() {
return threat_subcategories_lkpPersistence;
}
/**
* Sets the threat_subcategories_lkp persistence.
*
* @param threat_subcategories_lkpPersistence the threat_subcategories_lkp persistence
*/
public void setthreat_subcategories_lkpPersistence(
threat_subcategories_lkpPersistence threat_subcategories_lkpPersistence) {
this.threat_subcategories_lkpPersistence = threat_subcategories_lkpPersistence;
}
/**
* Returns the threat_summary_current local service.
*
* @return the threat_summary_current local service
*/
public threat_summary_currentLocalService getthreat_summary_currentLocalService() {
return threat_summary_currentLocalService;
}
/**
* Sets the threat_summary_current local service.
*
* @param threat_summary_currentLocalService the threat_summary_current local service
*/
public void setthreat_summary_currentLocalService(
threat_summary_currentLocalService threat_summary_currentLocalService) {
this.threat_summary_currentLocalService = threat_summary_currentLocalService;
}
/**
* Returns the threat_summary_current persistence.
*
* @return the threat_summary_current persistence
*/
public threat_summary_currentPersistence getthreat_summary_currentPersistence() {
return threat_summary_currentPersistence;
}
/**
* Sets the threat_summary_current persistence.
*
* @param threat_summary_currentPersistence the threat_summary_current persistence
*/
public void setthreat_summary_currentPersistence(
threat_summary_currentPersistence threat_summary_currentPersistence) {
this.threat_summary_currentPersistence = threat_summary_currentPersistence;
}
/**
* Returns the threat_summary_overall local service.
*
* @return the threat_summary_overall local service
*/
public threat_summary_overallLocalService getthreat_summary_overallLocalService() {
return threat_summary_overallLocalService;
}
/**
* Sets the threat_summary_overall local service.
*
* @param threat_summary_overallLocalService the threat_summary_overall local service
*/
public void setthreat_summary_overallLocalService(
threat_summary_overallLocalService threat_summary_overallLocalService) {
this.threat_summary_overallLocalService = threat_summary_overallLocalService;
}
/**
* Returns the threat_summary_overall persistence.
*
* @return the threat_summary_overall persistence
*/
public threat_summary_overallPersistence getthreat_summary_overallPersistence() {
return threat_summary_overallPersistence;
}
/**
* Sets the threat_summary_overall persistence.
*
* @param threat_summary_overallPersistence the threat_summary_overall persistence
*/
public void setthreat_summary_overallPersistence(
threat_summary_overallPersistence threat_summary_overallPersistence) {
this.threat_summary_overallPersistence = threat_summary_overallPersistence;
}
/**
* Returns the threat_summary_potential local service.
*
* @return the threat_summary_potential local service
*/
public threat_summary_potentialLocalService getthreat_summary_potentialLocalService() {
return threat_summary_potentialLocalService;
}
/**
* Sets the threat_summary_potential local service.
*
* @param threat_summary_potentialLocalService the threat_summary_potential local service
*/
public void setthreat_summary_potentialLocalService(
threat_summary_potentialLocalService threat_summary_potentialLocalService) {
this.threat_summary_potentialLocalService = threat_summary_potentialLocalService;
}
/**
* Returns the threat_summary_potential persistence.
*
* @return the threat_summary_potential persistence
*/
public threat_summary_potentialPersistence getthreat_summary_potentialPersistence() {
return threat_summary_potentialPersistence;
}
/**
* Sets the threat_summary_potential persistence.
*
* @param threat_summary_potentialPersistence the threat_summary_potential persistence
*/
public void setthreat_summary_potentialPersistence(
threat_summary_potentialPersistence threat_summary_potentialPersistence) {
this.threat_summary_potentialPersistence = threat_summary_potentialPersistence;
}
/**
* Returns the trend_lkp local service.
*
* @return the trend_lkp local service
*/
public trend_lkpLocalService gettrend_lkpLocalService() {
return trend_lkpLocalService;
}
/**
* Sets the trend_lkp local service.
*
* @param trend_lkpLocalService the trend_lkp local service
*/
public void settrend_lkpLocalService(
trend_lkpLocalService trend_lkpLocalService) {
this.trend_lkpLocalService = trend_lkpLocalService;
}
/**
* Returns the trend_lkp persistence.
*
* @return the trend_lkp persistence
*/
public trend_lkpPersistence gettrend_lkpPersistence() {
return trend_lkpPersistence;
}
/**
* Sets the trend_lkp persistence.
*
* @param trend_lkpPersistence the trend_lkp persistence
*/
public void settrend_lkpPersistence(
trend_lkpPersistence trend_lkpPersistence) {
this.trend_lkpPersistence = trend_lkpPersistence;
}
/**
* Returns the unesco_region local service.
*
* @return the unesco_region local service
*/
public unesco_regionLocalService getunesco_regionLocalService() {
return unesco_regionLocalService;
}
/**
* Sets the unesco_region local service.
*
* @param unesco_regionLocalService the unesco_region local service
*/
public void setunesco_regionLocalService(
unesco_regionLocalService unesco_regionLocalService) {
this.unesco_regionLocalService = unesco_regionLocalService;
}
/**
* Returns the unesco_region persistence.
*
* @return the unesco_region persistence
*/
public unesco_regionPersistence getunesco_regionPersistence() {
return unesco_regionPersistence;
}
/**
* Sets the unesco_region persistence.
*
* @param unesco_regionPersistence the unesco_region persistence
*/
public void setunesco_regionPersistence(
unesco_regionPersistence unesco_regionPersistence) {
this.unesco_regionPersistence = unesco_regionPersistence;
}
/**
* Returns the unesco_region_country local service.
*
* @return the unesco_region_country local service
*/
public unesco_region_countryLocalService getunesco_region_countryLocalService() {
return unesco_region_countryLocalService;
}
/**
* Sets the unesco_region_country local service.
*
* @param unesco_region_countryLocalService the unesco_region_country local service
*/
public void setunesco_region_countryLocalService(
unesco_region_countryLocalService unesco_region_countryLocalService) {
this.unesco_region_countryLocalService = unesco_region_countryLocalService;
}
/**
* Returns the unesco_region_country persistence.
*
* @return the unesco_region_country persistence
*/
public unesco_region_countryPersistence getunesco_region_countryPersistence() {
return unesco_region_countryPersistence;
}
/**
* Sets the unesco_region_country persistence.
*
* @param unesco_region_countryPersistence the unesco_region_country persistence
*/
public void setunesco_region_countryPersistence(
unesco_region_countryPersistence unesco_region_countryPersistence) {
this.unesco_region_countryPersistence = unesco_region_countryPersistence;
}
/**
* Returns the whp_contact local service.
*
* @return the whp_contact local service
*/
public whp_contactLocalService getwhp_contactLocalService() {
return whp_contactLocalService;
}
/**
* Sets the whp_contact local service.
*
* @param whp_contactLocalService the whp_contact local service
*/
public void setwhp_contactLocalService(
whp_contactLocalService whp_contactLocalService) {
this.whp_contactLocalService = whp_contactLocalService;
}
/**
* Returns the whp_contact persistence.
*
* @return the whp_contact persistence
*/
public whp_contactPersistence getwhp_contactPersistence() {
return whp_contactPersistence;
}
/**
* Sets the whp_contact persistence.
*
* @param whp_contactPersistence the whp_contact persistence
*/
public void setwhp_contactPersistence(
whp_contactPersistence whp_contactPersistence) {
this.whp_contactPersistence = whp_contactPersistence;
}
/**
* Returns the whp_criteria_lkp local service.
*
* @return the whp_criteria_lkp local service
*/
public whp_criteria_lkpLocalService getwhp_criteria_lkpLocalService() {
return whp_criteria_lkpLocalService;
}
/**
* Sets the whp_criteria_lkp local service.
*
* @param whp_criteria_lkpLocalService the whp_criteria_lkp local service
*/
public void setwhp_criteria_lkpLocalService(
whp_criteria_lkpLocalService whp_criteria_lkpLocalService) {
this.whp_criteria_lkpLocalService = whp_criteria_lkpLocalService;
}
/**
* Returns the whp_criteria_lkp persistence.
*
* @return the whp_criteria_lkp persistence
*/
public whp_criteria_lkpPersistence getwhp_criteria_lkpPersistence() {
return whp_criteria_lkpPersistence;
}
/**
* Sets the whp_criteria_lkp persistence.
*
* @param whp_criteria_lkpPersistence the whp_criteria_lkp persistence
*/
public void setwhp_criteria_lkpPersistence(
whp_criteria_lkpPersistence whp_criteria_lkpPersistence) {
this.whp_criteria_lkpPersistence = whp_criteria_lkpPersistence;
}
/**
* Returns the whp_site_danger_list local service.
*
* @return the whp_site_danger_list local service
*/
public whp_site_danger_listLocalService getwhp_site_danger_listLocalService() {
return whp_site_danger_listLocalService;
}
/**
* Sets the whp_site_danger_list local service.
*
* @param whp_site_danger_listLocalService the whp_site_danger_list local service
*/
public void setwhp_site_danger_listLocalService(
whp_site_danger_listLocalService whp_site_danger_listLocalService) {
this.whp_site_danger_listLocalService = whp_site_danger_listLocalService;
}
/**
* Returns the whp_site_danger_list remote service.
*
* @return the whp_site_danger_list remote service
*/
public whp_site_danger_listService getwhp_site_danger_listService() {
return whp_site_danger_listService;
}
/**
* Sets the whp_site_danger_list remote service.
*
* @param whp_site_danger_listService the whp_site_danger_list remote service
*/
public void setwhp_site_danger_listService(
whp_site_danger_listService whp_site_danger_listService) {
this.whp_site_danger_listService = whp_site_danger_listService;
}
/**
* Returns the whp_site_danger_list persistence.
*
* @return the whp_site_danger_list persistence
*/
public whp_site_danger_listPersistence getwhp_site_danger_listPersistence() {
return whp_site_danger_listPersistence;
}
/**
* Sets the whp_site_danger_list persistence.
*
* @param whp_site_danger_listPersistence the whp_site_danger_list persistence
*/
public void setwhp_site_danger_listPersistence(
whp_site_danger_listPersistence whp_site_danger_listPersistence) {
this.whp_site_danger_listPersistence = whp_site_danger_listPersistence;
}
/**
* Returns the whp_sites local service.
*
* @return the whp_sites local service
*/
public whp_sitesLocalService getwhp_sitesLocalService() {
return whp_sitesLocalService;
}
/**
* Sets the whp_sites local service.
*
* @param whp_sitesLocalService the whp_sites local service
*/
public void setwhp_sitesLocalService(
whp_sitesLocalService whp_sitesLocalService) {
this.whp_sitesLocalService = whp_sitesLocalService;
}
/**
* Returns the whp_sites remote service.
*
* @return the whp_sites remote service
*/
public whp_sitesService getwhp_sitesService() {
return whp_sitesService;
}
/**
* Sets the whp_sites remote service.
*
* @param whp_sitesService the whp_sites remote service
*/
public void setwhp_sitesService(whp_sitesService whp_sitesService) {
this.whp_sitesService = whp_sitesService;
}
/**
* Returns the whp_sites persistence.
*
* @return the whp_sites persistence
*/
public whp_sitesPersistence getwhp_sitesPersistence() {
return whp_sitesPersistence;
}
/**
* Sets the whp_sites persistence.
*
* @param whp_sitesPersistence the whp_sites persistence
*/
public void setwhp_sitesPersistence(
whp_sitesPersistence whp_sitesPersistence) {
this.whp_sitesPersistence = whp_sitesPersistence;
}
/**
* Returns the whp_sites finder.
*
* @return the whp_sites finder
*/
public whp_sitesFinder getwhp_sitesFinder() {
return whp_sitesFinder;
}
/**
* Sets the whp_sites finder.
*
* @param whp_sitesFinder the whp_sites finder
*/
public void setwhp_sitesFinder(whp_sitesFinder whp_sitesFinder) {
this.whp_sitesFinder = whp_sitesFinder;
}
/**
* Returns the whp_sites_boundary_modification local service.
*
* @return the whp_sites_boundary_modification local service
*/
public whp_sites_boundary_modificationLocalService getwhp_sites_boundary_modificationLocalService() {
return whp_sites_boundary_modificationLocalService;
}
/**
* Sets the whp_sites_boundary_modification local service.
*
* @param whp_sites_boundary_modificationLocalService the whp_sites_boundary_modification local service
*/
public void setwhp_sites_boundary_modificationLocalService(
whp_sites_boundary_modificationLocalService whp_sites_boundary_modificationLocalService) {
this.whp_sites_boundary_modificationLocalService = whp_sites_boundary_modificationLocalService;
}
/**
* Returns the whp_sites_boundary_modification persistence.
*
* @return the whp_sites_boundary_modification persistence
*/
public whp_sites_boundary_modificationPersistence getwhp_sites_boundary_modificationPersistence() {
return whp_sites_boundary_modificationPersistence;
}
/**
* Sets the whp_sites_boundary_modification persistence.
*
* @param whp_sites_boundary_modificationPersistence the whp_sites_boundary_modification persistence
*/
public void setwhp_sites_boundary_modificationPersistence(
whp_sites_boundary_modificationPersistence whp_sites_boundary_modificationPersistence) {
this.whp_sites_boundary_modificationPersistence = whp_sites_boundary_modificationPersistence;
}
/**
* Returns the whp_sites_budget local service.
*
* @return the whp_sites_budget local service
*/
public whp_sites_budgetLocalService getwhp_sites_budgetLocalService() {
return whp_sites_budgetLocalService;
}
/**
* Sets the whp_sites_budget local service.
*
* @param whp_sites_budgetLocalService the whp_sites_budget local service
*/
public void setwhp_sites_budgetLocalService(
whp_sites_budgetLocalService whp_sites_budgetLocalService) {
this.whp_sites_budgetLocalService = whp_sites_budgetLocalService;
}
/**
* Returns the whp_sites_budget persistence.
*
* @return the whp_sites_budget persistence
*/
public whp_sites_budgetPersistence getwhp_sites_budgetPersistence() {
return whp_sites_budgetPersistence;
}
/**
* Sets the whp_sites_budget persistence.
*
* @param whp_sites_budgetPersistence the whp_sites_budget persistence
*/
public void setwhp_sites_budgetPersistence(
whp_sites_budgetPersistence whp_sites_budgetPersistence) {
this.whp_sites_budgetPersistence = whp_sites_budgetPersistence;
}
/**
* Returns the whp_sites_component local service.
*
* @return the whp_sites_component local service
*/
public whp_sites_componentLocalService getwhp_sites_componentLocalService() {
return whp_sites_componentLocalService;
}
/**
* Sets the whp_sites_component local service.
*
* @param whp_sites_componentLocalService the whp_sites_component local service
*/
public void setwhp_sites_componentLocalService(
whp_sites_componentLocalService whp_sites_componentLocalService) {
this.whp_sites_componentLocalService = whp_sites_componentLocalService;
}
/**
* Returns the whp_sites_component persistence.
*
* @return the whp_sites_component persistence
*/
public whp_sites_componentPersistence getwhp_sites_componentPersistence() {
return whp_sites_componentPersistence;
}
/**
* Sets the whp_sites_component persistence.
*
* @param whp_sites_componentPersistence the whp_sites_component persistence
*/
public void setwhp_sites_componentPersistence(
whp_sites_componentPersistence whp_sites_componentPersistence) {
this.whp_sites_componentPersistence = whp_sites_componentPersistence;
}
/**
* Returns the whp_sites_contacts local service.
*
* @return the whp_sites_contacts local service
*/
public whp_sites_contactsLocalService getwhp_sites_contactsLocalService() {
return whp_sites_contactsLocalService;
}
/**
* Sets the whp_sites_contacts local service.
*
* @param whp_sites_contactsLocalService the whp_sites_contacts local service
*/
public void setwhp_sites_contactsLocalService(
whp_sites_contactsLocalService whp_sites_contactsLocalService) {
this.whp_sites_contactsLocalService = whp_sites_contactsLocalService;
}
/**
* Returns the whp_sites_contacts persistence.
*
* @return the whp_sites_contacts persistence
*/
public whp_sites_contactsPersistence getwhp_sites_contactsPersistence() {
return whp_sites_contactsPersistence;
}
/**
* Sets the whp_sites_contacts persistence.
*
* @param whp_sites_contactsPersistence the whp_sites_contacts persistence
*/
public void setwhp_sites_contactsPersistence(
whp_sites_contactsPersistence whp_sites_contactsPersistence) {
this.whp_sites_contactsPersistence = whp_sites_contactsPersistence;
}
/**
* Returns the whp_sites_country local service.
*
* @return the whp_sites_country local service
*/
public whp_sites_countryLocalService getwhp_sites_countryLocalService() {
return whp_sites_countryLocalService;
}
/**
* Sets the whp_sites_country local service.
*
* @param whp_sites_countryLocalService the whp_sites_country local service
*/
public void setwhp_sites_countryLocalService(
whp_sites_countryLocalService whp_sites_countryLocalService) {
this.whp_sites_countryLocalService = whp_sites_countryLocalService;
}
/**
* Returns the whp_sites_country persistence.
*
* @return the whp_sites_country persistence
*/
public whp_sites_countryPersistence getwhp_sites_countryPersistence() {
return whp_sites_countryPersistence;
}
/**
* Sets the whp_sites_country persistence.
*
* @param whp_sites_countryPersistence the whp_sites_country persistence
*/
public void setwhp_sites_countryPersistence(
whp_sites_countryPersistence whp_sites_countryPersistence) {
this.whp_sites_countryPersistence = whp_sites_countryPersistence;
}
/**
* Returns the whp_sites_dsocr local service.
*
* @return the whp_sites_dsocr local service
*/
public whp_sites_dsocrLocalService getwhp_sites_dsocrLocalService() {
return whp_sites_dsocrLocalService;
}
/**
* Sets the whp_sites_dsocr local service.
*
* @param whp_sites_dsocrLocalService the whp_sites_dsocr local service
*/
public void setwhp_sites_dsocrLocalService(
whp_sites_dsocrLocalService whp_sites_dsocrLocalService) {
this.whp_sites_dsocrLocalService = whp_sites_dsocrLocalService;
}
/**
* Returns the whp_sites_dsocr persistence.
*
* @return the whp_sites_dsocr persistence
*/
public whp_sites_dsocrPersistence getwhp_sites_dsocrPersistence() {
return whp_sites_dsocrPersistence;
}
/**
* Sets the whp_sites_dsocr persistence.
*
* @param whp_sites_dsocrPersistence the whp_sites_dsocr persistence
*/
public void setwhp_sites_dsocrPersistence(
whp_sites_dsocrPersistence whp_sites_dsocrPersistence) {
this.whp_sites_dsocrPersistence = whp_sites_dsocrPersistence;
}
/**
* Returns the whp_sites_external_documents local service.
*
* @return the whp_sites_external_documents local service
*/
public whp_sites_external_documentsLocalService getwhp_sites_external_documentsLocalService() {
return whp_sites_external_documentsLocalService;
}
/**
* Sets the whp_sites_external_documents local service.
*
* @param whp_sites_external_documentsLocalService the whp_sites_external_documents local service
*/
public void setwhp_sites_external_documentsLocalService(
whp_sites_external_documentsLocalService whp_sites_external_documentsLocalService) {
this.whp_sites_external_documentsLocalService = whp_sites_external_documentsLocalService;
}
/**
* Returns the whp_sites_external_documents persistence.
*
* @return the whp_sites_external_documents persistence
*/
public whp_sites_external_documentsPersistence getwhp_sites_external_documentsPersistence() {
return whp_sites_external_documentsPersistence;
}
/**
* Sets the whp_sites_external_documents persistence.
*
* @param whp_sites_external_documentsPersistence the whp_sites_external_documents persistence
*/
public void setwhp_sites_external_documentsPersistence(
whp_sites_external_documentsPersistence whp_sites_external_documentsPersistence) {
this.whp_sites_external_documentsPersistence = whp_sites_external_documentsPersistence;
}
/**
* Returns the whp_sites_flagship_species local service.
*
* @return the whp_sites_flagship_species local service
*/
public whp_sites_flagship_speciesLocalService getwhp_sites_flagship_speciesLocalService() {
return whp_sites_flagship_speciesLocalService;
}
/**
* Sets the whp_sites_flagship_species local service.
*
* @param whp_sites_flagship_speciesLocalService the whp_sites_flagship_species local service
*/
public void setwhp_sites_flagship_speciesLocalService(
whp_sites_flagship_speciesLocalService whp_sites_flagship_speciesLocalService) {
this.whp_sites_flagship_speciesLocalService = whp_sites_flagship_speciesLocalService;
}
/**
* Returns the whp_sites_flagship_species persistence.
*
* @return the whp_sites_flagship_species persistence
*/
public whp_sites_flagship_speciesPersistence getwhp_sites_flagship_speciesPersistence() {
return whp_sites_flagship_speciesPersistence;
}
/**
* Sets the whp_sites_flagship_species persistence.
*
* @param whp_sites_flagship_speciesPersistence the whp_sites_flagship_species persistence
*/
public void setwhp_sites_flagship_speciesPersistence(
whp_sites_flagship_speciesPersistence whp_sites_flagship_speciesPersistence) {
this.whp_sites_flagship_speciesPersistence = whp_sites_flagship_speciesPersistence;
}
/**
* Returns the whp_sites_indigenous_communities local service.
*
* @return the whp_sites_indigenous_communities local service
*/
public whp_sites_indigenous_communitiesLocalService getwhp_sites_indigenous_communitiesLocalService() {
return whp_sites_indigenous_communitiesLocalService;
}
/**
* Sets the whp_sites_indigenous_communities local service.
*
* @param whp_sites_indigenous_communitiesLocalService the whp_sites_indigenous_communities local service
*/
public void setwhp_sites_indigenous_communitiesLocalService(
whp_sites_indigenous_communitiesLocalService whp_sites_indigenous_communitiesLocalService) {
this.whp_sites_indigenous_communitiesLocalService = whp_sites_indigenous_communitiesLocalService;
}
/**
* Returns the whp_sites_indigenous_communities persistence.
*
* @return the whp_sites_indigenous_communities persistence
*/
public whp_sites_indigenous_communitiesPersistence getwhp_sites_indigenous_communitiesPersistence() {
return whp_sites_indigenous_communitiesPersistence;
}
/**
* Sets the whp_sites_indigenous_communities persistence.
*
* @param whp_sites_indigenous_communitiesPersistence the whp_sites_indigenous_communities persistence
*/
public void setwhp_sites_indigenous_communitiesPersistence(
whp_sites_indigenous_communitiesPersistence whp_sites_indigenous_communitiesPersistence) {
this.whp_sites_indigenous_communitiesPersistence = whp_sites_indigenous_communitiesPersistence;
}
/**
* Returns the whp_sites_inscription_criteria local service.
*
* @return the whp_sites_inscription_criteria local service
*/
public whp_sites_inscription_criteriaLocalService getwhp_sites_inscription_criteriaLocalService() {
return whp_sites_inscription_criteriaLocalService;
}
/**
* Sets the whp_sites_inscription_criteria local service.
*
* @param whp_sites_inscription_criteriaLocalService the whp_sites_inscription_criteria local service
*/
public void setwhp_sites_inscription_criteriaLocalService(
whp_sites_inscription_criteriaLocalService whp_sites_inscription_criteriaLocalService) {
this.whp_sites_inscription_criteriaLocalService = whp_sites_inscription_criteriaLocalService;
}
/**
* Returns the whp_sites_inscription_criteria persistence.
*
* @return the whp_sites_inscription_criteria persistence
*/
public whp_sites_inscription_criteriaPersistence getwhp_sites_inscription_criteriaPersistence() {
return whp_sites_inscription_criteriaPersistence;
}
/**
* Sets the whp_sites_inscription_criteria persistence.
*
* @param whp_sites_inscription_criteriaPersistence the whp_sites_inscription_criteria persistence
*/
public void setwhp_sites_inscription_criteriaPersistence(
whp_sites_inscription_criteriaPersistence whp_sites_inscription_criteriaPersistence) {
this.whp_sites_inscription_criteriaPersistence = whp_sites_inscription_criteriaPersistence;
}
/**
* Returns the whp_sites_inscription_date local service.
*
* @return the whp_sites_inscription_date local service
*/
public whp_sites_inscription_dateLocalService getwhp_sites_inscription_dateLocalService() {
return whp_sites_inscription_dateLocalService;
}
/**
* Sets the whp_sites_inscription_date local service.
*
* @param whp_sites_inscription_dateLocalService the whp_sites_inscription_date local service
*/
public void setwhp_sites_inscription_dateLocalService(
whp_sites_inscription_dateLocalService whp_sites_inscription_dateLocalService) {
this.whp_sites_inscription_dateLocalService = whp_sites_inscription_dateLocalService;
}
/**
* Returns the whp_sites_inscription_date persistence.
*
* @return the whp_sites_inscription_date persistence
*/
public whp_sites_inscription_datePersistence getwhp_sites_inscription_datePersistence() {
return whp_sites_inscription_datePersistence;
}
/**
* Sets the whp_sites_inscription_date persistence.
*
* @param whp_sites_inscription_datePersistence the whp_sites_inscription_date persistence
*/
public void setwhp_sites_inscription_datePersistence(
whp_sites_inscription_datePersistence whp_sites_inscription_datePersistence) {
this.whp_sites_inscription_datePersistence = whp_sites_inscription_datePersistence;
}
/**
* Returns the whp_sites_iucn_pa_category local service.
*
* @return the whp_sites_iucn_pa_category local service
*/
public whp_sites_iucn_pa_categoryLocalService getwhp_sites_iucn_pa_categoryLocalService() {
return whp_sites_iucn_pa_categoryLocalService;
}
/**
* Sets the whp_sites_iucn_pa_category local service.
*
* @param whp_sites_iucn_pa_categoryLocalService the whp_sites_iucn_pa_category local service
*/
public void setwhp_sites_iucn_pa_categoryLocalService(
whp_sites_iucn_pa_categoryLocalService whp_sites_iucn_pa_categoryLocalService) {
this.whp_sites_iucn_pa_categoryLocalService = whp_sites_iucn_pa_categoryLocalService;
}
/**
* Returns the whp_sites_iucn_pa_category persistence.
*
* @return the whp_sites_iucn_pa_category persistence
*/
public whp_sites_iucn_pa_categoryPersistence getwhp_sites_iucn_pa_categoryPersistence() {
return whp_sites_iucn_pa_categoryPersistence;
}
/**
* Sets the whp_sites_iucn_pa_category persistence.
*
* @param whp_sites_iucn_pa_categoryPersistence the whp_sites_iucn_pa_category persistence
*/
public void setwhp_sites_iucn_pa_categoryPersistence(
whp_sites_iucn_pa_categoryPersistence whp_sites_iucn_pa_categoryPersistence) {
this.whp_sites_iucn_pa_categoryPersistence = whp_sites_iucn_pa_categoryPersistence;
}
/**
* Returns the whp_sites_iucn_recommendation local service.
*
* @return the whp_sites_iucn_recommendation local service
*/
public whp_sites_iucn_recommendationLocalService getwhp_sites_iucn_recommendationLocalService() {
return whp_sites_iucn_recommendationLocalService;
}
/**
* Sets the whp_sites_iucn_recommendation local service.
*
* @param whp_sites_iucn_recommendationLocalService the whp_sites_iucn_recommendation local service
*/
public void setwhp_sites_iucn_recommendationLocalService(
whp_sites_iucn_recommendationLocalService whp_sites_iucn_recommendationLocalService) {
this.whp_sites_iucn_recommendationLocalService = whp_sites_iucn_recommendationLocalService;
}
/**
* Returns the whp_sites_iucn_recommendation remote service.
*
* @return the whp_sites_iucn_recommendation remote service
*/
public whp_sites_iucn_recommendationService getwhp_sites_iucn_recommendationService() {
return whp_sites_iucn_recommendationService;
}
/**
* Sets the whp_sites_iucn_recommendation remote service.
*
* @param whp_sites_iucn_recommendationService the whp_sites_iucn_recommendation remote service
*/
public void setwhp_sites_iucn_recommendationService(
whp_sites_iucn_recommendationService whp_sites_iucn_recommendationService) {
this.whp_sites_iucn_recommendationService = whp_sites_iucn_recommendationService;
}
/**
* Returns the whp_sites_iucn_recommendation persistence.
*
* @return the whp_sites_iucn_recommendation persistence
*/
public whp_sites_iucn_recommendationPersistence getwhp_sites_iucn_recommendationPersistence() {
return whp_sites_iucn_recommendationPersistence;
}
/**
* Sets the whp_sites_iucn_recommendation persistence.
*
* @param whp_sites_iucn_recommendationPersistence the whp_sites_iucn_recommendation persistence
*/
public void setwhp_sites_iucn_recommendationPersistence(
whp_sites_iucn_recommendationPersistence whp_sites_iucn_recommendationPersistence) {
this.whp_sites_iucn_recommendationPersistence = whp_sites_iucn_recommendationPersistence;
}
/**
* Returns the whp_sites_mee local service.
*
* @return the whp_sites_mee local service
*/
public whp_sites_meeLocalService getwhp_sites_meeLocalService() {
return whp_sites_meeLocalService;
}
/**
* Sets the whp_sites_mee local service.
*
* @param whp_sites_meeLocalService the whp_sites_mee local service
*/
public void setwhp_sites_meeLocalService(
whp_sites_meeLocalService whp_sites_meeLocalService) {
this.whp_sites_meeLocalService = whp_sites_meeLocalService;
}
/**
* Returns the whp_sites_mee persistence.
*
* @return the whp_sites_mee persistence
*/
public whp_sites_meePersistence getwhp_sites_meePersistence() {
return whp_sites_meePersistence;
}
/**
* Sets the whp_sites_mee persistence.
*
* @param whp_sites_meePersistence the whp_sites_mee persistence
*/
public void setwhp_sites_meePersistence(
whp_sites_meePersistence whp_sites_meePersistence) {
this.whp_sites_meePersistence = whp_sites_meePersistence;
}
/**
* Returns the whp_sites_mgmt_plan_state local service.
*
* @return the whp_sites_mgmt_plan_state local service
*/
public whp_sites_mgmt_plan_stateLocalService getwhp_sites_mgmt_plan_stateLocalService() {
return whp_sites_mgmt_plan_stateLocalService;
}
/**
* Sets the whp_sites_mgmt_plan_state local service.
*
* @param whp_sites_mgmt_plan_stateLocalService the whp_sites_mgmt_plan_state local service
*/
public void setwhp_sites_mgmt_plan_stateLocalService(
whp_sites_mgmt_plan_stateLocalService whp_sites_mgmt_plan_stateLocalService) {
this.whp_sites_mgmt_plan_stateLocalService = whp_sites_mgmt_plan_stateLocalService;
}
/**
* Returns the whp_sites_mgmt_plan_state persistence.
*
* @return the whp_sites_mgmt_plan_state persistence
*/
public whp_sites_mgmt_plan_statePersistence getwhp_sites_mgmt_plan_statePersistence() {
return whp_sites_mgmt_plan_statePersistence;
}
/**
* Sets the whp_sites_mgmt_plan_state persistence.
*
* @param whp_sites_mgmt_plan_statePersistence the whp_sites_mgmt_plan_state persistence
*/
public void setwhp_sites_mgmt_plan_statePersistence(
whp_sites_mgmt_plan_statePersistence whp_sites_mgmt_plan_statePersistence) {
this.whp_sites_mgmt_plan_statePersistence = whp_sites_mgmt_plan_statePersistence;
}
/**
* Returns the whp_sites_mission local service.
*
* @return the whp_sites_mission local service
*/
public whp_sites_missionLocalService getwhp_sites_missionLocalService() {
return whp_sites_missionLocalService;
}
/**
* Sets the whp_sites_mission local service.
*
* @param whp_sites_missionLocalService the whp_sites_mission local service
*/
public void setwhp_sites_missionLocalService(
whp_sites_missionLocalService whp_sites_missionLocalService) {
this.whp_sites_missionLocalService = whp_sites_missionLocalService;
}
/**
* Returns the whp_sites_mission persistence.
*
* @return the whp_sites_mission persistence
*/
public whp_sites_missionPersistence getwhp_sites_missionPersistence() {
return whp_sites_missionPersistence;
}
/**
* Sets the whp_sites_mission persistence.
*
* @param whp_sites_missionPersistence the whp_sites_mission persistence
*/
public void setwhp_sites_missionPersistence(
whp_sites_missionPersistence whp_sites_missionPersistence) {
this.whp_sites_missionPersistence = whp_sites_missionPersistence;
}
/**
* Returns the whp_sites_other_designations local service.
*
* @return the whp_sites_other_designations local service
*/
public whp_sites_other_designationsLocalService getwhp_sites_other_designationsLocalService() {
return whp_sites_other_designationsLocalService;
}
/**
* Sets the whp_sites_other_designations local service.
*
* @param whp_sites_other_designationsLocalService the whp_sites_other_designations local service
*/
public void setwhp_sites_other_designationsLocalService(
whp_sites_other_designationsLocalService whp_sites_other_designationsLocalService) {
this.whp_sites_other_designationsLocalService = whp_sites_other_designationsLocalService;
}
/**
* Returns the whp_sites_other_designations persistence.
*
* @return the whp_sites_other_designations persistence
*/
public whp_sites_other_designationsPersistence getwhp_sites_other_designationsPersistence() {
return whp_sites_other_designationsPersistence;
}
/**
* Sets the whp_sites_other_designations persistence.
*
* @param whp_sites_other_designationsPersistence the whp_sites_other_designations persistence
*/
public void setwhp_sites_other_designationsPersistence(
whp_sites_other_designationsPersistence whp_sites_other_designationsPersistence) {
this.whp_sites_other_designationsPersistence = whp_sites_other_designationsPersistence;
}
/**
* Returns the whp_sites_soc_reports local service.
*
* @return the whp_sites_soc_reports local service
*/
public whp_sites_soc_reportsLocalService getwhp_sites_soc_reportsLocalService() {
return whp_sites_soc_reportsLocalService;
}
/**
* Sets the whp_sites_soc_reports local service.
*
* @param whp_sites_soc_reportsLocalService the whp_sites_soc_reports local service
*/
public void setwhp_sites_soc_reportsLocalService(
whp_sites_soc_reportsLocalService whp_sites_soc_reportsLocalService) {
this.whp_sites_soc_reportsLocalService = whp_sites_soc_reportsLocalService;
}
/**
* Returns the whp_sites_soc_reports persistence.
*
* @return the whp_sites_soc_reports persistence
*/
public whp_sites_soc_reportsPersistence getwhp_sites_soc_reportsPersistence() {
return whp_sites_soc_reportsPersistence;
}
/**
* Sets the whp_sites_soc_reports persistence.
*
* @param whp_sites_soc_reportsPersistence the whp_sites_soc_reports persistence
*/
public void setwhp_sites_soc_reportsPersistence(
whp_sites_soc_reportsPersistence whp_sites_soc_reportsPersistence) {
this.whp_sites_soc_reportsPersistence = whp_sites_soc_reportsPersistence;
}
/**
* Returns the whp_sites_soouv local service.
*
* @return the whp_sites_soouv local service
*/
public whp_sites_soouvLocalService getwhp_sites_soouvLocalService() {
return whp_sites_soouvLocalService;
}
/**
* Sets the whp_sites_soouv local service.
*
* @param whp_sites_soouvLocalService the whp_sites_soouv local service
*/
public void setwhp_sites_soouvLocalService(
whp_sites_soouvLocalService whp_sites_soouvLocalService) {
this.whp_sites_soouvLocalService = whp_sites_soouvLocalService;
}
/**
* Returns the whp_sites_soouv persistence.
*
* @return the whp_sites_soouv persistence
*/
public whp_sites_soouvPersistence getwhp_sites_soouvPersistence() {
return whp_sites_soouvPersistence;
}
/**
* Sets the whp_sites_soouv persistence.
*
* @param whp_sites_soouvPersistence the whp_sites_soouv persistence
*/
public void setwhp_sites_soouvPersistence(
whp_sites_soouvPersistence whp_sites_soouvPersistence) {
this.whp_sites_soouvPersistence = whp_sites_soouvPersistence;
}
/**
* Returns the whp_sites_visitors local service.
*
* @return the whp_sites_visitors local service
*/
public whp_sites_visitorsLocalService getwhp_sites_visitorsLocalService() {
return whp_sites_visitorsLocalService;
}
/**
* Sets the whp_sites_visitors local service.
*
* @param whp_sites_visitorsLocalService the whp_sites_visitors local service
*/
public void setwhp_sites_visitorsLocalService(
whp_sites_visitorsLocalService whp_sites_visitorsLocalService) {
this.whp_sites_visitorsLocalService = whp_sites_visitorsLocalService;
}
/**
* Returns the whp_sites_visitors persistence.
*
* @return the whp_sites_visitors persistence
*/
public whp_sites_visitorsPersistence getwhp_sites_visitorsPersistence() {
return whp_sites_visitorsPersistence;
}
/**
* Sets the whp_sites_visitors persistence.
*
* @param whp_sites_visitorsPersistence the whp_sites_visitors persistence
*/
public void setwhp_sites_visitorsPersistence(
whp_sites_visitorsPersistence whp_sites_visitorsPersistence) {
this.whp_sites_visitorsPersistence = whp_sites_visitorsPersistence;
}
/**
* Returns the counter local service.
*
* @return the counter local service
*/
public CounterLocalService getCounterLocalService() {
return counterLocalService;
}
/**
* Sets the counter local service.
*
* @param counterLocalService the counter local service
*/
public void setCounterLocalService(CounterLocalService counterLocalService) {
this.counterLocalService = counterLocalService;
}
/**
* Returns the resource local service.
*
* @return the resource local service
*/
public ResourceLocalService getResourceLocalService() {
return resourceLocalService;
}
/**
* Sets the resource local service.
*
* @param resourceLocalService the resource local service
*/
public void setResourceLocalService(
ResourceLocalService resourceLocalService) {
this.resourceLocalService = resourceLocalService;
}
/**
* Returns the resource remote service.
*
* @return the resource remote service
*/
public ResourceService getResourceService() {
return resourceService;
}
/**
* Sets the resource remote service.
*
* @param resourceService the resource remote service
*/
public void setResourceService(ResourceService resourceService) {
this.resourceService = resourceService;
}
/**
* Returns the resource persistence.
*
* @return the resource persistence
*/
public ResourcePersistence getResourcePersistence() {
return resourcePersistence;
}
/**
* Sets the resource persistence.
*
* @param resourcePersistence the resource persistence
*/
public void setResourcePersistence(ResourcePersistence resourcePersistence) {
this.resourcePersistence = resourcePersistence;
}
/**
* Returns the user local service.
*
* @return the user local service
*/
public UserLocalService getUserLocalService() {
return userLocalService;
}
/**
* Sets the user local service.
*
* @param userLocalService the user local service
*/
public void setUserLocalService(UserLocalService userLocalService) {
this.userLocalService = userLocalService;
}
/**
* Returns the user remote service.
*
* @return the user remote service
*/
public UserService getUserService() {
return userService;
}
/**
* Sets the user remote service.
*
* @param userService the user remote service
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* Returns the user persistence.
*
* @return the user persistence
*/
public UserPersistence getUserPersistence() {
return userPersistence;
}
/**
* Sets the user persistence.
*
* @param userPersistence the user persistence
*/
public void setUserPersistence(UserPersistence userPersistence) {
this.userPersistence = userPersistence;
}
public void afterPropertiesSet() {
PersistedModelLocalServiceRegistryUtil.register("com.iucn.whp.dbservice.model.contact_category",
contact_categoryLocalService);
}
public void destroy() {
PersistedModelLocalServiceRegistryUtil.unregister(
"com.iucn.whp.dbservice.model.contact_category");
}
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
public String getBeanIdentifier() {
return _beanIdentifier;
}
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
public void setBeanIdentifier(String beanIdentifier) {
_beanIdentifier = beanIdentifier;
}
public Object invokeMethod(String name, String[] parameterTypes,
Object[] arguments) throws Throwable {
return _clpInvoker.invokeMethod(name, parameterTypes, arguments);
}
protected Class<?> getModelClass() {
return contact_category.class;
}
protected String getModelClassName() {
return contact_category.class.getName();
}
/**
* Performs an SQL query.
*
* @param sql the sql query
*/
protected void runSQL(String sql) throws SystemException {
try {
DataSource dataSource = contact_categoryPersistence.getDataSource();
SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(dataSource,
sql, new int[0]);
sqlUpdate.update();
}
catch (Exception e) {
throw new SystemException(e);
}
}
@BeanReference(type = active_conservation_projectsLocalService.class)
protected active_conservation_projectsLocalService active_conservation_projectsLocalService;
@BeanReference(type = active_conservation_projectsPersistence.class)
protected active_conservation_projectsPersistence active_conservation_projectsPersistence;
@BeanReference(type = advance_query_assessmentLocalService.class)
protected advance_query_assessmentLocalService advance_query_assessmentLocalService;
@BeanReference(type = advance_query_assessmentPersistence.class)
protected advance_query_assessmentPersistence advance_query_assessmentPersistence;
@BeanReference(type = advance_query_siteLocalService.class)
protected advance_query_siteLocalService advance_query_siteLocalService;
@BeanReference(type = advance_query_sitePersistence.class)
protected advance_query_sitePersistence advance_query_sitePersistence;
@BeanReference(type = assessing_threats_currentLocalService.class)
protected assessing_threats_currentLocalService assessing_threats_currentLocalService;
@BeanReference(type = assessing_threats_currentPersistence.class)
protected assessing_threats_currentPersistence assessing_threats_currentPersistence;
@BeanReference(type = assessing_threats_potentialLocalService.class)
protected assessing_threats_potentialLocalService assessing_threats_potentialLocalService;
@BeanReference(type = assessing_threats_potentialPersistence.class)
protected assessing_threats_potentialPersistence assessing_threats_potentialPersistence;
@BeanReference(type = assessment_lang_lkpLocalService.class)
protected assessment_lang_lkpLocalService assessment_lang_lkpLocalService;
@BeanReference(type = assessment_lang_lkpPersistence.class)
protected assessment_lang_lkpPersistence assessment_lang_lkpPersistence;
@BeanReference(type = assessment_lang_versionLocalService.class)
protected assessment_lang_versionLocalService assessment_lang_versionLocalService;
@BeanReference(type = assessment_lang_versionPersistence.class)
protected assessment_lang_versionPersistence assessment_lang_versionPersistence;
@BeanReference(type = assessment_stagesLocalService.class)
protected assessment_stagesLocalService assessment_stagesLocalService;
@BeanReference(type = assessment_stagesPersistence.class)
protected assessment_stagesPersistence assessment_stagesPersistence;
@BeanReference(type = assessment_statusLocalService.class)
protected assessment_statusLocalService assessment_statusLocalService;
@BeanReference(type = assessment_statusPersistence.class)
protected assessment_statusPersistence assessment_statusPersistence;
@BeanReference(type = assessment_validationLocalService.class)
protected assessment_validationLocalService assessment_validationLocalService;
@BeanReference(type = assessment_validationPersistence.class)
protected assessment_validationPersistence assessment_validationPersistence;
@BeanReference(type = assessment_whvaluesLocalService.class)
protected assessment_whvaluesLocalService assessment_whvaluesLocalService;
@BeanReference(type = assessment_whvaluesPersistence.class)
protected assessment_whvaluesPersistence assessment_whvaluesPersistence;
@BeanReference(type = assessment_whvalues_whcriterionLocalService.class)
protected assessment_whvalues_whcriterionLocalService assessment_whvalues_whcriterionLocalService;
@BeanReference(type = assessment_whvalues_whcriterionPersistence.class)
protected assessment_whvalues_whcriterionPersistence assessment_whvalues_whcriterionPersistence;
@BeanReference(type = benefit_checksubtype_lkpLocalService.class)
protected benefit_checksubtype_lkpLocalService benefit_checksubtype_lkpLocalService;
@BeanReference(type = benefit_checksubtype_lkpPersistence.class)
protected benefit_checksubtype_lkpPersistence benefit_checksubtype_lkpPersistence;
@BeanReference(type = benefit_checktype_lkpLocalService.class)
protected benefit_checktype_lkpLocalService benefit_checktype_lkpLocalService;
@BeanReference(type = benefit_checktype_lkpPersistence.class)
protected benefit_checktype_lkpPersistence benefit_checktype_lkpPersistence;
@BeanReference(type = benefit_rating_lkpLocalService.class)
protected benefit_rating_lkpLocalService benefit_rating_lkpLocalService;
@BeanReference(type = benefit_rating_lkpPersistence.class)
protected benefit_rating_lkpPersistence benefit_rating_lkpPersistence;
@BeanReference(type = benefitsLocalService.class)
protected benefitsLocalService benefitsLocalService;
@BeanReference(type = benefitsPersistence.class)
protected benefitsPersistence benefitsPersistence;
@BeanReference(type = benefits_summaryLocalService.class)
protected benefits_summaryLocalService benefits_summaryLocalService;
@BeanReference(type = benefits_summaryPersistence.class)
protected benefits_summaryPersistence benefits_summaryPersistence;
@BeanReference(type = benefits_type_refLocalService.class)
protected benefits_type_refLocalService benefits_type_refLocalService;
@BeanReference(type = benefits_type_refPersistence.class)
protected benefits_type_refPersistence benefits_type_refPersistence;
@BeanReference(type = biodiversity_valuesLocalService.class)
protected biodiversity_valuesLocalService biodiversity_valuesLocalService;
@BeanReference(type = biodiversity_valuesPersistence.class)
protected biodiversity_valuesPersistence biodiversity_valuesPersistence;
@BeanReference(type = boundary_modification_type_lkpLocalService.class)
protected boundary_modification_type_lkpLocalService boundary_modification_type_lkpLocalService;
@BeanReference(type = boundary_modification_type_lkpPersistence.class)
protected boundary_modification_type_lkpPersistence boundary_modification_type_lkpPersistence;
@BeanReference(type = conservation_outlookLocalService.class)
protected conservation_outlookLocalService conservation_outlookLocalService;
@BeanReference(type = conservation_outlookPersistence.class)
protected conservation_outlookPersistence conservation_outlookPersistence;
@BeanReference(type = conservation_outlook_rating_lkpLocalService.class)
protected conservation_outlook_rating_lkpLocalService conservation_outlook_rating_lkpLocalService;
@BeanReference(type = conservation_outlook_rating_lkpPersistence.class)
protected conservation_outlook_rating_lkpPersistence conservation_outlook_rating_lkpPersistence;
@BeanReference(type = contact_categoryLocalService.class)
protected contact_categoryLocalService contact_categoryLocalService;
@BeanReference(type = contact_categoryPersistence.class)
protected contact_categoryPersistence contact_categoryPersistence;
@BeanReference(type = country_lkpLocalService.class)
protected country_lkpLocalService country_lkpLocalService;
@BeanReference(type = country_lkpPersistence.class)
protected country_lkpPersistence country_lkpPersistence;
@BeanReference(type = current_state_trendLocalService.class)
protected current_state_trendLocalService current_state_trendLocalService;
@BeanReference(type = current_state_trendPersistence.class)
protected current_state_trendPersistence current_state_trendPersistence;
@BeanReference(type = current_state_trend_valuesLocalService.class)
protected current_state_trend_valuesLocalService current_state_trend_valuesLocalService;
@BeanReference(type = current_state_trend_valuesPersistence.class)
protected current_state_trend_valuesPersistence current_state_trend_valuesPersistence;
@BeanReference(type = current_threat_assessment_catLocalService.class)
protected current_threat_assessment_catLocalService current_threat_assessment_catLocalService;
@BeanReference(type = current_threat_assessment_catPersistence.class)
protected current_threat_assessment_catPersistence current_threat_assessment_catPersistence;
@BeanReference(type = current_threat_valuesLocalService.class)
protected current_threat_valuesLocalService current_threat_valuesLocalService;
@BeanReference(type = current_threat_valuesPersistence.class)
protected current_threat_valuesPersistence current_threat_valuesPersistence;
@BeanReference(type = danger_list_status_lkpLocalService.class)
protected danger_list_status_lkpLocalService danger_list_status_lkpLocalService;
@BeanReference(type = danger_list_status_lkpPersistence.class)
protected danger_list_status_lkpPersistence danger_list_status_lkpPersistence;
@BeanReference(type = docs_customDataLocalService.class)
protected docs_customDataLocalService docs_customDataLocalService;
@BeanReference(type = docs_customDataPersistence.class)
protected docs_customDataPersistence docs_customDataPersistence;
@BeanReference(type = docs_customDataFinder.class)
protected docs_customDataFinder docs_customDataFinder;
@BeanReference(type = docs_sitedataLocalService.class)
protected docs_sitedataLocalService docs_sitedataLocalService;
@BeanReference(type = docs_sitedataPersistence.class)
protected docs_sitedataPersistence docs_sitedataPersistence;
@BeanReference(type = effective_prot_mgmt_iothreatsLocalService.class)
protected effective_prot_mgmt_iothreatsLocalService effective_prot_mgmt_iothreatsLocalService;
@BeanReference(type = effective_prot_mgmt_iothreatsPersistence.class)
protected effective_prot_mgmt_iothreatsPersistence effective_prot_mgmt_iothreatsPersistence;
@BeanReference(type = flagship_species_lkpLocalService.class)
protected flagship_species_lkpLocalService flagship_species_lkpLocalService;
@BeanReference(type = flagship_species_lkpPersistence.class)
protected flagship_species_lkpPersistence flagship_species_lkpPersistence;
@BeanReference(type = inscription_criteria_lkpLocalService.class)
protected inscription_criteria_lkpLocalService inscription_criteria_lkpLocalService;
@BeanReference(type = inscription_criteria_lkpPersistence.class)
protected inscription_criteria_lkpPersistence inscription_criteria_lkpPersistence;
@BeanReference(type = inscription_type_lkpLocalService.class)
protected inscription_type_lkpLocalService inscription_type_lkpLocalService;
@BeanReference(type = inscription_type_lkpPersistence.class)
protected inscription_type_lkpPersistence inscription_type_lkpPersistence;
@BeanReference(type = iucn_pa_lkp_categoryLocalService.class)
protected iucn_pa_lkp_categoryLocalService iucn_pa_lkp_categoryLocalService;
@BeanReference(type = iucn_pa_lkp_categoryPersistence.class)
protected iucn_pa_lkp_categoryPersistence iucn_pa_lkp_categoryPersistence;
@BeanReference(type = iucn_regionLocalService.class)
protected iucn_regionLocalService iucn_regionLocalService;
@BeanReference(type = iucn_regionPersistence.class)
protected iucn_regionPersistence iucn_regionPersistence;
@BeanReference(type = iucn_region_countryLocalService.class)
protected iucn_region_countryLocalService iucn_region_countryLocalService;
@BeanReference(type = iucn_region_countryPersistence.class)
protected iucn_region_countryPersistence iucn_region_countryPersistence;
@BeanReference(type = key_conservation_issuesLocalService.class)
protected key_conservation_issuesLocalService key_conservation_issuesLocalService;
@BeanReference(type = key_conservation_issuesPersistence.class)
protected key_conservation_issuesPersistence key_conservation_issuesPersistence;
@BeanReference(type = key_conservation_scale_lkpLocalService.class)
protected key_conservation_scale_lkpLocalService key_conservation_scale_lkpLocalService;
@BeanReference(type = key_conservation_scale_lkpPersistence.class)
protected key_conservation_scale_lkpPersistence key_conservation_scale_lkpPersistence;
@BeanReference(type = mission_lkpLocalService.class)
protected mission_lkpLocalService mission_lkpLocalService;
@BeanReference(type = mission_lkpPersistence.class)
protected mission_lkpPersistence mission_lkpPersistence;
@BeanReference(type = negative_factors_level_impactLocalService.class)
protected negative_factors_level_impactLocalService negative_factors_level_impactLocalService;
@BeanReference(type = negative_factors_level_impactPersistence.class)
protected negative_factors_level_impactPersistence negative_factors_level_impactPersistence;
@BeanReference(type = negative_factors_trendLocalService.class)
protected negative_factors_trendLocalService negative_factors_trendLocalService;
@BeanReference(type = negative_factors_trendPersistence.class)
protected negative_factors_trendPersistence negative_factors_trendPersistence;
@BeanReference(type = other_designation_lkpLocalService.class)
protected other_designation_lkpLocalService other_designation_lkpLocalService;
@BeanReference(type = other_designation_lkpPersistence.class)
protected other_designation_lkpPersistence other_designation_lkpPersistence;
@BeanReference(type = potential_project_needsLocalService.class)
protected potential_project_needsLocalService potential_project_needsLocalService;
@BeanReference(type = potential_project_needsPersistence.class)
protected potential_project_needsPersistence potential_project_needsPersistence;
@BeanReference(type = potential_threat_assessment_catLocalService.class)
protected potential_threat_assessment_catLocalService potential_threat_assessment_catLocalService;
@BeanReference(type = potential_threat_assessment_catPersistence.class)
protected potential_threat_assessment_catPersistence potential_threat_assessment_catPersistence;
@BeanReference(type = potential_threat_valuesLocalService.class)
protected potential_threat_valuesLocalService potential_threat_valuesLocalService;
@BeanReference(type = potential_threat_valuesPersistence.class)
protected potential_threat_valuesPersistence potential_threat_valuesPersistence;
@BeanReference(type = prot_mgmt_best_practicesLocalService.class)
protected prot_mgmt_best_practicesLocalService prot_mgmt_best_practicesLocalService;
@BeanReference(type = prot_mgmt_best_practicesPersistence.class)
protected prot_mgmt_best_practicesPersistence prot_mgmt_best_practicesPersistence;
@BeanReference(type = prot_mgmt_overallLocalService.class)
protected prot_mgmt_overallLocalService prot_mgmt_overallLocalService;
@BeanReference(type = prot_mgmt_overallPersistence.class)
protected prot_mgmt_overallPersistence prot_mgmt_overallPersistence;
@BeanReference(type = protection_managementLocalService.class)
protected protection_managementLocalService protection_managementLocalService;
@BeanReference(type = protection_managementPersistence.class)
protected protection_managementPersistence protection_managementPersistence;
@BeanReference(type = protection_management_ratings_lkpLocalService.class)
protected protection_management_ratings_lkpLocalService protection_management_ratings_lkpLocalService;
@BeanReference(type = protection_management_ratings_lkpPersistence.class)
protected protection_management_ratings_lkpPersistence protection_management_ratings_lkpPersistence;
@BeanReference(type = protection_mgmt_checklist_lkpLocalService.class)
protected protection_mgmt_checklist_lkpLocalService protection_mgmt_checklist_lkpLocalService;
@BeanReference(type = protection_mgmt_checklist_lkpPersistence.class)
protected protection_mgmt_checklist_lkpPersistence protection_mgmt_checklist_lkpPersistence;
@BeanReference(type = recommendation_type_lkpLocalService.class)
protected recommendation_type_lkpLocalService recommendation_type_lkpLocalService;
@BeanReference(type = recommendation_type_lkpPersistence.class)
protected recommendation_type_lkpPersistence recommendation_type_lkpPersistence;
@BeanReference(type = referencesLocalService.class)
protected referencesLocalService referencesLocalService;
@BeanReference(type = referencesPersistence.class)
protected referencesPersistence referencesPersistence;
@BeanReference(type = reinforced_monitoringLocalService.class)
protected reinforced_monitoringLocalService reinforced_monitoringLocalService;
@BeanReference(type = reinforced_monitoringPersistence.class)
protected reinforced_monitoringPersistence reinforced_monitoringPersistence;
@BeanReference(type = site_assessmentLocalService.class)
protected site_assessmentLocalService site_assessmentLocalService;
@BeanReference(type = site_assessmentPersistence.class)
protected site_assessmentPersistence site_assessmentPersistence;
@BeanReference(type = site_assessmentFinder.class)
protected site_assessmentFinder site_assessmentFinder;
@BeanReference(type = site_assessment_versionsLocalService.class)
protected site_assessment_versionsLocalService site_assessment_versionsLocalService;
@BeanReference(type = site_assessment_versionsPersistence.class)
protected site_assessment_versionsPersistence site_assessment_versionsPersistence;
@BeanReference(type = site_assessment_versionsFinder.class)
protected site_assessment_versionsFinder site_assessment_versionsFinder;
@BeanReference(type = sites_thematicLocalService.class)
protected sites_thematicLocalService sites_thematicLocalService;
@BeanReference(type = sites_thematicPersistence.class)
protected sites_thematicPersistence sites_thematicPersistence;
@BeanReference(type = state_lkpLocalService.class)
protected state_lkpLocalService state_lkpLocalService;
@BeanReference(type = state_lkpPersistence.class)
protected state_lkpPersistence state_lkpPersistence;
@BeanReference(type = state_trend_biodivvalsLocalService.class)
protected state_trend_biodivvalsLocalService state_trend_biodivvalsLocalService;
@BeanReference(type = state_trend_biodivvalsPersistence.class)
protected state_trend_biodivvalsPersistence state_trend_biodivvalsPersistence;
@BeanReference(type = state_trend_whvaluesLocalService.class)
protected state_trend_whvaluesLocalService state_trend_whvaluesLocalService;
@BeanReference(type = state_trend_whvaluesPersistence.class)
protected state_trend_whvaluesPersistence state_trend_whvaluesPersistence;
@BeanReference(type = thematic_lkpLocalService.class)
protected thematic_lkpLocalService thematic_lkpLocalService;
@BeanReference(type = thematic_lkpPersistence.class)
protected thematic_lkpPersistence thematic_lkpPersistence;
@BeanReference(type = threat_categories_lkpLocalService.class)
protected threat_categories_lkpLocalService threat_categories_lkpLocalService;
@BeanReference(type = threat_categories_lkpPersistence.class)
protected threat_categories_lkpPersistence threat_categories_lkpPersistence;
@BeanReference(type = threat_rating_lkpLocalService.class)
protected threat_rating_lkpLocalService threat_rating_lkpLocalService;
@BeanReference(type = threat_rating_lkpPersistence.class)
protected threat_rating_lkpPersistence threat_rating_lkpPersistence;
@BeanReference(type = threat_subcategories_lkpLocalService.class)
protected threat_subcategories_lkpLocalService threat_subcategories_lkpLocalService;
@BeanReference(type = threat_subcategories_lkpPersistence.class)
protected threat_subcategories_lkpPersistence threat_subcategories_lkpPersistence;
@BeanReference(type = threat_summary_currentLocalService.class)
protected threat_summary_currentLocalService threat_summary_currentLocalService;
@BeanReference(type = threat_summary_currentPersistence.class)
protected threat_summary_currentPersistence threat_summary_currentPersistence;
@BeanReference(type = threat_summary_overallLocalService.class)
protected threat_summary_overallLocalService threat_summary_overallLocalService;
@BeanReference(type = threat_summary_overallPersistence.class)
protected threat_summary_overallPersistence threat_summary_overallPersistence;
@BeanReference(type = threat_summary_potentialLocalService.class)
protected threat_summary_potentialLocalService threat_summary_potentialLocalService;
@BeanReference(type = threat_summary_potentialPersistence.class)
protected threat_summary_potentialPersistence threat_summary_potentialPersistence;
@BeanReference(type = trend_lkpLocalService.class)
protected trend_lkpLocalService trend_lkpLocalService;
@BeanReference(type = trend_lkpPersistence.class)
protected trend_lkpPersistence trend_lkpPersistence;
@BeanReference(type = unesco_regionLocalService.class)
protected unesco_regionLocalService unesco_regionLocalService;
@BeanReference(type = unesco_regionPersistence.class)
protected unesco_regionPersistence unesco_regionPersistence;
@BeanReference(type = unesco_region_countryLocalService.class)
protected unesco_region_countryLocalService unesco_region_countryLocalService;
@BeanReference(type = unesco_region_countryPersistence.class)
protected unesco_region_countryPersistence unesco_region_countryPersistence;
@BeanReference(type = whp_contactLocalService.class)
protected whp_contactLocalService whp_contactLocalService;
@BeanReference(type = whp_contactPersistence.class)
protected whp_contactPersistence whp_contactPersistence;
@BeanReference(type = whp_criteria_lkpLocalService.class)
protected whp_criteria_lkpLocalService whp_criteria_lkpLocalService;
@BeanReference(type = whp_criteria_lkpPersistence.class)
protected whp_criteria_lkpPersistence whp_criteria_lkpPersistence;
@BeanReference(type = whp_site_danger_listLocalService.class)
protected whp_site_danger_listLocalService whp_site_danger_listLocalService;
@BeanReference(type = whp_site_danger_listService.class)
protected whp_site_danger_listService whp_site_danger_listService;
@BeanReference(type = whp_site_danger_listPersistence.class)
protected whp_site_danger_listPersistence whp_site_danger_listPersistence;
@BeanReference(type = whp_sitesLocalService.class)
protected whp_sitesLocalService whp_sitesLocalService;
@BeanReference(type = whp_sitesService.class)
protected whp_sitesService whp_sitesService;
@BeanReference(type = whp_sitesPersistence.class)
protected whp_sitesPersistence whp_sitesPersistence;
@BeanReference(type = whp_sitesFinder.class)
protected whp_sitesFinder whp_sitesFinder;
@BeanReference(type = whp_sites_boundary_modificationLocalService.class)
protected whp_sites_boundary_modificationLocalService whp_sites_boundary_modificationLocalService;
@BeanReference(type = whp_sites_boundary_modificationPersistence.class)
protected whp_sites_boundary_modificationPersistence whp_sites_boundary_modificationPersistence;
@BeanReference(type = whp_sites_budgetLocalService.class)
protected whp_sites_budgetLocalService whp_sites_budgetLocalService;
@BeanReference(type = whp_sites_budgetPersistence.class)
protected whp_sites_budgetPersistence whp_sites_budgetPersistence;
@BeanReference(type = whp_sites_componentLocalService.class)
protected whp_sites_componentLocalService whp_sites_componentLocalService;
@BeanReference(type = whp_sites_componentPersistence.class)
protected whp_sites_componentPersistence whp_sites_componentPersistence;
@BeanReference(type = whp_sites_contactsLocalService.class)
protected whp_sites_contactsLocalService whp_sites_contactsLocalService;
@BeanReference(type = whp_sites_contactsPersistence.class)
protected whp_sites_contactsPersistence whp_sites_contactsPersistence;
@BeanReference(type = whp_sites_countryLocalService.class)
protected whp_sites_countryLocalService whp_sites_countryLocalService;
@BeanReference(type = whp_sites_countryPersistence.class)
protected whp_sites_countryPersistence whp_sites_countryPersistence;
@BeanReference(type = whp_sites_dsocrLocalService.class)
protected whp_sites_dsocrLocalService whp_sites_dsocrLocalService;
@BeanReference(type = whp_sites_dsocrPersistence.class)
protected whp_sites_dsocrPersistence whp_sites_dsocrPersistence;
@BeanReference(type = whp_sites_external_documentsLocalService.class)
protected whp_sites_external_documentsLocalService whp_sites_external_documentsLocalService;
@BeanReference(type = whp_sites_external_documentsPersistence.class)
protected whp_sites_external_documentsPersistence whp_sites_external_documentsPersistence;
@BeanReference(type = whp_sites_flagship_speciesLocalService.class)
protected whp_sites_flagship_speciesLocalService whp_sites_flagship_speciesLocalService;
@BeanReference(type = whp_sites_flagship_speciesPersistence.class)
protected whp_sites_flagship_speciesPersistence whp_sites_flagship_speciesPersistence;
@BeanReference(type = whp_sites_indigenous_communitiesLocalService.class)
protected whp_sites_indigenous_communitiesLocalService whp_sites_indigenous_communitiesLocalService;
@BeanReference(type = whp_sites_indigenous_communitiesPersistence.class)
protected whp_sites_indigenous_communitiesPersistence whp_sites_indigenous_communitiesPersistence;
@BeanReference(type = whp_sites_inscription_criteriaLocalService.class)
protected whp_sites_inscription_criteriaLocalService whp_sites_inscription_criteriaLocalService;
@BeanReference(type = whp_sites_inscription_criteriaPersistence.class)
protected whp_sites_inscription_criteriaPersistence whp_sites_inscription_criteriaPersistence;
@BeanReference(type = whp_sites_inscription_dateLocalService.class)
protected whp_sites_inscription_dateLocalService whp_sites_inscription_dateLocalService;
@BeanReference(type = whp_sites_inscription_datePersistence.class)
protected whp_sites_inscription_datePersistence whp_sites_inscription_datePersistence;
@BeanReference(type = whp_sites_iucn_pa_categoryLocalService.class)
protected whp_sites_iucn_pa_categoryLocalService whp_sites_iucn_pa_categoryLocalService;
@BeanReference(type = whp_sites_iucn_pa_categoryPersistence.class)
protected whp_sites_iucn_pa_categoryPersistence whp_sites_iucn_pa_categoryPersistence;
@BeanReference(type = whp_sites_iucn_recommendationLocalService.class)
protected whp_sites_iucn_recommendationLocalService whp_sites_iucn_recommendationLocalService;
@BeanReference(type = whp_sites_iucn_recommendationService.class)
protected whp_sites_iucn_recommendationService whp_sites_iucn_recommendationService;
@BeanReference(type = whp_sites_iucn_recommendationPersistence.class)
protected whp_sites_iucn_recommendationPersistence whp_sites_iucn_recommendationPersistence;
@BeanReference(type = whp_sites_meeLocalService.class)
protected whp_sites_meeLocalService whp_sites_meeLocalService;
@BeanReference(type = whp_sites_meePersistence.class)
protected whp_sites_meePersistence whp_sites_meePersistence;
@BeanReference(type = whp_sites_mgmt_plan_stateLocalService.class)
protected whp_sites_mgmt_plan_stateLocalService whp_sites_mgmt_plan_stateLocalService;
@BeanReference(type = whp_sites_mgmt_plan_statePersistence.class)
protected whp_sites_mgmt_plan_statePersistence whp_sites_mgmt_plan_statePersistence;
@BeanReference(type = whp_sites_missionLocalService.class)
protected whp_sites_missionLocalService whp_sites_missionLocalService;
@BeanReference(type = whp_sites_missionPersistence.class)
protected whp_sites_missionPersistence whp_sites_missionPersistence;
@BeanReference(type = whp_sites_other_designationsLocalService.class)
protected whp_sites_other_designationsLocalService whp_sites_other_designationsLocalService;
@BeanReference(type = whp_sites_other_designationsPersistence.class)
protected whp_sites_other_designationsPersistence whp_sites_other_designationsPersistence;
@BeanReference(type = whp_sites_soc_reportsLocalService.class)
protected whp_sites_soc_reportsLocalService whp_sites_soc_reportsLocalService;
@BeanReference(type = whp_sites_soc_reportsPersistence.class)
protected whp_sites_soc_reportsPersistence whp_sites_soc_reportsPersistence;
@BeanReference(type = whp_sites_soouvLocalService.class)
protected whp_sites_soouvLocalService whp_sites_soouvLocalService;
@BeanReference(type = whp_sites_soouvPersistence.class)
protected whp_sites_soouvPersistence whp_sites_soouvPersistence;
@BeanReference(type = whp_sites_visitorsLocalService.class)
protected whp_sites_visitorsLocalService whp_sites_visitorsLocalService;
@BeanReference(type = whp_sites_visitorsPersistence.class)
protected whp_sites_visitorsPersistence whp_sites_visitorsPersistence;
@BeanReference(type = CounterLocalService.class)
protected CounterLocalService counterLocalService;
@BeanReference(type = ResourceLocalService.class)
protected ResourceLocalService resourceLocalService;
@BeanReference(type = ResourceService.class)
protected ResourceService resourceService;
@BeanReference(type = ResourcePersistence.class)
protected ResourcePersistence resourcePersistence;
@BeanReference(type = UserLocalService.class)
protected UserLocalService userLocalService;
@BeanReference(type = UserService.class)
protected UserService userService;
@BeanReference(type = UserPersistence.class)
protected UserPersistence userPersistence;
private String _beanIdentifier;
private contact_categoryLocalServiceClpInvoker _clpInvoker = new contact_categoryLocalServiceClpInvoker();
} | gpl-2.0 |
marian37/Autoskola | src/main/java/sk/upjs/ics/paz1c/autoskola/BeanFactory.java | 3473 | package sk.upjs.ics.paz1c.autoskola;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import sk.upjs.ics.paz1c.dao.*;
import sk.upjs.ics.paz1c.databazoveDao.*;
public enum BeanFactory {
INSTANCE;
public static final int PRVY_ROK = 2014;
public static final int PRVY_ROK_NARODENIA = 1900;
private StudentiDao studentiDao;
private VozidlaDao vozidlaDao;
private InstruktoriDao instruktoriDao;
private JazdyDao jazdyDao;
private SkuskyDao skuskyDao;
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
public StudentiDao getStudentiDao() {
if (studentiDao == null) {
studentiDao = new DatabazoveStudentiDao(jdbcTemplate());
}
return this.studentiDao;
}
public VozidlaDao getVozidlaDao() {
if (vozidlaDao == null) {
vozidlaDao = new DatabazoveVozidlaDao(jdbcTemplate());
}
return this.vozidlaDao;
}
public InstruktoriDao getInstruktoriDao() {
if (instruktoriDao == null) {
instruktoriDao = new DatabazoveInstruktoriDao(jdbcTemplate());
}
return this.instruktoriDao;
}
public JazdyDao getJazdyDao() {
if (jazdyDao == null) {
jazdyDao = new DatabazoveJazdyDao(jdbcTemplate());
}
return this.jazdyDao;
}
public SkuskyDao getSkuskyDao() {
if (skuskyDao == null) {
skuskyDao = new DatabazoveSkuskyDao(jdbcTemplate());
}
return this.skuskyDao;
}
public JdbcTemplate jdbcTemplate() {
if (this.jdbcTemplate == null) {
this.jdbcTemplate = new JdbcTemplate(dataSource());
}
return this.jdbcTemplate;
}
private DataSource dataSource() {
if (this.dataSource == null) {
MysqlDataSource dataSource = new MysqlDataSource();
Properties properties = getProperties();
if ("test".equals(properties.get("rezim"))) {
dataSource.setUrl("jdbc:mysql://db4free.net:3306/autoskolapaztest?zeroDateTimeBehavior=convertToNull");
dataSource.setUser("autoskolapaztest");
} else {
dataSource.setUrl("jdbc:mysql://db4free.net:3306/autoskolapaz1c?zeroDateTimeBehavior=convertToNull");
dataSource.setUser("autoskolapaz1c");
}
dataSource.setPassword(properties.getProperty("heslo"));
this.dataSource = dataSource;
}
return this.dataSource;
}
private Properties getProperties() {
try {
String propertiesFile;
if ("true".equals(System.getProperty("testovaciRezim"))) {
propertiesFile = "/autoskola-test.properties";
} else {
propertiesFile = "/autoskola.properties";
}
InputStream in = BeanFactory.class.getResourceAsStream(propertiesFile);
Properties properties = new Properties();
properties.load(in);
return properties;
} catch (IOException e) {
throw new IllegalStateException("Nenasiel sa konfiguracny subor");
}
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/fdivp_ST0_ST6.java | 2148 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.vm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fdivp_ST0_ST6 extends Executable
{
public fdivp_ST0_ST6(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(0);
double freg1 = cpu.fpu.ST(6);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg1 == 0.0) && !Double.isNaN(freg0) && !Double.isInfinite(freg0))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(0, freg0/freg1);
cpu.fpu.pop();
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
vlabatut/totalboumboum | src/org/totalboumboum/ai/v201213/adapter/data/internal/AiDataItem.java | 12342 | package org.totalboumboum.ai.v201213.adapter.data.internal;
/*
* Total Boum Boum
* Copyright 2008-2014 Vincent Labatut
*
* This file is part of Total Boum Boum.
*
* Total Boum Boum 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.
*
* Total Boum Boum is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Total Boum Boum. If not, see <http://www.gnu.org/licenses/>.
*
*/
import java.util.ArrayList;
import java.util.List;
import org.totalboumboum.ai.v201213.adapter.data.AiBomb;
import org.totalboumboum.ai.v201213.adapter.data.AiFire;
import org.totalboumboum.ai.v201213.adapter.data.AiHero;
import org.totalboumboum.ai.v201213.adapter.data.AiItem;
import org.totalboumboum.ai.v201213.adapter.data.AiItemType;
import org.totalboumboum.ai.v201213.adapter.data.AiSprite;
import org.totalboumboum.ai.v201213.adapter.data.AiStopType;
import org.totalboumboum.engine.content.feature.Contact;
import org.totalboumboum.engine.content.feature.Direction;
import org.totalboumboum.engine.content.feature.Orientation;
import org.totalboumboum.engine.content.feature.Role;
import org.totalboumboum.engine.content.feature.TilePosition;
import org.totalboumboum.engine.content.feature.ability.AbstractAbility;
import org.totalboumboum.engine.content.feature.ability.StateAbility;
import org.totalboumboum.engine.content.feature.ability.StateAbilityName;
import org.totalboumboum.engine.content.feature.action.Circumstance;
import org.totalboumboum.engine.content.feature.action.GeneralAction;
import org.totalboumboum.engine.content.feature.action.appear.GeneralAppear;
import org.totalboumboum.engine.content.feature.action.movelow.GeneralMoveLow;
import org.totalboumboum.engine.content.sprite.item.Item;
/**
* Reprรฉsente un item du jeu, ie un bonus ou un malus que le joueur peut ramasser.
* un item est caractรฉrisรฉ par son type, reprรฉsentant le pouvoir apportรฉ (ou enlevรฉ)
* par l'item. Ce type est reprรฉsentรฉe par une valeur de type AiItemType.
*
* @author Vincent Labatut
*
* @deprecated
* Ancienne API d'IA, ร ne plus utiliser.
*/
final class AiDataItem extends AiDataSprite<Item> implements AiItem
{ /** Id de la classe */
private static final long serialVersionUID = 1L;
/**
* Crรฉe une reprรฉsentation de l'item passรฉ en paramรจtre, et contenue dans
* la case passรฉe en paramรจtre.
*
* @param tile
* Case contenant le sprite.
* @param sprite
* Sprite ร reprรฉsenter.
*/
protected AiDataItem(AiDataTile tile, Item sprite)
{ super(tile,sprite);
initType();
initStrength();
initContagious();
updateDurations();
updateCollisions();
}
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
protected void update(AiDataTile tile, long elapsedTime)
{ super.update(tile,elapsedTime);
updateDurations();
updateCollisions();
}
/////////////////////////////////////////////////////////////////
// TYPE /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Type d'item reprรฉsentรฉ */
private AiItemType type;
@Override
public AiItemType getType()
{ return type;
}
/**
* Initialise le type de l'item reprรฉsentรฉ.
*/
private void initType()
{ Item item = getSprite();
type = AiItemType.makeItemType(item.getItemName());
}
/////////////////////////////////////////////////////////////////
// STRENGTH /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Force de l'item */
private double strength;
/**
* Initialise la force de cet item.
*/
private void initStrength()
{ if(type==AiItemType.ANTI_BOMB || type==AiItemType.EXTRA_BOMB || type==AiItemType.GOLDEN_BOMB || type==AiItemType.NO_BOMB)
{ StateAbility ability = sprite.getCurrentItemAbility(StateAbilityName.HERO_BOMB_NUMBER);
strength = ability.getStrength();
}
else if(type==AiItemType.ANTI_FLAME || type==AiItemType.EXTRA_FLAME || type==AiItemType.GOLDEN_FLAME || type==AiItemType.NO_FLAME)
{ StateAbility ability = sprite.getCurrentItemAbility(StateAbilityName.HERO_BOMB_RANGE);
strength = ability.getStrength();
}
else if(type==AiItemType.ANTI_SPEED || type==AiItemType.EXTRA_SPEED || type==AiItemType.GOLDEN_SPEED || type==AiItemType.NO_SPEED)
{ StateAbility ability = sprite.getCurrentItemAbility(StateAbilityName.HERO_WALK_SPEED_MODULATION);
strength = ability.getStrength();
}
else
strength = 0;
}
@Override
public double getStrength()
{ return strength;
}
/////////////////////////////////////////////////////////////////
// COLLISIONS /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Indique si ce bloc laisse passer les joueurs */
private AiStopType stopBombs;
/** Indique si ce bloc laisse passer le feu */
private AiStopType stopFires;
@Override
public AiStopType hasStopFires()
{ return stopFires;
}
@Override
public AiStopType hasStopBombs()
{ return stopBombs;
}
/**
* Met jour les diffรฉrentes caractรฉristiques de ce bloc
* concernant la gestion des collisions avec les autres sprites.
*/
private void updateCollisions()
{ Item sprite = getSprite();
// bloque les bombes
{ GeneralAction generalAction = new GeneralMoveLow();
generalAction.addActor(Role.BOMB);
generalAction.addDirection(Direction.RIGHT);
Circumstance actorCircumstance = new Circumstance();
actorCircumstance.addContact(Contact.COLLISION);
actorCircumstance.addOrientation(Orientation.FACE);
actorCircumstance.addTilePosition(TilePosition.NEIGHBOR);
Circumstance targetCircumstance = new Circumstance();
List<AbstractAbility> actorProperties = new ArrayList<AbstractAbility>();
List<AbstractAbility> targetProperties = new ArrayList<AbstractAbility>();
boolean temp = sprite.isThirdPreventing(generalAction,actorProperties,targetProperties,actorCircumstance,targetCircumstance);
if(temp)
{ StateAbility ability = new StateAbility(StateAbilityName.SPRITE_TRAVERSE_ITEM);
actorProperties.add(ability);
temp = sprite.isThirdPreventing(generalAction,actorProperties,targetProperties,actorCircumstance,targetCircumstance);
if(temp)
stopBombs = AiStopType.STRONG_STOP;
else
stopBombs = AiStopType.WEAK_STOP;
}
else
stopBombs = AiStopType.NO_STOP;
}
// bloque le feu
{ GeneralAction generalAction = new GeneralAppear();
generalAction.addActor(Role.FIRE);
generalAction.addDirection(Direction.NONE);
Circumstance actorCircumstance = new Circumstance();
actorCircumstance.addContact(Contact.INTERSECTION);
actorCircumstance.addOrientation(Orientation.NEUTRAL);
actorCircumstance.addTilePosition(TilePosition.SAME);
Circumstance targetCircumstance = new Circumstance();
List<AbstractAbility> actorProperties = new ArrayList<AbstractAbility>();
List<AbstractAbility> targetProperties = new ArrayList<AbstractAbility>();
boolean temp = sprite.isThirdPreventing(generalAction,actorProperties,targetProperties,actorCircumstance,targetCircumstance);
if(temp)
{ StateAbility ability = new StateAbility(StateAbilityName.SPRITE_TRAVERSE_ITEM);
actorProperties.add(ability);
temp = sprite.isThirdPreventing(generalAction,actorProperties,targetProperties,actorCircumstance,targetCircumstance);
if(temp)
stopFires = AiStopType.STRONG_STOP;
else
stopFires = AiStopType.WEAK_STOP;
}
else
stopFires = AiStopType.NO_STOP;
}
}
@Override
public boolean isCrossableBy(AiSprite sprite)
{ // par dรฉfaut, on bloque
boolean result = false;
// si le sprite considรฉrรฉ est un personnage
if(sprite instanceof AiHero)
{ result = true;
}
// si le sprite considรฉrรฉ est un feu
else if(sprite instanceof AiFire)
{ AiFire fire = (AiFire) sprite;
if(stopFires==AiStopType.NO_STOP)
result = true;
else if(stopFires==AiStopType.WEAK_STOP)
result = fire.hasThroughItems();
else if(stopFires==AiStopType.STRONG_STOP)
result = false;
}
// si le sprite considรฉrรฉ est une bombe
else if(sprite instanceof AiBomb)
{ AiBomb bomb = (AiBomb) sprite;
if(stopBombs==AiStopType.NO_STOP)
result = true;
else if(stopBombs==AiStopType.WEAK_STOP)
result = bomb.hasThroughItems();
else if(stopBombs==AiStopType.STRONG_STOP)
result = false;
}
return result;
}
/////////////////////////////////////////////////////////////////
// CONTAGION /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Indique si cet item a un effet contagieux */
private boolean contagious = false;
/**
* Initialise l'indicateur de contagion.
*/
private void initContagious()
{ Item item = getSprite();
StateAbility ability = item.getAbility(StateAbilityName.ITEM_CONTAGION_MODE);
float mode = ability.getStrength();
contagious = mode!=StateAbilityName.ITEM_CONTAGION_NONE;
}
@Override
public boolean isContagious()
{ return contagious;
}
/////////////////////////////////////////////////////////////////
// DURATION /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Indique si cet item a un effet ร durรฉe limitรฉe */
private boolean limitedDuration;
/** Durรฉe de l'effet de cet item( s'il a une durรฉe limitรฉe) */
private long normalDuration;
/** Durรฉe รฉcoulรฉe depuis que cet item a commencรฉ ร faire son effet */
private long elapsedTime;
/**
* Initialise les champs relatifs aux durรฉes de l'effet
* de cet item.
*/
private void updateDurations()
{ Item item = getSprite();
// we suppose the temporary item makes the player blink
StateAbility ability = item.getOriginalItemAbility(StateAbilityName.SPRITE_TWINKLE_COLOR);
if(ability.isActive())
{ normalDuration = (long)ability.getTime();
limitedDuration = normalDuration>-1;
ability = item.getCurrentItemAbility(StateAbilityName.SPRITE_TWINKLE_COLOR);
long remainingTime = (long)ability.getTime();
elapsedTime = normalDuration - remainingTime;
//if(item.getName().equals("No bomb"))
// System.out.println("normalDuration="+normalDuration+" limitedDuration="+limitedDuration+" elapsedTime="+elapsedTime);
}
else
{ normalDuration = -1;
limitedDuration = false;
elapsedTime = -1;
}
}
@Override
public boolean hasLimitedDuration()
{ return limitedDuration;
}
@Override
public long getNormalDuration()
{ return normalDuration;
}
@Override
public long getElapsedTime()
{ return elapsedTime;
}
/////////////////////////////////////////////////////////////////
// TEXT /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
public String toString()
{ StringBuffer result = new StringBuffer();
result.append("Item: [");
result.append(super.toString());
result.append(" - type: "+type);
result.append(" - contagious: "+contagious);
result.append(" - limited: "+limitedDuration);
result.append(" ("+elapsedTime+"/"+normalDuration+")");
result.append(" ]");
return result.toString();
}
/////////////////////////////////////////////////////////////////
// FINISH /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
protected void finish()
{ super.finish();
}
}
| gpl-2.0 |
titobrasolin/dataworkshop | src/dataWorkshop/gui/data/structure/atomic/RepeatLengthPane.java | 4206 | package dataWorkshop.gui.data.structure.atomic;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import dataWorkshop.DataWorkshop;
import dataWorkshop.LocaleStrings;
import dataWorkshop.gui.ComboPane;
import dataWorkshop.number.IntegerFormatFactory;
import dataWorkshop.data.structure.DataFieldDefinition;
import dataWorkshop.data.structure.atomic.LengthDefinition;
import dataWorkshop.data.structure.atomic.PointerLengthDefinition;
import dataWorkshop.data.structure.atomic.StaticLengthDefinition;
/**
* <p>
* DataWorkshop - a binary data editor
* <br>
* Copyright (C) 2000, 2004 Martin Pape (martin.pape@gmx.de)
* <br>
* <br>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* <br>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <br>
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* </p>
*/
public class RepeatLengthPane extends JPanel implements ActionListener, LocaleStrings
{
final static String STATIC_TYPE = "Static";
final static String POINTER_TYPE = "Pointer";
ComboPane typeBox;
JPanel lengthPane;
StaticLengthPane staticLengthPane;
PointerLengthPane pointerLengthPane;
DataFieldDefinition[] possibleFields = new DataFieldDefinition[0];
/******************************************************************************
* Constructors
*/
public RepeatLengthPane(String label)
{
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
IntegerFormatFactory integerFormat = DataWorkshop.getInstance().getIntegerFormatFactory();
staticLengthPane = new StaticLengthPane(integerFormat.getUnsignedCount(), label);
pointerLengthPane = new PointerLengthPane(integerFormat.getSignedCount(), label);
typeBox = new ComboPane(new String[] {STATIC_TYPE, POINTER_TYPE });
typeBox.setSelectedItem(STATIC_TYPE);
typeBox.setMaximumSize(new Dimension(10000, (int) typeBox.getMinimumSize().getHeight()));
//typeBox.setMaximumSize(typeBox.getMinimumSize());
typeBox.addActionListener(this);
lengthPane = staticLengthPane;
add(typeBox);
add(Box.createRigidArea(new Dimension(0, 6)));
add(lengthPane);
}
/******************************************************************************
* ActionListener
*/
public void actionPerformed(ActionEvent e)
{
remove(lengthPane);
String type = (String) typeBox.getSelectedItem();
if (type == STATIC_TYPE)
{
lengthPane = staticLengthPane;
}
else if (type == POINTER_TYPE)
{
lengthPane = pointerLengthPane;
pointerLengthPane.setPointerLength(new PointerLengthDefinition(), possibleFields);
}
add(lengthPane);
revalidate();
}
/******************************************************************************
* Public Methods
*/
public LengthDefinition getLength()
{
String type = (String) typeBox.getSelectedItem();
if (type == STATIC_TYPE)
{
return staticLengthPane.getStaticLength();
}
else if (type == POINTER_TYPE)
{
return pointerLengthPane.getPointerLength();
}
else
{
throw new RuntimeException("There is no case defined for " + type);
}
}
public void setLength(LengthDefinition length, DataFieldDefinition[] possibleFields)
{
this.possibleFields = possibleFields;
if (length instanceof StaticLengthDefinition)
{
typeBox.setSelectedItem(STATIC_TYPE);
staticLengthPane.setStaticLength((StaticLengthDefinition) length);
}
else if (length instanceof PointerLengthDefinition)
{
typeBox.setSelectedItem(POINTER_TYPE);
pointerLengthPane.setPointerLength((PointerLengthDefinition) length, possibleFields);
}
}
} | gpl-2.0 |
mcdjw/sip-servlets | talkbac/src/oracle/communications/talkbac/CallFlow5.java | 14090 | /*
* Ringback Tone during Blind Transfer
* w/DTMF & Keep Alive
*
* A Controller B
* |(1) INVITE w/SDP | |
* |<---------------------| |
* |(2) 200 OK | |
* |--------------------->| |
* |(3) ACK | |
* |<---------------------| |
* | (4) 250ms delay |
* |(5) REFER | |
* |<---------------------| |
* |(6) 202 Accepted | |
* |--------------------->| |
* |(7) NOTIFY | |
* |--------------------->| |
* |(8) 200 OK | |
* |<---------------------| |
* |(9) BYE | |
* |<---------------------| |
* |(10) 200 OK | |
* |--------------------->| |
* |(11) INVITE w/SDP | |
* |--------------------->| |
* | |(12) INVITE w/o SDP |
* | |--------------------->|
* | |(13a) 180 Ringing |
* | |<---------------------|
* |(14a) 180 Ringing | |
* |<---------------------| |
* | |(13b) 200 OK |
* | |<---------------------|
* |(13b) 200 OK | |
* |<---------------------| |
* |(14) ACK | |
* |--------------------->| |
* | |(15) ACK |
* | |--------------------->|
* |.............................................|
* ReINVITE
*
*/
package oracle.communications.talkbac;
import javax.servlet.sip.Address;
import javax.servlet.sip.ServletTimer;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
public class CallFlow5 extends CallFlowHandler {
private static final long serialVersionUID = 1L;
private Address origin;
private Address destination;
// private String destinationUser;
// private String originUser;
// String callId;
// String toTag;
// String fromTag;
SipServletRequest destinationRequest;
SipServletResponse destinationResponse;
SipServletRequest originRequest;
SipServletResponse originResponse;
SipServletRequest originPrack;
CallFlow5(Address origin, Address destination) {
this.origin = origin;
this.destination = destination;
}
CallFlow5(CallFlow5 that) {
this.origin = that.origin;
this.destination = that.destination;
this.destinationRequest = that.destinationRequest;
this.destinationResponse = that.destinationResponse;
this.originRequest = that.originRequest;
this.originResponse = that.originResponse;
}
@Override
public void processEvent(SipApplicationSession appSession, MessageUtility msgUtility, SipServletRequest request, SipServletResponse response,
ServletTimer timer) throws Exception {
TalkBACMessage msg;
int status = (null != response) ? response.getStatus() : 0;
// Deal with unexpected requests
if (request != null) {
switch (TalkBACSipServlet.SipMethod.valueOf(request.getMethod())) {
case CANCEL:
case OPTIONS:
case REGISTER:
case SUBSCRIBE:
case PUBLISH:
case INFO:
case REFER:
case UPDATE:
SipServletResponse updateResponse = request.createResponse(200);
updateResponse.send();
this.printOutboundMessage(updateResponse);
return;
default:
// do nothing
}
}
switch (state) {
case 1: // send INVITE
appSession.setAttribute(TalkBACSipServlet.ORIGIN_ADDRESS, origin);
appSession.setAttribute(TalkBACSipServlet.DESTINATION_ADDRESS, destination);
msg = new TalkBACMessage(appSession, "call_created");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
this.printOutboundMessage(msgUtility.send(msg));
originRequest = TalkBACSipServlet.factory.createRequest(appSession, "INVITE", destination, origin);
destinationRequest = TalkBACSipServlet.factory.createRequest(appSession, "INVITE", origin, destination);
// Save this info in case we need to terminate
destinationRequest.getSession().setAttribute(REQUEST_DIRECTION, "OUTBOUND");
destinationRequest.getSession().setAttribute(INITIAL_INVITE_REQUEST, destinationRequest);
originRequest.getSession().setAttribute(REQUEST_DIRECTION, "OUTBOUND");
originRequest.getSession().setAttribute(INITIAL_INVITE_REQUEST, originRequest);
destinationRequest.getSession().setAttribute(PEER_SESSION_ID, originRequest.getSession().getId());
originRequest.getSession().setAttribute(PEER_SESSION_ID, destinationRequest.getSession().getId());
originRequest.getSession().setAttribute(INITIAL_INVITE_REQUEST, originRequest);
originRequest.setHeader("Allow", ORIGIN_ALLOW);
originRequest.setHeader("Call-Info", TalkBACSipServlet.callInfo);
originRequest.setHeader("Allow-Events", "telephone-event");
originRequest.setHeader("Supported", "100rel, timer, resource-priority, replaces");
// originRequest.setHeader("Require", "100rel");
originRequest.setContent(blackhole.getBytes(), "application/sdp");
originRequest.send();
this.printOutboundMessage(originRequest);
state = 2;
originRequest.getSession().setAttribute(CALL_STATE_HANDLER, this);
appSession.setAttribute(DESTINATION_SESSION_ID, destinationRequest.getSession().getId());
appSession.setAttribute(ORIGIN_SESSION_ID, originRequest.getSession().getId());
break;
case 2: // receive 200 OK
case 3: // send ack
if (response != null && response.getMethod().equals("INVITE")) {
String require = response.getHeader("Require");
if (status < 200 && require != null && require.equals("100rel")) {
SipServletRequest prack = response.createPrack();
prack.send();
this.printOutboundMessage(prack);
} else if (status == 200) {
// callId = response.getCallId();
// toTag = response.getTo().getParameter("tag");
// fromTag = response.getFrom().getParameter("tag");
discoverOptions(response);
originResponse = response;
SipServletRequest originAck = response.createAck();
originAck.send();
this.printOutboundMessage(originAck);
// set timer
state = 4;
ServletTimer t = TalkBACSipServlet.timer.createTimer(appSession, 250, false, this);
this.printTimer(t);
msg = new TalkBACMessage(appSession, "source_connected");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
msg.setStatus(183, "Session Progress");
this.printOutboundMessage(msgUtility.send(msg));
} else if (status >= 400) {
msg = new TalkBACMessage(appSession, "call_failed");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
msg.setStatus(response.getStatus(), response.getReasonPhrase());
this.printOutboundMessage(msgUtility.send(msg));
}
}
break;
case 4: // receive timeout
case 5: // send REFER
SipServletRequest refer = originRequest.getSession().createRequest("REFER");
String key = (String) appSession.getAttribute(KEY);
Address refer_to = TalkBACSipServlet.factory.createAddress("<sip:" + key + "@" + TalkBACSipServlet.listenAddress + ">");
refer.setAddressHeader("Refer-To", refer_to);
refer.setAddressHeader("Referred-By", destination);
refer.send();
this.printOutboundMessage(refer);
state = 6;
refer.getSession().setAttribute(CALL_STATE_HANDLER, this);
break;
case 6: // receive 202 Accepted
case 7: // receive NOTIFY
case 8: // send 200 OK
case 9: // send BYE
case 10: // receive BYE 200 OK
if (request != null && (request.getMethod().equals("NOTIFY"))) {
SipServletResponse rsp = request.createResponse(200);
rsp.send();
this.printOutboundMessage(rsp);
if (request.getContent() != null) {
String sipfrag = new String((byte[]) request.getContent());
if (sipfrag.contains("100")) {
SipServletRequest bye = request.getSession().createRequest("BYE");
bye.send();
this.printOutboundMessage(bye);
}
}
} else if (response != null && response.getStatus() == 202) {
// Prepare for that INVITE
CallStateHandler csh = new CallFlow5(this);
csh.state = 11;
appSession.setAttribute(CALL_STATE_HANDLER, csh);
appSession.setAttribute(TalkBACSipServlet.MESSAGE_UTILITY, msgUtility);
}
break;
case 11: // receive INVITE
case 12: // send INVITE
// Save this info in case we need to terminate.
request.getSession().setAttribute(REQUEST_DIRECTION, "INBOUND");
request.getSession().setAttribute(INITIAL_INVITE_REQUEST, request);
appSession.removeAttribute(CALL_STATE_HANDLER);
if (false == request.getCallId().equals(originResponse.getCallId())) {
appSession.setAttribute("IGNORE_BYE", originResponse.getCallId());
}
originRequest = request;
// originRequest.getSession().setInvalidateWhenReady(false);
// destinationRequest.getSession().setInvalidateWhenReady(false);
appSession.setAttribute(ORIGIN_SESSION_ID, request.getSession().getId());
request.getSession().setAttribute(PEER_SESSION_ID, destinationRequest.getSession().getId());
destinationRequest.getSession().setAttribute(PEER_SESSION_ID, request.getSession().getId());
destinationRequest.setHeader("Allow", DESTINATION_ALLOW);
destinationRequest.setHeader("Call-Info", TalkBACSipServlet.callInfo);
copyHeadersAndContent(request, destinationRequest);
destinationRequest.send();
printOutboundMessage(destinationRequest);
state = 13;
destinationRequest.getSession().setAttribute(CALL_STATE_HANDLER, this);
break;
case 13: // receive 180 / 183 / 200
case 14: // send 180 / 183 / 200
if (request != null && request.getMethod().equals("PRACK")) {
originPrack = request;
// SipServletRequest prack = destinationRequest.getSession().createRequest("PRACK");
SipServletRequest prack = destinationResponse.createPrack();
copyHeadersAndContent(request, prack);
prack.send();
this.printOutboundMessage(prack);
prack.getSession().setAttribute(CALL_STATE_HANDLER, this);
return;
}
if (response != null && response.getMethod().equals("PRACK")) {
SipServletResponse prackResponse = originPrack.createResponse(response.getStatus());
prackResponse.send();
this.printOutboundMessage(prackResponse);
return;
}
if (response != null) {
destinationResponse = response;
if (status < 400) {
originResponse = originRequest.createResponse(response.getStatus());
copyHeadersAndContent(response, originResponse);
if (status < 200) {
if (response.getHeader("Require") != null && response.getHeader("Require").equals("100rel")) {
originResponse.sendReliably();
} else {
originResponse.send();
}
originResponse.getSession().setAttribute(CALL_STATE_HANDLER, this);
} else {
originResponse.send();
state = 15;
originResponse.getSession().setAttribute(CALL_STATE_HANDLER, this);
}
this.printOutboundMessage(originResponse);
if (status == 200) {
msg = new TalkBACMessage(appSession, "destination_connected");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
msg.setStatus(response.getStatus(), response.getReasonPhrase());
this.printOutboundMessage(msgUtility.send(msg));
}
} else {
response.getSession().removeAttribute(CALL_STATE_HANDLER);
originResponse.getSession().removeAttribute(CALL_STATE_HANDLER);
msg = new TalkBACMessage(appSession, "call_failed");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
msg.setStatus(response.getStatus(), response.getReasonPhrase());
this.printOutboundMessage(msgUtility.send(msg));
TerminateCall terminate = new TerminateCall();
terminate.processEvent(appSession, msgUtility, request, response, timer);
}
}
break;
case 15: // receive ACK
case 16: // send ACK
if (request != null && request.getMethod().equals("ACK")) {
SipServletRequest destAck = destinationResponse.createAck();
copyHeadersAndContent(request, destAck);
destAck.send();
this.printOutboundMessage(destAck);
// Launch KPML Subscribe
if (this.kpml_supported) {
KpmlRelay kpmlRelay = new KpmlRelay(3600);
kpmlRelay.delayedSubscribe(appSession, 2000);
}
// Launch Keep Alive Timer
if (this.update_supported) {
UpdateKeepAlive ka = new UpdateKeepAlive(60 * 1000);
ka.startTimer(appSession);
}
msg = new TalkBACMessage(appSession, "call_connected");
msg.setParameter("origin", origin.getURI().toString());
msg.setParameter("destination", destination.getURI().toString());
this.printOutboundMessage(msgUtility.send(msg));
destAck.getSession().removeAttribute(CALL_STATE_HANDLER);
request.getSession().removeAttribute(CALL_STATE_HANDLER);
}
break;
}
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.adempiere.adempiere/base/src/test/java/org/adempiere/test/AdempiereTestHelper.java | 4980 | package org.adempiere.test;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.Properties;
import org.adempiere.ad.persistence.cache.AbstractModelListCacheLocal;
import org.adempiere.ad.wrapper.POJOLookupMap;
import org.adempiere.ad.wrapper.POJOWrapper;
import org.adempiere.context.SwingContextProvider;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.model.IContextAware;
import org.adempiere.model.InterfaceWrapperHelper;
import org.adempiere.model.PlainContextAware;
import org.adempiere.util.Check;
import org.adempiere.util.Services;
import org.adempiere.util.UnitTestServiceNamePolicy;
import org.adempiere.util.proxy.Cached;
import org.adempiere.util.proxy.impl.JavaAssistInterceptor;
import org.adempiere.util.reflect.TestingClassInstanceProvider;
import org.adempiere.util.time.SystemTime;
import org.compiere.Adempiere;
import org.compiere.model.I_AD_Client;
import org.compiere.util.CacheMgt;
import org.compiere.util.Env;
import org.compiere.util.Ini;
import org.compiere.util.Util;
import ch.qos.logback.classic.Level;
import de.metas.adempiere.form.IClientUI;
import de.metas.adempiere.util.cache.CacheInterceptor;
import de.metas.i18n.Language;
import de.metas.logging.LogManager;
/**
* Helper to be used in order to setup ANY test which depends on ADempiere.
*
* @author tsa
*
*/
public class AdempiereTestHelper
{
private static final AdempiereTestHelper instance = new AdempiereTestHelper();
public static final String AD_LANGUAGE = "de_DE";
public static AdempiereTestHelper get()
{
return instance;
}
private boolean staticInitialized = false;
public void staticInit()
{
if (staticInitialized)
{
return;
}
Adempiere.enableUnitTestMode();
Check.setDefaultExClass(AdempiereException.class);
Util.setClassInstanceProvider(TestingClassInstanceProvider.instance);
//
// Configure services; note the this is not the place to register individual services, see init() for that.
Services.setAutodetectServices(true);
Services.setServiceNameAutoDetectPolicy(new UnitTestServiceNamePolicy()); // 04113
//
// Make sure cache is empty
CacheMgt.get().clear();
staticInitialized = true;
}
public void init()
{
// Make sure context is clear before starting a new test
final Properties ctx = setupContext();
// By default we are running in client mode
Ini.setClient(true);
// Make sure staticInit was called
staticInit();
// Make sure database is clean
POJOLookupMap.resetAll();
//
// POJOWrapper defaults
POJOWrapper.setAllowRefreshingChangedModels(false);
POJOWrapper.setDefaultStrictValues(POJOWrapper.DEFAULT_StrictValues);
//
// Setup services
{
// Make sure we don't have custom registered services
// Each test shall init it's services if it wants
Services.clear();
//
// Register our cache interceptor
// NOTE: in normal run, it is registered from org.compiere.Adempiere.startup(RunMode)
Services.getInterceptor().registerInterceptor(Cached.class, new CacheInterceptor()); // task 06952
JavaAssistInterceptor.FAIL_ON_ERROR = true;
Services.registerService(IClientUI.class, new TestClientUI());
}
//
// Base Language
Language.setBaseLanguage(() -> AD_LANGUAGE);
Env.setContext(ctx, Env.CTXNAME_AD_Language, AD_LANGUAGE);
//
// Reset System Time
SystemTime.setTimeSource(null);
//
// Caching
AbstractModelListCacheLocal.DEBUG = true;
//
// Logging
LogManager.setLevel(Level.WARN);
}
private static Properties setupContext()
{
Env.setContextProvider(new SwingContextProvider());
final Properties ctx = Env.getCtx();
ctx.clear();
return ctx;
}
public void setupContext_AD_Client_IfNotSet()
{
final Properties ctx = Env.getCtx();
// Do nothing if already set
if (Env.getAD_Client_ID(ctx) > 0)
{
return;
}
final IContextAware contextProvider = new PlainContextAware(ctx);
final I_AD_Client adClient = InterfaceWrapperHelper.newInstance(I_AD_Client.class, contextProvider);
adClient.setValue("Test");
adClient.setName("Test");
adClient.setAD_Language(AD_LANGUAGE);
InterfaceWrapperHelper.save(adClient);
Env.setContext(ctx, Env.CTXNAME_AD_Client_ID, adClient.getAD_Client_ID());
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.commission.ait/src/main/java/test/integration/commission/bPartner/MBPartnerTestEventListener.java | 4953 | package test.integration.commission.bPartner;
/*
* #%L
* de.metas.commission.ait
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import java.util.List;
import org.adempiere.model.InterfaceWrapperHelper;
import org.adempiere.util.Services;
import org.compiere.model.MSysConfig;
import org.compiere.model.Query;
import org.compiere.util.Env;
import de.metas.adempiere.ait.event.EventType;
import de.metas.adempiere.ait.event.TestEvent;
import de.metas.adempiere.ait.test.annotation.ITEventListener;
import de.metas.commission.interfaces.I_C_BPartner;
import de.metas.commission.model.I_C_Sponsor;
import de.metas.commission.model.I_C_Sponsor_SalesRep;
import de.metas.commission.modelvalidator.SponsorValidator;
import de.metas.commission.service.ISponsorDAO;
import test.integration.swat.bPartner.BPartnerTestDriver;
public class MBPartnerTestEventListener
{
private List<I_C_Sponsor_SalesRep> parentSponsorSSRs;
private I_C_Sponsor parentSponsor;
/**
* Check the default parent sponsor and make sure that it has at least two parent link SSRs (i.e. two commission
* systems).
*
* Otherwise there is no point in testing. Also loads those SSRs to chack agains the parent link SSRs of the new
* BPartner, after it has been created
*
* @param evt
*/
@ITEventListener(
driver = BPartnerTestDriver.class,
eventTypes = EventType.BPARTNER_CREATE_BEFORE)
public void onTestBegins(final TestEvent evt)
{
assertEquals(EventType.BPARTNER_CREATE_BEFORE, evt.getEventType());
final String parentSponsorNo =
MSysConfig.getValue(SponsorValidator.SYSCONFIG_DEFAULT_PARENT_SPONSOR_NO, "",
Env.getAD_Client_ID(Env.getCtx()),
Env.getAD_Org_ID(Env.getCtx()));
assertNotNull(SponsorValidator.SYSCONFIG_DEFAULT_PARENT_SPONSOR_NO + " is not defined in AD_SysConfig", parentSponsorNo);
parentSponsor = new Query(Env.getCtx(), I_C_Sponsor.Table_Name, I_C_Sponsor.COLUMNNAME_SponsorNo + "=?", null)
.setParameters(parentSponsorNo)
.setApplyAccessFilter(true)
.firstOnly(I_C_Sponsor.class);
assertNotNull("Default parent sponsor '" + parentSponsorNo + "' can'T be loaded", parentSponsor);
parentSponsorSSRs = Services.get(ISponsorDAO.class).retrieveParentLinksSSRs(parentSponsor);
assertTrue(parentSponsor + " has less than two parent links", parentSponsorSSRs.size() > 1);
}
@ITEventListener(
driver = BPartnerTestDriver.class,
eventTypes = EventType.BPARTNER_CREATE_AFTER)
public void onBPartnerCreated(final TestEvent evt)
{
assertEquals(EventType.BPARTNER_CREATE_AFTER, evt.getEventType());
final I_C_BPartner newBPartner = InterfaceWrapperHelper.create(evt.getObj(), I_C_BPartner.class);
// verify that 'newBPartner' has been created with the expected default C_Sponsor_Parent_ID
assertEquals(newBPartner + " has the wrong C_Sponsor_Parent_ID",
parentSponsor.getC_Sponsor_ID(), newBPartner.getC_Sponsor_Parent_ID());
final I_C_Sponsor newSponsor = Services.get(ISponsorDAO.class).retrieveForBPartner(newBPartner, true);
assertNotNull(newBPartner + " has no sponsor", newSponsor);
//
// Here come the actual checks for 02171
final List<I_C_Sponsor_SalesRep> newSponsorSSRs = Services.get(ISponsorDAO.class).retrieveParentLinksSSRs(newSponsor);
assertEquals(newSponsor + " has wthe wrong number of parent links",
parentSponsorSSRs.size(), newSponsorSSRs.size());
// Note: we also expect the order within 'parentSponsorSSRs' and 'newSponsorSSRs' to match
for (int i = 0; i < newSponsorSSRs.size(); i++)
{
final I_C_Sponsor_SalesRep newSSR = newSponsorSSRs.get(i);
final I_C_Sponsor_SalesRep parentSSR = parentSponsorSSRs.get(i);
assertEquals(newSSR + " has a wrong C_Sponsor_Parent_ID",
parentSponsor.getC_Sponsor_ID(), newSSR.getC_Sponsor_Parent_ID());
assertEquals(newSSR + " has a wrong C_AdvComSystem_ID",
parentSSR.getC_AdvComSystem_ID(), newSSR.getC_AdvComSystem_ID());
assertEquals(newSSR + " has a wrong ValidFrom",
parentSSR.getValidFrom(), newSSR.getValidFrom());
assertEquals(newSSR + " has a wrong ValidTo",
parentSSR.getValidTo(), newSSR.getValidTo());
}
}
}
| gpl-2.0 |
tomdkt/DriveSales | src/main/java/br/com/drivesales/controller/IndexController.java | 5314 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.drivesales.controller;
import br.com.drivesales.domain.Company;
import br.com.drivesales.domain.MessageError;
import br.com.drivesales.dto.LocationAndTotalDTO;
import br.com.drivesales.dto.MonthTopSalles;
import br.com.drivesales.exception.LineErrorException;
import br.com.drivesales.repository.BranchRepository;
import br.com.drivesales.repository.CompanyRepository;
import br.com.drivesales.repository.SaleRepository;
import br.com.drivesales.service.ProcessStream;
import br.com.drivesales.util.DateParser;
import br.com.drivesales.util.DelimitersEnum;
import br.com.drivesales.vo.SummaryVO;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author Thomas Daniel Kaneko Teixeira(tomdkt)
*/
@Controller
public class IndexController {
private final Logger logger = LoggerFactory.getLogger(IndexController.class);
private final ProcessStream<Company> processStream;
private final CompanyRepository companyRepository;
private final BranchRepository branchRepository;
private final SaleRepository saleRepository;
@Autowired
public IndexController(ProcessStream<Company> processStream, CompanyRepository companyRepository, BranchRepository branchRepository, SaleRepository saleRepository) {
this.processStream = processStream;
this.companyRepository = companyRepository;
this.branchRepository = branchRepository;
this.saleRepository = saleRepository;
}
@RequestMapping("/")
String index() {
return "index";
}
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public @ResponseBody
ModelAndView handleFileUpload(@RequestParam("tempFile") MultipartFile file) {
if (!file.isEmpty()) {
String name = file.getName();
try {
this.companyRepository.deleteAll(); //clean database, because we dont have logic business set
InputStreamReader in = new InputStreamReader(file.getInputStream(), "latin1");
Company company = this.processStream.parseToEntity(in, DelimitersEnum.TAB);
this.companyRepository.save(company);
SummaryVO summary = this.getSummaryVO();
ModelAndView mav = new ModelAndView("summary");
mav.addObject("summary", summary);
return mav;
} catch (LineErrorException e) {
logger.error("LineErrorException", e);
ModelAndView mav = new ModelAndView("messageError");
MessageError msg = new MessageError("Ocorreu um erro ao processar: line: \"" + e.getLineError() + "\" | lineNumber:" + e.getLineNumber() + " | mensagem de erro => " + e.getMessage());
mav.addObject("messageError", msg);
return mav;
}catch (IOException | InstantiationException | IllegalAccessException e) {
logger.error("Error in handleFileUpload", e);
ModelAndView mav = new ModelAndView("messageError");
MessageError msg = new MessageError("You failed to upload " + name + " => " + e.getMessage());
mav.addObject("messageError", msg);
return mav;
}
}
ModelAndView mav = new ModelAndView("messageError");
MessageError msg = new MessageError("The selected file was empty and could not be uploaded.");
mav.addObject("messageError", msg);
return mav;
}
private SummaryVO getSummaryVO(){
SummaryVO summary = new SummaryVO();
List<LocationAndTotalDTO> branchs = this.branchRepository.getMostSold();
if(branchs != null && !branchs.isEmpty()){
summary.setBranchMostSold(branchs.iterator().next());
}
List<MonthTopSalles> monthTopSalles = this.saleRepository.getMonthWithMoreSalesDTO();
if(monthTopSalles != null && !monthTopSalles.isEmpty()){
summary.setMonthTopSalles(DateParser.getMonthNameFromBrazil(monthTopSalles.iterator().next().getInicialDate()));
}
//TODO improve query
List<LocationAndTotalDTO> branchsMoreIncrease = this.branchRepository.getBranchMoreIncrease();
if(branchsMoreIncrease != null && !branchsMoreIncrease.isEmpty()){
summary.setBranchMoreIncrease(branchsMoreIncrease.get(0));
summary.setBranchLessIncrease(branchsMoreIncrease.get(branchsMoreIncrease.size() - 1));
}
return summary;
}
}
| gpl-2.0 |
Ankama/harvey | src/com/ankamagames/dofus/harvey/engine/generic/sets/classes/BaseCompositeSortedGenericSet.java | 11997 | /**
*
*/
package com.ankamagames.dofus.harvey.engine.generic.sets.classes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeSet;
import com.ankamagames.dofus.harvey.engine.common.sets.classes.AbstractCompositeBoundBridge;
import com.ankamagames.dofus.harvey.engine.common.sets.classes.AbstractCompositeSortedSet;
import com.ankamagames.dofus.harvey.engine.generic.incrementors.SurroundingValuesProvider;
import com.ankamagames.dofus.harvey.generic.sets.interfaces.ICompositeSortedGenericSet;
import com.ankamagames.dofus.harvey.generic.sets.interfaces.IElementarySortedGenericSet;
import com.ankamagames.dofus.harvey.generic.sets.interfaces.IGenericBound;
import com.ankamagames.dofus.harvey.generic.sets.interfaces.ISimpleSortedGenericSet;
import com.ankamagames.dofus.harvey.generic.sets.interfaces.ISortedGenericSet;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
/**
* @author sgros
*
*/
@NonNullByDefault
public class BaseCompositeSortedGenericSet<Data, ChildType extends ISortedGenericSet<Data>>
extends AbstractCompositeSortedSet
<
IGenericBound<Data>,
ISortedGenericSet<Data>, // Set
ISimpleSortedGenericSet<Data>, // SimpleSet
IElementarySortedGenericSet<Data>, // ElementarySet
ICompositeSortedGenericSet<Data, ?>, // CompositeSet
ChildType, // ChildType
TreeSet<ChildType> // InternalChildrenCollectionType
>
implements ICompositeSortedGenericSet<Data, ChildType>
{
private static final float MAX_SAMPLE = 200f;
protected Comparator<? super Data> _comparator;
protected SurroundingValuesProvider<Data> _surroundingProvider;
CompositeSortedGenericSetBridge<Data, ChildType> _bridge;
AbstractCompositeBoundBridge<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data, ?>, ChildType, BaseCompositeSortedGenericSet<Data, ChildType>> _boundBridge;
CommonCompositeSortedGenericSetBridge<Data, IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data, ?>, ChildType, BaseCompositeSortedGenericSet<Data, ChildType>> _compositeBridge;
protected BaseCompositeSortedGenericSet(final Comparator<? super Data> comparator, final SurroundingValuesProvider<Data> surroundingProvider)
{
_bridge = new CompositeSortedGenericSetBridge<Data, ChildType>(this, comparator, surroundingProvider);
_compositeBridge = new CommonCompositeSortedGenericSetBridge<Data, IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(
this, comparator, _bridge.getSetCreationToolbox());
_boundBridge = new AbstractCompositeBoundBridge<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(this);
_comparator = comparator;
_surroundingProvider = surroundingProvider;
}
@SuppressWarnings("unchecked")
protected BaseCompositeSortedGenericSet(final ChildType element, final Comparator<? super Data> comparator, final SurroundingValuesProvider<Data> surroundingProvider)
{
_bridge = new CompositeSortedGenericSetBridge<Data, ChildType>(this, comparator, surroundingProvider, element);
_compositeBridge = new CommonCompositeSortedGenericSetBridge<Data, IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(
this, comparator, _bridge.getSetCreationToolbox());
_boundBridge = new AbstractCompositeBoundBridge<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(this);
_comparator = comparator;
_surroundingProvider = surroundingProvider;
}
protected BaseCompositeSortedGenericSet(final Collection<ChildType> collection, final Comparator<? super Data> comparator,
final SurroundingValuesProvider<Data> surroundingProvider)
{
_bridge = new CompositeSortedGenericSetBridge<Data, ChildType>(this, comparator, surroundingProvider, collection);
_compositeBridge = new CommonCompositeSortedGenericSetBridge<Data, IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(
this, comparator, _bridge.getSetCreationToolbox());
_boundBridge = new AbstractCompositeBoundBridge<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>>(this);
_comparator = comparator;
_surroundingProvider = surroundingProvider;
}
@Override
protected CompositeSortedGenericSetBridge<Data, ChildType> getBridge()
{
return _bridge;
}
@Override
protected AbstractCompositeBoundBridge<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, ICompositeSortedGenericSet<Data,?>, ChildType, BaseCompositeSortedGenericSet<Data,ChildType>> getBoundBridge()
{
return _boundBridge;
}
@Override
public ISortedGenericSet<Data> getAsSet()
{
return this;
}
@Override
public ICompositeSortedGenericSet<Data, ChildType> getAsComposite()
{
return this;
}
@Override
public @Nullable IGenericBound<Data> getLowerBound()
{
return _compositeBridge.getLowerBound();
}
@Override
public @Nullable IGenericBound<Data> getUpperBound()
{
return _compositeBridge.getUpperBound();
}
@Override
public boolean contains(@Nullable final Data value)
{
return _compositeBridge.contains(value);
}
@Override
public List<? extends ISortedGenericSet<Data>> split(final Data[] values, final boolean[] isIntervalStart)
{
return _compositeBridge.split(values, isIntervalStart);
}
@Override
public List<? extends ISortedGenericSet<Data>> split(final Data... values)
{
final boolean[] inNextInterval = new boolean[values.length];
Arrays.fill(inNextInterval, true);
return split(values, inNextInterval);
}
@Override
public ISimpleSortedGenericSet<Data> getSimpleSet()
{
return super.getSimpleSet().getAsSimpleSet();
}
class IteratorValuePair
{
Iterator<Data> iterator;
@Nullable Data value;
public IteratorValuePair(final Iterator<Data> _iterator, final @Nullable Data _value)
{
iterator = _iterator;
value = _value;
}
}
Comparator<IteratorValuePair> ascendingComparator = new Comparator<IteratorValuePair>()
{
@Override
public int compare(final @Nullable IteratorValuePair o1, final @Nullable IteratorValuePair o2)
{
if(o1 == null)
if(o2 == null)
return 0;
else
return 1;
if(o2 == null)
return -1;
return _comparator.compare(o1.value, o2.value);
}
};
Comparator<IteratorValuePair> descendingComparator = new Comparator<IteratorValuePair>()
{
@Override
public int compare(final @Nullable IteratorValuePair o1, final @Nullable IteratorValuePair o2)
{
if(o1==null)
if(o2==null)
return 0;
else
return -1;
if(o2==null)
return 1;
return _comparator.compare(o2.value, o1.value);
}
};
protected abstract class GenericSortedSetIterator
implements Iterator<Data>
{
PriorityQueue<IteratorValuePair> iteratorQueue = initializeQueue();
protected abstract PriorityQueue<IteratorValuePair> initializeQueue();
@Override
public boolean hasNext()
{
return !iteratorQueue.isEmpty();
}
@Override
public @Nullable Data next()
{
final IteratorValuePair nextItValuePair = iteratorQueue.poll();
if(nextItValuePair.iterator.hasNext())
{
final Data next = nextItValuePair.iterator.next();
final Iterator<IteratorValuePair> it = iteratorQueue.iterator();
final LinkedList<IteratorValuePair> toAdd = new LinkedList<IteratorValuePair>();
while(it.hasNext())
{
final IteratorValuePair currentIt = it.next();
if(currentIt.value != null && currentIt.value.equals(next))
it.remove();
if(currentIt.iterator.hasNext())
{
currentIt.value = currentIt.iterator.next();
toAdd.add(currentIt);
}
}
iteratorQueue.addAll(toAdd);
iteratorQueue.add(new IteratorValuePair(nextItValuePair.iterator, next));
}
return nextItValuePair.value;
}
}
@Override
public Iterator<Data> getDataIterator()
{
return new GenericSortedSetIterator()
{
@Override
protected PriorityQueue<IteratorValuePair> initializeQueue()
{
final PriorityQueue<IteratorValuePair> r = new PriorityQueue<IteratorValuePair>(Math.max(1, getChildrenCount()), ascendingComparator);
for(final ChildType child:getChildren())
{
final Iterator<Data> dataIterator = child.getDataIterator();
if(dataIterator.hasNext())
r.add(new IteratorValuePair(dataIterator, dataIterator.next()));
}
return r;
}
};
}
@Override
public Iterator<Data> getReverseDataIterator()
{
return new GenericSortedSetIterator()
{
@Override
protected PriorityQueue<IteratorValuePair> initializeQueue()
{
final PriorityQueue<IteratorValuePair> r = new PriorityQueue<IteratorValuePair>(Math.max(1, getChildrenCount()), descendingComparator);
for(final ChildType child:getChildrenDescending())
{
final Iterator<Data> dataIterator = child.getReverseDataIterator();
if(dataIterator.hasNext())
r.add(new IteratorValuePair(dataIterator, dataIterator.next()));
}
return r;
}
};
}
@Override
public List<Data> sample(final int numberOfSample)
{
if(numberOfSample<=0 || numberOfSample > size())
return sample();
final int chunk = (int) (size()/(numberOfSample-1));
final List<Data> ret = new ArrayList<Data>(numberOfSample);
final Iterator<IGenericBound<Data>> it = getBoundIterator();
IGenericBound<Data> currentLowerBound = it.next();
IGenericBound<Data> currentUpperBound = it.next();
Data next = currentLowerBound.getValue();
ret.add(next);
int currentChunckProgress = chunk;
int dist = currentUpperBound.compareTo(currentLowerBound)+1;
while(ret.size()<numberOfSample)
{
if(currentChunckProgress <= dist)
{
dist-= currentChunckProgress;
next = _surroundingProvider.getSuccessor(next, currentChunckProgress);
currentChunckProgress = chunk;
ret.add(next);
}
else
{
currentChunckProgress -= dist;
currentLowerBound = it.next();
currentUpperBound = it.next();
next = currentLowerBound.getValue();
dist = currentUpperBound.compareTo(currentLowerBound)+1;
}
}
return ret;
}
@Override
public List<Data> sample()
{
// the formula of the number of samples
// I wanted it to grow quickly for little sets and as they goes bigger and bigger the number of samples will be stabilized at MAX_SAMPLE
// I've stated from the Sigmoรฏde formula and then stretched it as I wanted. --> http://fooplot.com/plot/gn0f2ulnmz
//Math.min((1.f/(1.f+(Math.exp(-10.f/200.f)))*200.f*2.f-200.f+1.f), 200.f)
final int numberOfSample = (int) Math.min((1.f/(1.f+(Math.exp(-size()/MAX_SAMPLE)))*MAX_SAMPLE*2.f-MAX_SAMPLE+1.f), MAX_SAMPLE);
return sample(numberOfSample);
}
} | gpl-2.0 |
lsilvestre/Jogre | api/src/org/jogre/client/JogreController.java | 14839 | /*
* JOGRE (Java Online Gaming Real-time Engine) - API
* Copyright (C) 2004 Bob Marks (marksie531@yahoo.com)
* http://jogre.sourceforge.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jogre.client;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import nanoxml.XMLElement;
import org.jogre.client.awt.JogreComponent;
import org.jogre.common.JogreModel;
import org.jogre.common.Player;
import org.jogre.common.PlayerList;
import org.jogre.common.Table;
import org.jogre.common.comm.CommControllerObject;
import org.jogre.common.comm.CommControllerProperty;
import org.jogre.common.comm.CommNextPlayer;
import org.jogre.common.comm.ITransmittable;
/**
* <p>Adapter game controller class which creates empty methods for the
* MouseListener, MouseMotionListener and KeyListener event interfaces.
* This class also contains a link to the JogreModel, a connection thread to the
* server and also a JogreComponent where the mouse movements/key presses are taking
* place on.</p>
*
* <p>To use this controller a class must extend it e.g. ChessController and
* then override one of its event methods, update the correct model and send
* communication to other users. To use the controller on a JogreComponent
* a JogreComponent calls its <code>public void setController (JogreController
* controller)</code> method.</p>
*
* <p>Any of the following methods can be overwritten to do something:</p>
* <code>
* <ul>
* <li>public void mouseEntered (MouseEvent e)</li>
* <li>public void mouseExited (MouseEvent e)</li>
* <li>public void mouseClicked (MouseEvent e)</li>
* <li>public void mouseReleased (MouseEvent e)</li>
* <li>public void mousePressed (MouseEvent e)</li>
* <li>public void mouseMoved (MouseEvent e)</li>
* <li>public void mouseDragged (MouseEvent e)</li>
* <li>public void keyPressed (KeyEvent e)</li>
* <li>public void keyReleased (KeyEvent e)</li>
* <li>public void keyTyped (KeyEvent e)</li>
* </ul>
* </code>
*
* <p>This class also contains a link to the ClientConnectionThread. This
* allows access to the UserList and TableList object which allow access to what
* is happening on the server. This class also provides various useful methods
* such as returning the table number, current player, current player's seat
* number, this players seat number, etc.</p>
*
* <p>Since Alpha 0.2, the controller contains convience methods for sending
* and receving properties and XML objects easily and quickly to other players
* at a game using the following send methods:</p>
*
* <p>
* <code>
* <ul>
* <li>public void sendProperty (String key, String value)</li>
* <li>public void sendProperty (String key, int value)</li>
* <li>public void sendProperty (String key, int x, int y)</li>
* <li>public void sendObject (ITransmittable object)</li>
* <li>public void sendObject (XMLElement element)</li>
* </ul>
* </code>
* </p>
*
* <p>All of these methods send something to the server. If a send method
* is used then its corresponding adapter receive method must also be fillin.
* e.g. if a method calls:</p>
* <p><blockquote>sendProperty ("move", 5, 5");</blockquote></p>
* <p>then the following recieve method must be filled in to do as the
* controllers for the other players will receive this property.</p>
* <p><blockquote>recieveProperty (String key, int x, int y) { ...</blockquote></p>
*
* <p><b>Note:</b> Each sub class of JogreController most implement the
* abstract <i>start()</i> method. This is used for things like resetting
* the model / controller timers etc.
*
* @author Bob Marks
* @version Alpha 0.2.3
*/
public abstract class JogreController implements MouseListener, MouseMotionListener, KeyListener {
/** Link to the game model. */
protected JogreModel model;
/** Link to the JogreComponent this is controlling . */
protected JogreComponent JogreComponent;
/** Link to the client's connection thread. */
protected TableConnectionThread conn;
/** Table number which this controller is controlling. */
protected int tableNum;
/**
* Reset method which is called every time a new game is created. Each
* sub class of this must have this method. This method is called when the
* game starts for the first time.
*/
public abstract void start ();
/**
* Default constructor class which doesn't set up the network connection.
*
* @param model Model which the controller can update depending on
* what the user input is.
* @param JogreComponent The JogreComponent which the controller is
* listening on.
*/
public JogreController (JogreModel model, JogreComponent JogreComponent) {
this.model = model;
this.JogreComponent = JogreComponent;
}
/**
* Set up a network connection for this controller.
*
* @param conn Link to the TableConnectionThread.
*/
public void setConnection (TableConnectionThread conn) {
this.conn = conn;
this.tableNum = conn.getTableNum();
}
/**
* Return the current player.
*
* @return Current player's username.
*/
public String getCurrentPlayer () {
// if connection is not equal to null then there is access to the
// current player etc.
if (this.conn != null) {
return getTable().getPlayerList().getCurrentPlayerName();
}
return null;
}
/**
* Return the player num (between 0 and the number of players).
*
* @return Seat number of current player.
*/
public int getCurrentPlayerSeatNum () {
// Check connection has been set
if (this.conn != null) {
Player currentPlayer = getTable().getPlayerList().getCurrentPlayer();
if (currentPlayer != null)
return currentPlayer.getSeatNum();
}
return 0;
}
/**
* Return the table number.
*
* @return table number.
*/
public int getTableNum () {
return this.tableNum;
}
/**
* Convience method for returning a table.
*
* @return Current table i.e. tableList.getTable (current table).
*/
public Table getTable () {
return this.conn.getTable();
}
/**
* Return the seat number of a user.
*
* @return If -1 user is standing, otherwise seatNum >=0 and < number
* of seats available.
*/
public int getSeatNum () {
if (this.conn != null) {
PlayerList playerList = getTable().getPlayerList();
Player player = playerList.getPlayer (this.conn.getUsername());
if (player != null)
return player.getSeatNum();
}
return Player.NOT_SEATED;
}
/**
* Return the player name from a seat num.
*
* @param seatNum Seat number of the user.
* @return If -1 user is standing, otherwise seatNum >=0 and < number
* of seats available.
*/
public String getPlayer (int seatNum) {
if (this.conn != null) {
Table table = this.conn.getTableList().getTable (this.tableNum);
return table.getPlayerList().getPlayer (seatNum).getPlayerName();
}
return null;
}
/**
* Return the seat number of a specified player.
*
* @param player Name of the player.
* @return Number of specified players seat.
*/
public int getSeatNum (String player) {
if (this.conn != null) {
Table table = this.conn.getTableList ().getTable (this.tableNum);
return table.getPlayerList ().getPlayer (player).getSeatNum();
}
return Player.NOT_SEATED;
}
/**
* Return true/false if the game is started or not.
*
* NOTE: This will return true even if a player is not seated at a table.
*
* @return Returns true if a game is underway.
*/
public boolean isGamePlaying () {
if (this.conn != null) {
Table table = this.conn.getTableList().getTable (this.tableNum);
if (table != null)
return table.isGamePlaying();
}
return false;
}
/**
* Returns true if game is playing AND player is also seated - useful
* for non-turned based style games.
*
* @return
*/
public boolean isPlayerPlaying () {
if (this.conn != null) {
Table table = this.conn.getTableList().getTable (this.tableNum);
if (table != null) {
return table.isGamePlaying() && getSeatNum() != Player.NOT_SEATED;
}
}
return false;
}
/**
* Send a more complex object (any object which implements the ITransmittable
* interface). The recieve (XMLElement element) method must be overwritten
* to recieve it.
*
* @param object A more complex piece of data encoded in XML.
*/
public void sendObject (ITransmittable object) {
sendObject (object.flatten());
}
/**
* Send a more complex object (any object which implements the ITransmittable
* interface). The recieve (XMLElement element) method must be overwritten
* to recieve it.
*
* @param message A more complex piece of data encoded in XML.
*/
public void sendObject (XMLElement message) {
// Create property communications object, add data and send to server
CommControllerObject commObject = new CommControllerObject ();
commObject.setData (message);
this.conn.send (commObject);
}
/**
* Send a normal String valued property.
*
* @param key
* @param value
*/
public void sendProperty (String key, String value) {
// Create property communications object and send to server
CommControllerProperty commContProp = new CommControllerProperty (
CommControllerProperty.TYPE_STRING, key, value);
this.conn.send(commContProp);
}
/**
* Send a single integer property.
*
* @param key
* @param value
*/
public void sendProperty (String key, int value) {
// Create property communications object and send to server
String valueStr = String.valueOf(value);
CommControllerProperty commContProp = new CommControllerProperty (
CommControllerProperty.TYPE_INT, key, valueStr);
this.conn.send(commContProp);
}
/**
* Send a co-ordinate property (x and y integer values).
*
* @param key
* @param x
* @param y
*/
public void sendProperty (String key, int x, int y) {
// Create property communications object and send to server
CommControllerProperty commContProp = new CommControllerProperty (
CommControllerProperty.TYPE_INT_TWO, key, x + " " + y);
this.conn.send(commContProp);
}
/**
* Adapter method for receiving property as a key and value from another client.
*
* @param key Key of property to be read from server.
* @param value String value of property to be read from server.
*/
public void receiveProperty (String key, String value) {
// over written in sub class
}
/**
* Recieve property as a String key and integer value.
*
* @param key Key of property to be read from server.
* @param value Integer value of property to be read from server.
*/
public void receiveProperty (String key, int value) {
// over written in sub class
}
/**
* Recieve property from another client as a co-ordinate (x and y integer).
*
* @param key Key of property to be read from server.
* @param x Integer x co-ordinate value property to be read from server.
* @param y Integer y co-ordinate value property to be read from server.
*/
public void receiveProperty (String key, int x, int y) {
// over written in sub class
}
/**
* Recieve object as XML from a client or server (use this when more advanced
* data is required from the server or a client).
*
* @param message Receive a more complex XML object from a server.
*/
public void receiveObject (XMLElement message) {}
/**
* Return new if it is this players turn.
*
* @return True if this current players turn.
*/
public boolean isThisPlayersTurn () {
if (PlayerList.NO_PLAYER.equals (getCurrentPlayer()))
return false;
else
return (getSeatNum() == getCurrentPlayerSeatNum());
}
/**
* Method which tells the server that it is next players turn.
*/
public void nextPlayer () {
// Create communcations table action of type "Next Player".
CommNextPlayer nextPlayer = new CommNextPlayer ();
// Fix for bug 1176951 - "Possibility of consequent moves"
conn.getTable().getPlayerList().setCurrentPlayer (PlayerList.NO_PLAYER);
// send to server from client
this.conn.send (nextPlayer);
}
//==========================================================================
// Empty implementations of "MouseListener"
//==========================================================================
/**
* Invoked when the mouse enters a JogreComponent.
*
* @param e
*/
public void mouseEntered(MouseEvent e) {}
/**
* Invoked when the mouse exits a JogreComponent.
*
* @param e
*/
public void mouseExited(MouseEvent e) {}
/**
* Invoked when the mouse has been clicked on a JogreComponent.
*
* @param e
*/
public void mouseClicked(MouseEvent e) {}
/**
* Invoked when a mouse button has been released on a JogreComponent.
*
* @param e
*/
public void mouseReleased (MouseEvent e) {}
/**
* Invoked when a mouse button has been pressed on a JogreComponent.
*
* @param e
*/
public void mousePressed (MouseEvent e) {}
//==========================================================================
// Empty implementations of "MouseMotionListener"
//==========================================================================
/**
* Invoked when the mouse button has been moved on a JogreComponent
* (with no buttons no down).
*
* @param e
*/
public void mouseMoved(MouseEvent e) {}
/**
* Invoked when a mouse button is pressed on a JogreComponent and
* then dragged.
*
* @param e
*/
public void mouseDragged (MouseEvent e) {}
//==========================================================================
// Empty implementations of "KeyListener"
//==========================================================================
/**
* Invoked when a key has been pressed.
*
* @param e
*/
public void keyPressed(KeyEvent e) {}
/**
* Invoked when a key has been released.
*
* @param e
*/
public void keyReleased(KeyEvent e) {}
/**
* Invoked when a key has been typed.
*
* @param e
*/
public void keyTyped(KeyEvent e) {}
}
| gpl-2.0 |
carvalhomb/tsmells | tests/Pieces/IndentedTest/java/IfForSingleTCom/src/MyTest.java | 244 | import org.junit.TestCase;
public class MyTest extends TestCase {
public void testCommand() {
if (true) {
assertTrue(true);
}
for (int i=0; i < 2; i++) {
assertTrue(true);
}
}
} | gpl-2.0 |
cpesch/CarCosts | car-costs/src/main/java/slash/gui/toolkit/KeyStrokeManager.java | 15710 | package slash.gui.toolkit;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeListener;
import java.util.*;
import java.util.List;
/**
* A KeyStrokeManager handles the mapping of keyboard short cuts, called
* KeyStrokes in Swing, and the actions, that are fired when pressing a
* key stroke.
*
* @see ActionManager
*/
public class KeyStrokeManager implements KeyListener {
/**
* Creates a new KeyStrokeManager.
*/
public KeyStrokeManager(ActionManager actionMgr) {
this.actionMgr = actionMgr;
keymap = addKeymap(DEFAULT_KEYMAP, null);
keymap.setDefaultAction(new DefaultEditorKit.DefaultKeyTypedAction());
}
/* Adds the KeyStrokeManager to receive key events from
* the given component.
* @param c the Component
* @see java.awt.event.KeyEvent
* @see java.awt.event.KeyListener
*/
public void attachTo(Component c) {
listeners.add(c);
c.addKeyListener(this);
}
/**
* Removes the KeyStrokeManager so that it no longer
* receives key events from the given component.
*
* @param c the Component
* @see java.awt.event.KeyEvent
* @see java.awt.event.KeyListener
*/
public void detachFrom(Component c) {
c.removeKeyListener(this);
listeners.remove(c);
}
/**
* Detach all Listeners. This is also called by the finalizer to avoid
* useless Listerers escpecially on Actions
*/
public void detach() {
// System.out.println("Detaching "+listeners.size()+" adaptor listeners from KeyStroke Manager");
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
Component component = (Component) iterator.next();
component.removeKeyListener(this);
}
// remove all listeners
listeners.clear();
}
// --- key listener interface ------------------------------
/**
* Invoked when a key has been typed.
* This event occurs when a key press is followed by a key release.
*/
public void keyTyped(KeyEvent e) {
// System.out.println("KeyTyped:" + e);
processComponentKeyEvent(e);
}
/**
* Invoked when a key has been pressed.
*/
public void keyPressed(KeyEvent e) {
// System.out.println("KeyPressed:"+e);
processComponentKeyEvent(e);
}
/**
* Invoked when a key has been released.
*/
public void keyReleased(KeyEvent e) {
// System.out.println("KeyReleased:"+e);
processComponentKeyEvent(e);
}
// --- property change support -----------------------------
private SwingPropertyChangeSupport changeSupport;
/**
* Add a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
* <p/>
* A PropertyChangeEvent will get fired in response to setting
* a bound property, e.g. setFont, setBackground, or setForeground.
* Note that if the current component is inheriting its foreground,
* background, or font from its container, then no event will be
* fired in response to a change in the inherited property.
*
* @param listener The PropertyChangeListener to be added
*/
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/**
* Remove a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener The PropertyChangeListener to be removed
*/
public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
/**
* Support for reporting bound property changes. If oldValue and
* newValue are not equal and the PropertyChangeEvent listener list
* isn't empty, then fire a PropertyChange event to each listener.
* This method has an overloaded method for each primitive type. For
* example, here's how to write a bound property set method whose
* value is an int:
* <pre>
* public void setFoo(int newValue) {
* int oldValue = foo;
* foo = newValue;
* firePropertyChange("foo", oldValue, newValue);
* }
* </pre>
* <p/>
* This method will migrate to java.awt.Component in the next major JDK release
*
* @param propertyName The programmatic name of the property that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @see java.beans.PropertyChangeSupport
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (changeSupport != null) {
changeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
// --- keymap support --------------------------------------
/**
* Sets the keymap to use for binding events to
* actions. Setting to null effectively disables keyboard input.
* A PropertyChange event ("keymap") is fired when a new keymap
* is installed.
*
* @param map the keymap
* @see #getKeymap
*/
public void setKeymap(Keymap map) {
Keymap old = keymap;
keymap = map;
firePropertyChange("keymap", old, keymap);
}
/**
* Fetches the keymap currently active.
*
* @return the keymap
*/
public Keymap getKeymap() {
return keymap;
}
/**
* Adds a new keymap into the keymap hierarchy. Keymap bindings
* resolve from bottom up so an attribute specified in a child
* will override an attribute specified in the parent.
*
* @param nm the name of the keymap (must be unique within the collection of
* named keymaps). The name may be null if the keymap is unnamed, but the
* caller is responsible for managing the reference returned as an unnamed
* keymap can't be fetched by name.
* @param parent the parent keymap. This may be null if unspecified
* bindings need not be resolved in some other keymap.
* @return the keymap
*/
public static Keymap addKeymap(String nm, Keymap parent) {
Keymap map = new DefaultKeymap(nm, parent);
if (nm != null) {
// add a named keymap, a class of bindings
keymapTable.put(nm, map);
}
return map;
}
/**
* Removes a named keymap previously added. Keymaps
* with null names may not be removed in this way.
*
* @param nm the name of the keymap to remove
* @return the keymap that was removed
*/
public static Keymap removeKeymap(String nm) {
return (Keymap) keymapTable.remove(nm);
}
/**
* Fetches a named keymap previously added to the document.
* This does not work with null-named keymaps.
*
* @param nm the name of the keymap
* @return the keymap
*/
public static Keymap getKeymap(String nm) {
return keymapTable.get(nm);
}
/**
* Loads a keymap with a bunch of
* bindings. This can be used to take a static table of
* definitions and load them into some keymap. The following
* example illustrates an example of binding some keys to
* the cut, copy, and paste actions associated with a
* JTextComponent. A code fragment to accomplish
* this might look as follows:
* <pre><code>
* <p/>
* static final JTextComponent.KeyBinding[] defaultBindings = {
* new JTextComponent.KeyBinding(
* KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
* DefaultEditorKit.copyAction),
* new JTextComponent.KeyBinding(
* KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
* DefaultEditorKit.pasteAction),
* new JTextComponent.KeyBinding(
* KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
* DefaultEditorKit.cutAction),
* };
* <p/>
* keyStrokeMgr.loadKeymap(defaultBindings);
* </code></pre>
* The sets of bindings and actions may be empty but must be non-null.
*
* @param bindings the bindings
*/
public void loadKeymap(JTextComponent.KeyBinding[] bindings) {
for (JTextComponent.KeyBinding binding : bindings) {
Action a = actionMgr.getAction(binding.actionName, false);
if (a != null) {
keymap.addActionForKeyStroke(binding.key, a);
} else
System.out.println("Action " + binding.actionName + " for KeyStroke " +
binding.key + " not found.");
}
}
/**
* Maps an event to an action if one is defined in the
* installed keymap, and perform the action. If the action is
* performed, the event is consumed.
*
* @return true if an action was performed, false otherwise.
*/
private boolean mapEventToAction(KeyEvent e) {
Keymap binding = getKeymap();
if (binding != null) {
KeyStroke k = KeyStroke.getKeyStrokeForEvent(e);
Action a = binding.getAction(k);
if (a != null) {
String command = null;
if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
command = String.valueOf(e.getKeyChar());
}
ActionEvent ae = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED,
command, e.getModifiers());
a.actionPerformed(ae);
e.consume();
System.out.println("Action " + a + " fired for " + k);
return true;
}
}
return false;
}
/**
* Processes any key events that the components itself recognize and fire
* throught the key listener. This will be called after the focus manager
* and any interested listeners have been given a chance to steal away the
* event. This method will only be called is the event has not yet been
* consumed. This method is called prior to the keyboard UI logic.
*
* @param e the event
*/
private void processComponentKeyEvent(KeyEvent e) {
int id = e.getID();
switch (id) {
case KeyEvent.KEY_TYPED:
if (!mapEventToAction(e)) {
// default behavior is to input translated
// characters as content if the character
// hasn't been mapped in the keymap.
Keymap binding = getKeymap();
if (binding != null) {
Action a = binding.getDefaultAction();
if (a != null) {
ActionEvent ae = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED,
String.valueOf(e.getKeyChar()),
e.getModifiers());
a.actionPerformed(ae);
e.consume();
}
}
}
break;
case KeyEvent.KEY_PRESSED:
mapEventToAction(e);
break;
case KeyEvent.KEY_RELEASED:
mapEventToAction(e);
break;
}
}
// --- inner classes ---------------------------------------
/**
* An Implementation of a KeyMap for the KeyStrokeManager.
*/
public static class DefaultKeymap implements Keymap {
public DefaultKeymap(String nm, Keymap parent) {
this.nm = nm;
this.parent = parent;
bindings = new Hashtable<KeyStroke, Action>();
}
/**
* Fetch the default action to fire if a
* key is typed (ie a KEY_TYPED KeyEvent is received)
* and there is no binding for it. Typically this
* would be some action that inserts text so that
* the keymap doesn't require an action for each
* possible key.
*/
public Action getDefaultAction() {
if (defaultAction != null) {
return defaultAction;
}
return (parent != null) ? parent.getDefaultAction() : null;
}
/**
* Set the default action to fire if a key is typed.
*/
public void setDefaultAction(Action a) {
defaultAction = a;
}
public String getName() {
return nm;
}
public Action getAction(KeyStroke key) {
Action a = bindings.get(key);
if ((a == null) && (parent != null)) {
a = parent.getAction(key);
}
return a;
}
public KeyStroke[] getBoundKeyStrokes() {
KeyStroke[] keys = new KeyStroke[bindings.size()];
int i = 0;
for (Enumeration e = bindings.keys(); e.hasMoreElements();) {
keys[i++] = (KeyStroke) e.nextElement();
}
return keys;
}
public Action[] getBoundActions() {
Action[] actions = new Action[bindings.size()];
int i = 0;
for (Enumeration e = bindings.elements(); e.hasMoreElements();) {
actions[i++] = (Action) e.nextElement();
}
return actions;
}
public KeyStroke[] getKeyStrokesForAction(Action a) {
return null;
}
public boolean isLocallyDefined(KeyStroke key) {
return bindings.containsKey(key);
}
public void addActionForKeyStroke(KeyStroke key, Action a) {
bindings.put(key, a);
}
public void removeKeyStrokeBinding(KeyStroke key) {
bindings.remove(key);
}
public void removeBindings() {
bindings.clear();
}
public Keymap getResolveParent() {
return parent;
}
public void setResolveParent(Keymap parent) {
this.parent = parent;
}
/**
* String representation of the keymap... potentially
* a very long string.
*/
public String toString() {
return "Keymap[" + nm + "]" + bindings;
}
String nm;
Keymap parent;
Hashtable<KeyStroke, Action> bindings;
Action defaultAction;
}
/**
* This is the name of the default keymap that will be shared by all
* KeyStrokeManager instances unless they have had a different
* keymap set.
*/
public static final String DEFAULT_KEYMAP = "default";
// --- member variables ------------------------------------
private static Map<String, Keymap> keymapTable = new HashMap<String, Keymap>(17);
private static Keymap keymap = null;
private List<Component> listeners = new ArrayList<Component>();
private ActionManager actionMgr;
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java | 4373 | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.hibernate3;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.engine.FilterDefinition;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Convenient FactoryBean for defining Hibernate FilterDefinitions.
* Exposes a corresponding Hibernate FilterDefinition object.
*
* <p>Typically defined as an inner bean within a LocalSessionFactoryBean
* definition, as the list element for the "filterDefinitions" bean property.
* For example:
*
* <pre class="code">
* <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
* ...
* <property name="filterDefinitions">
* <list>
* <bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
* <property name="filterName" value="myFilter"/>
* <property name="parameterTypes">
* <map>
* <entry key="myParam" value="string"/>
* <entry key="myOtherParam" value="long"/>
* </map>
* </property>
* </bean>
* </list>
* </property>
* ...
* </bean></pre>
*
* Alternatively, specify a bean id (or name) attribute for the inner bean,
* instead of the "filterName" property.
*
* @author Juergen Hoeller
* @since 1.2
* @see org.hibernate.engine.FilterDefinition
* @see LocalSessionFactoryBean#setFilterDefinitions
* @deprecated as of Spring 4.3, in favor of Hibernate 4.x/5.x
*/
@Deprecated
public class FilterDefinitionFactoryBean implements FactoryBean<FilterDefinition>, BeanNameAware, InitializingBean {
private final TypeResolver typeResolver = new TypeResolver();
private String filterName;
private Map<String, Type> parameterTypeMap = new HashMap<String, Type>();
private String defaultFilterCondition;
private FilterDefinition filterDefinition;
/**
* Set the name of the filter.
*/
public void setFilterName(String filterName) {
this.filterName = filterName;
}
/**
* Set the parameter types for the filter,
* with parameter names as keys and type names as values.
* See {@code org.hibernate.type.TypeResolver#heuristicType(String)}.
*/
public void setParameterTypes(Map<String, String> parameterTypes) {
if (parameterTypes != null) {
this.parameterTypeMap = new HashMap<String, Type>(parameterTypes.size());
for (Map.Entry<String, String> entry : parameterTypes.entrySet()) {
this.parameterTypeMap.put(entry.getKey(), this.typeResolver.heuristicType(entry.getValue()));
}
}
else {
this.parameterTypeMap = new HashMap<String, Type>();
}
}
/**
* Specify a default filter condition for the filter, if any.
*/
public void setDefaultFilterCondition(String defaultFilterCondition) {
this.defaultFilterCondition = defaultFilterCondition;
}
/**
* If no explicit filter name has been specified, the bean name of
* the FilterDefinitionFactoryBean will be used.
* @see #setFilterName
*/
@Override
public void setBeanName(String name) {
if (this.filterName == null) {
this.filterName = name;
}
}
@Override
public void afterPropertiesSet() {
this.filterDefinition =
new FilterDefinition(this.filterName, this.defaultFilterCondition, this.parameterTypeMap);
}
@Override
public FilterDefinition getObject() {
return this.filterDefinition;
}
@Override
public Class<FilterDefinition> getObjectType() {
return FilterDefinition.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/webservices/WebServicesHandler.java | 6952 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package net.sourceforge.atunes.kernel.modules.webservices;
import java.util.List;
import javax.swing.ImageIcon;
import net.sourceforge.atunes.kernel.AbstractHandler;
import net.sourceforge.atunes.kernel.modules.webservices.lastfm.LastFmService;
import net.sourceforge.atunes.model.IAlbumInfo;
import net.sourceforge.atunes.model.IAlbumListInfo;
import net.sourceforge.atunes.model.IArtistInfo;
import net.sourceforge.atunes.model.IArtistTopTracks;
import net.sourceforge.atunes.model.IAudioObject;
import net.sourceforge.atunes.model.IEvent;
import net.sourceforge.atunes.model.ILocalAudioObject;
import net.sourceforge.atunes.model.ILovedTrack;
import net.sourceforge.atunes.model.ILyrics;
import net.sourceforge.atunes.model.ILyricsService;
import net.sourceforge.atunes.model.ISimilarArtistsInfo;
import net.sourceforge.atunes.model.IStateContext;
import net.sourceforge.atunes.model.ITaskService;
import net.sourceforge.atunes.model.IWebServicesHandler;
/**
* Responsible of interact with web services (last.fm, lyrics, etc)
*
* @author alex
*
*/
public class WebServicesHandler extends AbstractHandler implements
IWebServicesHandler {
private ILyricsService lyricsService;
private ITaskService taskService;
private IStateContext stateContext;
/**
* @param stateContext
*/
public void setStateContext(final IStateContext stateContext) {
this.stateContext = stateContext;
}
/**
* @return last fm service
*/
private LastFmService getLastFmService() {
// use lazy initialization to speedup startup
return getBean(LastFmService.class);
}
/**
* @param lyricsService
*/
public final void setLyricsService(final ILyricsService lyricsService) {
this.lyricsService = lyricsService;
}
/**
* @param taskService
*/
public void setTaskService(final ITaskService taskService) {
this.taskService = taskService;
}
@Override
public void deferredInitialization() {
getLastFmService().submitCacheToLastFm(this.taskService);
}
@Override
public void applicationFinish() {
getLastFmService().finishService();
this.lyricsService.finishService();
}
@Override
public void applicationStateChanged() {
this.lyricsService.updateService();
if (!this.stateContext.isCacheLastFmContent()) {
getLastFmService().clearCache();
}
}
@Override
protected void initHandler() {
this.lyricsService.updateService();
}
@Override
public boolean clearCache() {
boolean exception = getLastFmService().clearCache();
exception = this.lyricsService.clearCache() || exception;
return exception;
}
@Override
public void submitNowPlayingInfo(final IAudioObject audioObject) {
if (audioObject instanceof ILocalAudioObject) {
getLastFmService().submitNowPlayingInfoToLastFm(
(ILocalAudioObject) audioObject, this.taskService);
}
}
@Override
public void addBannedSong(final IAudioObject audioObject) {
getLastFmService().addBannedSong(audioObject);
}
@Override
public void addLovedSong(final IAudioObject audioObject) {
getLastFmService().addLovedSong(audioObject);
}
@Override
public IAlbumInfo getAlbum(final String artist, final String album) {
return getLastFmService().getAlbum(artist, album);
}
@Override
public IAlbumListInfo getAlbumList(final String artist) {
return getLastFmService().getAlbumList(artist);
}
@Override
public ImageIcon getAlbumImage(final IAlbumInfo albumInfo) {
return getLastFmService().getAlbumImage(albumInfo);
}
@Override
public ImageIcon getAlbumThumbImage(final IAlbumInfo albumInfo) {
return getLastFmService().getAlbumThumbImage(albumInfo);
}
@Override
public ImageIcon getAlbumImage(final String artist, final String album) {
return getLastFmService().getAlbumImage(artist, album);
}
@Override
public ImageIcon getArtistImage(final String artist) {
return getLastFmService().getArtistImage(artist);
}
@Override
public String getBioText(final String artist) {
return getLastFmService().getWikiText(artist);
}
@Override
public String getBioURL(final String artist) {
return getLastFmService().getWikiURL(artist);
}
@Override
public IArtistTopTracks getTopTracks(final String artist) {
return getLastFmService().getTopTracks(artist);
}
@Override
public String getTitleForAudioObject(final IAudioObject f) {
if (f instanceof ILocalAudioObject) {
return getLastFmService().getTitleForFile((ILocalAudioObject) f);
}
return null;
}
@Override
public List<ILovedTrack> getLovedTracks() {
return getLastFmService().getLovedTracks();
}
@Override
public Boolean testLogin(final String user, final String password) {
return getLastFmService().testLogin(user, password);
}
@Override
public void submit(final IAudioObject audioObject, final long listened) {
getLastFmService().submitToLastFm(audioObject, listened,
this.taskService);
}
@Override
public String getArtistTopTag(final String artist) {
return getLastFmService().getArtistTopTag(artist);
}
@Override
public ImageIcon getArtistThumbImage(final IArtistInfo artist) {
return getLastFmService().getArtistThumbImage(artist);
}
@Override
public ISimilarArtistsInfo getSimilarArtists(final String artist) {
return getLastFmService().getSimilarArtists(artist);
}
@Override
public int getTrackNumber(final ILocalAudioObject audioObject) {
return getLastFmService().getTrackNumberForFile(audioObject);
}
@Override
public void removeLovedSong(final IAudioObject song) {
getLastFmService().removeLovedSong(song);
}
@Override
public ILyrics getLyrics(final String artist, final String title) {
return this.lyricsService.getLyrics(artist, title);
}
@Override
public void consolidateWebContent() {
getLastFmService().flush();
}
@Override
public List<IEvent> getArtistEvents(String artist) {
return getLastFmService().getArtistEvents(artist);
}
@Override
public List<IEvent> getRecommendedEvents() {
return getLastFmService().getRecommendedEvents();
}
}
| gpl-2.0 |
NorthFacing/step-by-Java | CS-data-structure/src/main/java/com/book/book01/chapter06/demo/binarySearch/binarySearch.java | 3405 | package com.book.book01.chapter06.demo.binarySearch;
// binarySearch.java
// demonstrates recursive binary search
// to run this program: C>java BinarySearchApp
////////////////////////////////////////////////////////////////
class ordArray {
private long[] a; // ref to array a
private int nElems; // number of data items
//-----------------------------------------------------------
public ordArray(int max) // constructor
{
a = new long[max]; // create array
nElems = 0;
}
//-----------------------------------------------------------
public int size() {
return nElems;
}
//-----------------------------------------------------------
public int find(long searchKey) {
return recFind(searchKey, 0, nElems - 1);
}
//-----------------------------------------------------------
private int recFind(long searchKey, int lowerBound,
int upperBound) {
int curIn;
curIn = (lowerBound + upperBound) / 2;
if (a[curIn] == searchKey)
return curIn; // found it
else if (lowerBound > upperBound)
return nElems; // can't find it
else // divide range
{
if (a[curIn] < searchKey) // it's in upper half
return recFind(searchKey, curIn + 1, upperBound);
else // it's in lower half
return recFind(searchKey, lowerBound, curIn - 1);
} // end else divide range
} // end recFind()
//-----------------------------------------------------------
public void insert(long value) // put element into array
{
int j;
for (j = 0; j < nElems; j++) // find where it goes
if (a[j] > value) // (linear search)
break;
for (int k = nElems; k > j; k--) // move bigger ones up
a[k] = a[k - 1];
a[j] = value; // insert it
nElems++; // increment size
} // end insert()
//-----------------------------------------------------------
public void display() // displays array contents
{
for (int j = 0; j < nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}
//-----------------------------------------------------------
} // end class ordArray
////////////////////////////////////////////////////////////////
class BinarySearchApp {
public static void main(String[] args) {
int maxSize = 100; // array size
ordArray arr; // reference to array
arr = new ordArray(maxSize); // create the array
arr.insert(72); // insert items
arr.insert(90);
arr.insert(45);
arr.insert(126);
arr.insert(54);
arr.insert(99);
arr.insert(144);
arr.insert(27);
arr.insert(135);
arr.insert(81);
arr.insert(18);
arr.insert(108);
arr.insert(9);
arr.insert(117);
arr.insert(63);
arr.insert(36);
arr.display(); // display array
int searchKey = 27; // search for item
if (arr.find(searchKey) != arr.size())
System.out.println("Found " + searchKey);
else
System.out.println("Can't find " + searchKey);
} // end main()
} // end class BinarySearchApp
////////////////////////////////////////////////////////////////
| gpl-2.0 |
h0MER247/jPC | src/Hardware/CPU/Intel80386/Instructions/i386/Datatransfer/LGDT32.java | 1727 | /*
* Copyright (C) 2017 h0MER247
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package Hardware.CPU.Intel80386.Instructions.i386.Datatransfer;
import Hardware.CPU.Intel80386.Exceptions.CPUException;
import Hardware.CPU.Intel80386.Instructions.Instruction;
import Hardware.CPU.Intel80386.Intel80386;
import Hardware.CPU.Intel80386.Operands.Operand;
public final class LGDT32 extends Instruction {
private final Operand m_limit;
private final Operand m_base;
public LGDT32(Intel80386 cpu,
Operand limit,
Operand base) {
super(cpu);
m_limit = limit;
m_base = base;
}
@Override
public void run() {
if(m_cpu.getCPL() != 0)
throw CPUException.getGeneralProtectionFault(0);
m_cpu.GDT.setLimit(m_limit.getValue());
m_cpu.GDT.setBase(m_base.getValue());
}
@Override
public String toString() {
return String.format("lgdt %s", m_limit.toString());
}
}
| gpl-2.0 |
Distrotech/tigervnc | java/com/tigervnc/network/SSLEngineManager.java | 7957 | /* Copyright (C) 2012 Brian P. Hinz
* Copyright (C) 2012 D. R. Commander. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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, 5th Floor, Boston, MA 02110-1301 USA
*/
package com.tigervnc.network;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.tigervnc.rdr.FdInStream;
import com.tigervnc.rdr.FdOutStream;
public class SSLEngineManager {
private SSLEngine engine = null;
private int applicationBufferSize;
private int packetBufferSize;
private ByteBuffer myAppData;
private ByteBuffer myNetData;
private ByteBuffer peerAppData;
private ByteBuffer peerNetData;
private Executor executor;
private FdInStream inStream;
private FdOutStream outStream;
public SSLEngineManager(SSLEngine sslEngine, FdInStream is,
FdOutStream os) throws IOException {
inStream = is;
outStream = os;
engine = sslEngine;
executor = Executors.newSingleThreadExecutor();
packetBufferSize = engine.getSession().getPacketBufferSize();
applicationBufferSize = engine.getSession().getApplicationBufferSize();
myAppData = ByteBuffer.allocate(applicationBufferSize);
myNetData = ByteBuffer.allocate(packetBufferSize);
peerAppData = ByteBuffer.allocate(applicationBufferSize);
peerNetData = ByteBuffer.allocate(packetBufferSize);
}
public void doHandshake() throws Exception {
// Begin handshake
engine.beginHandshake();
SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();
// Process handshaking message
while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
switch (hs) {
case NEED_UNWRAP:
// Receive handshaking data from peer
pull(peerNetData);
//if (pull(peerNetData) < 0) {
// Handle closed channel
//}
// Process incoming handshaking data
peerNetData.flip();
SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
peerNetData.compact();
hs = res.getHandshakeStatus();
// Check status
switch (res.getStatus()) {
case OK :
// Handle OK status
break;
// Handle other status: BUFFER_UNDERFLOW, BUFFER_OVERFLOW, CLOSED
//...
}
break;
case NEED_WRAP :
// Empty the local network packet buffer.
myNetData.clear();
// Generate handshaking data
res = engine.wrap(myAppData, myNetData);
hs = res.getHandshakeStatus();
// Check status
switch (res.getStatus()) {
case OK :
//myNetData.flip();
push(myNetData);
// Send the handshaking data to peer
//while (myNetData.hasRemaining()) {
// if (push(myNetData) < 0) {
// // Handle closed channel
// }
//}
break;
// Handle other status: BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED
//...
}
break;
case NEED_TASK :
// Handle blocking tasks
executeTasks();
break;
// Handle other status: // FINISHED or NOT_HANDSHAKING
//...
}
hs = engine.getHandshakeStatus();
}
// Processes after handshaking
//...
}
private void executeTasks() {
Runnable task;
while ((task = engine.getDelegatedTask()) != null) {
executor.execute(task);
}
}
public int read(byte[] data, int dataPtr, int length) throws IOException {
// Read SSL/TLS encoded data from peer
int bytesRead = 0;
SSLEngineResult res;
do {
// Process incoming data
int packetLength = pull(peerNetData);
peerNetData.flip();
res = engine.unwrap(peerNetData, peerAppData);
peerNetData.compact();
bytesRead += packetLength;
} while (res.getStatus() != SSLEngineResult.Status.OK);
peerAppData.flip();
int n = Math.min(peerAppData.remaining(), length);
peerAppData.get(data, dataPtr, n);
peerAppData.compact();
return n;
}
public int write(byte[] data, int dataPtr, int length) throws IOException {
int n = 0;
//while (myAppData.hasRemaining()) {
// Generate SSL/TLS encoded data (handshake or application data)
// FIXME:
// Need to make sure myAppData has space for data!
myAppData.put(data, dataPtr, length);
myAppData.flip();
SSLEngineResult res = engine.wrap(myAppData, myNetData);
myAppData.compact();
// Process status of call
//if (res.getStatus() == SSLEngineResult.Status.OK) {
//myAppData.compact();
// Send SSL/TLS encoded data to peer
//while(myNetData.hasRemaining()) {
int num = push(myNetData);
if (num == -1) {
// handle closed channel
} else if (num == 0) {
// no bytes written; try again later
}
//n += num;
//}
//}
// Handle other status: BUFFER_OVERFLOW, CLOSED
//...
//}
return num;
}
private int push(ByteBuffer src) throws IOException {
src.flip();
int n = src.remaining();
byte[] b = new byte[n];
src.get(b);
src.clear();
outStream.writeBytes(b, 0, n);
outStream.flush();
return n;
}
private int pull(ByteBuffer dst) throws IOException {
inStream.checkNoWait(5);
//if (!inStream.checkNoWait(5)) {
// return 0;
//}
byte[] header = new byte[5];
inStream.readBytes(header, 0, 5);
// Reference: http://publib.boulder.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtps5%2Fs5rcd.html
int sslRecordType = header[0] & 0xFF;
int sslVersion = header[1] & 0xFF;
int sslDataLength = (int)((header[3] << 8) | (header[4] & 0xFF));
if (sslRecordType < 20 || sslRecordType > 23 || sslVersion != 3 ||
sslDataLength == 0) {
// Not SSL v3 or TLS. Could be SSL v2 or bad data
// Reference: http://www.homeport.org/~adam/ssl.html
// and the SSL v2 protocol specification
int headerBytes;
if ((header[0] & 0x80) != 0x80) {
headerBytes = 2;
sslDataLength = (int)(((header[0] & 0x7f) << 8) | header[1]);
} else {
headerBytes = 3;
sslDataLength = (int)(((header[0] & 0x3f) << 8) | header[1]);
}
// In SSL v2, the version is part of the handshake
sslVersion = header[headerBytes + 1] & 0xFF;
if (sslVersion < 2 || sslVersion > 3 || sslDataLength == 0)
throw new IOException("not an SSL/TLS record");
// The number of bytes left to read
sslDataLength -= (5 - headerBytes);
}
assert sslDataLength > 0;
byte[] buf = new byte[sslDataLength];
inStream.readBytes(buf, 0, sslDataLength);
dst.put(header);
dst.put(buf);
return sslDataLength;
}
public SSLSession getSession() {
return engine.getSession();
}
}
| gpl-2.0 |
amirlotfi/Nikagram | app/src/main/java/ir/nikagram/ui/ChangeNameActivity.java | 8279 |
package ir.nikagram.ui;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import ir.nikagram.messenger.AndroidUtilities;
import ir.nikagram.messenger.LocaleController;
import ir.nikagram.messenger.ApplicationLoader;
import ir.nikagram.messenger.R;
import ir.nikagram.tgnet.ConnectionsManager;
import ir.nikagram.tgnet.RequestDelegate;
import ir.nikagram.tgnet.TLObject;
import ir.nikagram.tgnet.TLRPC;
import ir.nikagram.messenger.MessagesController;
import ir.nikagram.messenger.NotificationCenter;
import ir.nikagram.messenger.UserConfig;
import ir.nikagram.ui.ActionBar.ActionBar;
import ir.nikagram.ui.ActionBar.ActionBarMenu;
import ir.nikagram.ui.ActionBar.BaseFragment;
import ir.nikagram.ui.Components.LayoutHelper;
public class ChangeNameActivity extends BaseFragment {
private EditText firstNameField;
private EditText lastNameField;
private View headerLabelView;
private View doneButton;
private final static int done_button = 1;
@Override
public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == done_button) {
if (firstNameField.getText().length() != 0) {
saveName();
finishFragment();
}
}
}
});
ActionBarMenu menu = actionBar.createMenu();
doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
}
LinearLayout linearLayout = new LinearLayout(context);
fragmentView = linearLayout;
fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL);
fragmentView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
firstNameField = new EditText(context);
firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
firstNameField.setHintTextColor(0xff979797);
firstNameField.setTextColor(0xff212121);
firstNameField.setMaxLines(1);
firstNameField.setLines(1);
firstNameField.setSingleLine(true);
firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName));
AndroidUtilities.clearCursorDrawable(firstNameField);
linearLayout.addView(firstNameField, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 24, 24, 24, 0));
firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_NEXT) {
lastNameField.requestFocus();
lastNameField.setSelection(lastNameField.length());
return true;
}
return false;
}
});
lastNameField = new EditText(context);
lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
lastNameField.setHintTextColor(0xff979797);
lastNameField.setTextColor(0xff212121);
lastNameField.setMaxLines(1);
lastNameField.setLines(1);
lastNameField.setSingleLine(true);
lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE);
lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName));
AndroidUtilities.clearCursorDrawable(lastNameField);
linearLayout.addView(lastNameField, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 24, 16, 24, 0));
lastNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
doneButton.performClick();
return true;
}
return false;
}
});
if (user != null) {
firstNameField.setText(user.first_name);
firstNameField.setSelection(firstNameField.length());
lastNameField.setText(user.last_name);
}
return fragmentView;
}
@Override
public void onResume() {
super.onResume();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) {
firstNameField.requestFocus();
AndroidUtilities.showKeyboard(firstNameField);
}
}
private void saveName() {
TLRPC.User currentUser = UserConfig.getCurrentUser();
if (currentUser == null || lastNameField.getText() == null || firstNameField.getText() == null) {
return;
}
String newFirst = firstNameField.getText().toString();
String newLast = lastNameField.getText().toString();
if (currentUser.first_name != null && currentUser.first_name.equals(newFirst) && currentUser.last_name != null && currentUser.last_name.equals(newLast)) {
return;
}
TLRPC.TL_account_updateProfile req = new TLRPC.TL_account_updateProfile();
req.flags = 3;
currentUser.first_name = req.first_name = newFirst;
currentUser.last_name = req.last_name = newLast;
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null) {
user.first_name = req.first_name;
user.last_name = req.last_name;
}
UserConfig.saveConfig(true);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
});
}
@Override
public void onTransitionAnimationEnd(boolean isOpen, boolean backward) {
if (isOpen) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (firstNameField != null) {
firstNameField.requestFocus();
AndroidUtilities.showKeyboard(firstNameField);
}
}
}, 100);
}
}
}
| gpl-2.0 |
ProjectGroep1/Joetz-Android | Project/app/src/main/java/com/hogent_joetz/joetzapplication/domain/Person.java | 6192 | package com.hogent_joetz.joetzapplication.domain;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import com.hogent_joetz.joetzapplication.domain.converter.UnixDateTimeConverter;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.joda.time.DateTime;
/**
* Created by Sam on 21/10/2014.
*/
/**
* JsonIgnoreProperties(ignoreUnknown = true) indicates that while converting the JSON string from
* the server to a User object, fields not defined here will be ignored instead of
* throwing an error.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person implements Parcelable {
@JsonProperty("FirstName")
private String firstName;
@JsonProperty("LastName")
private String lastName;
@JsonProperty("Email")
private String email;
//Separate getter/setter for unix conversion.
@JsonIgnore
private DateTime dateOfBirth;
@JsonProperty("Street")
private String street;
@JsonProperty("HouseNumber")
private String houseNumber;
@JsonProperty("Bus")
private String bus;
@JsonProperty("PostalCode")
private int postalCode;
@JsonProperty("City")
private String city;
@JsonProperty("Telephone")
private String phone;
@JsonProperty("RijksRegisterNummer")
private String rijksRegisterNummer;
@JsonProperty("Aansluitingsnr")
private String bondAansluitingsNr;
@JsonProperty("CodeGerechtigde")
private String bondCodeGerechtigde;
@JsonProperty("SubscribedToNewsletter")
private boolean subscribedToNewsletter;
//TODO Registrations
public Person(){
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public DateTime getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(DateTime dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@JsonProperty("DateOfBirth")
public int getUnixDateOfBirth(){
return UnixDateTimeConverter.getUnix(dateOfBirth);
}
@JsonProperty("DateOfBirth")
public void setUnixDateOfBirth(int unixTime){
setDateOfBirth(UnixDateTimeConverter.getDate(unixTime));
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getPostalCode() {
return postalCode;
}
public void setPostalCode(int postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRijksRegisterNummer() {
return rijksRegisterNummer;
}
public void setRijksRegisterNummer(String rijksRegisterNummer) {
this.rijksRegisterNummer = rijksRegisterNummer;
}
public String getBondCodeGerechtigde() {
return bondCodeGerechtigde;
}
public void setBondCodeGerechtigde(String bondCodeGerechtigde) {
this.bondCodeGerechtigde = bondCodeGerechtigde;
}
public String getBondAansluitingsNr() {
return bondAansluitingsNr;
}
public void setBondAansluitingsNr(String bondAansluitingsNr) {
this.bondAansluitingsNr = bondAansluitingsNr;
}
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getBus() {
return bus;
}
public void setBus(String bus) {
this.bus = bus;
}
public boolean isSubscribedToNewsletter() {
return subscribedToNewsletter;
}
public void setSubscribedToNewsletter(boolean subscribedToNewsletter) {
this.subscribedToNewsletter = subscribedToNewsletter;
}
@Override
public String toString() {
return "User[Name: " + firstName + " " + lastName + " || Email: " + email + "]";
}
//Parcelable area
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel pc, int flags) {
pc.writeString(firstName);
pc.writeString(lastName);
pc.writeString(email);
pc.writeInt(getUnixDateOfBirth());
pc.writeString(street);
pc.writeString(houseNumber);
pc.writeString(bus);
pc.writeInt(postalCode);
pc.writeString(city);
pc.writeString(phone);
pc.writeString(rijksRegisterNummer);
pc.writeString(bondAansluitingsNr);
pc.writeString(bondCodeGerechtigde);
pc.writeInt(subscribedToNewsletter ? 1 : 0);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>(){
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
public Person(Parcel pc){
firstName = pc.readString();
lastName = pc.readString();
email = pc.readString();
setUnixDateOfBirth(pc.readInt());
street = pc.readString();
houseNumber = pc.readString();
bus = pc.readString();
postalCode = pc.readInt();
city = pc.readString();
phone = pc.readString();
rijksRegisterNummer = pc.readString();
bondAansluitingsNr = pc.readString();
bondCodeGerechtigde = pc.readString();
subscribedToNewsletter = pc.readInt() == 1 ? true : false;
}
}
| gpl-2.0 |
carvalhomb/tsmells | tests/Pieces/EagerTest/java/FiveMethodInvocations/src/FooTest.java | 215 | import org.junit.TestCase;
public class FooTest extends TestCase {
Bar bar;
Baz baz;
Fal fal;
Foo foo;
Fuu fuu;
public void testFoo() {
bar.bar();
baz.baz();
fal.fal();
foo.foo();
fuu.fuu();
}
}
| gpl-2.0 |
jackkiexu/tuomatuo | tuomatuo-search/src/main/java/com/lami/tuomatuo/search/base/concurrent/unsafe/CustomerClass.java | 728 | package com.lami.tuomatuo.search.base.concurrent.unsafe;
import lombok.Data;
/**
* Created by xjk on 2016/5/13.
*/
@Data
public class CustomerClass {
private byte byteField = 1;
private short shortField = 2;
private int intField = 3;
private long longField = 6;
private double doubleField = 5.5;
private char charField = 'a';
private String strField = "abc";
private Person person;
public CustomerClass() {}
public CustomerClass(String strField) {
this.strField = strField;
}
@Data
public static class Person{
int id;
String name;
public Person() {
}
public Person(int id) {
this.id = id;
}
}
}
| gpl-2.0 |
shaharyarshamshi/teammates | src/main/java/teammates/common/util/FieldValidator.java | 39328 | package teammates.common.util;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.appengine.api.datastore.Text;
import teammates.common.datatransfer.FeedbackParticipantType;
/**
* Used to handle the data validation aspect e.g. validate emails, names, etc.
*/
public class FieldValidator {
/////////////////
// FIELD TYPES //
/////////////////
// name-related
public static final String PERSON_NAME_FIELD_NAME = "person name";
public static final int PERSON_NAME_MAX_LENGTH = 100;
public static final String NATIONALITY_FIELD_NAME = "nationality";
public static final int NATIONALITY_MAX_LENGTH = 55; // one more than longest official nationality name
public static final String COURSE_NAME_FIELD_NAME = "course name";
public static final int COURSE_NAME_MAX_LENGTH = 64;
public static final String FEEDBACK_SESSION_NAME_FIELD_NAME = "feedback session name";
public static final int FEEDBACK_SESSION_NAME_MAX_LENGTH = 38;
public static final String TEAM_NAME_FIELD_NAME = "team name";
public static final int TEAM_NAME_MAX_LENGTH = 60;
public static final String SECTION_NAME_FIELD_NAME = "section name";
public static final int SECTION_NAME_MAX_LENGTH = 60;
public static final String INSTITUTE_NAME_FIELD_NAME = "institute name";
public static final int INSTITUTE_NAME_MAX_LENGTH = 64;
// email-related
public static final String EMAIL_FIELD_NAME = "email";
public static final int EMAIL_MAX_LENGTH = 254;
public static final String EMAIL_SUBJECT_FIELD_NAME = "email subject";
public static final int EMAIL_SUBJECT_MAX_LENGTH = 200;
public static final String EMAIL_CONTENT_FIELD_NAME = "email content";
public static final String EMAIL_CONTENT_ERROR_MESSAGE = EMAIL_CONTENT_FIELD_NAME + " should not be empty.";
// others
public static final String STUDENT_ROLE_COMMENTS_FIELD_NAME = "comments about a student enrolled in a course";
public static final int STUDENT_ROLE_COMMENTS_MAX_LENGTH = 500;
/*
* =======================================================================
* Field: Course ID
* Unique: system-wide, not just among the course of that instructor.
* Technically, we can get rid of CourseID field and enforce users to use
* CourseName as a unique ID. In that case, we have to enforce CourseName
* must be unique across the full system. However, users expect names to be
* non-unique and more tolerant of enforcing uniqueness on an ID. Whenever
* possible, must be displayed in the same case as user entered. This is
* because the case of the letters can mean something. Furthermore,
* converting to same case can reduce readability.
*
* Course ID is necessary because the course name is not unique enough to
* distinguish between courses because the same course can be offered
* multiple times and courses can be shared between instructors and many
* students. Allowing same Course ID among different instructors could be
* problematic if we allow multiple instructors for a single course.
* TODO: make case insensitive
*/
public static final String COURSE_ID_FIELD_NAME = "course ID";
public static final int COURSE_ID_MAX_LENGTH = 40;
public static final String SESSION_START_TIME_FIELD_NAME = "start time";
public static final String SESSION_END_TIME_FIELD_NAME = "end time";
public static final String TIME_ZONE_FIELD_NAME = "time zone";
public static final String GOOGLE_ID_FIELD_NAME = "Google ID";
public static final int GOOGLE_ID_MAX_LENGTH = 254;
public static final String GENDER_FIELD_NAME = "gender";
public static final String ROLE_FIELD_NAME = "access-level";
public static final List<String> ROLE_ACCEPTED_VALUES =
Collections.unmodifiableList(
Arrays.asList(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER,
Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_MANAGER,
Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_OBSERVER,
Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_TUTOR,
Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_CUSTOM));
public static final String GIVER_TYPE_NAME = "feedback giver";
public static final String RECIPIENT_TYPE_NAME = "feedback recipient";
public static final String VIEWER_TYPE_NAME = "feedback viewer";
////////////////////
// ERROR MESSAGES //
////////////////////
// possible reasons for invalidity
public static final String REASON_EMPTY = "is empty";
public static final String REASON_TOO_LONG = "is too long";
public static final String REASON_INCORRECT_FORMAT = "is not in the correct format";
public static final String REASON_CONTAINS_INVALID_CHAR = "contains invalid characters";
public static final String REASON_START_WITH_NON_ALPHANUMERIC_CHAR = "starts with a non-alphanumeric character";
public static final String REASON_UNAVAILABLE_AS_CHOICE = "is not available as a choice";
// error message components
public static final String EMPTY_STRING_ERROR_INFO =
"The field '${fieldName}' is empty.";
public static final String ERROR_INFO =
"\"${userInput}\" is not acceptable to TEAMMATES as a/an ${fieldName} because it ${reason}.";
public static final String HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_POSSIBLY_EMPTY =
"The value of a/an ${fieldName} should be no longer than ${maxLength} characters.";
public static final String HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY =
HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_POSSIBLY_EMPTY + " It should not be empty.";
public static final String HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY_NO_SPACES =
"It cannot be longer than ${maxLength} characters, cannot be empty and cannot contain spaces.";
public static final String HINT_FOR_CORRECT_FORMAT_FOR_INVALID_NAME =
"A/An ${fieldName} must start with an alphanumeric character, and cannot contain any vertical bar "
+ "(|) or percent sign (%).";
// generic (i.e., not specific to any field) error messages
public static final String SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY;
public static final String SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE_EMPTY_STRING =
EMPTY_STRING_ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY;
public static final String SIZE_CAPPED_POSSIBLY_EMPTY_STRING_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_POSSIBLY_EMPTY;
public static final String INVALID_NAME_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_FOR_INVALID_NAME;
public static final String WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE =
"The provided ${fieldName} is not acceptable to TEAMMATES as it contains only whitespace "
+ "or contains extra spaces at the beginning or at the end of the text.";
public static final String NON_HTML_FIELD_ERROR_MESSAGE =
SanitizationHelper.sanitizeForHtml("The provided ${fieldName} is not acceptable to TEAMMATES "
+ "as it cannot contain the following special html characters"
+ " in brackets: (< > \" / ' &)");
public static final String NON_NULL_FIELD_ERROR_MESSAGE =
"The provided ${fieldName} is not acceptable to TEAMMATES as it cannot be empty.";
// field-specific error messages
public static final String HINT_FOR_CORRECT_EMAIL =
"An email address contains some text followed by one '@' sign followed by some more text. "
+ HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY_NO_SPACES;
public static final String EMAIL_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_EMAIL;
public static final String EMAIL_ERROR_MESSAGE_EMPTY_STRING =
EMPTY_STRING_ERROR_INFO + " " + HINT_FOR_CORRECT_EMAIL;
public static final String HINT_FOR_CORRECT_COURSE_ID =
"A course ID can contain letters, numbers, fullstops, hyphens, underscores, and dollar signs. "
+ HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY_NO_SPACES;
public static final String COURSE_ID_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_COURSE_ID;
public static final String COURSE_ID_ERROR_MESSAGE_EMPTY_STRING =
EMPTY_STRING_ERROR_INFO + " " + HINT_FOR_CORRECT_COURSE_ID;
public static final String HINT_FOR_CORRECT_FORMAT_OF_GOOGLE_ID =
"A Google ID must be a valid id already registered with Google. "
+ HINT_FOR_CORRECT_FORMAT_FOR_SIZE_CAPPED_NON_EMPTY_NO_SPACES;
public static final String GOOGLE_ID_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_OF_GOOGLE_ID;
public static final String GOOGLE_ID_ERROR_MESSAGE_EMPTY_STRING =
EMPTY_STRING_ERROR_INFO + " " + HINT_FOR_CORRECT_FORMAT_OF_GOOGLE_ID;
public static final String HINT_FOR_CORRECT_TIME_ZONE =
"The value must be one of the values from the time zone dropdown selector.";
public static final String TIME_ZONE_ERROR_MESSAGE =
ERROR_INFO + " " + HINT_FOR_CORRECT_TIME_ZONE;
public static final String HINT_FOR_CORRECT_GRACE_PERIOD =
"The value must be one of the options in the grace period dropdown selector.";
public static final String GRACE_PERIOD_NEGATIVE_ERROR_MESSAGE = "Grace period should not be negative." + " "
+ HINT_FOR_CORRECT_GRACE_PERIOD;
public static final String HINT_FOR_CORRECT_NATIONALITY =
"The value must be one of the values from the nationality dropdown selector.";
public static final String NATIONALITY_ERROR_MESSAGE =
"\"%s\" is not an accepted " + NATIONALITY_FIELD_NAME + " to TEAMMATES. "
+ HINT_FOR_CORRECT_NATIONALITY;
public static final String ROLE_ERROR_MESSAGE =
"\"%s\" is not an accepted " + ROLE_FIELD_NAME + " to TEAMMATES. ";
public static final String SESSION_VISIBLE_TIME_FIELD_NAME = "time when the session will be visible";
public static final String RESULTS_VISIBLE_TIME_FIELD_NAME = "time when the results will be visible";
public static final String TIME_FRAME_ERROR_MESSAGE =
"The %s for this feedback session cannot be earlier than the %s.";
public static final String PARTICIPANT_TYPE_ERROR_MESSAGE = "%s is not a valid %s.";
public static final String PARTICIPANT_TYPE_TEAM_ERROR_MESSAGE =
"The feedback recipients cannot be \"%s\" when the feedback giver is \"%s\". "
+ "Did you mean to use \"Self\" instead?";
///////////////////////////////////////
// VALIDATION REGEX FOR INTERNAL USE //
///////////////////////////////////////
/**
* Must start with alphanumeric character, cannot contain vertical bar(|) or percent sign(%).
*/
public static final String REGEX_NAME = "^[\\p{IsL}\\p{IsN}][^|%]*+$";
/**
* Allows English alphabet, numbers, underscore, dot, dollar sign and hyphen.
*/
public static final String REGEX_COURSE_ID = "[a-zA-Z0-9_.$-]+";
/**
* A normal course ID followed by the word '-demo' and then followed any amount of digits.
*/
public static final String REGEX_SAMPLE_COURSE_ID = REGEX_COURSE_ID + "-demo\\d*";
/**
* Local part:
* <li>Can only start with letters, digits, hyphen or plus sign;
* <li>Special characters allowed are ! # $ % & ' * + - / = ? ^ _ ` { } ~
* <li>Dot can only appear between any 2 characters and cannot appear continuously<br>
* Domain part:
* <li>Only allow letters, digits, hyphen and dot; Must end with letters
*/
public static final String REGEX_EMAIL = "^[\\w+-][\\w+!#$%&'*/=?^_`{}~-]*+(\\.[\\w+!#$%&'*/=?^_`{}~-]+)*+"
+ "@([A-Za-z0-9-]+\\.)*[A-Za-z]+$";
/**
* Allows English alphabet, numbers, underscore, dot and hyphen.
*/
public static final String REGEX_GOOGLE_ID_NON_EMAIL = "[a-zA-Z0-9_.-]+";
/*
* =======================================================================
* Regex used for checking header column name in enroll lines
*/
public static final List<String> REGEX_COLUMN_SECTION = Collections.unmodifiableList(
Arrays.asList(
new String[] {"sections?", "sect?", "courses?\\s+sec(tion)?s?"}));
public static final List<String> REGEX_COLUMN_TEAM = Collections.unmodifiableList(
Arrays.asList(
new String[] {
"teams?", "groups?", "students?\\s+teams?", "students?\\s+groups?", "courses?\\s+teams?"
}));
public static final List<String> REGEX_COLUMN_NAME = Collections.unmodifiableList(
Arrays.asList(
new String[] {"names?", "students?\\s+names?", "full\\s+names?", "students?\\s+full\\s+names?"}));
public static final List<String> REGEX_COLUMN_EMAIL = Collections.unmodifiableList(
Arrays.asList(
new String[] {
"emails?", "mails?", "e-mails?", "e\\s+mails?", "emails?\\s+address(es)?",
"e-mails?\\s+address(es)?", "contacts?"
}));
public static final List<String> REGEX_COLUMN_COMMENT = Collections.unmodifiableList(
Arrays.asList(
new String[] {"comments?", "notes?"}));
/////////////////////////////////////////
// VALIDATION METHODS FOR EXTERNAL USE //
/////////////////////////////////////////
/**
* Checks if {@code emailContent} is not null and not empty.
* @return An explanation of why the {@code emailContent} is not acceptable.
* Returns an empty string if the {@code emailContent} is acceptable.
*/
public String getInvalidityInfoForEmailContent(Text emailContent) {
Assumption.assertNotNull("Non-null value expected", emailContent);
if (emailContent.getValue().isEmpty()) {
return EMAIL_CONTENT_ERROR_MESSAGE;
}
return "";
}
/**
* Checks if {@code emailSubject} is a non-null non-empty string no longer than the specified length
* {@code EMAIL_SUBJECT_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code emailSubject} is not acceptable.
* Returns an empty string if the {@code emailSubject} is acceptable.
*/
public String getInvalidityInfoForEmailSubject(String emailSubject) {
return getValidityInfoForAllowedName(
EMAIL_SUBJECT_FIELD_NAME, EMAIL_SUBJECT_MAX_LENGTH, emailSubject);
}
/**
* Checks if {@code email} is not null, not empty, not longer than {@code EMAIL_MAX_LENGTH}, and is a
* valid email address according to {@code REGEX_EMAIL}.
* @return An explanation of why the {@code email} is not acceptable.
* Returns an empty string if the {@code email} is acceptable.
*/
public String getInvalidityInfoForEmail(String email) {
Assumption.assertNotNull("Non-null value expected", email);
String sanitizedValue = SanitizationHelper.sanitizeForHtml(email);
if (email.isEmpty()) {
return getPopulatedEmptyStringErrorMessage(EMAIL_ERROR_MESSAGE_EMPTY_STRING, EMAIL_FIELD_NAME,
EMAIL_MAX_LENGTH);
} else if (isUntrimmed(email)) {
return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", EMAIL_FIELD_NAME);
} else if (email.length() > EMAIL_MAX_LENGTH) {
return getPopulatedErrorMessage(EMAIL_ERROR_MESSAGE, sanitizedValue, EMAIL_FIELD_NAME,
REASON_TOO_LONG, EMAIL_MAX_LENGTH);
} else if (!StringHelper.isMatching(email, REGEX_EMAIL)) {
return getPopulatedErrorMessage(EMAIL_ERROR_MESSAGE, sanitizedValue, EMAIL_FIELD_NAME,
REASON_INCORRECT_FORMAT, EMAIL_MAX_LENGTH);
}
return "";
}
/**
* Checks if {@code gracePeriod} is not negative.
* @return An explanation why the {@code gracePeriod} is not acceptable.
* Returns an empty string if the {@code gracePeriod} is acceptable.
*/
public String getInvalidityInfoForGracePeriod(Duration gracePeriod) {
if (gracePeriod.isNegative()) {
return GRACE_PERIOD_NEGATIVE_ERROR_MESSAGE;
}
return "";
}
/**
* Checks if {@code googleId} is not null, not empty, not longer than {@code GOOGLE_ID_MAX_LENGTH}, does
* not contain any invalid characters (| or %), AND is either a Google username (without the "@gmail.com")
* or a valid email address that does not end in "@gmail.com".
* @return An explanation of why the {@code googleId} is not acceptable.
* Returns an empty string if the {@code googleId} is acceptable.
*/
public String getInvalidityInfoForGoogleId(String googleId) {
Assumption.assertNotNull("Non-null value expected", googleId);
Assumption.assertTrue("\"" + googleId + "\"" + "is not expected to be a gmail address.",
!googleId.toLowerCase().endsWith("@gmail.com"));
String sanitizedValue = SanitizationHelper.sanitizeForHtml(googleId);
boolean isValidFullEmail = StringHelper.isMatching(googleId, REGEX_EMAIL);
boolean isValidEmailWithoutDomain = StringHelper.isMatching(googleId, REGEX_GOOGLE_ID_NON_EMAIL);
if (googleId.isEmpty()) {
return getPopulatedEmptyStringErrorMessage(GOOGLE_ID_ERROR_MESSAGE_EMPTY_STRING,
GOOGLE_ID_FIELD_NAME, GOOGLE_ID_MAX_LENGTH);
} else if (isUntrimmed(googleId)) {
return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", GOOGLE_ID_FIELD_NAME);
} else if (googleId.length() > GOOGLE_ID_MAX_LENGTH) {
return getPopulatedErrorMessage(GOOGLE_ID_ERROR_MESSAGE, sanitizedValue, GOOGLE_ID_FIELD_NAME,
REASON_TOO_LONG, GOOGLE_ID_MAX_LENGTH);
} else if (!(isValidFullEmail || isValidEmailWithoutDomain)) {
return getPopulatedErrorMessage(GOOGLE_ID_ERROR_MESSAGE, sanitizedValue, GOOGLE_ID_FIELD_NAME,
REASON_INCORRECT_FORMAT, GOOGLE_ID_MAX_LENGTH);
}
return "";
}
/**
* Checks if {@code courseId} is not null, not empty, has no surrounding whitespaces, not longer than
* {@code COURSE_ID_MAX_LENGTH}, is sanitized for HTML, and match the REGEX {@code REGEX_COURSE_ID}.
* @return An explanation of why the {@code courseId} is not acceptable.
* Returns an empty string if the {@code courseId} is acceptable.
*/
public String getInvalidityInfoForCourseId(String courseId) {
Assumption.assertNotNull("Non-null value expected", courseId);
if (courseId.isEmpty()) {
return getPopulatedEmptyStringErrorMessage(COURSE_ID_ERROR_MESSAGE_EMPTY_STRING,
COURSE_ID_FIELD_NAME, COURSE_ID_MAX_LENGTH);
}
if (isUntrimmed(courseId)) {
return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}",
COURSE_NAME_FIELD_NAME);
}
String sanitizedValue = SanitizationHelper.sanitizeForHtml(courseId);
if (courseId.length() > COURSE_ID_MAX_LENGTH) {
return getPopulatedErrorMessage(COURSE_ID_ERROR_MESSAGE, sanitizedValue, COURSE_ID_FIELD_NAME,
REASON_TOO_LONG, COURSE_ID_MAX_LENGTH);
}
if (!StringHelper.isMatching(courseId, REGEX_COURSE_ID)) {
return getPopulatedErrorMessage(COURSE_ID_ERROR_MESSAGE, sanitizedValue, COURSE_ID_FIELD_NAME,
REASON_INCORRECT_FORMAT, COURSE_ID_MAX_LENGTH);
}
return "";
}
/**
* Checks if {@code sectionName} is a non-null non-empty string no longer than the specified length
* {@code SECTION_NAME_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code sectionName} is not acceptable.
* Returns an empty string if the {@code sectionName} is acceptable.
*/
public String getInvalidityInfoForSectionName(String sectionName) {
return getValidityInfoForAllowedName(SECTION_NAME_FIELD_NAME, SECTION_NAME_MAX_LENGTH, sectionName);
}
/**
* Checks if {@code teamName} is a non-null non-empty string no longer than the specified length
* {@code TEAM_NAME_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code teamName} is not acceptable.
* Returns an empty string if the {@code teamName} is acceptable.
*/
public String getInvalidityInfoForTeamName(String teamName) {
return getValidityInfoForAllowedName(TEAM_NAME_FIELD_NAME, TEAM_NAME_MAX_LENGTH, teamName);
}
/**
* Checks if the given studentRoleComments is a non-null string no longer than
* the specified length {@code STUDENT_ROLE_COMMENTS_MAX_LENGTH}. However, this string can be empty.
* @return An explanation of why the {@code studentRoleComments} is not acceptable.
* Returns an empty string "" if the {@code studentRoleComments} is acceptable.
*/
public String getInvalidityInfoForStudentRoleComments(String studentRoleComments) {
return getValidityInfoForSizeCappedPossiblyEmptyString(STUDENT_ROLE_COMMENTS_FIELD_NAME,
STUDENT_ROLE_COMMENTS_MAX_LENGTH,
studentRoleComments);
}
/**
* Checks if {@code feedbackSessionName} is a non-null non-empty string no longer than the specified length
* {@code FEEDBACK_SESSION_NAME_MAX_LENGTH}, does not contain any invalid characters (| or %), and has no
* unsanitized HTML characters.
* @return An explanation of why the {@code feedbackSessionName} is not acceptable.
* Returns an empty string if the {@code feedbackSessionName} is acceptable.
*/
public String getInvalidityInfoForFeedbackSessionName(String feedbackSessionName) {
String errorsFromAllowedNameValidation = getValidityInfoForAllowedName(
FEEDBACK_SESSION_NAME_FIELD_NAME, FEEDBACK_SESSION_NAME_MAX_LENGTH, feedbackSessionName);
// return early if error already exists because session name is too long etc.
if (!errorsFromAllowedNameValidation.isEmpty()) {
return errorsFromAllowedNameValidation;
}
// checks for unsanitized HTML characters
return getValidityInfoForNonHtmlField(FEEDBACK_SESSION_NAME_FIELD_NAME, feedbackSessionName);
}
/**
* Checks if {@code courseName} is a non-null non-empty string no longer than the specified length
* {@code COURSE_NAME_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code courseName} is not acceptable.
* Returns an empty string if the {@code courseName} is acceptable.
*/
public String getInvalidityInfoForCourseName(String courseName) {
return getValidityInfoForAllowedName(COURSE_NAME_FIELD_NAME, COURSE_NAME_MAX_LENGTH, courseName);
}
/**
* Checks if {@code nationality} is a non-null non-empty string contained in the {@link NationalityHelper}'s
* list of nationalities.
* @return An explanation of why the {@code nationality} is not acceptable.
* Returns an empty string if the {@code nationality} is acceptable.
*/
public String getInvalidityInfoForNationality(String nationality) {
Assumption.assertNotNull("Non-null value expected", nationality);
if (!NationalityHelper.getNationalities().contains(nationality)) {
return String.format(NATIONALITY_ERROR_MESSAGE, SanitizationHelper.sanitizeForHtml(nationality));
}
return "";
}
/**
* Checks if {@code instituteName} is a non-null non-empty string no longer than the specified length
* {@code INSTITUTE_NAME_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code instituteName} is not acceptable.
* Returns an empty string if the {@code instituteName} is acceptable.
*/
public String getInvalidityInfoForInstituteName(String instituteName) {
return getValidityInfoForAllowedName(INSTITUTE_NAME_FIELD_NAME, INSTITUTE_NAME_MAX_LENGTH,
instituteName);
}
/**
* Checks if {@code personName} is a non-null non-empty string no longer than the specified length
* {@code PERSON_NAME_MAX_LENGTH}, and also does not contain any invalid characters (| or %).
* @return An explanation of why the {@code personName} is not acceptable.
* Returns an empty string if the {@code personName} is acceptable.
*/
public String getInvalidityInfoForPersonName(String personName) {
return getValidityInfoForAllowedName(PERSON_NAME_FIELD_NAME, PERSON_NAME_MAX_LENGTH, personName);
}
/**
* Checks if the given string is a non-null string contained in Java's list of
* regional time zone IDs.
* @return An explanation of why the {@code timeZoneValue} is not acceptable.
* Returns an empty string if the {@code timeZoneValue} is acceptable.
*/
public String getInvalidityInfoForTimeZone(String timeZoneValue) {
Assumption.assertNotNull("Non-null value expected", timeZoneValue);
if (!ZoneId.getAvailableZoneIds().contains(timeZoneValue)) {
String sanitizedValue = SanitizationHelper.sanitizeForHtml(timeZoneValue);
return getPopulatedErrorMessage(TIME_ZONE_ERROR_MESSAGE,
sanitizedValue, TIME_ZONE_FIELD_NAME, REASON_UNAVAILABLE_AS_CHOICE);
}
return "";
}
/**
* Checks if {@code role} is one of the recognized roles {@link #ROLE_ACCEPTED_VALUES}.
*
* @return An explanation of why the {@code role} is not acceptable.
* Returns an empty string if the {@code role} is acceptable.
*/
public String getInvalidityInfoForRole(String role) {
Assumption.assertNotNull("Non-null value expected", role);
String sanitizedValue = SanitizationHelper.sanitizeForHtml(role);
if (!ROLE_ACCEPTED_VALUES.contains(role)) {
return String.format(ROLE_ERROR_MESSAGE, sanitizedValue);
}
return "";
}
/**
* Checks if the given name (including person name, institute name, course name, feedback session and team name)
* is a non-null non-empty string no longer than the specified length {@code maxLength},
* and also does not contain any invalid characters (| or %).
*
* @param fieldName
* A descriptive name of the field e.g., "student name", to be
* used in the return value to make the explanation more
* descriptive.
* @param value
* The string to be checked.
* @return An explanation of why the {@code value} is not acceptable.
* Returns an empty string "" if the {@code value} is acceptable.
*/
public String getValidityInfoForAllowedName(String fieldName, int maxLength, String value) {
Assumption.assertNotNull("Non-null value expected for " + fieldName, value);
if (value.isEmpty()) {
return getPopulatedEmptyStringErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE_EMPTY_STRING,
fieldName, maxLength);
}
if (isUntrimmed(value)) {
return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", fieldName);
}
String sanitizedValue = SanitizationHelper.sanitizeForHtml(value);
if (value.length() > maxLength) {
return getPopulatedErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, sanitizedValue,
fieldName, REASON_TOO_LONG, maxLength);
}
if (!Character.isLetterOrDigit(value.codePointAt(0))) {
boolean hasStartingBrace = value.charAt(0) == '{' && value.contains("}");
if (!hasStartingBrace) {
return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue,
fieldName, REASON_START_WITH_NON_ALPHANUMERIC_CHAR);
}
if (!StringHelper.isMatching(value.substring(1), REGEX_NAME)) {
return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName,
REASON_CONTAINS_INVALID_CHAR);
}
return "";
}
if (!StringHelper.isMatching(value, REGEX_NAME)) {
return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName,
REASON_CONTAINS_INVALID_CHAR);
}
return "";
}
/**
* Checks if the given string is a non-null string no longer than
* the specified length {@code maxLength}. However, this string can be empty.
*
* @param fieldName
* A descriptive name of the field e.g., "student name", to be
* used in the return value to make the explanation more
* descriptive.
* @param value
* The string to be checked.
* @return An explanation of why the {@code value} is not acceptable.
* Returns an empty string "" if the {@code value} is acceptable.
*/
public String getValidityInfoForSizeCappedPossiblyEmptyString(String fieldName, int maxLength, String value) {
Assumption.assertNotNull("Non-null value expected for " + fieldName, value);
if (isUntrimmed(value)) {
return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", fieldName);
}
if (value.length() > maxLength) {
String sanitizedValue = SanitizationHelper.sanitizeForHtml(value);
return getPopulatedErrorMessage(SIZE_CAPPED_POSSIBLY_EMPTY_STRING_ERROR_MESSAGE, sanitizedValue,
fieldName, REASON_TOO_LONG, maxLength);
}
return "";
}
/**
* Checks if Session Start Time is before Session End Time.
* @return Error string if {@code sessionStart} is before {@code sessionEnd}
* Empty string if {@code sessionStart} is after {@code sessionEnd}
*/
public String getInvalidityInfoForTimeForSessionStartAndEnd(Instant sessionStart, Instant sessionEnd) {
return getInvalidityInfoForFirstTimeIsBeforeSecondTime(
sessionStart, sessionEnd, SESSION_START_TIME_FIELD_NAME, SESSION_END_TIME_FIELD_NAME);
}
/**
* Checks if Session Visibility Start Time is before Session Start Time.
* @return Error string if {@code visibilityStart} is before {@code sessionStart}
* Empty string if {@code visibilityStart} is after {@code sessionStart}
*/
public String getInvalidityInfoForTimeForVisibilityStartAndSessionStart(
Instant visibilityStart, Instant sessionStart) {
return getInvalidityInfoForFirstTimeIsBeforeSecondTime(
visibilityStart, sessionStart, SESSION_VISIBLE_TIME_FIELD_NAME, SESSION_START_TIME_FIELD_NAME);
}
/**
* Checks if Visibility Start Time is before Results Publish Time.
* @return Error string if {@code visibilityStart} is before {@code resultsPublish}
* Empty string if {@code visibilityStart} is after {@code resultsPublish}
*/
public String getInvalidityInfoForTimeForVisibilityStartAndResultsPublish(
Instant visibilityStart, Instant resultsPublish) {
return getInvalidityInfoForFirstTimeIsBeforeSecondTime(visibilityStart, resultsPublish,
SESSION_VISIBLE_TIME_FIELD_NAME, RESULTS_VISIBLE_TIME_FIELD_NAME);
}
private String getInvalidityInfoForFirstTimeIsBeforeSecondTime(
Instant earlierTime, Instant laterTime, String earlierTimeFieldName, String laterTimeFieldName) {
Assumption.assertNotNull("Non-null value expected", earlierTime);
Assumption.assertNotNull("Non-null value expected", laterTime);
if (TimeHelper.isSpecialTime(earlierTime) || TimeHelper.isSpecialTime(laterTime)) {
return "";
}
if (laterTime.isBefore(earlierTime)) {
return String.format(TIME_FRAME_ERROR_MESSAGE, laterTimeFieldName, earlierTimeFieldName);
}
return "";
}
public List<String> getValidityInfoForFeedbackParticipantType(
FeedbackParticipantType giverType, FeedbackParticipantType recipientType) {
Assumption.assertNotNull("Non-null value expected", giverType);
Assumption.assertNotNull("Non-null value expected", recipientType);
List<String> errors = new LinkedList<>();
if (!giverType.isValidGiver()) {
errors.add(String.format(PARTICIPANT_TYPE_ERROR_MESSAGE, giverType.toString(), GIVER_TYPE_NAME));
}
if (!recipientType.isValidRecipient()) {
errors.add(String.format(PARTICIPANT_TYPE_ERROR_MESSAGE, recipientType.toString(), RECIPIENT_TYPE_NAME));
}
if (giverType == FeedbackParticipantType.TEAMS
&& (recipientType == FeedbackParticipantType.OWN_TEAM
|| recipientType == FeedbackParticipantType.OWN_TEAM_MEMBERS)) {
errors.add(String.format(PARTICIPANT_TYPE_TEAM_ERROR_MESSAGE,
recipientType.toDisplayRecipientName(),
giverType.toDisplayGiverName()));
}
return errors;
}
public List<String> getValidityInfoForFeedbackResponseVisibility(
List<FeedbackParticipantType> showResponsesTo,
List<FeedbackParticipantType> showGiverNameTo,
List<FeedbackParticipantType> showRecipientNameTo) {
Assumption.assertNotNull("Non-null value expected", showResponsesTo);
Assumption.assertNotNull("Non-null value expected", showGiverNameTo);
Assumption.assertNotNull("Non-null value expected", showRecipientNameTo);
Assumption.assertTrue("Non-null value expected", !showResponsesTo.contains(null));
Assumption.assertTrue("Non-null value expected", !showGiverNameTo.contains(null));
Assumption.assertTrue("Non-null value expected", !showRecipientNameTo.contains(null));
List<String> errors = new LinkedList<>();
for (FeedbackParticipantType type : showGiverNameTo) {
if (!type.isValidViewer()) {
errors.add(String.format(PARTICIPANT_TYPE_ERROR_MESSAGE,
type.toString(), VIEWER_TYPE_NAME));
}
if (!showResponsesTo.contains(type)) {
errors.add("Trying to show giver name to "
+ type.toString()
+ " without showing response first.");
}
}
for (FeedbackParticipantType type : showRecipientNameTo) {
if (!type.isValidViewer()) {
errors.add(String.format(PARTICIPANT_TYPE_ERROR_MESSAGE,
type.toString(), VIEWER_TYPE_NAME));
}
if (!showResponsesTo.contains(type)) {
errors.add("Trying to show recipient name to "
+ type.toString()
+ " without showing response first.");
}
}
for (FeedbackParticipantType type : showResponsesTo) {
if (!type.isValidViewer()) {
errors.add(String.format(PARTICIPANT_TYPE_ERROR_MESSAGE,
type.toString(), VIEWER_TYPE_NAME));
}
}
return errors;
}
public String getValidityInfoForNonHtmlField(String fieldName, String value) {
String sanitizedValue = SanitizationHelper.sanitizeForHtml(value);
//Fails if sanitized value is not same as value
return value.equals(sanitizedValue) ? "" : NON_HTML_FIELD_ERROR_MESSAGE.replace("${fieldName}", fieldName);
}
public String getValidityInfoForNonNullField(String fieldName, Object value) {
return value == null ? NON_NULL_FIELD_ERROR_MESSAGE.replace("${fieldName}", fieldName) : "";
}
public static boolean isUntrimmed(String value) {
return value.length() != value.trim().length();
}
/**
* Checks whether a given text input represents a format of a valid email address.
* @param email text input which needs the validation
* @return true if it is a valid email address, else false.
*/
public static boolean isValidEmailAddress(String email) {
return StringHelper.isMatching(email, REGEX_EMAIL);
}
/**
* Checks whether all the elements in a Collection are unique.
* @param elements The Collection of elements to be checked.
* @return true if all elements are unique, else false.
*/
public static <T> boolean areElementsUnique(Collection<T> elements) {
Set<T> uniqueElements = new HashSet<>(elements);
return uniqueElements.size() == elements.size();
}
public static String getPopulatedErrorMessage(
String messageTemplate, String userInput, String fieldName, String errorReason, int maxLength) {
return getPopulatedErrorMessage(messageTemplate, userInput, fieldName, errorReason)
.replace("${maxLength}", String.valueOf(maxLength));
}
private static String getPopulatedErrorMessage(
String messageTemplate, String userInput, String fieldName, String errorReason) {
return messageTemplate.replace("${userInput}", userInput)
.replace("${fieldName}", fieldName)
.replace("${reason}", errorReason);
}
public static String getPopulatedEmptyStringErrorMessage(String messageTemplate,
String fieldName, int maxLength) {
return messageTemplate.replace("${fieldName}", fieldName)
.replace("${maxLength}", String.valueOf(maxLength));
}
}
| gpl-2.0 |
sgrosven/gromurph | Javascore/src/main/java/org/gromurph/util/BaseEditor.java | 6469 | // === File Prolog===========================================================
// This code was developed as part of the open source regatta scoring
// program, JavaScore.
//
// Version: $Id: BaseEditor.java,v 1.4 2006/01/15 21:10:34 sandyg Exp $
//
// Copyright Sandy Grosvenor, 2000-2015
// Email sandy@gromurph.org, www.gromurph.org/javascore
//
// OSI Certified Open Source Software (www.opensource.org)
// This software is licensed under the GNU General Public License,
// available at www.opensource.org/licenses/gpl-license.html
// === End File Prolog=======================================================
package org.gromurph.util;
import java.beans.PropertyChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* BaseEditor - covering class for Panels that edit things. Keeps a saved version of the object being editted and
* provides support for "restoring" that object.
* <P>
* BaseEditors are designed to be put into parent BaseEditorContainers. The BaseEditor may put toolbar and/or menu items
* into the parent container in their start() and stop() methods. And should rely on the container for
* Save/Restore/Cancel buttons as parent may need
*
**/
public abstract class BaseEditor<T extends BaseObjectModel> extends PanelStartStop implements PropertyChangeListener {
protected Logger logger = LoggerFactory.getLogger( this.getClass());
public static final String EMPTY = "";
public static final String NEWLINE = Util.NEWLINE;
public static final String BLANK = " ";
public static final String PERIOD = ".";
private String fTitle = "";
public String getTitle() {
return fTitle;
}
public void setTitle(String t) {
fTitle = t;
}
/**
* the backup unchanged version of the object being editted
**/
protected T fObjectBackup;
/**
* the current, maybe unsaved, version of object being editted. Subclasses that keep their own version for casting
* purposes should be careful to make sure that the two stay pointed to same object
**/
protected T fObjectCurrent = null;
public BaseEditor(BaseEditorContainer parent) {
super();
//setPreferredSize( new Dimension(
// getInsets().left + getInsets().right + 220,
// getInsets().top + getInsets().bottom + 130));
setEditorParent(parent);
setName(getClass().getName());
}
public void restore() {
if ((fObjectCurrent != null) && (fObjectBackup != null)) {
restore(fObjectCurrent, fObjectBackup);
updateFields();
}
}
/**
* restores the editable fields. It is a subclass's responsibility to keep restore functional at its level
**/
public void restore(T activeM, T backupM) {
try {
BaseObject active = (BaseObject) activeM;
BaseObject backup = (BaseObject) backupM;
active.setLastModified(backup.getLastModified());
active.setCreateDate(backup.getCreateDate());
} catch (ClassCastException e) {
Util.showError(e, true);
} // do nothing
}
/**
* called when the parent dialog closes with an OK
*/
public void exitOK() {}
private boolean doOKOnWindowClose = true;
public void setExitOKonWindowClose(boolean doOK) {
doOKOnWindowClose = doOK;
}
public boolean isExitOKOnWindowClose() {
return doOKOnWindowClose;
}
/**
* called when parent dialog closes after a CANCEL
*/
public void exitCancel() {}
/**
* returns true if backup and current objects are NOT equal
**/
public boolean changesPending() {
if (fObjectCurrent == null && fObjectBackup == null)
return false;
else if (fObjectCurrent == null || fObjectBackup == null)
return true;
else
return !fObjectCurrent.equals(fObjectBackup);
}
/**
* sets the object, dumps the old backup and sets new backup to clone/restore of current object. Child classes will
* usually override this, but should be CAREFUL to not forget to call this parent version
**/
public void setObject(T obj) throws ClassCastException {
if (obj != null) {
fObjectCurrent = obj;
if (fObjectBackup == null) {
try {
fObjectBackup = (T) obj.getClass().newInstance();
} catch (Exception e) {
logger.warn( "unable to make newinstance of object", e);
}
}
if (fObjectBackup != null) {
restore(fObjectBackup, fObjectCurrent);
}
} else {
fObjectCurrent = null;
}
updateFields();
}
public T getObject() {
return fObjectCurrent;
}
protected boolean isStarted = false;
/**
* fired when the editor is about to become active to the user
**/
@Override public void startUp() {
updateFields();
if (!isStarted) {
isStarted = true;
start();
}
}
/**
* fired when the editor is about to become de-active to the user
**/
@Override public void shutDown() {
if (isStarted) {
isStarted = false;
stop();
}
}
BaseEditorContainer fEditorParent;
/**
* sets the parent container holding this BaseEditor
**/
public void setEditorParent(BaseEditorContainer parent) {
if (fEditorParent != null && fEditorParent != parent) {
logger.warn("*** parent change!" + this.getClass().toString());
}
fEditorParent = parent;
if (fEditorParent == null) {
logger.warn("*** NULL Parent" + this.getClass().toString());
}
}
/**
* returns the parent container.
**/
public BaseEditorContainer getEditorParent() {
return fEditorParent;
}
}
/**
* $Log: BaseEditor.java,v $ Revision 1.4 2006/01/15 21:10:34 sandyg resubmit at 5.1.02
*
* Revision 1.2 2006/01/11 02:27:14 sandyg updating copyright years
*
* Revision 1.1 2006/01/01 02:27:02 sandyg preliminary submission to centralize code in a new module
*
* Revision 1.8.4.2 2005/11/26 17:45:15 sandyg implement race weight & nondiscardable, did some gui test cleanups.
*
* Revision 1.8.4.1 2005/11/01 02:36:02 sandyg Java5 update - using generics
*
* Revision 1.8 2004/04/10 20:49:39 sandyg Copyright year update
*
* Revision 1.7 2003/04/27 21:03:30 sandyg lots of cleanup, unit testing for 4.1.1 almost complete
*
* Revision 1.6 2003/03/30 00:05:50 sandyg moved to eclipse 2.1
*
* Revision 1.5 2003/03/19 02:38:17 sandyg made start() stop() abstract to BaseEditor, the isStarted check now done in
* BaseEditor.startUp and BaseEditor.shutDown().
*
* Revision 1.4 2003/01/04 17:53:05 sandyg Prefix/suffix overhaul
*
*/
| gpl-2.0 |
zjg/jedit-CtagsInterface | src/ctagsinterface/jedit/CtagsInterfaceCompletionProvider.java | 1205 | package ctagsinterface.jedit;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.gjt.sp.jedit.Mode;
import org.gjt.sp.jedit.View;
import completion.service.CompletionCandidate;
import completion.service.CompletionProvider;
import ctagsinterface.index.TagIndex;
import ctagsinterface.main.CtagsInterfacePlugin;
import ctagsinterface.main.Tag;
public class CtagsInterfaceCompletionProvider implements CompletionProvider {
@Override
public List<CompletionCandidate> getCompletionCandidates(View view) {
String prefix = CtagsInterfacePlugin.getCompletionPrefix(view);
if (prefix == null)
return null;
final Vector<Tag> tags = getCompletions(view, prefix);
if (tags == null || tags.isEmpty())
return null;
List<CompletionCandidate> candidates = new ArrayList<CompletionCandidate>();
for (Tag t: tags)
candidates.add(new CtagsCompletionCandidate(t));
return candidates;
}
@Override
public Set<Mode> restrictToModes() {
return null;
}
private Vector<Tag> getCompletions(View view, String prefix)
{
String q = TagIndex._NAME_FLD + ":" + prefix + "*";
return CtagsInterfacePlugin.runScopedQuery(view, q);
}
}
| gpl-2.0 |
bensmith87/risk | player/src/main/java/ben/risk/player/mvc/IView.java | 281 | package ben.risk.player.mvc;
/**
* View Interface.
* @param <T> the type of model that the view is for
*/
public interface IView<T extends IModel> {
/**
* The view has been removed and needs to remove its Graph Objects from the Viewport.
*/
void remove();
}
| gpl-2.0 |
52North/SensorPlanningService | 52n-sps-api/src/main/java/org/n52/sps/service/SpsOperator.java | 9610 | /**
* ๏ปฟCopyright (C) 2012-${latestYearOfContribution} 52ยฐNorth Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as publishedby the Free
* Software Foundation.
*
* If the program is linked with libraries which are licensed under one of the
* following licenses, the combination of the program with the linked library is
* not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed under
* the aforementioned licenses, is permitted by the copyright holders if the
* distribution is compliant with both the GNU General Public License version 2
* and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*/
package org.n52.sps.service;
import java.util.List;
import net.opengis.ows.x11.DCPDocument.DCP;
import net.opengis.ows.x11.HTTPDocument;
import net.opengis.ows.x11.OperationDocument.Operation;
import net.opengis.ows.x11.OperationsMetadataDocument.OperationsMetadata;
import net.opengis.sps.x20.CapabilitiesType;
import net.opengis.swes.x20.ExtensibleRequestType;
import org.apache.xmlbeans.XmlObject;
import org.n52.ows.exception.InvalidParameterValueException;
import org.n52.ows.exception.MissingParameterValueException;
import org.n52.ows.exception.OptionNotSupportedException;
import org.n52.ows.exception.OwsException;
import org.n52.ows.exception.OwsExceptionReport;
import org.n52.ows.service.binding.HttpBinding;
import org.n52.oxf.swes.exception.RequestExtensionNotSupportedException;
import org.n52.sps.sensor.NonBlockingTaskingDecorator;
import org.n52.sps.sensor.SensorPlugin;
import org.n52.sps.sensor.model.SensorTask;
import org.n52.sps.service.core.SensorInstanceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SpsOperator {
private static final Logger LOGGER = LoggerFactory.getLogger(SpsOperator.class);
private SensorInstanceProvider sensorInstanceProvider;
protected SensorTask getSensorTask(String sensorTaskId) throws OwsException {
if (!sensorInstanceProvider.containsTaskWith(sensorTaskId)) {
handleInvalidParameter("task", sensorTaskId);
}
return sensorInstanceProvider.getTaskForTaskId(sensorTaskId);
}
/**
* Gets the sensor instance for a given procedure. If the procedure is not known to the service an
* {@link InvalidParameterValueException} is thrown as required by the SPS specification.<br/>
* <br/>
* To avoid a freezing framework when a sensor instance gets stuck executing (tasking) requests the
* returned {@link SensorPlugin} instance is decorated to enable non blocking execution via a
* {@link NonBlockingTaskingDecorator}.
*
* @param procedure
* the <code>procedure</code> to lookup SensorPlugin instance for.
* @return the SensorPlugin instance associated with the given <code>procedure</code>
* @throws InvalidParameterValueException
* if no SensorPlugin instance could be found (according to REQ 4: <a
* href="http://www.opengis.net/spec/SPS/2.0/req/exceptions/UnknownIdentifier"
* >http://www.opengis.net/spec/SPS/2.0/req/exceptions/UnknownIdentifier</a>)
* @throws MissingParameterValueException
* if an empty procedure parameter was given (according to REQ 4: <a
* href="http://www.opengis.net/spec/SWES/2.0/req/SOAP/Fault/MissingParameterValueException"
* >http://www.opengis.net/spec/SWES/2.0/req/SOAP/Fault/MissingParameterValueException</a>)
*/
public SensorPlugin getSensorInstance(String procedure) throws OwsException {
if (!sensorInstanceProvider.containsSensorWith(procedure)) {
handleInvalidParameter("procedure", procedure);
}
SensorPlugin sensorPlugin = sensorInstanceProvider.getSensorForProcedure(procedure);
return NonBlockingTaskingDecorator.enableNonBlockingTasking(sensorPlugin);
}
private void handleInvalidParameter(String locator, String parameter) throws MissingParameterValueException, InvalidParameterValueException {
if (isParameterValueMissing(parameter)) {
LOGGER.info("Task parameter is missing.");
throwNewMissingParamterValueException(locator);
} else {
LOGGER.info("Invalid parameter: {}", parameter);
throwNewInvalidParameterValueException(locator, parameter);
}
}
protected boolean isParameterValueMissing(String parameter) {
return parameter == null || parameter.isEmpty();
}
protected void throwNewMissingParamterValueException(String locator, String... messages) throws MissingParameterValueException {
MissingParameterValueException e = new MissingParameterValueException(locator);
e.addExceptionText(String.format("The %s paramter is missing.", locator));
addDetailedMessagesToOwsException(e, messages);
throw e;
}
protected void throwNewInvalidParameterValueException(String locator, String parameterValue, String... messages) throws InvalidParameterValueException {
InvalidParameterValueException e = new InvalidParameterValueException(locator);
e.addExceptionText(String.format("'%s' is unknown.", parameterValue));
addDetailedMessagesToOwsException(e, messages);
throw e;
}
protected void throwNewOptionNotSupportedException(String locator, String... messages) throws OptionNotSupportedException {
OptionNotSupportedException e = new OptionNotSupportedException(locator);
addDetailedMessagesToOwsException(e, messages);
throw e;
}
private void addDetailedMessagesToOwsException(OwsException e, String[] messages) {
for (String message : messages) {
e.addExceptionText(message);
}
}
public SensorInstanceProvider getSensorInstanceProvider() {
return this.sensorInstanceProvider;
}
public void setSensorInstanceProvider(SensorInstanceProvider sensorInstanceProvider) {
this.sensorInstanceProvider = sensorInstanceProvider;
}
protected OperationsMetadata getOperationsMetadata(CapabilitiesType capabilities) {
OperationsMetadata operationsMetadata = capabilities.getOperationsMetadata();
if (operationsMetadata == null) {
operationsMetadata = capabilities.addNewOperationsMetadata();
}
return operationsMetadata;
}
/**
* @param operation
* the operation for which to add each binding
* @param httpBindings
* all bindings supported by the service.
*/
protected void addSupportedBindings(Operation operation, List<HttpBinding> httpBindings) {
for (HttpBinding httpBinding : httpBindings) {
addDcpBinding(operation, httpBinding);
}
}
protected void addDcpBinding(Operation operation, HttpBinding httpBinding) {
HTTPDocument httpInfo = httpBinding.getHttpInfo();
addDistributedComputingPlatform(operation, httpInfo);
}
protected void addDcpExtensionBinding(Operation operation, HttpBinding httpBinding, String resource) {
HTTPDocument httpInfo = httpBinding.getHttpInfo(resource);
addDistributedComputingPlatform(operation, httpInfo);
}
private void addDistributedComputingPlatform(Operation operation, HTTPDocument httpInfo) {
DCP distributedComputingPlatform = operation.addNewDCP();
distributedComputingPlatform.setHTTP(httpInfo.getHTTP());
}
/**
* @return <code>true</code> if the implementing operator supports extension(s), <code>false</code>
* otherwise.
*/
public abstract boolean isSupportingExtensions();
/**
* Checks if the passed extension array is supported. For each unsupported extension found, a
* {@link RequestExtensionNotSupportedException} is added to an {@link OwsExceptionReport} which
* is thrown at the end.
*
* @param extensions
* the extensions to check.
* @throws OwsExceptionReport
* if there are unsupported extensions.
*/
protected abstract void checkSupportingSpsRequestExtensions(XmlObject[] extensions) throws OwsExceptionReport;
/**
* Checks if the passed extension array is supported. If a not supported extension is found, a
* {@link RequestExtensionNotSupportedException} is added to the given {@link OwsExceptionReport}
*
* @param extensibleRequest
* the extensible request.
* @throws OwsExceptionReport
* if there are unsupported extensions.
*/
protected abstract void checkSupportingSwesRequestExtensions(ExtensibleRequestType extensibleRequest) throws OwsExceptionReport;
}
| gpl-2.0 |
christianchristensen/resin | modules/resin/src/com/caucho/jms/connection/QueueConnectionImpl.java | 2621 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.jms.connection;
import javax.jms.ConnectionConsumer;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.XAQueueConnection;
import javax.jms.QueueSession;
import javax.jms.XAQueueSession;
import javax.jms.ServerSessionPool;
/**
* A sample queue connection factory.
*/
public class QueueConnectionImpl extends ConnectionImpl
implements XAQueueConnection
{
/**
* Create a new queue connection.
*/
public QueueConnectionImpl(ConnectionFactoryImpl factory, boolean isXA)
{
super(factory, isXA);
}
/**
* Create a new queue connection.
*/
public QueueConnectionImpl(ConnectionFactoryImpl factory)
{
super(factory);
}
/**
* Creates a new consumer (optional)
*/
public ConnectionConsumer
createConnectionConsumer(Queue queue, String messageSelector,
ServerSessionPool sessionPool, int maxMessages)
throws JMSException
{
throw new UnsupportedOperationException();
}
/**
* Creates a new connection session.
*/
public QueueSession createQueueSession(boolean transacted,
int acknowledgeMode)
throws JMSException
{
checkOpen();
assignClientID();
return new QueueSessionImpl(this, transacted, acknowledgeMode, isXA());
}
/**
* Creates a new connection session.
*/
public XAQueueSession createXAQueueSession()
throws JMSException
{
checkOpen();
assignClientID();
return new QueueSessionImpl(this, true, 0, true);
}
}
| gpl-2.0 |
gcoulby/MVCCalc | src/controller/CalculatorController.java | 6479 | package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.CalculatorModel;
import view.CalculatorView;
/**
* @author Apalis
* @version 0.7
*/
public class CalculatorController
{
private view.CalculatorView theView;
private model.CalculatorModel theModel;
private int equalsCount = 0;
/**
* Constructor for CalculatorController Class
*
* @param theView
* : The view class (GUI)
* @param theModel
* : The model class (functionality)
*/
public CalculatorController(CalculatorView theView, CalculatorModel theModel)
{
this.theView = theView;
this.theModel = theModel;
this.theView.addNumberListener(new NumberListener());
this.theView.addOperatorListener(new OperatorListener());
this.theView.addCalculateListener(new CalculateListener());
this.theView.addClearListener(new ClearListener());
this.theView.addMemoryListener(new MemoryListener());
this.theView.addNegListener(new NegListener());
this.theView.addSquareListener(new SquareListener());
this.theView.addPercListener(new PercentageListener());
}
/**
* Listener for the number buttons
*/
class NumberListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (equalsCount > 0)
{
equalsCount = 0;
theModel.needsReset = true;
}
String clicked = ((JButton) e.getSource()).getText();
theView.appendToInputField(clicked, theModel.needsReset);
theModel.needsReset = false;
}
}
/**
* Listener for the operator buttons
*/
// TODO control how the repetition works with operation of final total i.e
// =,=,=,= + 5 = n
class OperatorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String clicked = ((JButton) e.getSource()).getText();
theModel.setOperation(clicked);
theModel.needsReset = true;
String inputValue = theView.getInputFieldValue();
double doubleValue = getFieldValueAsDouble(inputValue);
theView.setFirstNumber(doubleValue);
}
}
/**
* Listener for the equals button
*/
// TODO modify how the repetition works with minus numbers
// TODO REPETITION DOESN'T WORK WITH MINUS
class CalculateListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (equalsCount == 0)
{
String inputValue = theView.getInputFieldValue();
double doubleValue = getFieldValueAsDouble(inputValue);
theView.setSecondNumber(doubleValue);
}
double firstNumber = theView.getFirstNumber();
double secondNumber = theView.getSecondNumber();
theModel.calculate(firstNumber, secondNumber);
if (equalsCount == 0)
{
theView.setFirstNumber(secondNumber);
}
theView.setSecondNumber(theModel.getCalculationValue());
theView.setInputField(theModel.getCalculationValue());
equalsCount++;
}
}
/**
* Listener for the clear button
*/
class ClearListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String clicked = ((JButton) e.getSource()).getText();
switch (clicked)
{
case "โ":
String theValue = theView.getInputFieldValue();
String inputValue = theValue.substring(0, theValue.length() - 1);
double doubleValue = getFieldValueAsDouble(inputValue);
theView.setInputField(doubleValue);
break;
case "CE":
theView.setInputField(0);
break;
case "C":
theModel.needsReset = false;
theView.setFirstNumber(0);
theView.setSecondNumber(0);
theView.setInputField(0);
break;
default:
break;
}
}
}
/**
* Listener for the memory buttons
*/
class MemoryListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String clicked = ((JButton) e.getSource()).getText();
String inputValue = theView.getInputFieldValue();
double doubleValue = getFieldValueAsDouble(inputValue);
double memory = 0;
switch (clicked)
{
case "MC":
theModel.setMemory(0);
break;
case "MR":
memory = theModel.getMemory();
theView.setInputField(memory);
break;
case "MS":
theModel.setMemory(doubleValue);
break;
case "M+":
theModel.memorySums("+", doubleValue);
memory = theModel.getMemory();
theModel.setMemory(memory);
break;
case "M-":
theModel.memorySums("-", doubleValue);
memory = theModel.getMemory();
theModel.setMemory(memory);
break;
default:
break;
}
}
}
/**
* Listener for the negative button
*/
class NegListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String theValue = theView.getInputFieldValue();
double doubleValue = 0;
if (!theValue.equals("0"))
{
doubleValue = getFieldValueAsDouble("-" + theValue);
}
theView.setInputField(doubleValue);
}
}
/**
* Listener for the square root button
*/
class SquareListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String theValue = theView.getInputFieldValue();
double doubleValue = getFieldValueAsDouble(theValue);
double squareRoot = theModel.squareRoot(doubleValue);
theView.setInputField(squareRoot);
}
}
/**
* Listener for the percentage button
*/
class PercentageListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (equalsCount == 0)
{
String inputValue = theView.getInputFieldValue();
double doubleValue = getFieldValueAsDouble(inputValue);
theView.setSecondNumber(doubleValue);
}
double firstNumber = theView.getFirstNumber();
double secondNumber = theView.getSecondNumber();
theModel.percentage(firstNumber, secondNumber);
if (equalsCount == 0)
{
theView.setFirstNumber(secondNumber);
}
theView.setSecondNumber(theModel.getCalculationValue());
theView.setInputField(theModel.getCalculationValue());
equalsCount++;
}
}
/**
* Takes String input and converts it to a double using a try catch
*
* @param inputValue
* : string value from field
* @return doubleVlue : double value from conversion
*/
public double getFieldValueAsDouble(String inputValue)
{
double doubleValue;
try
{
doubleValue = Double.parseDouble(inputValue);
}
catch (NumberFormatException ex)
{
try
{
int intValue = Integer.parseInt(inputValue);
doubleValue = (double) intValue;
}
catch (NumberFormatException ex1)
{
doubleValue = 0;
}
}
return doubleValue;
}
}
| gpl-2.0 |
dlitz/resin | modules/jpa/src/javax/persistence/IdClass.java | 1457 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.persistence;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* The @IdClass annotation specifies the class to be used for the primary
* key.
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface IdClass {
@SuppressWarnings("unchecked")
Class value();
}
| gpl-2.0 |
abstractionlayer/spring-demo-guestbook | gb-infrastructure/src/main/java/gb/common/events/BaseDomainEvent.java | 444 | package gb.common.events;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.NonNull;
public abstract class BaseDomainEvent
implements DomainEvent {
@NonNull UUID id = UUID.randomUUID();
@NonNull LocalDateTime createdAt = LocalDateTime.now();
@Override
public final UUID getId() {
return id;
}
@Override
public final LocalDateTime getCreatedAt() {
return createdAt;
}
}
| gpl-2.0 |
bensmith87/risk | player/src/main/java/ben/risk/player/game/GamePane.java | 732 | package ben.risk.player.game;
import ben.risk.player.game.map.model.MapModelManager;
import ben.risk.player.game.map.view.MapViewManager;
import ben.ui.widget.IWidget;
import ben.ui.widget.StackPane;
/**
* Game Pane.
*/
public class GamePane {
private StackPane gamePane;
public GamePane() {
gamePane = new StackPane(null);
WorldCanvas worldCanvas = new WorldCanvas();
gamePane.add(worldCanvas);
gamePane.add(new WorldPane());
MapModelManager mapModelManager = new MapModelManager();
MapViewManager mapController = new MapViewManager(mapModelManager, worldCanvas);
mapController.start();
}
public IWidget getPane() {
return gamePane;
}
}
| gpl-2.0 |
fantesy84/java-code-tutorials | java-code-tutorials-design-pattern/java-code-tutorials-design-pattern-facade/src/main/java/net/fantesy84/computer/Memory.java | 469 | /**
* ้กน็ฎๅ: java-code-tutorials-design-pattern-facade
* ๅ
ๅ: net.fantesy84.computer
* ๆไปถๅ: Memory.java
* Copy Right ยฉ 2015 Andronicus Ge
* ๆถ้ด: 2015ๅนด11ๆ27ๆฅ
*/
package net.fantesy84.computer;
/**
* @author Andronicus
* @since 2015ๅนด11ๆ27ๆฅ
*/
public class Memory {
public void startup(){
System.out.println("Memory: memory starting...");
}
public void shutdown(){
System.out.println("Memory: memory shutingdown...");
}
}
| gpl-2.0 |
leocockroach/JasperServer5.6 | jasperserver-remote-tests/src/test/java/com/jaspersoft/jasperserver/ws/xmla/XmlaTest.java | 7732 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* 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.jaspersoft.jasperserver.ws.xmla;
import java.net.URL;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.tonbeller.jpivot.core.Model;
import com.tonbeller.jpivot.core.ModelFactory;
import com.tonbeller.jpivot.xmla.XMLA_SOAP;
import com.tonbeller.jpivot.xmla.XMLA_Model;
import com.tonbeller.jpivot.xmla.XMLA_Result;
import com.tonbeller.jpivot.xmla.XMLA_OlapModelTag;
import com.jaspersoft.jasperserver.war.JasperServerConstants;
/**
* @author sbirney
*/
public class XmlaTest extends TestCase {
private static boolean ENABLED = true;
private static XMLA_SOAP XMLA_CLIENT = null;
/**
* default constructor
*/
public XmlaTest(String method) {
super(method);
}
/*
* setUp method
*/
public void setUp() throws Exception {
if (!ENABLED) return;
XMLA_CLIENT = new XMLA_SOAP( //"http://localhost:8080/mondrian-embedded/xmla",
JasperServerConstants.instance().XMLA_URL,
JasperServerConstants.instance().USERNAME,
JasperServerConstants.instance().PASSWORD );
}
/*
* tearDown method
*/
public void tearDown() {
//no tearDown
}
/**
* main method defined here
* @param args
*/
public static void main(String[] args) {
try {
junit.textui.TestRunner.run(suite());
} catch (Exception _ex) {
_ex.printStackTrace();
}
}
/**
* this method is for adding which all test case/s method/s need to be
* @return Test
* @throws Exception if fails
*/
public static Test suite() throws Exception {
TestSuite suite = new TestSuite();
TestCase test1 = new XmlaTest("testDiscoverCatalogs");
TestCase test2 = new XmlaTest("testDiscoverDSProperties");
TestCase test3 = new XmlaTest("testDiscoverSugarCRMCubes");
// disabled - failing 07-19-06
TestCase test4 = new XmlaTest("testXmlaQuery");
//TestCase test5 = new XmlaTest("testInvalidCredentials");
//TestCase test6 = new XmlaTest("testNoCredentials");
suite.addTest(test1);
suite.addTest(test2);
suite.addTest(test3);
suite.addTest(test4); // disabled 07-19-06
//suite.addTest(test5);
//suite.addTest(test6);
return suite;
}
/*
* test no credentials
*/
public void testNoCredentials() throws Exception {
if (!ENABLED) return;
System.out.println("testNoCredentials");
boolean success = true;
try {
XMLA_SOAP noCredClient = new XMLA_SOAP( JasperServerConstants.instance().XMLA_URL,
null, null ); // null or "" is empty
success = false;
} catch (Throwable t) {
// for some reason this seems to be throwing up some text/html about:
//org.acegisecurity.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
//org.acegisecurity.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:414)
//org.acegisecurity.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:308)
System.out.println("we should have just seen an exception printed but not thrown");
}
if (!success) {
throw new SecurityException("should have thrown a Bad credentials exception");
}
}
/*
* test invalid credentials
*/
public void testInvalidCredentials() throws Exception {
if (!ENABLED) return;
System.out.println("testInvalidCredentials");
try {
XMLA_SOAP badCredClient = new XMLA_SOAP( JasperServerConstants.instance().XMLA_URL,
"wrong",
"bad" );
throw new SecurityException("should have thrown a Bad credentials exception");
} catch (Throwable t) {
// message should look like this:
// javax.xml.soap.SOAPException: java.security.PrivilegedActionException:
// javax.xml.soap.SOAPException: Bad response: (401Bad credentials"
if (!t.getMessage().endsWith("Bad credentials")) {
//something other than we expected went wrong
throw new SecurityException("Unexpected error while testing credentials", t);
}
System.out.println("we should have just seen an exception printed but not thrown");
}
}
private String SAMPLE_SUGAR_CRM_MDX_QUERY =
"select {[Measures].[Total Sale Amount], [Measures].[Number of Sales], [Measures].[Avg Sale Amount], [Measures].[Avg Time To Close (Days)], [Measures].[Avg Close Probablility]} ON COLUMNS, " +
" NON EMPTY {([Account Categorization].[All Accounts], [Close Period].[All Periods])} ON ROWS " +
" from [SalesAnalysis] " +
" where [Sale State].[All Types].[Closed Won]";
/*
* test xmla query
*/
public void testXmlaQuery() throws Exception {
if (!ENABLED) return;
URL configUrl = XMLA_OlapModelTag.class.getResource("config.xml");
// let Digester create a model from config input
// the config input stream MUST refer to the XMLA_Model class
// <model class="com.tonbeller.bii.xmla.XMLA_Model"> is required
Model model;
model = ModelFactory.instance(configUrl);
XMLA_Model xmlaModel = (XMLA_Model) model;
xmlaModel.setCatalog("SugarCRM");
xmlaModel.setDataSource("Provider=Mondrian;DataSource=SugarCRM;");
xmlaModel.setMdxQuery(SAMPLE_SUGAR_CRM_MDX_QUERY);
xmlaModel.setID("SugarCRM-1");
xmlaModel.setUri(JasperServerConstants.instance().XMLA_URL);
xmlaModel.setUser(JasperServerConstants.instance().USERNAME);
xmlaModel.setPassword(JasperServerConstants.instance().PASSWORD);
/*
XMLA_SOAP xmlaClient = new XMLA_SOAP( JasperServerConstants.instance().XMLA_URL,
JasperServerConstants.instance().USERNAME,
JasperServerConstants.instance().PASSWORD,
xmlaModel.getDataSource() );
// this is how jpivot executes the remote query
XMLA_Result result = new XMLA_Result(xmlaModel,
xmlaClient,
"SugarCRM",
SAMPLE_SUGAR_CRM_MDX_QUERY,
false);
*/
xmlaModel.initialize();
xmlaModel.getResult();
}
/*
* test discover method
*/
public void testDiscoverCatalogs() throws Exception {
if (!ENABLED) return;
System.out.println("testDiscoverCatalogs");
List cats = XMLA_CLIENT.discoverCat();
if (cats == null) {
fail("no catalogs available");
return;
}
System.out.println("number of catalogs: " + cats.size());
}
/*
* test discover method
*/
public void testDiscoverSugarCRMCubes() throws Exception {
System.out.println("testDiscoverSugarCRMCubes");
}
/*
* test discover method
*/
public void testDiscoverDSProperties() throws Exception {
if (!ENABLED) return;
System.out.println("testDiscoverDSProperties");
List props = XMLA_CLIENT.discoverDSProps();
if (props == null) {
fail("no DSProperties available");
return;
}
System.out.println("XmlaTest::discoverDSProps props length " + props.size());
}
}
| gpl-2.0 |
tarent/invio | invio-localization/entities/src/test/java/de/tarent/nic/EdgeTest.java | 3127 | package de.tarent.nic;
import de.tarent.nic.entities.Edge;
import de.tarent.nic.entities.NicGeoPoint;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class EdgeTest {
@Test
public void testConstruction() {
NicGeoPoint p1 = mock(NicGeoPoint.class);
NicGeoPoint p2 = mock(NicGeoPoint.class);
Edge edge1 = new Edge(p1, p2);
assertEquals(p1, edge1.getPointA());
assertEquals(p2, edge1.getPointB());
}
@Test
public void testEquals() {
NicGeoPoint p1 = mock(NicGeoPoint.class);
NicGeoPoint p2 = mock(NicGeoPoint.class);
Edge edge1 = new Edge(p1, p2);
Edge edge2 = new Edge(p1, p2);
Edge edge3 = new Edge(p2, p1);
Edge edge4 = new Edge(p1, p1);
Edge edge5 = new Edge(p2, p2);
Edge edge6 = new Edge(p1, null);
Edge edge6a = new Edge(p1, null);
Edge edge7 = new Edge(null, p2);
Edge edge7a = new Edge(null, p2);
Edge edge8 = new Edge(null, null);
Edge edge8a = new Edge(null, null);
Edge edge9 = new Edge(null, p1);
Edge edge10 = new Edge(p2, null);
assertTrue(edge1.equals(edge1));
assertTrue(edge1.equals(edge2));
assertTrue(edge6.equals(edge6a));
assertTrue(edge7.equals(edge7a));
assertTrue(edge8.equals(edge8a));
assertFalse(edge1.equals(null));
assertFalse(edge1.equals(this));
assertFalse(edge1.equals(edge4));
assertFalse(edge1.equals(edge5));
assertFalse(edge1.equals(edge6));
assertFalse(edge1.equals(edge7));
assertFalse(edge1.equals(edge8));
assertFalse(edge8.equals(edge1));
assertFalse(edge9.equals(edge7));
assertFalse(edge7.equals(edge9));
assertFalse(edge6.equals(edge10));
assertFalse(edge10.equals(edge6));
// TODO: fix this in Edge, the order of points should be irrelevant!
// assertTrue(edge1.equals(edge3));
}
@Test
public void testHashCode() {
NicGeoPoint p1 = mock(NicGeoPoint.class);
NicGeoPoint p2 = mock(NicGeoPoint.class);
Edge edge1 = new Edge(p1, p2);
Edge edge2 = new Edge(p1, p2);
Edge edge3 = new Edge(p2, p1);
Edge edge4 = new Edge(p1, p1);
Edge edge5 = new Edge(p2, p2);
Edge edge6 = new Edge(p1, null);
Edge edge7 = new Edge(null, p2);
assertEquals(edge1.hashCode(), edge2.hashCode());
assertEquals(edge1.hashCode(), edge2.hashCode());
assertFalse(edge1.hashCode() == edge4.hashCode());
assertFalse(edge1.hashCode() == edge5.hashCode());
assertFalse(edge6.hashCode() == edge1.hashCode());
assertFalse(edge7.hashCode() == edge1.hashCode());
assertFalse(edge7.hashCode() == edge6.hashCode());
// TODO: fix this in Edge, the order of points should be irrelevant!
//assertEquals(edge1.hashCode(), edge3.hashCode());
}
}
| gpl-2.0 |
callakrsos/Gargoyle | gargoyle-commons/src/main/java/com/kyj/fx/commons/utils/FxTreeViewUtil.java | 3997 | /********************************
* ํ๋ก์ ํธ : gargoyle-commons
* ํจํค์ง : com.kyj.fx.commons.utils
* ์์ฑ์ผ : 2019. 1. 11.
* ์์ฑ์ : KYJ (callakrsos@naver.com)
*******************************/
package com.kyj.fx.commons.utils;
import java.util.function.BiConsumer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.ScrollToEvent;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyEvent;
import javafx.util.StringConverter;
/**
* @author KYJ (callakrsos@naver.com)
*
*/
public class FxTreeViewUtil {
/**
*
* install keyClick event. <br/>
*
* if user key click , this function find the matched preffix text. and then
* is selected the row <br/>
*
* find value from toString method. <br/>
*
* @์์ฑ์ : KYJ (callakrsos@naver.com)
* @์์ฑ์ผ : 2019. 1. 11.
* @param tv
* @param converter
*/
public static <T> void installKeywordMoveEvent(TreeView<T> tv) {
installKeywordMoveEvent(tv, null);
}
/**
* install keyClick event. <br/>
*
* if user key click , this function find the matched preffix text. and then
* is selected the row <br/>
*
* find value by converter method. <br/>
*
* @์์ฑ์ : KYJ (callakrsos@naver.com)
* @์์ฑ์ผ : 2019. 1. 11.
* @param tv
* @param converter
*/
public static <T> void installKeywordMoveEvent(TreeView<T> tv, StringConverter<T> converter) {
tv.addEventHandler(KeyEvent.KEY_PRESSED, ev -> {
// ํน์ํค๊ฐ ๋๋ ค์ง๊ฒฝ์ฐ๋ Skip.
if (!ev.getCode().isLetterKey()) {
return;
}
if(ev.isControlDown() || ev.isShiftDown() || ev.isAltDown())
return;
if (ev.isConsumed())
return;
ev.consume();
String preffix = ev.getText().toLowerCase();
MultipleSelectionModel<TreeItem<T>> selectionModel = tv.getSelectionModel();
//tree item index.
TreeItem<T> selectedItem = selectionModel.getSelectedItem();
if (selectedItem == null)
return;
TreeItem<T> parent = selectionModel.getSelectedItem().getParent();
ObservableList<TreeItem<T>> items = FXCollections.emptyObservableList();
if (parent != null) {
items = parent.getChildren();
}
int selectedIndex = items.indexOf(selectedItem);
// tv.setOnScrollTo(new EventHandler<ScrollToEvent<Integer>>() {
//
// @Override
// public void handle(ScrollToEvent<Integer> event) {
// Integer scrollTarget = event.getScrollTarget();
//
// }
// });
int size = items.size();
BiConsumer<TreeItem<T>, Integer> findFunction = (ti, idx) -> {
selectionModel.clearSelection();
selectionModel.select(ti);
// move to selected index.
tv.scrollTo(selectionModel.getSelectedIndex());
};
if (find(items, preffix, converter, selectedIndex + 1, size, findFunction)) {
return;
}
find(items, preffix, converter, 0, selectedIndex , findFunction);
});
}
/**
* @์์ฑ์ : KYJ (callakrsos@naver.com)
* @์์ฑ์ผ : 2019. 1. 11.
* @param items
* @param preffix
* @param converter
* @param startIdx
* @param endIdx
* @return
*/
private static <T> boolean find(ObservableList<TreeItem<T>> items, String preffix, StringConverter<T> converter, int startIdx,
int endIdx, BiConsumer<TreeItem<T>, Integer> findFunction) {
boolean isFound = false;
if (startIdx >= endIdx)
return false;
for (int i = startIdx; i < endIdx; i++) {
TreeItem<T> tmp = items.get(i);
T data = tmp.getValue();
String string = null;
if (converter == null)
string = data.toString().toLowerCase();
else
string = converter.toString(data).toLowerCase();
if (string == null)
continue;
if (string.startsWith(preffix)) {
findFunction.accept(tmp, i);
isFound = true;
break;
}
}
return isFound;
}
}
| gpl-2.0 |
plegat/PlegatFEM2D_Prepro | src_plegatFem2D_prepro_06mar2013/plegatfem2d_prepro/objects_old/IPFEM2DDrawableObject.java | 532 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package plegatfem2d_prepro.objects;
import java.awt.Graphics;
import plegatfem2d_prepro.PFem2DGuiPanel;
/**
*
* @author jmb2
*/
public interface IPFEM2DDrawableObject {
public void draw(Graphics g, PFem2DGuiPanel panel);
public void setVisible(boolean flag);
public boolean isVisible();
public PFEM2DPoint[] getPoints();
public String getId();
public double[] getBoundingBox();
}
| gpl-2.0 |
light88/dental-spring | web/src/main/java/com/dental/web/rest/ProfileRestController.java | 1365 | package com.dental.web.rest;
import com.dental.init.LoggedDentist;
import com.dental.persistence.entity.Dentist;
import com.dental.service.DentistService;
import com.dental.web.dto.DTOUtils;
import com.dental.web.dto.ProfileDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* Created by light on 12/5/2015.
*/
@RestController
public class ProfileRestController extends BaseRestController {
private Logger LOG = LoggerFactory.getLogger(PasswordRestController.class);
@Autowired
private DentistService dentistService;
@RequestMapping(value = "/profile", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.ALL_VALUE)
public ResponseEntity<?> profile(HttpServletRequest httpServletRequest, @LoggedDentist Dentist loggedDentist) {
Dentist dentist = dentistService.get(loggedDentist.getId());
ProfileDTO profileDTO = DTOUtils.convertToProfile(dentist);
return success(profileDTO);
}
} | gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/sun/security/util/DerValue/NegInt.java | 1664 | /*
* Copyright 2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6855671
* @summary DerOutputStream encodes negative integer incorrectly
*/
import sun.security.util.DerOutputStream;
public class NegInt {
public static void main(String[] args) throws Exception {
DerOutputStream out;
out = new DerOutputStream();
out.putInteger(-128);
if(out.toByteArray().length != 3) {
throw new Exception("-128 encode error");
}
out = new DerOutputStream();
out.putInteger(-129);
if(out.toByteArray().length != 4) {
throw new Exception("-129 encode error");
}
}
}
| gpl-2.0 |
gszasz/dome-control | src/Mount.java | 14673 | /*
* Dome Control - A Dome Control Client for Java platform
* Copyright (C) 2007 Hlohovec Observatory
*
* This program is licensed under the terms found in the COPYING file.
*/
import javax.vecmath.*;
class Mount {
// Inicialization from Properties
private AppProperties ap = DomeControl.customProps;
// GEM Flip States
public static final int NON_FLIPPED = 0;
public static final int FLIPPED = 1;
// Variables
private double hourAngle = 0;
private double declination = 0;
private double latitude = 0;
private double positionAngle = 0;
private int flipState = NON_FLIPPED;
private double scopeDiameter = 1;
private int sensorCount = ap.sensorCount;
// Vectors
private Vector3d legAxisPosition = new Vector3d();
private Vector3d legAxis = new Vector3d();
private Vector3d polarAxis = new Vector3d();
private Vector3d polarAxisDirection = new Vector3d();
private Vector3d decAxis = new Vector3d();
private Vector3d decAxisPosition = new Vector3d();
private Vector3d decAxisDirection = new Vector3d();
private Vector3d scopeOffset = new Vector3d();
private Vector3d scopeOffsetDirection = new Vector3d();
private Vector3d scopePosition = new Vector3d();
private Vector3d scopeDirection = new Vector3d();
private Vector3d[] sensorOffsets = new Vector3d[sensorCount];
private Vector3d[] sensorPositions = new Vector3d[sensorCount];
// Transformation Matrices
private Matrix3d polarAxisTransform = new Matrix3d();
private Matrix3d decAxisTransform = new Matrix3d();
// Tracking Motor
private TrackingMotor trackingMotor;
// Constructor
public Mount() {
// Initialize Leg Axis Position
legAxisPosition.add(new Vector3d(0, 0, -ap.wallHeight));
legAxisPosition.add(new Vector3d(ap.excentricDistance, 0, 0));
// Initialize Leg Axis
legAxis.set(0, 0, ap.legAxisLength);
// Initialize Latitude
latitude = Math.toRadians(ap.latitude);
// Initialize Polar Axis, Polar Axis Direction and Polar Axis Transform
computePolarAxis(ap.polarAxisLength);
// Initialize Dec Axis Position
computeDecAxisPosition();
// Initialize Dec Axis and Dec Axis Direction
computeDecAxis(ap.decAxisLength);
// Initialize Scope Direction
computeScopeDirection();
// Initialize Scope Position Angle
positionAngle = Math.toRadians(ap.scopePA);
// Initialize Scope Offset, Scope Offset Direction and Dec Axis Transform
computeScopeOffset(ap.scopeOffset);
// Initialize Scope Position
computeScopePosition();
// Initialize Scope Diameter
scopeDiameter = ap.scopeDiameter;
// Initialize Sensor Offsets and Sensor Positions
for(int i=0; i<sensorPositions.length; i++) {
sensorOffsets[i] = new Vector3d();
sensorPositions[i] = new Vector3d();
}
computeSensorPositions();
// Initialze Tracking Motor
initTrackingMotor();
}
private void computePolarAxis() {
computePolarAxis(polarAxis.length());
}
private void computePolarAxis(double length) {
polarAxisDirection.set(-Math.cos(latitude), 0, Math.sin(latitude));
if(latitude < 0)
polarAxisDirection.negate();
if(length != 0)
polarAxis.scale(length, polarAxisDirection);
polarAxisTransform.rotY(-(Math.PI/2-latitude));
}
private void computeDecAxis() {
computeDecAxis(decAxis.length());
}
private void computeDecAxis(double length) {
decAxisDirection.set(Math.sin(hourAngle), -Math.cos(hourAngle), 0);
if(flipState == FLIPPED)
decAxisDirection.negate();
polarAxisTransform.transform(decAxisDirection);
if(length != 0)
decAxis.scale(length, decAxisDirection);
}
private void computeScopeDirection() {
scopeDirection.set(Math.cos(hourAngle)*Math.cos(declination),
Math.sin(hourAngle)*Math.cos(declination),
Math.sin(declination));
polarAxisTransform.transform(scopeDirection);
}
private void computeScopeOffset() {
computeScopeOffset(scopeOffset.length());
}
private void computeScopeOffset(double length) {
Vector3d orthogonalDirection = new Vector3d();
orthogonalDirection.cross(scopeDirection, decAxisDirection);
decAxisTransform.setColumn(0, decAxisDirection) ;
decAxisTransform.setColumn(1, orthogonalDirection);
decAxisTransform.setColumn(2, scopeDirection);
if(positionAngle == 0)
scopeOffsetDirection.set(decAxisDirection);
else {
scopeOffsetDirection.set(Math.cos(positionAngle), Math.sin(positionAngle), 0);
decAxisTransform.transform(scopeOffsetDirection);
}
if(length != 0)
scopeOffset.scale(length, scopeOffsetDirection);
}
private void computeDecAxisPosition() {
decAxisPosition.scale(0);
decAxisPosition.add(legAxisPosition);
decAxisPosition.add(legAxis);
decAxisPosition.add(polarAxis);
}
private void computeScopePosition() {
scopePosition.scale(0);
scopePosition.add(decAxisPosition);
scopePosition.add(decAxis);
scopePosition.add(scopeOffset);
}
private void computeSensorPositions() {
double step = Math.toRadians(360.0/sensorCount);
for(int i=0; i<sensorOffsets.length; i++) {
sensorOffsets[i].set(Math.cos(i*step), Math.sin(i*step), 0);
decAxisTransform.transform(sensorOffsets[i]);
sensorOffsets[i].scale(scopeDiameter/2.0);
sensorPositions[i].add(sensorOffsets[i], scopePosition);
}
}
public Vector3d getLegAxisPosition() {
return legAxisPosition;
}
public Vector3d getLegAxis() {
return legAxis;
}
public Vector3d getPolarAxis() {
return polarAxis;
}
public Vector3d getDecAxis() {
return decAxis;
}
public Vector3d getScopeOffset() {
return scopeOffset;
}
public Vector3d getScopeDirection() {
return scopeDirection;
}
public Vector3d getScopePosition() {
return scopePosition;
}
public Vector3d[] getSensorOffsets() {
return sensorOffsets;
}
public Vector3d[] getSensorPositions() {
return sensorPositions;
}
public double getHourAngle() {
return Math.toDegrees(hourAngle);
}
public double getDeclination() {
return Math.toDegrees(declination);
}
public double getLatitude() {
return Math.toDegrees(latitude);
}
public int getFlipState() {
return flipState;
}
public double getScopePositionAngle() {
return Math.toDegrees(positionAngle);
}
public int getSensorCount() {
return sensorCount;
}
public double getScopeDiameter() {
return scopeDiameter;
}
// Set Leg Axis Position
public void setLegAxisPosition(double wallHeight, double excentricDistance) {
Vector3d floorCenter = new Vector3d(0, 0, -wallHeight);
Vector3d legOffset = new Vector3d(excentricDistance, 0, 0);
legAxisPosition.add(floorCenter, legOffset);
computeDecAxisPosition();
computeDecAxis();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Leg Axis Length
public void setLegAxisLength(double legAxisLength) {
if(legAxis.length() == legAxisLength)
return;
legAxis.set(0, 0, legAxisLength);
computeDecAxisPosition();
computeDecAxis();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Polar Axis Length
public void setPolarAxisLength(double polarAxisLength) {
if(polarAxis.length() == polarAxisLength)
return;
polarAxis.scale(polarAxisLength, polarAxisDirection);
computeDecAxisPosition();
computeDecAxis();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Declination Axis Length
public void setDecAxisLength(double decAxisLength) {
if(decAxis.length() == decAxisLength)
return;
decAxis.scale(decAxisLength, decAxisDirection);
computeDecAxis();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Scope Offset Length
public void setScopeOffsetLength(double scopeOffsetLength) {
if(scopeOffset.length() == scopeOffsetLength)
return;
scopeOffset.scale(scopeOffsetLength, scopeOffsetDirection);
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Scope Position Angle
public void setScopePositionAngle(double positionAngle) {
if(positionAngle < -360 || positionAngle > 360)
return;
this.positionAngle = Math.toRadians(positionAngle);
// double pa = Math.toRadians(positionAngle);
// double length = scopeOffset.length();
// scopeOffsetDirection.set(Math.cos(pa), Math.sin(pa), 0);
// decAxisTransform.transform(scopeOffsetDirection);
// scopeOffset.scale(length, scopeOffsetDirection);
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Latitude
public void setLatitude(double latitude) {
this.latitude = Math.toRadians(latitude);
computePolarAxis();
computeDecAxisPosition();
computeDecAxis();
computeScopeDirection();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
trackingMotor.computeRotationMatrix();
}
// Set Hour Angle
public void setHourAngle(double hourAngle) {
if(hourAngle < 0 || hourAngle > 360)
return;
this.hourAngle = Math.toRadians(hourAngle);
computeScopeDirection();
computeDecAxis();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
public void setDeclination(double declination) {
if(declination < -90 || hourAngle > 90)
return;
this.declination = Math.toRadians(declination);
computeScopeDirection();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set GEM Flip State
public void setFlipState(int flipState) {
if(flipState != NON_FLIPPED && flipState != FLIPPED)
return;
if(flipState != this.flipState) {
this.flipState = flipState;
decAxisDirection.negate();
decAxis.negate();
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
}
// Set Scope Diameter
public void setScopeDiameter(double scopeDiameter) {
if(scopeDiameter < 0)
return;
this.scopeDiameter = scopeDiameter;
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
// Set Number of Sensors
public void setSensorCount(int sensorCount) {
if(sensorCount < 0)
return;
this.sensorCount = sensorCount;
sensorOffsets = new Vector3d[sensorCount];
sensorPositions = new Vector3d[sensorCount];
for(int i=0; i < sensorPositions.length; i++) {
sensorOffsets[i] = new Vector3d();
sensorPositions[i] = new Vector3d();
}
computeScopeOffset();
computeScopePosition();
computeSensorPositions();
}
public void setFromAppProperties() {
// private double hourAngle = 0;
// private double declination = 0;
// private double latitude = 0;
// private double positionAngle = 0;
// private int flipState = NON_FLIPPED;
// private double scopeDiameter = 1;
// private int sensorCount = ap.sensorCount;
setLegAxisPosition(ap.wallHeight, ap.excentricDistance);
setLegAxisLength(ap.legAxisLength);
setLatitude(ap.latitude);
setPolarAxisLength(ap.polarAxisLength);
setDecAxisLength(ap.decAxisLength);
setScopeOffsetLength(ap.scopeOffset);
setSensorCount(ap.sensorCount);
}
// Tracking Motor
public void initTrackingMotor() {
if(trackingMotor == null) {
trackingMotor = new TrackingMotor();
trackingMotor.start();
}
}
public void startTrackingMotor() {
initTrackingMotor();
trackingMotor.switchOn();
}
public void startTrackingMotor(double speed) {
initTrackingMotor();
trackingMotor.setSpeed(speed);
trackingMotor.switchOn();
}
public boolean trackingMotorRunning() {
return trackingMotor.isRunning();
}
public void setTrackingMotorSpeed(double speed) {
trackingMotor.setSpeed(speed);
}
public void stopTrackingMotor() {
trackingMotor.switchOff();
}
public void destroyTrackingMotor() {
trackingMotor.terminate();
trackingMotor = null;
}
// Tracking Motor Simulator
class TrackingMotor extends Thread {
public final double INCREMENT = Math.toRadians(360.0/864000.0);
private Matrix3d polarAxisInverseTransform = new Matrix3d();
private Matrix3d rotationMatrix = new Matrix3d();
private double speed;
private boolean terminated = false;
private boolean suspended = true;
public TrackingMotor() {
this(1);
}
public TrackingMotor(double speed) {
this.speed = speed;
computeRotationMatrix();
}
public void computeRotationMatrix() {
polarAxisInverseTransform.invert(polarAxisTransform);
rotationMatrix.rotZ(INCREMENT*speed);
rotationMatrix.mul(polarAxisTransform, rotationMatrix);
rotationMatrix.mul(polarAxisInverseTransform);
}
public void setSpeed(double speed) {
this.speed = speed;
rotationMatrix.rotZ(INCREMENT*speed);
rotationMatrix.mul(polarAxisTransform, rotationMatrix);
rotationMatrix.mul(polarAxisInverseTransform);
}
public boolean isRunning() {
return (! suspended);
}
public void run() {
while(!terminated) {
try {
if (suspended) {
synchronized (this) {
while (suspended)
wait();
}
}
Thread.sleep(100);
// Rotate Declination Axis
rotationMatrix.transform(decAxisDirection);
decAxis.scale(decAxis.length(), decAxisDirection);
// Rotate Scope Offset
rotationMatrix.transform(scopeOffsetDirection);
scopeOffset.scale(scopeOffset.length(), scopeOffsetDirection);
rotationMatrix.transform(scopeDirection);
// Compute Scope position
computeScopePosition();
// Rotate Sensor Offsets and Compute Sensor Positions
for(int i=0; i<sensorPositions.length; i++) {
rotationMatrix.transform(sensorOffsets[i]);
sensorPositions[i].add(sensorOffsets[i], scopePosition);
}
// Set Hour Angle
hourAngle += INCREMENT*speed;
if(hourAngle >= Math.toRadians(360))
hourAngle -= Math.toRadians(360);
}
catch(InterruptedException e) {
terminated = true;
break;
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public synchronized void switchOn() {
if(suspended) {
suspended = false;
notifyAll();
}
}
public synchronized void switchOff() {
if(!suspended)
suspended = true;
}
public synchronized void terminate() {
terminated = true;
this.interrupt();
}
}
// Main Method for Testing purposes
public static void main(String[] args) {
Mount mount = new Mount();
System.out.println(mount.getScopePosition());
System.out.println(mount.getScopeDirection());
}
}
| gpl-2.0 |
niceforo1/Gestion | GestionMutuales/src/model/Chequeras.java | 4075 | package model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name = "CHEQUERAS")
public class Chequeras implements Serializable {
@Id
@Column(name = "CHS_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "CHS_NUM_CHQ_DESDE", nullable = true)
private Integer numChqDesde;
@Column(name = "CHS_NUM_IMPRESION", nullable = true)
private Long numImpresionChequera;
@Column(name = "CHS_CANTIDAD", nullable = true)
private Integer cantidad;
@Column(name = "CHS_IMPRESION", nullable = true)
private String impresion;
@Column(name = "CHS_NUM_CHQ_HASTA", nullable = true)
private Integer numChqHasta;
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "TPO_IMP_ID")
private TipoImpresion tipoImpresion;
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "EST_CHS_CODIGO")
private EstadoChequera estadoChequera;
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "TPO_CHQ_ID")
private TipoCheque tipoCheque;
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "CBN_ID")
private CuentaBancaria cuentaBancaria;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@Fetch(value = FetchMode.SUBSELECT)
private List<Cheque> cheques;
public Chequeras() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumChqDesde() {
return numChqDesde;
}
public void setNumChqDesde(Integer numChqDesde) {
this.numChqDesde = numChqDesde;
}
public Integer getCantidad() {
return cantidad;
}
public void setCantidad(Integer cantidad) {
this.cantidad = cantidad;
}
public String getImpresion() {
return impresion;
}
public void setImpresion(String impresion) {
this.impresion = impresion;
}
public Integer getNumChqHasta() {
return numChqHasta;
}
public void setNumChqHasta(Integer numChqHasta) {
this.numChqHasta = numChqHasta;
}
public TipoImpresion getTipoImpresion() {
return tipoImpresion;
}
public void setTipoImpresion(TipoImpresion tipoImpresion) {
this.tipoImpresion = tipoImpresion;
}
public EstadoChequera getEstadoChequera() {
return estadoChequera;
}
public void setEstadoChequera(EstadoChequera estadoChequera) {
this.estadoChequera = estadoChequera;
}
public TipoCheque getTipoCheque() {
return tipoCheque;
}
public void setTipoCheque(TipoCheque tipoCheque) {
this.tipoCheque = tipoCheque;
}
public CuentaBancaria getCuentaBancaria() {
return cuentaBancaria;
}
public void setCuentaBancaria(CuentaBancaria cuentaBancaria) {
this.cuentaBancaria = cuentaBancaria;
}
public Long getNumImpresionChequera() {
return numImpresionChequera;
}
public void setNumImpresionChequera(Long numImpresionChequera) {
this.numImpresionChequera = numImpresionChequera;
}
public List<Cheque> getCheques() {
return cheques;
}
public void setCheques(List<Cheque> cheques) {
this.cheques = cheques;
}
@Override
public String toString() {
return "Chequeras [id=" + id + ", numChqDesde=" + numChqDesde + ", numImpresionChequera=" + numImpresionChequera
+ ", cantidad=" + cantidad + ", impresion=" + impresion + ", numChqHasta=" + numChqHasta
+ ", tipoImpresion=" + tipoImpresion + ", estadoChequera=" + estadoChequera + ", tipoCheque="
+ tipoCheque + "]";
}
}
| gpl-2.0 |
Vhati/ftl-profile-editor | src/main/java/net/blerf/ftl/xml/WeaponAnim.java | 2212 | package net.blerf.ftl.xml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import net.blerf.ftl.xml.AnimSpec;
import net.blerf.ftl.xml.Offset;
@XmlRootElement(name = "weaponAnim")
@XmlAccessorType(XmlAccessType.FIELD)
public class WeaponAnim {
@XmlAttribute(name = "name")
private String id;
@XmlElement(name = "sheet")
private String sheetId;
@XmlElement(name = "desc")
private AnimSpec spec;
private int chargedFrame;
private int fireFrame;
private Offset firePoint;
private Offset mountPoint;
@XmlElement(name = "delayChargeAnim", required = false)
private Float chargeDelay;
@XmlElement(name = "chargeImage", required = false)
private String chargeImagePath;
public void setId( String id ) {
this.id = id;
}
public String getId() {
return id;
}
public void setSheetId( String sheetId ) {
this.sheetId = sheetId;
}
public String getSheetId() {
return sheetId;
}
public void setSpec( AnimSpec spec ) {
this.spec = spec;
}
public AnimSpec getSpec() {
return spec;
}
public void setChargedFrame( int chargedFrame ) {
this.chargedFrame = chargedFrame;
}
public int getChargedFrame() {
return chargedFrame;
}
public void setFireFrame( int fireFrame ) {
this.fireFrame = fireFrame;
}
public int getFireFrame() {
return fireFrame;
}
public void setFirePoint( Offset firePoint ) {
this.firePoint = firePoint;
}
public Offset getFirePoint() {
return firePoint;
}
public void setMountPoint( Offset mountPoint ) {
this.mountPoint = mountPoint;
}
public Offset getMountPoint() {
return mountPoint;
}
public void setChargeDelay( Float chargeDelay ) {
this.chargeDelay = chargeDelay;
}
public Float getChargeDelay() {
return chargeDelay;
}
public void setChargeImagePath( String chargeImagePath ) {
this.chargeImagePath = chargeImagePath;
}
public String getChargeImagePath() {
return chargeImagePath;
}
@Override
public String toString() {
return ""+id;
}
}
| gpl-2.0 |
diokey/ums | JavaSource/org/gs/model/Log.java | 1208 | package org.gs.model;
import java.util.Date;
public class Log {
public Log() {
// TODO Auto-generated constructor stub
}
public int getLogId() {
return logId;
}
public void setLogId(int logId) {
this.logId = logId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Date getLogDate() {
return logDate;
}
public void setLogDate(Date logDate) {
this.logDate = logDate;
}
public String getUserIp() {
return userIp;
}
public void setUserIp(String userIp) {
this.userIp = userIp;
}
public String getLogSeverity() {
return logSeverity;
}
public void setLogSeverity(String logSeverity) {
this.logSeverity = logSeverity;
}
private int logId;
private String description;
private String logSeverity;
private User user;
private int userId;
private Date logDate;
private String userIp;
}
| gpl-2.0 |
HelmetPlusOne/frua-box | frua-tools/src/main/java/com/helmetplusone/android/frua/tools/Switcher.java | 9437 | package com.helmetplusone.android.frua.tools;
import com.google.code.regexp.Matcher;
import com.google.code.regexp.Pattern;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Collections;
import java.util.List;
import static com.helmetplusone.android.frua.tools.CaseInsensitiveIoUtils.*;
import static java.util.Locale.US;
import static org.apache.commons.io.FileUtils.*;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.apache.commons.io.filefilter.FalseFileFilter.FALSE;
/**
* User: helmetplusone
* Date: 3/30/13
*/
public class Switcher {
private static final Logger logger = LoggerFactory.getLogger(Switcher.class);
private static final Pattern DQK_XMI_PATTERN = Pattern.compile("^dqk(?<num>\\d)\\.xmi$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final Pattern ITEM_UAT_PATTERN = Pattern.compile("^item\\.uat$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final Pattern ITEMS_UAT_PATTERN = Pattern.compile("^items\\.uat$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final Pattern CBODY_UAT_PATTERN = Pattern.compile("^cbody\\.uat$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final IOFileFilter DISK1_FILES = new RegexFileFilter("^" +
"instr\\.ad|" +
"addq\\d\\.xmi|" +
"pcdq\\d\\.xmi|" +
"rodq\\d\\.xmi|" +
"item\\.dat|" +
"item\\.uat|" +
"items\\.dat|" +
"items\\.uat|" +
"game\\.fon|" +
"sfxdq\\.voc|" +
"dqk\\d\\.xmi|" +
"dqk\\d\\.xmi|" +
"always.tlb|" +
"title.tlb" +
"$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final IOFileFilter DISK2_FILES = new RegexFileFilter("^" +
"8x8d[bc]\\.tlb|" +
"back\\.tlb|" +
"bigpi[cx]\\.tlb|" +
"comspr\\.tlb|" +
"cpic\\.tlb|" +
"dungcom\\.tlb|" +
"monst\\.glb|" +
"pic[a-f]\\.tlb|" +
"sprit\\.tlb|" +
"topview\\.tlb|" +
"wildcom\\.tlb" +
"$", java.util.regex.Pattern.CASE_INSENSITIVE);
private static final IOFileFilter DISK3_FILES = new RegexFileFilter("^" +
"cbody\\.tlb|" +
"cbody\\.uat|" +
"frame\\.tlb|" +
"game\\.glb|" +
"gen.tlb|" +
"geo\\.glb|" +
"menu\\.tlb|" +
"script\\.glb|" +
"strg\\.glb" +
"$", java.util.regex.Pattern.CASE_INSENSITIVE);
public void applyDesign(File designDsn) throws IOException {
if (!(designDsn.exists() && designDsn.isDirectory())) throw new IOException(
"Invalid design designDsn: [" + designDsn.getAbsolutePath() + "]");
File fruaRoot = designDsn.getParentFile();
// check consistency
File ckitExe = existingCi(fruaRoot, "ckit.exe");
File disk1 = existingCi(fruaRoot, "disk1");
File disk2 = existingCi(fruaRoot, "disk2");
File disk3 = existingCi(fruaRoot, "disk3");
// check default.dsn exists, create it if not
File defaultDsnOrNull = existingCiOrNull(fruaRoot, "default.dsn");
File defaultDsn = null != defaultDsnOrNull ? defaultDsnOrNull : createDefaultDsn(fruaRoot, ckitExe, disk1, disk2, disk3);
// apply default first
if(designDsn.equals(defaultDsn)) {
logger.debug("Copying panic.xxx");
copyFile(existingCi(defaultDsn, "panic.xxx"), ckitExe);
} else {
applyDesign(defaultDsn);
}
logger.info("Applying design: [{}], FRUA root: [{}]", designDsn, fruaRoot.getAbsolutePath());
// apply table
File diffTbl = existingCiOrNull(designDsn, "diff.tbl");
if (null != diffTbl && diffTbl.isFile()) new Patcher().applyTable(diffTbl, ckitExe);
// disk1
copyDisk1(designDsn, disk1);
// disk2
copyDisk2(designDsn, disk2);
// disk3
copyDisk3(designDsn, disk3);
// start.dat
writeStartDat(fruaRoot, designDsn.getName());
// check save dir
checkSaveDir(designDsn);
logger.info("Finished");
}
private void checkSaveDir(File designDsn) throws IOException {
File saveExists = existingCiOrNull(designDsn, "save");
if (null == saveExists) {
File save = new File(designDsn, "save");
logger.info("Creating directory: [" + save.getAbsolutePath() + "]");
boolean success = save.mkdir();
if(!success) throw new IOException("Cannot create dir: [" + save.getAbsolutePath() + "]");
}
}
private File createDefaultDsn(File fruaRoot, File ckitExe, File disk1, File disk2, File disk3) throws IOException {
logger.info("Creating default.dsn");
File defaultDsn = new File(fruaRoot, "default.dsn");
logger.info("Copying ckit.exe to default.dsn");
copyFile(ckitExe, new File(defaultDsn, "panic.xxx"));
logger.info("Copying disk1 contents to default.dsn");
copyDirectory(disk1, defaultDsn);
logger.info("Copying disk2 contents to default.dsn");
copyDirectory(disk2, defaultDsn);
logger.info("Copying disk3 contents to default.dsn");
copyDirectory(disk3, defaultDsn);
if(Thread.interrupted()) throw new IOException("Installation cancelled");
return defaultDsn;
}
@SuppressWarnings("unchecked") // listFiles API
private void copyDisk1(File designDsn, File disk1) throws IOException {
logger.info("Copying files to disk1");
List<File> disk1List = (List) listFiles(designDsn, DISK1_FILES, FALSE);
Collections.sort(disk1List);
for (File fi : disk1List) {
if(Thread.interrupted()) throw new IOException("Installation cancelled");
Matcher dqkMatcher = DQK_XMI_PATTERN.matcher(fi.getName());
Matcher itemMatcher = ITEM_UAT_PATTERN.matcher(fi.getName());
Matcher itemsMatcher = ITEMS_UAT_PATTERN.matcher(fi.getName());
if (dqkMatcher.matches()) {
int num = Integer.parseInt(dqkMatcher.group("num"));
File target1 = existingCi(disk1, "addq" + num + ".xmi");
logger.debug("Copying file: [{}] to : [{}]", fi, target1);
copyFileCi(fi, target1);
File target2 = existingCi(disk1, "pcdq" + num + ".xmi");
logger.debug("Copying file: [{}] to : [{}]", fi, target2);
copyFileCi(fi, target2);
File target3 = existingCi(disk1, "rodq" + num + ".xmi");
logger.debug("Copying file: [{}] to : [{}]", fi, target3);
copyFileCi(fi, target3);
} else if (itemMatcher.matches()) {
File target = existingCi(disk1, "item.dat");
logger.debug("Copying file: [{}] to : [{}]", fi, target);
copyFileCi(fi, target);
} else if (itemsMatcher.matches()) {
File target = existingCi(disk1, "items.dat");
logger.debug("Copying file: [{}] to : [{}]", fi, target);
copyFileCi(fi, target);
} else {
File target = existingCi(disk1, fi.getName());
logger.debug("Copying file: [{}] to : [{}]", fi, target);
copyFileCi(fi, target);
}
}
}
@SuppressWarnings("unchecked") // listFiles API
private void copyDisk2(File designDsn, File disk2) throws IOException {
logger.info("Copying files to disk2");
List<File> disk2List = (List) listFiles(designDsn, DISK2_FILES, FALSE);
Collections.sort(disk2List);
for (File fi : disk2List) {
if(Thread.interrupted()) throw new IOException("Installation cancelled");
File target = existingCi(disk2, fi.getName());
logger.debug("Copying file: [{}] to : [{}]", fi, target);
copyFileCi(fi, target);
}
}
@SuppressWarnings("unchecked") // listFiles API
private void copyDisk3(File designDsn, File disk3) throws IOException {
logger.info("Copying files to disk3");
List<File> disk3List = (List) listFiles(designDsn, DISK3_FILES, FALSE);
Collections.sort(disk3List);
for (File fi : disk3List) {
if(Thread.interrupted()) throw new IOException("Installation cancelled");
Matcher cbodyMatcher = CBODY_UAT_PATTERN.matcher(fi.getName());
String name = cbodyMatcher.matches() ? "cbody.tlb" : fi.getName();
File target = existingCi(disk3, name);
logger.debug("Copying file: [{}] to : [{}]", fi, target);
copyFile(fi, target);
}
}
private void writeStartDat(File fruaRoot, String designName) throws IOException {
logger.info("Updating start.dat");
RandomAccessFile raf = null;
try {
String name = designName.toUpperCase(US) + "\0";
File startDat = existingCi(fruaRoot, "start.dat");
raf = new RandomAccessFile(startDat, "rw");
raf.write(name.getBytes(ASCII_CHARSET));
} finally {
closeQuietly(raf);
}
}
}
| gpl-2.0 |
mrrusof/snippets | java/oca8/ch1/zoo/Zoo.java | 252 | public class Zoo {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
Animal a = new Animal();
a.setName("Python");
System.out.println(a.getName());
}
}
| gpl-2.0 |
AcademicTorrents/AcademicTorrents-Downloader | frostwire-merge/org/gudy/azureus2/ui/swt/views/tableitems/mytorrents/SwarmAverageSpeed.java | 2479 | /*
* Created : 11 nov. 2004
* By : Alon Rohter
*
* Copyright (C) 2004, 2005, 2006 Aelitis SAS, All rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* AELITIS, SAS au capital de 46,603.30 euros,
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*/
package org.gudy.azureus2.ui.swt.views.tableitems.mytorrents;
import org.gudy.azureus2.core3.download.DownloadManager;
import org.gudy.azureus2.core3.util.DisplayFormatters;
import org.gudy.azureus2.plugins.download.Download;
import org.gudy.azureus2.plugins.ui.tables.TableCell;
import org.gudy.azureus2.plugins.ui.tables.TableCellRefreshListener;
import org.gudy.azureus2.plugins.ui.tables.TableColumnInfo;
import org.gudy.azureus2.ui.swt.views.table.CoreTableColumnSWT;
public class SwarmAverageSpeed
extends CoreTableColumnSWT
implements TableCellRefreshListener
{
public static final Class DATASOURCE_TYPE = Download.class;
public static final String COLUMN_ID = "swarm_average_speed";
public SwarmAverageSpeed(String sTableID) {
super(DATASOURCE_TYPE, COLUMN_ID, ALIGN_TRAIL, 70, sTableID);
setRefreshInterval(INTERVAL_LIVE);
setMinWidthAuto(true);
}
public void fillTableColumnInfo(TableColumnInfo info) {
info.addCategories(new String[] {
CAT_SWARM,
});
info.setProficiency(TableColumnInfo.PROFICIENCY_INTERMEDIATE);
}
public void refresh(TableCell cell) {
long speed = -1;
DownloadManager dm = (DownloadManager)cell.getDataSource();
if( dm != null ) {
speed = dm.getStats().getTotalAveragePerPeer();
}
if( !cell.setSortValue( speed ) && cell.isValid() ) {
return;
}
if( speed < 0 ) {
cell.setText( "" );
}
else {
cell.setText( DisplayFormatters.formatByteCountToKiBEtcPerSec( speed ) );
}
}
}
| gpl-2.0 |