repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
amischler/JRebirth | org.jrebirth/core/src/main/java/org/jrebirth/core/resource/color/RGB255Color.java | 4156 | /**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : sebastien.bordes@jrebirth.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jrebirth.core.resource.color;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
/**
* The interface <strong>RGB255Color</strong>.
*
* @author Sébastien Bordes
*/
public final class RGB255Color extends AbstractBaseColor {
/** The green value [0-255]. */
private final IntegerProperty redProperty = new SimpleIntegerProperty();
/** The green value [0-255]. */
private final IntegerProperty greenProperty = new SimpleIntegerProperty();
/** The blue value [0-255]. */
private final IntegerProperty blueProperty = new SimpleIntegerProperty();
/**
* Default Constructor.
*
* @param red the red component [0-255]
* @param green the green component [0-255]
* @param blue the blue component [0-255]
*/
public RGB255Color(final int red, final int green, final int blue) {
super();
this.redProperty.set(red);
this.greenProperty.set(green);
this.blueProperty.set(blue);
}
/**
* Default Constructor.
*
* @param red the red component [0-255]
* @param green the green component [0-255]
* @param blue the blue component [0-255]
* @param opacity the color opacity [0.0-1.0]
*/
public RGB255Color(final int red, final int green, final int blue, final double opacity) {
super(opacity);
this.redProperty.set(red);
this.greenProperty.set(green);
this.blueProperty.set(blue);
}
/**
* @return Returns the red [0-255].
*/
public int red() {
return this.redProperty.get();
}
/**
* @return Returns the red property.
*/
public IntegerProperty redProperty() {
return this.redProperty;
}
/**
* @return Returns the green [0-255].
*/
public int green() {
return this.greenProperty.get();
}
/**
* @return Returns the green property.
*/
public IntegerProperty greenProperty() {
return this.greenProperty;
}
/**
* @return Returns the blue [0-255].
*/
public int blue() {
return this.blueProperty.get();
}
/**
* @return Returns the blue property.
*/
public IntegerProperty blueProperty() {
return this.blueProperty;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
append(sb, red());
append(sb, green());
append(sb, blue());
append(sb, opacity());
return cleanString(sb);
}
/**
* {@inheritDoc}
*/
@Override
public void parse(final String[] parameters) {
// Manage red composite
if (parameters.length >= 1) {
redProperty().set(readInteger(parameters[0], 0, 255));
}
// Manage green composite
if (parameters.length >= 2) {
greenProperty().set(readInteger(parameters[1], 0, 255));
}
// Manage blue composite
if (parameters.length >= 3) {
blueProperty().set(readInteger(parameters[2], 0, 255));
}
// Manage opacity
if (parameters.length >= 4) {
opacityProperty().set(readDouble(parameters[3], 0.0, 1.0));
}
}
}
| apache-2.0 |
Liujinliang0803/sailunpda | SailunPDA/src/com/sailunpda/common/MainUIAdapter.java | 1911 | package com.sailunpda.common;
import com.sailunpda.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MainUIAdapter extends BaseAdapter {
private static final String TAG = "MainUIAdapter";
private Context context;
private LayoutInflater inflater;
private static ImageView iv_icon;
private static TextView tv_name;
private SharedPreferences sp;
public MainUIAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
}
private static String[] names = { "班次选择", "生产入库", "转储入库", "库房管理","盘点执行","检查管理", "销售发货",
"帮助升级"};
private static int[] icons = { };
public int getCount() {
return names.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// getview的方法被调用了多少次?
// 9
// gridview 控件bug
// won't fix
// 使用静态的变量引用 减少内存中申请的引用的个数
Log.i(TAG,"getview "+ position);
View view = inflater.inflate(R.layout.mainscreen_item, null);
iv_icon = (ImageView) view.findViewById(R.id.iv_main_icon);
tv_name = (TextView) view.findViewById(R.id.tv_main_name);
iv_icon.setImageResource(icons[position]);
tv_name.setText(names[position]);
if(position==0){
String name = sp.getString("lost_name", null);
if(name!=null){
tv_name.setText(name);
}
}
return view;
}
}
| artistic-2.0 |
lifuz/Struts | StrutsValidation/src/com/lifuz/utils/IDCard.java | 1636 | package com.lifuz.utils;
public class IDCard {
final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
private int[] ai = new int[18];
public IDCard() {}
public boolean Verify(String idcard) {
if (idcard.length() == 15) {
idcard = uptoeighteen(idcard);
}
if (idcard.length() != 18) {
return false;
}
String verify = idcard.substring(17, 18);
if (verify.equals(getVerify(idcard))) {
return true;
}
return false;
}
public String getVerify(String eightcardid) {
int remaining = 0;
if (eightcardid.length() == 18) {
eightcardid = eightcardid.substring(0, 17);
}
if (eightcardid.length() == 17) {
int sum = 0;
for (int i = 0; i < 17; i++) {
String k = eightcardid.substring(i, i + 1);
ai[i] = Integer.parseInt(k);
}
for (int i = 0; i < 17; i++) {
sum = sum + wi[i] * ai[i];
}
remaining = sum % 11;
}
return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
}
public String uptoeighteen(String fifteencardid) {
String eightcardid = fifteencardid.substring(0, 6);
eightcardid = eightcardid + "19";
eightcardid = eightcardid + fifteencardid.substring(6, 15);
eightcardid = eightcardid + getVerify(eightcardid);
return eightcardid;
}
public static void main(String[] args) {
String idcard1 = "350211197607142059";
String idcard2 = "350211197607442059";
IDCard idcard = new IDCard();
System.out.println(idcard.Verify(idcard1));
System.out.println(idcard.Verify(idcard2));
}
}
| artistic-2.0 |
jpahle/jCell | src/jCell/Modulo5StateChangeFunction.java | 741 | package jCell;
import java.io.*;
/**
* Diese Klasse beschreibt die lokale Uebergangsfunktion fuer den ZA Modulo5.
*
* @version 0.9, 6/29/1999
* @author Juergen Pahle
*/
public class Modulo5StateChangeFunction implements StateChangeFunction, Serializable {
/**
* Diese Methode errechnet den neuen Zustand einer Zelle aus den Zustaenden ihrer
* benachbarten Zellen gemaess der Vorschrift fuer den ZA Modulo5.
*
* @param Array von int, der die Zustaende der benachbarten Zellen beinhaltet.
* @return int. Neuer Zustand.
*/
public int calculate(int[] states) {
int i;
int sum = 0;
for (i = 0; i < states.length; i++) {
sum = sum + states[i];
}
return sum % 5;
}
}
| artistic-2.0 |
HealthyBytes/Beacon-2015 | AndroidApp/app/src/main/java/marand/beaconmarand/LoginFragment.java | 3299 | package marand.beaconmarand;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import marand.beaconmarand.marand.beaconmarand.api.RestClient;
import marand.beaconmarand.marand.beaconmarand.utils.Util;
/**
* Created by virusss8 on 13.7.2015.
*/
public class LoginFragment extends Fragment implements View.OnClickListener {
private View view;
private EditText firstname, surname;
private Spinner gender;
private Button register;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("LoginFragment", "onCreateView");
view = inflater.inflate(R.layout.fragment_login, container, false);
firstname = (EditText) view.findViewById(R.id.et_firstname);
surname = (EditText) view.findViewById(R.id.et_surname);
gender = (Spinner) view.findViewById(R.id.spinner_gender);
register = (Button) view.findViewById(R.id.btn_register);
register.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager)getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
switch (v.getId()) {
case R.id.btn_register:
Log.v("registrar",
firstname.getText() + " " +
surname.getText() + " " +
gender.getSelectedItem().toString());
Log.v("doctorid", "" + Util.getDoctorID());
if (Util.getDoctorID() != -1 && checkFields()) {
Log.v("doctorIDD", "yes");
((MainActivity)this.getActivity()).setProgressDialog();
RestClient restClient = new RestClient();
restClient.firstLoginToDoctor(
this.getActivity(),
firstname.getText().toString(),
surname.getText().toString(),
gender.getSelectedItem().toString(),
Util.getDoctorID());
}
break;
}
}
public boolean checkFields() {
if (firstname.getText().toString().equalsIgnoreCase("")) {
Toast.makeText(this.getActivity(), "Prosim vnesite svoje ime...", Toast.LENGTH_SHORT).show();
return false;
}
if (surname.getText().toString().equalsIgnoreCase("")) {
Toast.makeText(this.getActivity(), "Prosim vnesite svoj priimek...", Toast.LENGTH_SHORT).show();
return false;
}
if (gender.getSelectedItem().toString().equalsIgnoreCase("IZBERITE")) {
Toast.makeText(this.getActivity(), "Prosim izberite spol...", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
| artistic-2.0 |
andmatand/knitknit-gingerbread | src/com/example/knitknit/DatabaseHelper.java | 10860 | /*
* Copyright 2011 Andrew Anderson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.example.knitknit;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatabaseHelper {
private static final String TAG = "bunny-knitknit-DatabaseHelper";
private static final String DATABASE_NAME = "knitknit.db";
private static final int DATABASE_VERSION = 11;
private static final String PROJECT_TABLE = "projects";
public static final String PROJECT_KEY_ID = "_id";
public static final String PROJECT_KEY_NAME = "name";
public static final String PROJECT_KEY_DATECREATED = "dateCreated";
public static final String PROJECT_KEY_DATEACCESSED = "dateAccessed";
public static final String PROJECT_KEY_TOTALROWS = "totalRows";
private static final String COUNTER_TABLE = "counters";
public static final String COUNTER_KEY_ID = "_id";
public static final String COUNTER_KEY_PROJECTID = "projects_id";
public static final String COUNTER_KEY_NAME = "name";
public static final String COUNTER_KEY_VALUE = "value";
public static final String COUNTER_KEY_COUNTUP = "countUp";
public static final String COUNTER_KEY_PATTERNON = "patternOn";
public static final String COUNTER_KEY_PATTERNLENGTH = "patternLength";
public static final String COUNTER_KEY_NUMREPEATS = "numRepeats";
private static final String SETTINGS_TABLE = "settings";
public static final String SETTINGS_KEY_ID = "_id";
public static final String SETTINGS_KEY_KEEPSCREEENON = "keepScreenOn";
public static final String SETTINGS_KEY_SHOWCOUNTERNAMES =
"showCounterNames";
private static final String NOTE_TABLE = "notes";
private DatabaseOpenHelper mOpenHelper;
private SQLiteDatabase mDB;
private Context mContext;
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create projects table
db.execSQL(
"create table " + PROJECT_TABLE +
"(" + PROJECT_KEY_ID + " integer " +
"primary key autoincrement, " +
PROJECT_KEY_NAME + " tinytext not null, " +
PROJECT_KEY_DATECREATED + " datetime " +
"not null," +
PROJECT_KEY_DATEACCESSED + " datetime null, " +
PROJECT_KEY_TOTALROWS + ");");
// Create counters table
db.execSQL(
"create table " + COUNTER_TABLE +
"(" + COUNTER_KEY_ID + " integer " +
"primary key autoincrement, " +
COUNTER_KEY_PROJECTID + " integer not null, " +
"showNotes bool not null default 0, " +
COUNTER_KEY_NAME + " tinytext null, " +
"state integer not null default 0, " +
COUNTER_KEY_COUNTUP + " bool not null " +
"default 1, " +
COUNTER_KEY_VALUE + " integer not null " +
"default 0, " +
COUNTER_KEY_PATTERNON + " bool not null " +
"default 0, " +
COUNTER_KEY_PATTERNLENGTH + " integer " +
"not null default 10, " +
COUNTER_KEY_NUMREPEATS + " integer " +
"not null default 0, " +
"targetEnabled bool not null default 0, " +
"targetRows integer null);");
// Create notes table
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from " +
"version " + oldVersion + " to " + newVersion +
", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + PROJECT_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTER_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + NOTE_TABLE);
onCreate(db);
}
}
// Constructor
public DatabaseHelper(Context ctx) {
this.mContext = ctx;
}
public DatabaseHelper open() throws SQLException {
// Open the notes database. If it cannot be opened, try to
// create a new instance of the database. If it cannot be
// created, throw an exception to signal the failure
mOpenHelper = new DatabaseOpenHelper(mContext);
mDB = mOpenHelper.getWritableDatabase();
return this;
}
public void close() {
mOpenHelper.close();
}
/* Project ***********************************************************/
public boolean accessProject(long projectID) {
// Get current date
SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Update project's dateAccessed
ContentValues values = new ContentValues();
values.put(PROJECT_KEY_DATEACCESSED,
dateFormat.format(new Date()));
return mDB.update(
PROJECT_TABLE,
values,
PROJECT_KEY_ID + "=" + projectID,
null) > 0;
}
public boolean deleteProject(long projectID) {
// Get a cursor over the list of counters in this project
Cursor cursor = fetchAllCounters(projectID);
// Delete each counter
do {
if (!deleteCounter(cursor.getLong(
cursor.getColumnIndexOrThrow(COUNTER_KEY_ID))))
{
return false;
}
} while (cursor.moveToNext());
cursor.close();
// Delete the project
return mDB.delete(
PROJECT_TABLE,
PROJECT_KEY_ID + "=" + projectID,
null) > 0;
}
public Cursor fetchProjects() {
// Returns a Cursor over the list of all projects in the
// database
return mDB.query(
PROJECT_TABLE,
new String[] {PROJECT_KEY_ID, PROJECT_KEY_NAME},
null, null, null, null, null);
}
public String getProjectName(long projectID) {
Cursor cursor = mDB.query(
true,
PROJECT_TABLE,
new String[] {PROJECT_KEY_NAME},
PROJECT_KEY_ID + "=" + projectID,
null, null, null, null, null);
cursor.moveToFirst();
return cursor.getString(
cursor.getColumnIndexOrThrow(PROJECT_KEY_NAME));
}
public int getProjectTotalRows(long projectID) {
Cursor cursor = mDB.query(
true,
PROJECT_TABLE,
new String[] {PROJECT_KEY_TOTALROWS},
PROJECT_KEY_ID + "=" + projectID,
null, null, null, null, null);
cursor.moveToFirst();
return cursor.getInt(
cursor.getColumnIndexOrThrow(PROJECT_KEY_TOTALROWS));
}
public long insertProject(String name) {
// Get current date
SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues projectValues = new ContentValues();
projectValues.put(PROJECT_KEY_NAME, name);
projectValues.put(PROJECT_KEY_DATECREATED,
dateFormat.format(new Date()));
long projectID = mDB.insert(PROJECT_TABLE, null, projectValues);
// Exit if there was a database error
if (projectID == -1) {
return -1;
} else {
// Insert 1 counter to start
Log.w(TAG, "insertCounter returned:" +
insertCounter(projectID));
//insertCounter(projectID);
return projectID;
}
}
public boolean renameProject(long projectID, String name) {
ContentValues values = new ContentValues();
values.put(PROJECT_KEY_NAME, name);
return mDB.update(
PROJECT_TABLE,
values,
PROJECT_KEY_ID + "=" + projectID,
null) > 0;
}
public boolean updateProject(long projectID, int totalRows) {
ContentValues values = new ContentValues();
values.put(PROJECT_KEY_TOTALROWS, totalRows);
// Update project's current totalRows
return mDB.update(
PROJECT_TABLE,
values,
PROJECT_KEY_ID + "=" + projectID,
null) > 0;
}
/* Counter ***********************************************************/
public boolean deleteCounter(long counterID) {
return mDB.delete(
COUNTER_TABLE,
COUNTER_KEY_ID + "=" + counterID,
null) > 0;
}
public Cursor fetchAllCounters(long projectID) throws SQLException {
Log.w(TAG, "in fetchAllCounters");
Cursor cursor = mDB.query(
true,
COUNTER_TABLE,
new String[] {
COUNTER_KEY_ID,
COUNTER_KEY_NAME,
COUNTER_KEY_VALUE,
COUNTER_KEY_COUNTUP,
COUNTER_KEY_PATTERNON,
COUNTER_KEY_PATTERNLENGTH,
COUNTER_KEY_NUMREPEATS},
COUNTER_KEY_PROJECTID + "=" + projectID,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
if (cursor.getCount() == 0) {
Log.w(TAG, "counterCursor was empty");
}
return cursor;
}
public Cursor fetchCounter(long projectID, long counterID)
throws SQLException
{
Cursor cursor = mDB.query(
true,
COUNTER_TABLE,
new String[] {
COUNTER_KEY_ID,
COUNTER_KEY_NAME,
COUNTER_KEY_VALUE,
COUNTER_KEY_COUNTUP,
COUNTER_KEY_PATTERNON,
COUNTER_KEY_PATTERNLENGTH,
COUNTER_KEY_NUMREPEATS},
COUNTER_KEY_PROJECTID + "=" + projectID + " and " +
COUNTER_KEY_ID + "=" + counterID,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public long insertCounter(long projectID) {
ContentValues counterValues = new ContentValues();
counterValues.put(COUNTER_KEY_PROJECTID, projectID);
return mDB.insert(COUNTER_TABLE, null, counterValues);
}
public boolean updateCounter(long counterID, String name, int value,
boolean countUp, boolean patternOn,
int patternLength, int numRepeats)
{
ContentValues vals = new ContentValues();
vals.put(COUNTER_KEY_NAME, name);
vals.put(COUNTER_KEY_VALUE, value);
vals.put(COUNTER_KEY_COUNTUP, countUp);
vals.put(COUNTER_KEY_PATTERNON, patternOn);
vals.put(COUNTER_KEY_PATTERNLENGTH, patternLength);
vals.put(COUNTER_KEY_NUMREPEATS, numRepeats);
return mDB.update(
COUNTER_TABLE,
vals,
COUNTER_KEY_ID + "=" + counterID,
null) > 0;
}
}
| bsd-2-clause |
mrwinton/TheExcellentAdventure | src/test/parser_tests/GenerateGameTest.java | 3283 | package test.parser_tests;
import static org.junit.Assert.assertTrue;
import gameworld.Orientation;
import gameworld.Player;
import gameworld.items.Item;
import gameworld.items.ItemManager;
import gameworld.items.ItemManagerImpl;
import gameworld.items.ItemState;
import gameworld.rooms.Room;
import gameworld.rooms.RoomManager;
import gameworld.rooms.RoomManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import nodes.BasicNode;
import nodes.PlayerNode;
import nodes.RoomNode;
import org.junit.Before;
import org.junit.Test;
import parser.GsParser;
import datastorage.Game;
import datastorage.Game.GameMode;
import datastorage.GameState;
public class GenerateGameTest {
private GameState gs;
private Game game;
@Before
public void setUp() throws Exception {
ItemManager itemManager = new ItemManagerImpl();
RoomManager roomManager = new RoomManagerImpl();
gs = GsParser.generateGameState("RUN S R0 L C C C I0DA R1 L C L C I1FA I2FA I3FA R2 L C L L R3 L L C C I5DA I6DR I13DA I4DR R4 L C L L R5 C L L C I8DA I7DA I5DA R6 L C L L R7 C C L C I9DR R8 C L C C I10TA I11FA P0 0 N I4DR I9DR M EMPTY X");
GameMode gameMode = gs.getMode();
ArrayList<PlayerNode> playerNodes = gs.getPlayers();
HashMap<Integer, RoomNode> roomNodeMap = gs.getRooms();
ArrayList<Player> players = new ArrayList<Player>();
HashMap<Integer, Room> rooms = new HashMap<Integer, Room>();
for(PlayerNode pNode: playerNodes){
//setup player
int uid = pNode.getID();
int rid = pNode.getRoomID();
Orientation orientation = pNode.getOrientation();
Player p = new Player(uid, rid, orientation);
//add items to player
ArrayList<BasicNode> playerItems = pNode.getChildren();
for(BasicNode bNode : playerItems){
int itemId = bNode.getId();
ItemState itemState = bNode.getState();
Item item = itemManager.getItemWithIdAndState(itemId, itemState);
p.addItem(item);
}
//add player
players.add(p);
}
for(RoomNode rNode: roomNodeMap.values()){
//setup room
int rid = rNode.getID();
//add items to player
ArrayList<BasicNode> roomItems = rNode.getChildren();
ArrayList<Item> items = new ArrayList<Item>();
for(BasicNode bNode : roomItems){
int itemId = bNode.getId();
ItemState itemState = bNode.getState();
Item item = itemManager.getItemWithIdAndState(itemId, itemState);
items.add(item);
}
Room room = roomManager.getRoomWithIdAndItems(rid, items);
//add room
rooms.put(room.getId(), room);
}
game = new Game(gameMode, players, rooms);
}
/**
* Making sure the generated game is valid (not throwing any exceptions) and is not holding null or empty things
*/
@Test
public void test() {
ArrayList<Player> players = game.getPlayers();
HashMap<Integer, Room> rooms = game.getRooms();
GameMode gameMode = game.getMode();
boolean notNullOrEmpty = true;
if(gameMode == null){
notNullOrEmpty = false;
}
if(players == null || players.isEmpty()){
notNullOrEmpty = false;
}
if(rooms == null || rooms.isEmpty() ){
notNullOrEmpty = false;
}
assertTrue("The generated game is not null or empty", notNullOrEmpty);
}
}
| bsd-2-clause |
pm4j/org.pm4j | pm4j-core/src/main/java/org/pm4j/core/pm/impl/PmAttrShortImpl.java | 2649 | package org.pm4j.core.pm.impl;
import org.pm4j.common.converter.string.StringConverterShort;
import org.pm4j.core.exception.PmRuntimeException;
import org.pm4j.core.exception.PmValidationException;
import org.pm4j.core.pm.PmAttrShort;
import org.pm4j.core.pm.PmConstants;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.annotation.PmAttrShortCfg;
/**
* PM attribute implementation for {@link Short} values.
*
* @author olaf boede
*/
public class PmAttrShortImpl extends PmAttrNumBase<Short> implements PmAttrShort {
public PmAttrShortImpl(PmObject pmParent) {
super(pmParent);
}
// ======== Interface implementation ======== //
public Short getMaxValue() {
return getOwnMetaDataWithoutPmInitCall().maxValue;
}
public Short getMinValue() {
return getOwnMetaDataWithoutPmInitCall().minValue;
}
// ======== Value handling ======== //
@Override
protected void validate(Short value) throws PmValidationException {
super.validate(value);
if (value != null) {
int v = value.intValue();
if (v < getMinValue().longValue()) {
throw new PmValidationException(this, PmConstants.MSGKEY_VALIDATION_VALUE_TOO_LOW, getMinValue());
}
if (v > getMaxValue().longValue()) {
throw new PmValidationException(this, PmConstants.MSGKEY_VALIDATION_VALUE_TOO_HIGH, getMaxValue());
}
}
}
@Override
protected String getFormatDefaultResKey() {
return RESKEY_DEFAULT_INTEGER_FORMAT_PATTERN;
}
// ======== meta data ======== //
@Override
protected PmObjectBase.MetaData makeMetaData() {
MetaData md = new MetaData();
md.setStringConverter(StringConverterShort.INSTANCE);
return md;
}
@Override
protected void initMetaData(PmObjectBase.MetaData metaData) {
super.initMetaData(metaData);
MetaData myMetaData = (MetaData) metaData;
PmAttrShortCfg annotation = AnnotationUtil.findAnnotation(this, PmAttrShortCfg.class);
if (annotation != null) {
short maxValue = myMetaData.maxValue = annotation.maxValue();
short minValue = myMetaData.minValue = annotation.minValue();
if (minValue > maxValue) {
throw new PmRuntimeException(this, "minValue(" + minValue + ") > maxValue(" + maxValue + ")");
}
}
}
protected static class MetaData extends PmAttrNumBase.MetaData {
private short maxValue = Short.MAX_VALUE;
private short minValue = Short.MIN_VALUE;
@Override
protected double getMaxValueAsDouble() {
return maxValue;
}
}
private final MetaData getOwnMetaDataWithoutPmInitCall() {
return (MetaData) getPmMetaDataWithoutPmInitCall();
}
}
| bsd-2-clause |
sandor-balazs/nosql-java | mysql/src/main/java/com/github/sandor_balazs/nosql_java/config/DatabaseConfiguration.java | 5474 | package com.github.sandor_balazs.nosql_java.config;
import com.github.sandor_balazs.nosql_java.config.liquibase.AsyncSpringLiquibase;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.util.Arrays;
@Configuration
@EnableJpaRepositories("com.github.sandor_balazs.nosql_java.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
@Inject
private Environment env;
@Autowired(required = false)
private MetricRegistry metricRegistry;
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
config.addDataSourceProperty("url", dataSourceProperties.getUrl());
if (dataSourceProperties.getUsername() != null) {
config.addDataSourceProperty("user", dataSourceProperties.getUsername());
} else {
config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
}
if (dataSourceProperties.getPassword() != null) {
config.addDataSourceProperty("password", dataSourceProperties.getPassword());
} else {
config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
}
//MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
}
if (metricRegistry != null) {
config.setMetricRegistry(metricRegistry);
}
return new HikariDataSource(config);
}
@Bean
public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dataSourceProperties,
LiquibaseProperties liquibaseProperties) {
// Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
SpringLiquibase liquibase = new AsyncSpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setShouldRun(liquibaseProperties.isEnabled());
if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourceProperties.getDriverClassName())) {
liquibase.setShouldRun(true);
log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" +
" MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
} else {
liquibase.setShouldRun(false);
}
} else {
log.debug("Configuring Liquibase");
}
return liquibase;
}
@Bean
public Hibernate4Module hibernate4Module() {
return new Hibernate4Module();
}
}
| bsd-2-clause |
bnanes/slideset | src/main/java/org/nanes/slideset/dm/write/StringToStringWriter.java | 457 | package org.nanes.slideset.dm.write;
import org.nanes.slideset.dm.StringElement;
/**
*
* @author Benjamin Nanes
*/
@ElementWriterMetadata(
name = "Text",
elementType = StringElement.class,
processedType = String.class)
public class StringToStringWriter implements ElementWriter<StringElement, String> {
public void write(String data, StringElement elementToWrite) {
elementToWrite.setUnderlying(data);
}
}
| bsd-2-clause |
jackstraw66/web | livescribe/lsversion/src/test/java/com/livescribe/framework/version/service/VersionServiceImplTest.java | 995 | /**
* Created: May 13, 2013 5:00:23 PM
*/
package com.livescribe.framework.version.service;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.livescribe.framework.version.BaseTest;
import com.livescribe.framework.version.dao.CustomVersionDao;
/**
* <p></p>
*
* @author <a href="mailto:kmurdoff@livescribe.com">Kevin F. Murdoff</a>
* @version 1.0
*/
public class VersionServiceImplTest extends BaseTest {
@Autowired
private VersionService versionService;
@Autowired
private CustomVersionDao versionDao;
/**
* <p></p>
*
*/
public VersionServiceImplTest() {
super();
}
@Before
public void setUp() {
}
@Test
@Transactional("txVersions")
public void testPostVersion() {
// versionService.postVersion();
// versionService.getVersion();
// versionDao.findByAppAndEnvironment("testServletContext", Env.LOCAL);
}
}
| bsd-2-clause |
licehammer/perun | perun-core/src/main/java/cz/metacentrum/perun/core/impl/GroupsManagerImpl.java | 35489 | package cz.metacentrum.perun.core.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import cz.metacentrum.perun.core.api.exceptions.GroupRelationDoesNotExist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcPerunTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.GroupsManager;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.MembershipType;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.Status;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.GroupAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.GroupExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.NotGroupMemberException;
import cz.metacentrum.perun.core.api.exceptions.ParentGroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.blImpl.AuthzResolverBlImpl;
import cz.metacentrum.perun.core.implApi.GroupsManagerImplApi;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of GroupsManager
*
* @author Michal Prochazka michalp@ics.muni.cz
* @author Slavek Licehammer glory@ics.muni.cz
*/
public class GroupsManagerImpl implements GroupsManagerImplApi {
private final static Logger log = LoggerFactory.getLogger(GroupsManagerImpl.class);
public final static int MEMBERSGROUP = 1;
public final static int ADMINSGROUP = 2;
public final static int SUBGROUP = 3;
protected final static String groupMappingSelectQuery = "groups.id as groups_id, groups.parent_group_id as groups_parent_group_id, groups.name as groups_name, groups.dsc as groups_dsc, "
+ "groups.vo_id as groups_vo_id, groups.created_at as groups_created_at, groups.created_by as groups_created_by, groups.modified_by as groups_modified_by, groups.modified_at as groups_modified_at, "
+ "groups.modified_by_uid as groups_modified_by_uid, groups.created_by_uid as groups_created_by_uid ";
// http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
private JdbcPerunTemplate jdbc;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
// Group mapper
protected static final RowMapper<Group> GROUP_MAPPER = new RowMapper<Group>() {
public Group mapRow(ResultSet rs, int i) throws SQLException {
Group g = new Group();
g.setId(rs.getInt("groups_id"));
//ParentGroup with ID=0 is not supported
if(rs.getInt("groups_parent_group_id") != 0) g.setParentGroupId(rs.getInt("groups_parent_group_id"));
else g.setParentGroupId(null);
g.setName(rs.getString("groups_name"));
g.setShortName(g.getName().substring(g.getName().lastIndexOf(":") + 1));
g.setDescription(rs.getString("groups_dsc"));
g.setVoId(rs.getInt("groups_vo_id"));
g.setCreatedAt(rs.getString("groups_created_at"));
g.setCreatedBy(rs.getString("groups_created_by"));
g.setModifiedAt(rs.getString("groups_modified_at"));
g.setModifiedBy(rs.getString("groups_modified_by"));
if(rs.getInt("groups_modified_by_uid") == 0) g.setModifiedByUid(null);
else g.setModifiedByUid(rs.getInt("groups_modified_by_uid"));
if(rs.getInt("groups_created_by_uid") == 0) g.setCreatedByUid(null);
else g.setCreatedByUid(rs.getInt("groups_created_by_uid"));
return g;
}
};
private static final RowMapper<Pair<Group, Resource>> GROUP_RESOURCE_MAPPER = new RowMapper<Pair<Group, Resource>>() {
public Pair<Group, Resource> mapRow(ResultSet rs, int i) throws SQLException {
Pair<Group, Resource> pair = new Pair<Group, Resource>();
pair.put(GROUP_MAPPER.mapRow(rs, i), ResourcesManagerImpl.RESOURCE_MAPPER.mapRow(rs, i));
return pair;
}
};
/**
* Create new instance of this class.
*
*/
public GroupsManagerImpl(DataSource perunPool) {
this.jdbc = new JdbcPerunTemplate(perunPool);
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(perunPool);
}
public Group createGroup(PerunSession sess, Vo vo, Group group) throws GroupExistsException, InternalErrorException {
Utils.notNull(group, "group");
Utils.notNull(group.getName(), "group.getName()");
// Check if the group already exists
if(group.getParentGroupId() == null) {
// check if the TOP level group exists
if (1 == jdbc.queryForInt("select count('x') from groups where lower(name)=lower(?) and vo_id=? and parent_group_id IS NULL", group.getName(), vo.getId())) {
throw new GroupExistsException("Group [" + group.getName() + "] already exists under VO [" + vo.getShortName() + "] and has parent Group with id is [NULL]");
}
} else {
// check if subgroup exists under parent group
if (1 == jdbc.queryForInt("select count('x') from groups where lower(name)=lower(?) and vo_id=? and parent_group_id=?", group.getName(), vo.getId(), group.getParentGroupId())) {
throw new GroupExistsException("Group [" + group.getName() + "] already exists under VO [" + vo.getShortName() + "] and has parent Group with id [" + group.getParentGroupId() + "]");
}
}
// Check the group name, it can contain only a-Z0-9_- and space
if (!group.getShortName().matches("^[- a-zA-Z.0-9_]+$")) {
throw new InternalErrorException(new IllegalArgumentException("Wrong group name, group name can contain only a-Z0-9.-_: and space characters. " + group));
}
try {
// Store the group into the DB
int newId = Utils.getNewId(jdbc, "groups_id_seq");
jdbc.update("insert into groups (id, parent_group_id, name, dsc, vo_id, created_by,created_at,modified_by,modified_at,created_by_uid,modified_by_uid) " +
"values (?,?,?,?,?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?)", newId, group.getParentGroupId(),
group.getName(), group.getDescription(), vo.getId(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), sess.getPerunPrincipal().getUserId());
group.setId(newId);
group.setVoId(vo.getId());
return group;
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public String getName(int id) throws InternalErrorException {
List name= null;
try {
name = jdbc.query("group.name as (with temp (name, id, parent_group_id) as ((select name, id, parent_group_id from GROUPS where parent_group_id is null) union all (select cast((temp.name + ':' + groups.name) as varchar(128)), " +
"groups.id, groups.parent_group_id from groups inner join temp on temp.id = groups.parent_group_id )) select name from temp where group.id = ?"
,new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString(1);
}
},id);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
String result=(String)name.get(0);
return result;
}
/*
* Create a subgroup
*
* @see cz.metacentrum.perun.core.implApi.GroupsManagerImplApi#createGroup(cz.metacentrum.perun.core.api.PerunSession, cz.metacentrum.perun.core.api.Vo, cz.metacentrum.perun.core.api.Group, cz.metacentrum.perun.core.api.Group)
*/
public Group createGroup(PerunSession sess, Vo vo, Group parentGroup, Group group) throws GroupExistsException, InternalErrorException {
// Create new subGroup
group.setParentGroupId(parentGroup.getId());
group.setName(parentGroup.getName()+":"+group.getShortName());
group = createGroup(sess, vo, group);
return group;
}
public void deleteGroup(PerunSession sess, Vo vo, Group group) throws InternalErrorException, GroupAlreadyRemovedException {
Utils.notNull(group.getName(), "group.getName()");
try {
// Delete group's members
jdbc.update("delete from groups_members where group_id=?", group.getId());
// Delete authz entries for this group
AuthzResolverBlImpl.removeAllAuthzForGroup(sess, group);
int rowAffected = jdbc.update("delete from groups where id=?", group.getId());
if(rowAffected == 0) throw new GroupAlreadyRemovedException("Group: " + group + " , Vo: " + vo);
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public Group updateGroup(PerunSession sess, Group group) throws InternalErrorException {
Utils.notNull(group.getName(), "group.getName()");
// Get the group stored in the DB
Group dbGroup;
try {
dbGroup = this.getGroupById(sess, group.getId());
} catch (GroupNotExistsException e) {
throw new InternalErrorException("Group existence was checked at the higher level",e);
}
// we allow only update on shortName part of name
if (!dbGroup.getShortName().equals(group.getShortName())) {
dbGroup.setShortName(group.getShortName());
try {
jdbc.update("update groups set name=?,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", dbGroup.getName(),
sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), dbGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
if (group.getDescription() != null && !group.getDescription().equals(dbGroup.getDescription())) {
try {
jdbc.update("update groups set dsc=?, modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", group.getDescription(),
sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), group.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
dbGroup.setDescription(group.getDescription());
}
return dbGroup;
}
public Group updateGroupName(PerunSession sess, Group group) throws InternalErrorException {
Utils.notNull(group.getName(), "group.getName()");
// Get the group stored in the DB
Group dbGroup;
try {
dbGroup = this.getGroupById(sess, group.getId());
} catch (GroupNotExistsException e) {
throw new InternalErrorException("Group existence was checked at the higher level",e);
}
if (!dbGroup.getName().equals(group.getName())) {
dbGroup.setName(group.getName());
try {
jdbc.update("update groups set name=?,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", dbGroup.getName(),
sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), dbGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
return dbGroup;
}
public Group updateParentGroupId(PerunSession sess, Group group) throws InternalErrorException {
Utils.notNull(group, "group");
// Get the group stored in the DB
Group dbGroup;
try {
dbGroup = this.getGroupById(sess, group.getId());
} catch (GroupNotExistsException e) {
throw new InternalErrorException("Group existence was checked at the higher level",e);
}
//check if group parent id was changed to another id or to null
if ((group.getParentGroupId() != null && !group.getParentGroupId().equals(dbGroup.getParentGroupId())) ||
(group.getParentGroupId() == null && dbGroup.getParentGroupId() != null)) {
dbGroup.setParentGroupId(group.getParentGroupId());
try {
jdbc.update("update groups set parent_group_id=?,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", dbGroup.getParentGroupId(),
sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), dbGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
return dbGroup;
}
public Group getGroupById(PerunSession sess, int id) throws GroupNotExistsException, InternalErrorException {
try {
return jdbc.queryForObject("select " + groupMappingSelectQuery + " from groups where groups.id=? ", GROUP_MAPPER, id);
} catch (EmptyResultDataAccessException err) {
throw new GroupNotExistsException("Group id=" + id);
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public List<User> getGroupUsers(PerunSession sess, Group group) throws InternalErrorException {
try {
return jdbc.query("select " + UsersManagerImpl.userMappingSelectQuery + " from groups_members join members on members.id=member_id join " +
"users on members.user_id=users.id where group_id=? order by " + Compatibility.orderByBinary("users.last_name") + ", " +
Compatibility.orderByBinary("users.first_name"), UsersManagerImpl.USER_MAPPER, group.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public boolean isUserMemberOfGroup(PerunSession sess, User user, Group group) throws InternalErrorException {
try {
return 1 <= jdbc.queryForInt("select count(1) from groups_members join members on members.id = member_id where members.user_id=? and groups_members.group_id=?", user.getId(), group.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public List<Member> getGroupMembers(PerunSession sess, Group group) throws InternalErrorException {
try {
return jdbc.query("select " + MembersManagerImpl.groupsMembersMappingSelectQuery + " from groups_members join members on members.id=groups_members.member_id " +
"where groups_members.group_id=?", MembersManagerImpl.MEMBER_MAPPER, group.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Member>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Member> getGroupMembers(PerunSession sess, Group group, List<Status> statuses, boolean excludeStatus) throws InternalErrorException {
try {
MapSqlParameterSource parameters = new MapSqlParameterSource();
List<Integer> statusesCodes = new ArrayList<Integer>();
for (Status status: statuses) {
statusesCodes.add(status.getCode());
}
parameters.addValue("statuses", statusesCodes);
parameters.addValue("group_id", group.getId());
if (excludeStatus) {
// Exclude members with one of the status
return this.namedParameterJdbcTemplate.query("select " + MembersManagerImpl.groupsMembersMappingSelectQuery +
" from groups_members join members on members.id=groups_members.member_id " +
"where groups_members.group_id=:group_id and members.status"+Compatibility.castToInteger()+" not in (:statuses)", parameters, MembersManagerImpl.MEMBER_MAPPER);
} else {
// Include members with one of the status
return this.namedParameterJdbcTemplate.query("select " + MembersManagerImpl.groupsMembersMappingSelectQuery +
" from groups_members join members on members.id=groups_members.member_id " +
"where groups_members.group_id=:group_id and members.status"+Compatibility.castToInteger()+" in (:statuses)", parameters, MembersManagerImpl.MEMBER_MAPPER);
}
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Member>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Group> getGroups(PerunSession sess, Vo vo) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups where vo_id=? order by " +
Compatibility.orderByBinary("groups.name" + Compatibility.castToVarchar()),
GROUP_MAPPER, vo.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public List<Group> getAssignedGroupsToResource(PerunSession perunSession, Resource resource) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups join " +
" groups_resources on groups.id=groups_resources.group_id " +
" where groups_resources.resource_id=?",
GROUP_MAPPER, resource.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Group> getAssignedGroupsToResource(PerunSession perunSession, Resource resource, Member member) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups join " +
" groups_resources on groups.id=groups_resources.group_id and groups_resources.resource_id=?" +
" join groups_members on groups_members.group_id=groups.id and groups_members.member_id=?",
GROUP_MAPPER, resource.getId(), member.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Group> getAssignedGroupsToFacility(PerunSession perunSession, Facility facility) throws InternalErrorException {
try {
return jdbc.query("select distinct " + groupMappingSelectQuery + " from groups join " +
" groups_resources on groups.id=groups_resources.group_id " +
" join resources on groups_resources.resource_id=resources.id " +
"where resources.facility_id=?",
GROUP_MAPPER, facility.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Group> getSubGroups(PerunSession sess, Group parentGroup) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups where groups.parent_group_id=? " +
"order by " + Compatibility.orderByBinary("groups.name" + Compatibility.castToVarchar()),
GROUP_MAPPER, parentGroup.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public int getSubGroupsCount(PerunSession sess, Group parentGroup) throws InternalErrorException {
try {
return jdbc.queryForInt("select count(1) from groups where parent_group_id=?", parentGroup.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public List<Group> getAllGroups(PerunSession sess, Vo vo) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups where vo_id=?", GROUP_MAPPER, vo.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public Group getParentGroup(PerunSession sess, Group group) throws InternalErrorException, ParentGroupNotExistsException {
try {
return jdbc.queryForObject("select " + groupMappingSelectQuery + " from groups where groups.id=?",
GROUP_MAPPER, group.getParentGroupId());
} catch (EmptyResultDataAccessException e) {
throw new ParentGroupNotExistsException(e);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public Group getGroupByName(PerunSession sess, Vo vo, String name) throws GroupNotExistsException, InternalErrorException {
try {
return jdbc.queryForObject("select " + groupMappingSelectQuery + " from groups where groups.name=? and groups.vo_id=?",
GROUP_MAPPER, name, vo.getId());
} catch (EmptyResultDataAccessException err) {
throw new GroupNotExistsException("Group name=" + name + ", vo id=" + vo.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public Member addMember(PerunSession sess, Group group, Member member, MembershipType type, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException {
member.setMembershipType(type);
member.setSourceGroupId(sourceGroupId);
try {
jdbc.update("insert into groups_members (group_id, member_id, created_by, created_at, modified_by, modified_at, created_by_uid, modified_by_uid, membership_type, source_group_id) " +
"values (?,?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?,?,?)", group.getId(),
member.getId(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), sess.getPerunPrincipal().getUserId(), type.getCode(), sourceGroupId);
} catch(DuplicateKeyException ex) {
throw new AlreadyMemberException(member);
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
return member;
}
public List<Group> getGroupsByIds(PerunSession sess, List<Integer> groupsIds) throws InternalErrorException {
// If groupsIds are empty, we can immediately return empty result
if (groupsIds.size() == 0) {
return new ArrayList<Group>();
}
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", groupsIds);
try {
return this.namedParameterJdbcTemplate.query("select " + groupMappingSelectQuery + " from groups where groups.id in ( :ids )",
parameters, GROUP_MAPPER);
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<Group>();
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public List<Group> getAllMemberGroups(PerunSession sess, Member member) throws InternalErrorException {
try {
return jdbc.query("select distinct " + groupMappingSelectQuery + " from groups_members join groups on groups_members.group_id = groups.id " +
" where groups_members.member_id=?",
GROUP_MAPPER, member.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Group> getGroupsByAttribute(PerunSession sess, Attribute attribute) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from groups " +
"join group_attr_values on groups.id=group_attr_values.group_id where group_attr_values.attr_id=? and " +
"group_attr_values.attr_value=?",
GROUP_MAPPER, attribute.getId(), BeansUtils.attributeValueToString(attribute));
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public List<Pair<Group,Resource>> getGroupResourcePairsByAttribute(PerunSession sess, Attribute attribute) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + ", " + ResourcesManagerImpl.resourceMappingSelectQuery +
" from group_resource_attr_values " +
"join groups on groups.id=group_resource_attr_values.group_id " +
"join resources on resources.id=group_resource_attr_values.resource_id " +
"where group_resource_attr_values.attr_id=? and group_resource_attr_values.attr_value=?",
GROUP_RESOURCE_MAPPER, attribute.getId(), BeansUtils.attributeValueToString(attribute));
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Pair<Group, Resource>>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public boolean isGroupMember(PerunSession sess, Group group, Member member) throws InternalErrorException {
try {
return 1 <= jdbc.queryForInt("select count(1) from groups_members where group_id=? and member_id=?", group.getId(), member.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public boolean isDirectGroupMember(PerunSession sess, Group group, Member member) throws InternalErrorException {
try {
int count = jdbc.queryForInt("select count(1) from groups_members where group_id=? and member_id=? and membership_type = ?", group.getId(), member.getId(), MembershipType.DIRECT.getCode());
if (1 < count) throw new ConsistencyErrorException("There is more than one direct member in group" + group);
return 1 == count;
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, NotGroupMemberException {
if (member.getSourceGroupId() == null) {
throw new InternalErrorException("sourceGroupId not set for member object");
}
int ret;
try {
ret = jdbc.update("delete from groups_members where group_id=? and source_group_id=? and member_id=?", group.getId(), member.getSourceGroupId(), member.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
if(ret == 0) {
throw new NotGroupMemberException(member);
} else if(ret >= 1) {
return;
} else {
throw new ConsistencyErrorException(member + " and " + group + " have " + ret + " rows in groups_members table");
}
}
@Override
public List<User> getAdmins(PerunSession sess, Group group) throws InternalErrorException {
try {
Set<User> setOfAdmins = new HashSet<User>();
// direct admins
setOfAdmins.addAll(jdbc.query("select " + UsersManagerImpl.userMappingSelectQuery + " from authz join users on authz.user_id=users.id " +
"where authz.group_id=? and authz.role_id=(select id from roles where name='groupadmin')", UsersManagerImpl.USER_MAPPER, group.getId()));
// admins through a group
List<Group> listOfGroupAdmins = getGroupAdmins(sess, group);
for(Group authorizedGroup : listOfGroupAdmins) {
setOfAdmins.addAll(jdbc.query("select " + UsersManagerImpl.userMappingSelectQuery + " from users join members on users.id=members.user_id " +
"join groups_members on groups_members.member_id=members.id where groups_members.group_id=?", UsersManagerImpl.USER_MAPPER, authorizedGroup.getId()));
}
return new ArrayList(setOfAdmins);
} catch (EmptyResultDataAccessException e) {
return new ArrayList<User>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<User> getDirectAdmins(PerunSession sess, Group group) throws InternalErrorException {
try {
return jdbc.query("select " + UsersManagerImpl.userMappingSelectQuery + " from authz join users on authz.user_id=users.id " +
"where authz.group_id=? and authz.role_id=(select id from roles where name='groupadmin')", UsersManagerImpl.USER_MAPPER, group.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<User>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Group> getGroupAdmins(PerunSession sess, Group group) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery + " from authz join groups on authz.authorized_group_id=groups.id " +
"where authz.group_id=? and authz.role_id=(select id from roles where name='groupadmin')",
GROUP_MAPPER, group.getId());
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public int getGroupsCount(PerunSession sess, Vo vo) throws InternalErrorException {
try {
return jdbc.queryForInt("select count(1) from groups where vo_id=?", vo.getId());
} catch(RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
public int getVoId(PerunSession sess, Group group) throws InternalErrorException {
try {
return jdbc.queryForInt("select vo_id from groups where id=?", group.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void checkGroupExists(PerunSession sess, Group group) throws InternalErrorException, GroupNotExistsException {
if (!groupExists(sess, group)) throw new GroupNotExistsException("Group " + group);
}
public boolean groupExists(PerunSession sess, Group group) throws InternalErrorException {
try {
return 1 == jdbc.queryForInt("select 1 from groups where id=?", group.getId());
} catch(EmptyResultDataAccessException ex) {
return false;
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
/**
* Gets all groups which have enabled synchronization.
*
* @param sess
* @return list of groups to synchronize
* @throws InternalErrorException
*/
public List<Group> getGroupsToSynchronize(PerunSession sess) throws InternalErrorException {
try {
// Get all groups which have defined
return jdbc.query("select " + groupMappingSelectQuery + " from groups, attr_names, group_attr_values " +
"where attr_names.attr_name=? and attr_names.id=group_attr_values.attr_id and group_attr_values.attr_value='true' and " +
"group_attr_values.group_id=groups.id", GROUP_MAPPER, GroupsManager.GROUPSYNCHROENABLED_ATTRNAME);
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Group>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Integer> getGroupApplicationIds(PerunSession sess, Group group) throws InternalErrorException {
// get app ids for all applications
try {
return jdbc.query("select id from application where group_id=?", new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet rs, int arg1)
throws SQLException {
return rs.getInt("id");
}
},group.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Pair<String, String>> getApplicationReservedLogins(Integer appId) throws InternalErrorException {
try {
return jdbc.query("select namespace,login from application_reserved_logins where app_id=?", new RowMapper<Pair<String, String>>() {
@Override
public Pair<String, String> mapRow(ResultSet rs, int arg1) throws SQLException {
return new Pair<String, String>(rs.getString("namespace"), rs.getString("login"));
}
}, appId);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void deleteGroupReservedLogins(PerunSession sess, Group group) throws InternalErrorException {
// remove all reserved logins first
try {
for (Integer appId : getGroupApplicationIds(sess, group)) {
jdbc.update("delete from application_reserved_logins where app_id=?", appId);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public int getGroupsCount(PerunSession sess) throws InternalErrorException {
try {
return jdbc.queryForInt("select count(*) from groups");
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
@Override
public List<Group> getGroupsWithAssignedExtSourceInVo(PerunSession sess, ExtSource source, Vo vo) throws InternalErrorException {
try {
return jdbc.query("select " + groupMappingSelectQuery +
" from group_ext_sources g_exts inner join groups on g_exts.group_id=groups.id " +
" where g_exts.ext_source_id=? and groups.vo_id=?", GROUP_MAPPER, source.getId(), vo.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void removeGroupUnion(PerunSession sess, Group resultGroup, Group operandGroup) throws InternalErrorException, GroupRelationDoesNotExist {
try {
if (0 == jdbc.update("DELETE FROM groups_groups WHERE result_gid = ? AND operand_gid = ?",
resultGroup.getId(), operandGroup.getId())) {
throw new GroupRelationDoesNotExist("Union between " + resultGroup + " and " + operandGroup + " does not exist.");
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void removeResultGroupRelations(PerunSession sess, Group resultGroup) throws InternalErrorException {
try {
jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void saveGroupRelation(PerunSession sess, Group resultGroup, Group operandGroup, boolean parentFlag) throws InternalErrorException {
try {
jdbc.update("INSERT INTO groups_groups(result_gid, operand_gid, created_at, created_by, " +
"modified_at, modified_by, parent_flag) VALUES(?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?)",
resultGroup.getId(), operandGroup.getId(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), parentFlag);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public boolean isRelationRemovable(PerunSession sess, Group resultGroup, Group operandGroup) throws InternalErrorException {
try {
return 1 > jdbc.queryForInt("SELECT parent_flag"+Compatibility.castToInteger()+" FROM groups_groups WHERE result_gid=? AND operand_gid=?",
resultGroup.getId(), operandGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public boolean isRelationBetweenGroups(Group group1, Group group2) throws InternalErrorException {
try {
return 1 <= jdbc.queryForInt("SELECT count(1) FROM groups_groups WHERE (result_gid = ? AND operand_gid = ?) OR (result_gid = ? AND operand_gid = ?)",
group1.getId(), group2.getId(), group2.getId(), group1.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public boolean isOneWayRelationBetweenGroups(Group resultGroup, Group operandGroup) throws InternalErrorException {
try {
return 1 <= jdbc.queryForInt("SELECT count(1) FROM groups_groups WHERE result_gid = ? AND operand_gid = ?",
resultGroup.getId(), operandGroup.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Group> getResultGroups(PerunSession sess, int groupId) throws InternalErrorException {
try {
return jdbc.query("SELECT " + groupMappingSelectQuery + " FROM groups_groups JOIN groups " +
"ON groups.id = groups_groups.result_gid WHERE operand_gid=?", GROUP_MAPPER, groupId);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Group> getOperandGroups(PerunSession sess, int groupId) throws InternalErrorException {
try {
return jdbc.query("SELECT " + groupMappingSelectQuery + " FROM groups_groups JOIN groups " +
"ON groups.id = groups_groups.operand_gid WHERE result_gid=?", GROUP_MAPPER, groupId);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public List<Integer> getResultGroupsIds(PerunSession sess, int groupId) throws InternalErrorException {
try {
return jdbc.queryForList("SELECT result_gid FROM groups_groups WHERE operand_gid=?", Integer.class, groupId);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
}
| bsd-2-clause |
KorAP/Krill | src/main/java/de/ids_mannheim/korap/query/SpanSubspanQuery.java | 3940 | package de.ids_mannheim.korap.query;
import java.io.IOException;
import java.util.Map;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.Spans;
import org.apache.lucene.util.Bits;
import de.ids_mannheim.korap.query.spans.SubSpans;
/**
* This query extracts a subspan from another span. The subspan starts
* from a startOffset until startOffset + length. A positive
* startOffset is counted from the start of the span, while a negative
* startOffset is calculated from the end of the span. <br />
* <br />
* SpanSubspanQuery takes a SpanQuery as its input and creates
* subspans from the
* resulting spans of the SpanQuery. For instance:
*
* <pre>
* SpanElementQuery seq = new SpanElementQuery(new
* SpanElementQuery("tokens", "s");
* SpanSubspanQuery ssq = new SpanSubspanQuery(seq, 0, 2, true);
* </pre>
*
* In this example, the SpanSubspanQuery creates subspans, that are
* the first
* two tokens of all sentences.
*
* @author margaretha
*/
public class SpanSubspanQuery extends SimpleSpanQuery {
private int startOffset, length;
private int windowSize = 10;
/**
* Creates a SpanSubspanQuery (subspan) from the given
* {@link SpanQuery} with the specified startOffset and length.
*
* @param firstClause
* a SpanQuery
* @param startOffset
* the start offset of the subspan relative to the
* original span
* @param length
* the length of the subspan
* @param collectPayloads
* a boolean flag representing the value
* <code>true</code> if payloads are to be collected,
* otherwise
* <code>false</code>.
*/
public SpanSubspanQuery (SpanQuery firstClause, int startOffset, int length,
boolean collectPayloads) {
super(firstClause, collectPayloads);
this.startOffset = startOffset;
this.length = length;
}
@Override
public SimpleSpanQuery clone () {
SpanSubspanQuery sq = new SpanSubspanQuery(this.getFirstClause(),
this.startOffset, this.length, this.collectPayloads);
sq.setBoost(this.getBoost());
return sq;
}
@Override
public Spans getSpans (LeafReaderContext context, Bits acceptDocs,
Map<Term, TermContext> termContexts) throws IOException {
return new SubSpans(this, context, acceptDocs, termContexts);
}
@Override
public String toString (String field) {
StringBuilder sb = new StringBuilder();
sb.append("subspan(");
sb.append(this.firstClause.toString());
sb.append(", ");
sb.append(this.startOffset);
sb.append(", ");
sb.append(this.length);
sb.append(")");
return sb.toString();
}
/**
* Returns the start offset.
*
* @return the start offset.
*/
public int getStartOffset () {
return startOffset;
}
/**
* Sets the start offset.
*
* @param startOffset
* the start offset
*/
public void setStartOffset (int startOffset) {
this.startOffset = startOffset;
}
/**
* Returns the length of the subspan.
*
* @return the length of the subspan
*/
public int getLength () {
return length;
}
/**
* Sets the length of the subspan.
*
* @param length
* the length of the subspan.
*/
public void setLength (int length) {
this.length = length;
}
public int getWindowSize () {
return windowSize;
}
public void setWindowSize (int windowSize) {
this.windowSize = windowSize;
}
}
| bsd-2-clause |
highsource/javascript-codemodel | codemodel/src/main/java/org/hisrc/jscm/codemodel/expression/impl/ConditionalExpressionImpl.java | 1627 | package org.hisrc.jscm.codemodel.expression.impl;
import org.hisrc.jscm.codemodel.JSCodeModel;
import org.hisrc.jscm.codemodel.expression.JSAssignmentExpression;
import org.hisrc.jscm.codemodel.expression.JSConditionalExpression;
import org.hisrc.jscm.codemodel.expression.JSExpressionVisitor;
import org.hisrc.jscm.codemodel.expression.JSLogicalORExpression;
import org.hisrc.jscm.codemodel.lang.Validate;
public abstract class ConditionalExpressionImpl extends
AssignmentExpressionImpl implements JSConditionalExpression {
public ConditionalExpressionImpl(JSCodeModel codeModel) {
super(codeModel);
}
public static class ConditionalImpl extends ConditionalExpressionImpl
implements Conditional {
private final JSLogicalORExpression condition;
private final JSAssignmentExpression ifTrue;
private final JSAssignmentExpression ifFalse;
public ConditionalImpl(JSCodeModel codeModel,
JSLogicalORExpression condition, JSAssignmentExpression ifTrue,
JSAssignmentExpression ifFalse) {
super(codeModel);
Validate.notNull(condition);
Validate.notNull(ifTrue);
this.condition = condition;
this.ifTrue = ifTrue;
this.ifFalse = ifFalse;
}
public JSLogicalORExpression getCondition() {
return condition;
}
public JSAssignmentExpression getIfTrue() {
return ifTrue;
}
public JSAssignmentExpression getIfFalse() {
return ifFalse;
}
@Override
public <V, E extends Exception> V acceptExpressionVisitor(
JSExpressionVisitor<V, E> visitor) throws E {
return visitor.visitConditional(this);
}
}
}
| bsd-2-clause |
skynav/ttt | ttt-ttv/src/main/java/com/skynav/ttv/model/ttml/TTML1PresentationProfileSpecification.java | 7555 | /*
* Copyright 2013-2018 Skynav, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY SKYNAV, INC. AND ITS CONTRIBUTORS “AS IS” AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.skynav.ttv.model.ttml;
import java.net.URI;
import java.util.Map;
import com.skynav.ttv.model.Profile.Specification;
import com.skynav.ttv.model.Profile.Usage;
import static com.skynav.ttv.model.ttml.TTML1.Constants.*;
public class TTML1PresentationProfileSpecification extends Specification {
private static final Object[][] featureMapEntries = new Object[][] {
{ "#content", Usage.REQUIRED },
{ "#core", Usage.REQUIRED },
{ "#presentation", Usage.REQUIRED },
{ "#profile", Usage.REQUIRED },
{ "#structure", Usage.REQUIRED },
{ "#time-offset", Usage.REQUIRED },
{ "#timing", Usage.REQUIRED },
{ "#animation", Usage.OPTIONAL },
{ "#backgroundColor-block", Usage.OPTIONAL },
{ "#backgroundColor-inline", Usage.OPTIONAL },
{ "#backgroundColor-region", Usage.OPTIONAL },
{ "#backgroundColor", Usage.OPTIONAL },
{ "#bidi", Usage.OPTIONAL },
{ "#cellResolution", Usage.OPTIONAL },
{ "#clockMode-gps", Usage.OPTIONAL },
{ "#clockMode-local", Usage.OPTIONAL },
{ "#clockMode-utc", Usage.OPTIONAL },
{ "#clockMode", Usage.OPTIONAL },
{ "#color", Usage.OPTIONAL },
{ "#direction", Usage.OPTIONAL },
{ "#display-block", Usage.OPTIONAL },
{ "#display-inline", Usage.OPTIONAL },
{ "#display-region", Usage.OPTIONAL },
{ "#display", Usage.OPTIONAL },
{ "#displayAlign", Usage.OPTIONAL },
{ "#dropMode-dropNTSC", Usage.OPTIONAL },
{ "#dropMode-dropPAL", Usage.OPTIONAL },
{ "#dropMode-nonDrop", Usage.OPTIONAL },
{ "#dropMode", Usage.OPTIONAL },
{ "#extent-region", Usage.OPTIONAL },
{ "#extent-root", Usage.OPTIONAL },
{ "#extent", Usage.OPTIONAL },
{ "#fontFamily-generic", Usage.OPTIONAL },
{ "#fontFamily-non-generic", Usage.OPTIONAL },
{ "#fontFamily", Usage.OPTIONAL },
{ "#fontSize-anamorphic", Usage.OPTIONAL },
{ "#fontSize-isomorphic", Usage.OPTIONAL },
{ "#fontSize", Usage.OPTIONAL },
{ "#fontStyle-italic", Usage.OPTIONAL },
{ "#fontStyle-oblique", Usage.OPTIONAL },
{ "#fontStyle", Usage.OPTIONAL },
{ "#fontWeight-bold", Usage.OPTIONAL },
{ "#fontWeight", Usage.OPTIONAL },
{ "#frameRate", Usage.OPTIONAL },
{ "#frameRateMultiplier", Usage.OPTIONAL },
{ "#layout", Usage.OPTIONAL },
{ "#length-cell", Usage.OPTIONAL },
{ "#length-em", Usage.OPTIONAL },
{ "#length-integer", Usage.OPTIONAL },
{ "#length-negative", Usage.OPTIONAL },
{ "#length-percentage", Usage.OPTIONAL },
{ "#length-pixel", Usage.OPTIONAL },
{ "#length-positive", Usage.OPTIONAL },
{ "#length-real", Usage.OPTIONAL },
{ "#length", Usage.OPTIONAL },
{ "#lineBreak-uax14", Usage.OPTIONAL },
{ "#lineHeight", Usage.OPTIONAL },
{ "#markerMode-continuous", Usage.OPTIONAL },
{ "#markerMode-discontinuous", Usage.OPTIONAL },
{ "#markerMode", Usage.OPTIONAL },
{ "#metadata", Usage.OPTIONAL },
{ "#nested-div", Usage.OPTIONAL },
{ "#nested-span", Usage.OPTIONAL },
{ "#opacity", Usage.OPTIONAL },
{ "#origin", Usage.OPTIONAL },
{ "#overflow-visible", Usage.OPTIONAL },
{ "#overflow", Usage.OPTIONAL },
{ "#padding-1", Usage.OPTIONAL },
{ "#padding-2", Usage.OPTIONAL },
{ "#padding-3", Usage.OPTIONAL },
{ "#padding-4", Usage.OPTIONAL },
{ "#padding", Usage.OPTIONAL },
{ "#pixelAspectRatio", Usage.OPTIONAL },
{ "#showBackground", Usage.OPTIONAL },
{ "#styling-chained", Usage.OPTIONAL },
{ "#styling-inheritance-content", Usage.OPTIONAL },
{ "#styling-inheritance-region", Usage.OPTIONAL },
{ "#styling-inline", Usage.OPTIONAL },
{ "#styling-nested", Usage.OPTIONAL },
{ "#styling-referential", Usage.OPTIONAL },
{ "#styling", Usage.OPTIONAL },
{ "#subFrameRate", Usage.OPTIONAL },
{ "#textAlign-absolute", Usage.OPTIONAL },
{ "#textAlign-relative", Usage.OPTIONAL },
{ "#textAlign", Usage.OPTIONAL },
{ "#textDecoration-over", Usage.OPTIONAL },
{ "#textDecoration-through", Usage.OPTIONAL },
{ "#textDecoration-under", Usage.OPTIONAL },
{ "#textDecoration", Usage.OPTIONAL },
{ "#textOutline-blurred", Usage.OPTIONAL },
{ "#textOutline-unblurred", Usage.OPTIONAL },
{ "#textOutline", Usage.OPTIONAL },
{ "#tickRate", Usage.OPTIONAL },
{ "#time-clock-with-frames", Usage.OPTIONAL },
{ "#time-clock", Usage.OPTIONAL },
{ "#time-offset-with-frames", Usage.OPTIONAL },
{ "#time-offset-with-ticks", Usage.OPTIONAL },
{ "#timeBase-clock", Usage.OPTIONAL },
{ "#timeBase-media", Usage.OPTIONAL },
{ "#timeBase-smpte", Usage.OPTIONAL },
{ "#timeContainer", Usage.OPTIONAL },
{ "#transformation", Usage.OPTIONAL },
{ "#unicodeBidi", Usage.OPTIONAL },
{ "#visibility-block", Usage.OPTIONAL },
{ "#visibility-inline", Usage.OPTIONAL },
{ "#visibility-region", Usage.OPTIONAL },
{ "#visibility", Usage.OPTIONAL },
{ "#wrapOption", Usage.OPTIONAL },
{ "#writingMode-horizontal-lr", Usage.OPTIONAL },
{ "#writingMode-horizontal-rl", Usage.OPTIONAL },
{ "#writingMode-horizontal", Usage.OPTIONAL },
{ "#writingMode-vertical", Usage.OPTIONAL },
{ "#writingMode", Usage.OPTIONAL },
{ "#zIndex", Usage.OPTIONAL }
};
private static final Object[][] extensionMapEntries = new Object[][] {
};
public TTML1PresentationProfileSpecification(URI profileUri) {
super(profileUri, null, featuresMap(NAMESPACE_TT_FEATURE, featureMapEntries), extensionsMap(NAMESPACE_TT_EXTENSION, extensionMapEntries));
}
protected TTML1PresentationProfileSpecification(URI uri, String baseline, Map<URI,Usage> features, Map<URI,Usage> extensions) {
super(uri, baseline, features, extensions);
}
}
| bsd-2-clause |
RobertTDowling/java-caslib | doc/test-it-factory-keep-args/BFactory.java | 141 |
class BFactory extends SFactory {
public BFactory (S a, S b) { super (a, b); }
public S makeFrom (S from) { return from.makeBFrom (); }
}
| bsd-2-clause |
oblivion14/SO | so-service/src/main/java/com/pineone/icbms/so/service/logic/ServiceLogic.java | 843 | package com.pineone.icbms.so.service.logic;
import com.pineone.icbms.so.service.entity.Service;
import com.pineone.icbms.so.service.ref.ConceptService;
import com.pineone.icbms.so.service.ref.DeviceObject;
import com.pineone.icbms.so.service.ref.Status;
import java.util.List;
/**
* Created by melvin on 2016. 8. 5..
*/
public interface ServiceLogic {
List<DeviceObject> retrieveDeviceObjectList();
List<ConceptService> retrieveConceptService(DeviceObject deviceObject);
List<Status> retrieveStatusList(ConceptService conceptService);
String registerService(Service service);
Service retrieveServiceDetail(String serviceName);
List<String> retrieveServiceNameList();
List<String> retrieveServiceIdList();
void executeService(String serviceId, String sessionId);
List<Service> retrieveServiceList();
}
| bsd-2-clause |
SenshiSentou/SourceFight | slick_dev/tags/Slick0.1/tools/org/newdawn/slick/tools/peditor/ParticleCanvas.java | 7559 | package org.newdawn.slick.tools.peditor;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.AWTGLCanvas;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.particles.ConfigurableEmitter;
import org.newdawn.slick.particles.ParticleEmitter;
import org.newdawn.slick.particles.ParticleSystem;
import org.newdawn.slick.util.Log;
/**
* A LWJGL canvas displaying a particle system
*
* @author kevin
*/
public class ParticleCanvas extends AWTGLCanvas {
/** Emitters waiting to be added once the system is created */
private ArrayList waiting = new ArrayList();
/** The particle system being displayed on the panel */
private ParticleSystem system;
/** The last update time */
private long lastTime;
/** Graphics used to draw overlays */
private Graphics graphics;
/** The font used to display info on the canvas */
private Font defaultFont;
/** The list of emitters being displayed in the system */
private ArrayList emitters = new ArrayList();
/** The frame rate */
private int fps;
/** The last update of fps */
private int lastUpdate;
/** The number of frames since last count */
private int frameCount;
/** The maximum number of particles in use */
private int max;
/** True if the hud should be displayed */
private boolean hudOn = true;
/** True if the rendering is paused */
private boolean paused;
/** The amount the system moves */
private int systemMove;
/** The y position of the system */
private float ypos;
/**
* Create a new canvas
*
* @param editor The editor which this canvas is part of
* @throws LWJGLException Indicates a failure to create the OpenGL context
*/
public ParticleCanvas(ParticleEditor editor) throws LWJGLException {
super();
}
/**
* Set how much the system should move
*
* @param move The amount of the system should move
* @param reset True if the position should be reset
*/
public void setSystemMove(int move, boolean reset) {
this.systemMove = move;
if (reset) {
ypos = 0;
}
}
/**
* Indicate if this canvas should pause
*
* @param paused True if the rendering should pause
*/
public void setPaused(boolean paused) {
this.paused = paused;
}
/**
* Check if the canvas is paused
*
* @return True if the canvas is paused
*/
public boolean isPaused() {
return paused;
}
/**
* Check if this hud is being displayed
*
* @return True if this hud is being displayed
*/
public boolean isHudOn() {
return hudOn;
}
/**
* Indicate if the HUD should be drawn
*
* @param hud True if the HUD should be drawn
*/
public void setHud(boolean hud) {
this.hudOn = hud;
}
/**
* Add an emitter to the particle system held here
*
* @param emitter The emitter to add
*/
public void addEmitter(ConfigurableEmitter emitter) {
emitters.add(emitter);
if (system == null) {
waiting.add(emitter);
} else {
system.addEmitter(emitter);
}
}
/**
* Remove an emitter from the system held here
*
* @param emitter The emitter to be removed
*/
public void removeEmitter(ConfigurableEmitter emitter) {
emitters.remove(emitter);
system.removeEmitter(emitter);
}
/**
* @see org.lwjgl.opengl.AWTGLCanvas#initGL()
*/
protected void initGL() {
int width = getWidth();
int height = getHeight();
Log.info("Starting display "+width+"x"+height);
String extensions = GL11.glGetString(GL11.GL_EXTENSIONS);
Display.setVSyncEnabled(true);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glClearDepth(1);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glViewport(0,0,width,height);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, width, height, 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
system = new ParticleSystem("org/newdawn/slick/data/particle.tga",2000);
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
system.setRemoveCompletedEmitters(false);
for (int i=0;i<waiting.size();i++) {
system.addEmitter((ParticleEmitter) waiting.get(i));
}
waiting.clear();
lastTime = ((Sys.getTime() * 1000) / Sys.getTimerResolution());
graphics = new Graphics(width, height);
defaultFont = graphics.getFont();
}
/**
* Clear the particle system held in this canvas
*
* @param additive True if the particle system should be set to additive
*/
public void clearSystem(boolean additive) {
system = new ParticleSystem("org/newdawn/slick/data/particle.tga",2000);
if (additive) {
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
}
system.setRemoveCompletedEmitters(false);
}
/**
* Set the particle system to be displayed
*
* @param system The system to be displayed
*/
public void setSystem(ParticleSystem system) {
this.system = system;
emitters.clear();
system.setRemoveCompletedEmitters(false);
for (int i=0;i<system.getEmitterCount();i++) {
emitters.add(system.getEmitter(i));
}
}
/**
* Reset the counts held in this canvas (maximum particles for instance)
*/
public void resetCounts() {
max = 0;
}
/**
* @see org.lwjgl.opengl.AWTGLCanvas#paintGL()
*/
protected void paintGL() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
max = Math.max(max, system.getParticleCount());
if (hudOn) {
graphics.setColor(Color.white);
graphics.drawString("FPS: "+fps, 10,10);
graphics.drawString("Particles: "+system.getParticleCount(), 10,25);
graphics.drawString("Max: "+max, 10,40);
graphics.drawString("LMB: Position Emitter RMB: Default Position", 90,527);
}
GL11.glTranslatef(250,300,0);
for (int i=0;i<emitters.size();i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
graphics.setColor(new Color(0,0,0,0.5f));
graphics.fillRect(-1,-5,2,10);
graphics.fillRect(-5,-1,10,2);
try {
swapBuffers();
if (isVisible()) {
repaint();
}
} catch (Exception e) {/*OK*/
e.printStackTrace();
}
long thisTime = ((Sys.getTime() * 1000) / Sys.getTimerResolution());
long delta = thisTime - lastTime;
lastTime = thisTime;
frameCount++;
lastUpdate -= delta;
if (lastUpdate < 0) {
fps = frameCount;
frameCount = 0;
lastUpdate = 1000;
}
if (!paused) {
ypos += delta * 0.002 * systemMove;
if (ypos > 300) {
ypos = -300;
}
if (ypos < -300) {
ypos = 300;
}
for (int i=0;i<emitters.size();i++) {
((ConfigurableEmitter) emitters.get(i)).replayCheck();
}
for (int i=0;i<delta;i++) {
system.update(1);
}
}
}
/**
* Get the particle system being displayed
*
* @return The system being displayed
*/
public ParticleSystem getSystem() {
return system;
}
}
| bsd-2-clause |
ShaggSpawns/Finish-Clash | Finish Clash/src/building/resource/Dark_Elixir_Storage.java | 71 | package building.resource;
public class Dark_Elixir_Storage {
}
| bsd-2-clause |
kephale/imagej-ops | src/main/java/net/imagej/operator/OpMax.java | 2170 | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2015 Board of Regents of the University of
* Wisconsin-Madison, University of Konstanz and Brian Northan.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.operator;
import net.imglib2.ops.operation.real.binary.RealMax;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
import org.scijava.plugin.Plugin;
/**
* Image Calculator plugin for {@link RealMax} operation.
*
* @author Curtis Rueden
*/
@Deprecated
@Plugin(type = CalculatorOp.class, name = "Max", priority = OpMax.PRIORITY)
public class OpMax<I1 extends RealType<I1>, I2 extends RealType<I2>> extends
AbstractCalculatorOp<I1, I2>
{
public static final int PRIORITY = OpMin.PRIORITY - 1;
public OpMax() {
super(new RealMax<I1, I2, DoubleType>());
}
}
| bsd-2-clause |
RCRS-ADF/core | src/main/java/adf/launcher/option/OptionAmbulanceTeam.java | 393 | package adf.launcher.option;
import adf.launcher.ConfigKey;
import rescuecore2.config.Config;
public class OptionAmbulanceTeam extends Option
{
@Override
public boolean hasValue()
{
return true;
}
@Override
public String getKey()
{
return "-at";
}
@Override
public void setValue(Config config, String data)
{
config.setValue(ConfigKey.KEY_AMBULANCE_TEAM_COUNT, data);
}
} | bsd-2-clause |
ColaMachine/MyBlock | src/main/java/com/dozenx/game/engine/Role/bean/PlayerOne.java | 110 | package com.dozenx.game.engine.Role.bean;
/**
* Created by luying on 17/3/5.
*/
public class PlayerOne {
}
| bsd-2-clause |
Mytrin/UDPLib | UDPLib/src/com/gmail/lepeska/martin/udplib/util/ConfigLoader.java | 2695 | package com.gmail.lepeska.martin.udplib.util;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Class making easier handling XML files and loading basic library configuration.
*
* @author Martin Lepeška
*/
public final class ConfigLoader {
/**Version of this library*/
public static final String VERSION ="BETA 2";
/** Loaded values */
private static final HashMap<String, String> CONFIG = new HashMap<>();
/** Singleton */
private ConfigLoader(){}
/**
* Loads and sets new configuration.
* @param source config file
*
*/
public synchronized static final boolean loadConfig(File source){
try{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
NodeList configValues = doc.getDocumentElement().getElementsByTagName("item");
for (int i = 0; i < configValues.getLength(); i++) {
Node tag = configValues.item(i);
CONFIG.put(tag.getAttributes().getNamedItem("name").getTextContent(), tag.getTextContent());
}
}catch(ParserConfigurationException | SAXException | IOException | DOMException e){
return false;
}
return true;
}
/**
* @param itemName name of tag
* @param defaultValue returned value when item was not found
* @return its value or null
*/
public synchronized static String getString(String itemName, String defaultValue){
if(CONFIG.get(itemName) != null){
return CONFIG.get(itemName);
}
return defaultValue;
}
/**
* @param itemName name of tag
* @param defaultValue returned value when item was not found
* @return its value or null
*/
public synchronized static int getInt(String itemName, int defaultValue){
try{
String value = CONFIG.get(itemName);
if(value == null){
return defaultValue;
}
return Integer.parseInt(value);
}catch(NumberFormatException e){
Logger.getLogger(ConfigLoader.class.getName()).log(Level.SEVERE, "Item "+itemName+" is not number! ", e);
}
return defaultValue;
}
} | bsd-2-clause |
ffalchi/it.cnr.isti.vir | src/it/cnr/isti/vir/util/RandomVectors.java | 1959 | /*******************************************************************************
* Copyright (c) 2013, Fabrizio Falchi (NeMIS Lab., ISTI-CNR, Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package it.cnr.isti.vir.util;
import it.cnr.isti.vir.util.math.Normalize;
public class RandomVectors {
public static final float[] getUniformlyDistributedFloats(int dim ) {
return RandomOperations.getUniformlyDistributedFloats(dim);
}
public static final float[] getL2NormalizedFloats(int dim ) {
float[] res = getUniformlyDistributedFloats( dim );
Normalize.l2( res );
return res;
}
}
| bsd-2-clause |
Konstantin8105/GenericSort | sort/src/research/tests/string/TestStringUnique.java | 315 | package research.tests.string;
import research.base.TestString;
public class TestStringUnique<T extends String> extends TestString<String> {
public TestStringUnique() {
array = getRandomList(true);
}
@Override
public String getName() {
return this.getClass().toString();
}
} | bsd-2-clause |
jorgeyanesdiez/dnilettercalc | dnilettercalc-user/src/main/java/info/jorgeyanesdiez/dnilettercalc/user/Launcher.java | 705 | package info.jorgeyanesdiez.dnilettercalc.user;
import info.jorgeyanesdiez.dnilettercalc.gui.DniLetterCalculatorGui;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* A launcher to create an instance of the GUI.
*/
public class Launcher
{
/**
* Command-line entry point.
* @param args The command-line arguments.
*/
public static void main(String[] args)
{
Injector injector = Guice.createInjector(new InjectorConfiguration());
DniLetterCalculatorGui gui = injector.getInstance(DniLetterCalculatorGui.class);
gui.setVisible(true);
}
/**
* Main constructor.
*/
private Launcher()
{
super();
}
}
| bsd-2-clause |
highsource/annox | core/src/main/java/org/jvnet/annox/model/annotation/value/XEnumAnnotationValue.java | 306 | package org.jvnet.annox.model.annotation.value;
public class XEnumAnnotationValue<E extends Enum<E>> extends
XStaticAnnotationValue<E> {
public XEnumAnnotationValue(E value) {
super(value);
}
@Override
public <P> P accept(XAnnotationValueVisitor<P> visitor) {
return visitor.visit(this);
}
}
| bsd-2-clause |
PSemFlugSim/server | src/de/gymolching/fsb/Launcher.java | 4393 | package de.gymolching.fsb;
import com.pi4j.io.gpio.GpioFactory;
import de.gymolching.fsb.hal.ArmFactory;
import de.gymolching.fsb.halApi.ArmInterface;
import de.gymolching.fsb.network.api.FSBServerInterface;
import de.gymolching.fsb.network.implementation.FSBServer;
import java.io.IOException;
import java.util.Scanner;
/**
* This checks for pi4j and launches the program.
* @author sschaeffner
*/
public class Launcher {
//program name
private static final String NAME = "FSB";
//program version
private static final String VERSION = "0.1";
//whether the program should currently be running
private static boolean running;
//whether the program is currently exiting
private static boolean exiting;
public static void main(String[] args) {
if (checkForPi4J()) {
running = true;
exiting = false;
//create thread for program
Thread t = new Thread(() -> {
MainLoopHandler.getInstance().mainLoop();
}, "program");
t.start();
//start MiniConsole (blocking until user inputs "exit")
new MiniConsole().start();
exit();
}
}
/**
* Exits the program.
*/
public static void exit() {
if (!exiting) {
exiting = true;
//stop program
System.out.println("waiting for shutdown...");
stop();
try {
GpioFactory.getInstance().shutdown();
} catch (UnsupportedOperationException | NullPointerException e) {
//do nothing
}
//wait for other threads to stop
for (int i = 1; i < 20; i++) {
System.out.print(".");
if (i % 10 == 0) System.out.println();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("shutdown completed");
System.exit(0);
}
}
/**
* Checks whether Pi4J is in the classpath.
* @return whether Pi4J is in the classpath
*/
public static boolean checkForPi4J() {
try {
Class.forName("com.pi4j.io.gpio.GpioFactory");
return true;
} catch (ClassNotFoundException e) {
System.err.println("Pi4J could not be found in /opt/pi4j or in classpath");
System.err.println("please install Pi4J in the default location");
return false;
}
}
/**
* Returns whether the program should currently be running.
* @return whether the program should currently be running.
*/
public static boolean isRunning() {
return running;
}
/**
* Stops the program gracefully.
*/
public static void stop() {
running = false;
}
/**
* A simple console.
*/
public static class MiniConsole {
private Scanner scanner;
private static final String WELCOME_MESSAGE = "Welcome to " + NAME + " v" + VERSION + "!" + System.lineSeparator() + "Enter help for a list of commands.";
private static final String EXIT_COMMAND = "exit";
private static final String CONSOLE_PROMPT = "$ ";
public MiniConsole() {
scanner = new Scanner(System.in);
}
/**
* Starts the console.
* This is blocking until the user inputs "exit".
*/
public void start() {
System.out.println(WELCOME_MESSAGE);
System.out.print(CONSOLE_PROMPT);
String input;
while (!(input = scanner.nextLine()).equalsIgnoreCase(EXIT_COMMAND)) {
input = input.toLowerCase();
switch (input) {
case "help":
System.out.println(NAME + " v" + VERSION);
System.out.println("exit exits the program");
System.out.println("help prints this help");
break;
default:
System.err.println("Unknown command. Enter help for a list of commands.");
break;
}
System.out.print(CONSOLE_PROMPT);
}
}
}
}
| bsd-2-clause |
atomashpolskiy/link-rest | link-rest/src/test/java/com/nhl/link/rest/it/fixture/cayenne/E16.java | 193 | package com.nhl.link.rest.it.fixture.cayenne;
import com.nhl.link.rest.it.fixture.cayenne.auto._E16;
public class E16 extends _E16 {
private static final long serialVersionUID = 1L;
}
| bsd-2-clause |
bramp/ffmpeg-cli-wrapper | src/test/java/net/bramp/ffmpeg/io/HexOutputStream.java | 1345 | package net.bramp.ffmpeg.io;
import com.google.common.base.Charsets;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/** Converts bytes into hex output */
public class HexOutputStream extends OutputStream {
final Writer writer;
int count = 0;
/**
* Creates an output stream filter built on top of the specified underlying output stream.
*
* @param out the underlying output stream to be assigned to the field <tt>this.out</tt> for later
* use, or <code>null</code> if this instance is to be created without an underlying stream.
*/
public HexOutputStream(OutputStream out) {
writer = new OutputStreamWriter(out, Charsets.UTF_8);
}
@Override
public void write(int b) throws IOException {
writer.write(String.format("%02X ", b & 0xFF));
count++;
if (count > 16) {
count = 0;
writer.write("\n");
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
write(b[off++]);
}
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void flush() throws IOException {
writer.flush();
}
@Override
public void close() throws IOException {
writer.close();
}
}
| bsd-2-clause |
EPapadopoulou/PersoNIS | api/android/external2/src/main/java/org/societies/android/api/privacytrust/trust/ITrustClientCallback.java | 3058 | /**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.android.api.privacytrust.trust;
import java.util.Set;
import org.societies.api.schema.privacytrust.trust.model.TrustRelationshipBean;
/**
* Describe your class here...
*
* @author <a href="mailto:nicolas.liampotis@cn.ntua.gr">Nicolas Liampotis</a> (ICCS)
* @since 1.1
*/
public interface ITrustClientCallback {
/**
*
* @param trustRelationships
*/
public void onRetrievedTrustRelationships(Set<TrustRelationshipBean> trustRelationships);
/**
*
* @param trustRelationship
*/
public void onRetrievedTrustRelationship(TrustRelationshipBean trustRelationship);
/**
*
* @param trustValue
*/
public void onRetrievedTrustValue(Double trustValue);
/**
* Called upon successful addition of direct trust evidence using the
* TODO
*/
public void onAddedDirectTrustEvidence();
/**
* Associates an exception with this callback.
*
* @param exception the exception to associate with this callback.
*/
public void onException(TrustException exception);
} | bsd-2-clause |
ibcn-cloudlet/firefly | be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Change.java | 2253 | /*******************************************************************************
* Copyright (c) 2015, Tim Verbelen
* Internet Based Communication Networks and Services research group (IBCN),
* Department of Information Technology (INTEC), Ghent University - iMinds.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Ghent University - iMinds, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
package be.iminds.iot.things.rule.api;
import java.util.UUID;
public class Change {
public Change(UUID thingId, String stateVariable, Object value){
this.thingId = thingId;
this.stateVariable = stateVariable;
this.value = value;
}
public UUID thingId;
public String stateVariable;
public Object value;
}
| bsd-3-clause |
uwdb/pipegen | src/main/java/org/brandonhaynes/pipegen/mutation/rules/datapipe/HadoopFileSystemCreateRule.java | 4763 | package org.brandonhaynes.pipegen.mutation.rules.datapipe;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import javassist.CannotCompileException;
import javassist.NotFoundException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.brandonhaynes.pipegen.configuration.tasks.ExportTask;
import org.brandonhaynes.pipegen.instrumentation.StackFrame;
import org.brandonhaynes.pipegen.instrumentation.TraceResult;
import org.brandonhaynes.pipegen.instrumentation.injected.hadoop.InterceptedFSDataOutputStream;
import org.brandonhaynes.pipegen.mutation.ExpressionReplacer;
import org.brandonhaynes.pipegen.mutation.rules.Rule;
import org.brandonhaynes.pipegen.utilities.JarUtilities;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.logging.Logger;
import static org.brandonhaynes.pipegen.utilities.ClassUtilities.getPipeGenDependencies;
public class HadoopFileSystemCreateRule implements Rule {
private static final Logger log = Logger.getLogger(HadoopFileSystemCreateRule.class.getName());
private static final Collection<String> sourceClasses = Lists.newArrayList(
FileSystem.class.getName(), LocalFileSystem.class.getName(),
DistributedFileSystem.class.getName(), RawLocalFileSystem.class.getName());
private static final Class targetClass = InterceptedFSDataOutputStream.class;
private static final String template = String.format("$_ = %s.intercept($0, $$);", targetClass.getName());
private static final String targetExpression = "create";
private final ExportTask task;
public HadoopFileSystemCreateRule(ExportTask task) {
this.task = task;
}
public boolean isApplicable(TraceResult trace) {
return !getNodes(trace).isEmpty();
}
public boolean apply(TraceResult trace) throws IOException, NotFoundException, CannotCompileException {
boolean result = false;
for(JsonNode node: getNodes(trace))
if(isRelevantCallSite(node))
result |= apply(node);
return result;
}
public boolean apply(JsonNode node) throws IOException, NotFoundException, CannotCompileException {
// Modify the first stack frame that instantiates FileInputStream
for(JsonNode stackFrame: node.get("stack")) {
StackFrame frame = new StackFrame(stackFrame.asText());
if(isRelevantStackFrame(frame))
return isAlreadyModified(frame) ||
modifyCallSite(frame);
}
return false;
}
private boolean modifyCallSite(StackFrame frame) throws IOException, NotFoundException, CannotCompileException {
for (URL url : task.getConfiguration().instrumentationConfiguration.findClasses(frame.getClassName())) {
log.info(String.format("Modifying call sites in %s", url));
JarUtilities.replaceClasses(
url,
task.getConfiguration().instrumentationConfiguration.getClassPool(),
getPipeGenDependencies(),
task.getConfiguration().getVersion(),
task.getConfiguration().getBackupPath());
ExpressionReplacer.replaceExpression(
url, frame.getClassName(), frame.getMethodName(), frame.getLine(),
targetExpression, template, task.getConfiguration().getBackupPath());
}
task.getModifiedCallSites().add(frame);
return true;
}
private boolean isRelevantStackFrame(StackFrame frame) {
return !sourceClasses.contains(frame.getClassName());
}
private boolean isAlreadyModified(StackFrame frame) {
return task.getModifiedCallSites().contains(frame);
}
private boolean isRelevantCallSite(JsonNode node) {
String uri = getUri(node);
//TODO
return sourceClasses.contains(node.get("class").asText()) &&
uri != null && !uri.contains(".class") && !uri.contains(".properties");
}
private String getUri(JsonNode node) {
JsonNode uriNode = node.get("state").get("uri");
String uri = uriNode != null ? uriNode.asText() : null;
return uri != null && !uri.isEmpty() && !uri.equals("null")
? uri
: null;
}
private Collection<JsonNode> getNodes(TraceResult trace) {
Collection<JsonNode> nodes = Lists.newArrayList();
for(JsonNode entry: trace.getNodes())
if(entry.findValue("state") != null)
nodes.add(entry);
return nodes;
}
}
| bsd-3-clause |
lusaisai/m | app/LyricSearch/src/main/java/LyricSearch/Lrc123Lyricer.java | 1827 | package LyricSearch;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Lrc123Lyricer extends Lyricer {
private static final String SITE = "http://www.lrc123.com";
private static final String URL_PRE = SITE + "/?field=all&keyword=";
private static final String AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36";
public String findLrcLyric(String artist, String title) {
String url = URL_PRE + title.replaceAll("\\s+", "+") + "+" + artist.replaceAll("\\s+", "+");
System.out.println(url);
Document doc;
int timeout = 20000;
try {
doc = Jsoup.connect(url)
.userAgent(AGENT)
.timeout(timeout)
.get();
} catch (Exception e) {
return "";
}
Elements contents = doc.select("a.O3");
for(Element e: contents) {
String href = e.attr("href");
String link;
if ( href.startsWith("http") ) {
link = href;
} else {
link = SITE + href;
}
try {
File tmp = File.createTempFile("Lrc123Lyricer", "lrcFile");
FileUtils.copyURLToFile(new URL(link), tmp, timeout, timeout);
tmp.deleteOnExit();
String lyric = FileUtils.readFileToString(tmp, "GBK");
if ( lyric.length() > 0 ) return lyric;
} catch (IOException ignored) {}
}
return "";
}
}
| bsd-3-clause |
s0pau/Cosm4J | src/test/java/com/cosm/client/http/HttpClientTestSuite.java | 640 | package com.cosm.client.http;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.cosm.client.http.impl.ApiKeyRequesterTest;
import com.cosm.client.http.impl.DatapointRequesterTest;
import com.cosm.client.http.impl.DatastreamRequesterTest;
import com.cosm.client.http.impl.FeedRequesterTest;
import com.cosm.client.http.impl.TriggerRequesterTest;
@RunWith(Suite.class)
@SuiteClasses({ DatapointRequesterTest.class, DatastreamRequesterTest.class, FeedRequesterTest.class, TriggerRequesterTest.class,
ApiKeyRequesterTest.class })
public class HttpClientTestSuite
{
}
| bsd-3-clause |
lockss/lockss-daemon | plugins/src/org/lockss/plugin/bepress/BePressHttpToHttpsUrlConsumerFactory.java | 4235 | /*
* $Id$
*/
/*
Copyright (c) 2000-2018 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.bepress;
import java.util.regex.Pattern;
import org.lockss.daemon.Crawler.CrawlerFacade;
import org.lockss.plugin.*;
import org.lockss.plugin.base.HttpToHttpsUrlConsumer;
import org.lockss.plugin.base.HttpToHttpsUrlConsumerFactory;
import org.lockss.util.Logger;
import org.lockss.util.UrlUtil;
/**
* <p>
* A variant on
* {@link HttpToHttpsUrlConsumer}
* for Atypon that allows the redirect url to have additional args
* </p>
*
* @author Alexandra Ohlson
*/
public class BePressHttpToHttpsUrlConsumerFactory extends HttpToHttpsUrlConsumerFactory {
private static final Logger log = Logger.getLogger(BePressHttpToHttpsUrlConsumerFactory.class);
protected static final Pattern REF_ARG_PATTERN = Pattern.compile("referer=[^&]+&httpsredir=1(&)?");
protected static final Pattern TRAIL_SLASH_PATTERN = Pattern.compile("/$");
@Override
public UrlConsumer createUrlConsumer(CrawlerFacade crawlFacade,
FetchedUrlData fud) {
return new BePressHttpToHttpsUrlConsumer(crawlFacade, fud);
}
public class BePressHttpToHttpsUrlConsumer extends HttpToHttpsUrlConsumer {
public BePressHttpToHttpsUrlConsumer(CrawlerFacade facade, FetchedUrlData fud) {
super(facade, fud);
}
//
// bepress does a couple non-standard things on their https redirection
// 1. they add a "referrer=<something>&httpsredir=1" argument in to the new url for articles
// which we normalize out so the redirect url doesn't necessarily equal the fetch url
// 2. for TOC they're currently going from http to https and then back to http so allow for any number of
// redirection hops so long as the end = the start after normalization.
//
@Override
public boolean shouldStoreAtOrigUrl() {
log.debug3("FUD: " + fud.toString());
log.debug3("FUD fetch: " + fud.fetchUrl);
// In order to compare the original and fetched, remove the referer arg as well
// for redirected TOC, check against a version that didn't redirect to a version with a trailing slash
String normFetch = REF_ARG_PATTERN.matcher(fud.fetchUrl).replaceFirst("");
String noSlashFetch = TRAIL_SLASH_PATTERN.matcher(fud.fetchUrl).replaceFirst("");
return AuUtil.isBaseUrlHttp(au)
&& fud.redirectUrls != null
&& fud.redirectUrls.size() >= 1
//&& fud.fetchUrl.equals(fud.redirectUrls.get(0))
&& UrlUtil.isHttpUrl(fud.origUrl)
&& UrlUtil.isHttpsUrl(fud.fetchUrl)
&& (UrlUtil.stripProtocol(fud.origUrl).equals(UrlUtil.stripProtocol(fud.fetchUrl)) ||
UrlUtil.stripProtocol(fud.origUrl).equals(UrlUtil.stripProtocol(normFetch)) ||
UrlUtil.stripProtocol(fud.origUrl).equals(UrlUtil.stripProtocol(noSlashFetch)));
// return super.shouldStoreAtOrigUrl();
}
}
}
| bsd-3-clause |
jbauschatz/GreatPipes | src/pipes/editing/actions/SetEmbellishmentFamilyAction.java | 893 | package pipes.editing.actions;
import pipes.model.Note;
import pipes.model.embellishment.EmbellishmentFamily;
public class SetEmbellishmentFamilyAction implements EditAction {
public boolean isLegal() {
return newEmbellishment.canEmbellish(note.getTune().getNoteBefore(note), note);
}
public void execute() {
note.setEmbellishmentFamily(newEmbellishment);
}
public void undo() {
note.setEmbellishmentFamily(oldEmbellishment);
}
public EmbellishmentFamily getFamily() {
return newEmbellishment;
}
public Note getNote() {
return note;
}
public SetEmbellishmentFamilyAction(Note note, EmbellishmentFamily newEmbellishment) {
this.note = note;
this.newEmbellishment = newEmbellishment;
oldEmbellishment = note.getEmbellishmentFamily();
}
private Note note;
private EmbellishmentFamily oldEmbellishment;
private EmbellishmentFamily newEmbellishment;
}
| bsd-3-clause |
BaseXdb/basex | basex-core/src/main/java/org/basex/query/value/map/TrieBranch.java | 8002 | package org.basex.query.value.map;
import org.basex.query.*;
import org.basex.query.util.collation.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
/**
* Inner node of a {@link XQMap}.
*
* @author BaseX Team 2005-22, BSD License
* @author Leo Woerteler
*/
final class TrieBranch extends TrieNode {
/** Child array. */
private final TrieNode[] kids;
/** Bit array with a bit set for every used slot. */
final int used;
/**
* Constructor taking children array and the size of this map.
* @param kids children
* @param used bit array
* @param size size of this node
*/
TrieBranch(final TrieNode[] kids, final int used, final int size) {
super(size);
this.kids = kids;
this.used = used;
assert verify();
}
/**
* Copies the children array.
* This is faster than {@code kids.clone()} according to
* <a href="http://www.javaspecialists.eu/archive/Issue124.html">Heinz M. Kabutz</a>.
* @return copy of the child array
*/
TrieNode[] copyKids() {
final TrieNode[] copy = new TrieNode[KIDS];
Array.copy(kids, KIDS, copy);
return copy;
}
@Override
TrieNode put(final int hs, final Item key, final Value value, final int level,
final InputInfo ii) throws QueryException {
final int k = key(hs, level);
final TrieNode sub = kids[k], nsub;
final int bs, rem;
if(sub != null) {
nsub = sub.put(hs, key, value, level + 1, ii);
if(nsub == sub) return this;
bs = used;
rem = sub.size;
} else {
nsub = new TrieLeaf(hs, key, value);
bs = used | 1 << k;
rem = 0;
}
final TrieNode[] ks = copyKids();
ks[k] = nsub;
return new TrieBranch(ks, bs, size - rem + nsub.size);
}
@Override
TrieNode delete(final int hash, final Item key, final int level, final InputInfo ii)
throws QueryException {
final int k = key(hash, level);
final TrieNode sub = kids[k];
if(sub == null) return this;
final TrieNode nsub = sub.delete(hash, key, level + 1, ii);
if(nsub == sub) return this;
final int nu;
if(nsub == null) {
nu = used ^ 1 << k;
if(Integer.bitCount(nu) == 1) {
final TrieNode single = kids[Integer.numberOfTrailingZeros(nu)];
// check whether the child depends on the right offset
if(!(single instanceof TrieBranch)) return single;
}
} else {
nu = used;
}
final TrieNode[] ks = copyKids();
ks[k] = nsub;
return new TrieBranch(ks, nu, size - 1);
}
@Override
Value get(final int hash, final Item key, final int level, final InputInfo ii)
throws QueryException {
final int k = key(hash, level);
final TrieNode sub = kids[k];
return sub == null ? null : sub.get(hash, key, level + 1, ii);
}
@Override
boolean contains(final int hash, final Item key, final int level, final InputInfo ii)
throws QueryException {
final int k = key(hash, level);
final TrieNode sub = kids[k];
return sub != null && sub.contains(hash, key, level + 1, ii);
}
/** End strings. */
private static final String[] ENDS = { "|-- ", "| ", "`-- ", " " };
@Override
TrieNode addAll(final TrieNode node, final int level, final MergeDuplicates merge,
final QueryContext qc, final InputInfo ii) throws QueryException {
return node.add(this, level, merge, qc, ii);
}
@Override
TrieNode add(final TrieLeaf leaf, final int level, final MergeDuplicates merge,
final QueryContext qc, final InputInfo ii) throws QueryException {
qc.checkStop();
final int k = key(leaf.hash, level);
final TrieNode ch = kids[k], kid;
int n = 1;
if(ch != null) {
final TrieNode ins = ch.add(leaf, level + 1, merge, qc, ii);
if(ins == ch) return this;
n = ins.size - ch.size;
kid = ins;
} else {
kid = leaf;
}
final TrieNode[] ks = copyKids();
ks[k] = kid;
return new TrieBranch(ks, used | 1 << k, size + n);
}
@Override
TrieNode add(final TrieList list, final int level, final MergeDuplicates merge,
final QueryContext qc, final InputInfo ii) throws QueryException {
qc.checkStop();
final int k = key(list.hash, level);
final TrieNode ch = kids[k], kid;
int n = list.size;
if(ch != null) {
final TrieNode ins = ch.add(list, level + 1, merge, qc, ii);
if(ins == ch) return this;
n = ins.size - ch.size;
kid = ins;
} else {
kid = list;
}
final TrieNode[] ks = copyKids();
ks[k] = kid;
return new TrieBranch(ks, used | 1 << k, size + n);
}
@Override
TrieNode add(final TrieBranch branch, final int level, final MergeDuplicates merge,
final QueryContext qc, final InputInfo ii) throws QueryException {
TrieNode[] ch = null;
int nu = used, ns = size;
final int kl = kids.length;
for(int k = 0; k < kl; k++) {
final TrieNode n = kids[k], ok = branch.kids[k];
if(ok != null) {
final TrieNode kid = n == null ? ok : ok.addAll(n, level + 1, merge, qc, ii);
if(kid != n) {
if(ch == null) ch = copyKids();
ch[k] = kid;
nu |= 1 << k;
ns += kid.size - (n == null ? 0 : n.size);
}
}
}
return ch == null ? this : new TrieBranch(ch, nu, ns);
}
@Override
boolean verify() {
int c = 0;
for(int i = 0; i < KIDS; i++) {
final boolean bit = (used & 1 << i) != 0, act = kids[i] != null;
if(bit ^ act) return false;
if(act) c += kids[i].size;
}
return c == size;
}
@Override
void keys(final ItemList ks) {
for(final TrieNode nd : kids) {
if(nd != null) nd.keys(ks);
}
}
@Override
void values(final ValueBuilder vs) {
for(final TrieNode nd : kids) {
if(nd != null) nd.values(vs);
}
}
@Override
void cache(final boolean lazy, final InputInfo ii) throws QueryException {
for(final TrieNode nd : kids) {
if(nd != null) nd.cache(lazy, ii);
}
}
@Override
boolean materialized() throws QueryException {
for(final TrieNode nd : kids) {
if(nd != null && !nd.materialized()) return false;
}
return true;
}
@Override
void forEach(final ValueBuilder vb, final FItem func, final QueryContext qc, final InputInfo ii)
throws QueryException {
for(final TrieNode nd : kids) {
if(nd != null) nd.forEach(vb, func, qc, ii);
}
}
@Override
boolean instanceOf(final AtomType kt, final SeqType dt) {
for(final TrieNode nd : kids) {
if(nd != null && !nd.instanceOf(kt, dt)) return false;
}
return true;
}
@Override
int hash(final InputInfo ii) throws QueryException {
int hash = 0;
for(final TrieNode nd : kids) {
if(nd != null) hash = (hash << 5) - hash + nd.hash(ii);
}
return hash;
}
@Override
boolean deep(final TrieNode node, final Collation coll, final InputInfo ii)
throws QueryException {
if(!(node instanceof TrieBranch)) return false;
final TrieBranch ob = (TrieBranch) node;
// check bin usage first
if(used != ob.used) return false;
// recursively compare children
for(int i = 0; i < KIDS; i++)
if(kids[i] != null && !kids[i].deep(ob.kids[i], coll, ii)) return false;
// everything OK
return true;
}
@Override
StringBuilder append(final StringBuilder sb, final String indent) {
final int s = Integer.bitCount(used);
for(int i = 0, j = 0; i < s; i++, j++) {
while((used & 1 << j) == 0) j++;
final int e = i == s - 1 ? 2 : 0;
sb.append(indent).append(ENDS[e]).append(String.format("%x", j)).append('\n');
kids[j].append(sb, indent + ENDS[e + 1]);
}
return sb;
}
@Override
StringBuilder append(final StringBuilder sb) {
for(int i = 0; i < KIDS && more(sb); i++) {
if(kids[i] != null) kids[i].append(sb);
}
return sb;
}
}
| bsd-3-clause |
NCIP/cagrid-core | caGrid/projects/introduce/test/src/java/Introduce/gov/nih/nci/cagrid/introduce/test/steps/AddFactoryMethodStep.java | 3265 | /**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.introduce.test.steps;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputs;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.codegen.SyncTools;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.test.TestCaseInfo;
import java.io.File;
import javax.xml.namespace.QName;
public class AddFactoryMethodStep extends BaseStep {
private TestCaseInfo factorytci;
private TestCaseInfo ctci;
private String factoryMethodName;
private boolean copyFiles;
public AddFactoryMethodStep(TestCaseInfo factorytci, TestCaseInfo ctci, boolean build) throws Exception {
super(factorytci.getDir(), build);
this.factorytci = factorytci;
this.ctci = ctci;
this.factoryMethodName = "create" + ctci.getName();
this.copyFiles = copyFiles;
}
public void runStep() throws Throwable {
System.out.println("Adding an factory method for " + factorytci.getName() + " generating " + ctci.getName());
ServiceDescription introService = (ServiceDescription) Utils.deserializeDocument(getBaseDir() + File.separator
+ factorytci.getDir() + File.separator + "introduce.xml", ServiceDescription.class);
MethodType method = new MethodType();
method.setName(this.factoryMethodName);
MethodTypeOutput output = new MethodTypeOutput();
output.setIsClientHandle(true);
output.setIsCreatingResourceForClientHandle(true);
output.setClientHandleClass(ctci.getPackageName()+".client." + ctci.getName() + "Client");
output.setResourceClientIntroduceServiceName(ctci.getName());
output.setQName(new QName(ctci.getNamespace()+ "/types",ctci.getName() + "Reference"));
method.setOutput(output);
MethodTypeInputs inputs = new MethodTypeInputs();
method.setInputs(inputs);
CommonTools.addMethod(CommonTools.getService(introService.getServices(), factorytci.getName()), method);
Utils.serializeDocument(getBaseDir() + File.separator + factorytci.getDir() + File.separator + "introduce.xml",
introService, IntroduceConstants.INTRODUCE_SKELETON_QNAME);
try {
SyncTools sync = new SyncTools(new File(getBaseDir() + File.separator + factorytci.getDir()));
sync.sync();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
buildStep();
}
}
| bsd-3-clause |
andrewmw94/DroneSenDesg2015 | Drones/src/Drone/Drone.java | 517 | /*
* 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 Drone;
import Utils.Mesh;
/**
*
* @author awells
*/
public class Drone {
public Mesh mesh;
public DroneState ourState;
public Drone(Mesh m, float x, float y, float z) {
mesh = m;
ourState = new DroneState();
ourState.x = x;
ourState.y = y;
ourState.z = z;
}
}
| bsd-3-clause |
ThePrimedTNT/SkriptEditor | src/skripteditor/addons/skript/evt/EvtOnRegionEnterLeave.java | 629 | package skripteditor.addons.skript.evt;
import skripteditor.events.Event;
public class EvtOnRegionEnterLeave extends Event {
@Override
public void registerUserFriendyPatterns() {
registerUserFriendyPattern("region enter");
registerUserFriendyPattern("region (leave|exit)");
}
@Override
public void registerPatterns() {
registerPattern("region enter");
registerPattern("region (leave|exit)");
}
@Override
public String[] getExamples() {
return new String[] {
"on region exit:\n" + "\tmessage \"Leaving %region%.\""
};
}
@Override
public String getName() {
return "On Region Enter/Leave";
}
}
| bsd-3-clause |
speedfirst/leetcode | java/src/main/java/org/speedfirst/leetcode/array/MaxSubArray2.java | 1266 | package org.speedfirst.leetcode.array;
import java.util.ArrayList;
import java.util.Arrays;
/**
* http://lintcode.com/en/problem/maximum-subarray-ii/
*/
public class MaxSubArray2 {
public int maxTwoSubArrays(ArrayList<Integer> nums) {
int[] maxSumLeft = new int[nums.size()];
int[] maxSumRight= new int[nums.size()];
int tmp;
maxSumLeft[0] = tmp = nums.get(0);
for (int i = 1; i < nums.size(); i++) {
tmp = Math.max(tmp + nums.get(i), nums.get(i));
maxSumLeft[i] = Math.max(tmp, maxSumLeft[i - 1]);
}
maxSumRight[nums.size() - 1] = tmp = nums.get(nums.size() - 1);
for (int i = nums.size() - 2; i >= 0; i--) {
tmp = Math.max(tmp + nums.get(i), nums.get(i));
maxSumRight[i] = Math.max(tmp, maxSumRight[i + 1]);
}
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.size() - 1; i++) {
maxSum = Math.max(maxSum, maxSumLeft[i] + maxSumRight[i + 1]);
}
return maxSum;
}
public static void main(String[] args) {
MaxSubArray2 m = new MaxSubArray2();
int res = m.maxTwoSubArrays(new ArrayList<>(Arrays.asList(1,3,-1,2,-1,2)));
System.out.println(res);
}
}
| bsd-3-clause |
motech/MOTECH-Ghana | functional-tests/src/test/java/pages/OpenMRSLoginPage.java | 1326 | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import util.TestConfiguration;
public class OpenMRSLoginPage extends DefaultPage {
private TestConfiguration testConfiguration;
private String portNumber;
public OpenMRSLoginPage() {
driver = DefaultPage.getInstance();
testConfiguration = TestConfiguration.instance();
portNumber = testConfiguration.portNumber();
}
public void loginIntoOpenMRS(String loginName, String loginPassword) {
// Maximizing the Browser
((JavascriptExecutor)driver).executeScript("if (window.screen){window.moveTo(0, 0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);};");
driver.get("http://localhost:"+portNumber+"/openmrs/module/motechmodule/index.htm");
WebElement userName = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement login = driver.findElement(By.xpath("//input[@value = 'Log In']"));
userName.click();
userName.sendKeys(loginName);
password.sendKeys(loginPassword);
login.click();
}
public void close() {
driver.close();
}
}
| bsd-3-clause |
GameRevision/GWLP-R | protocol/src/main/java/gwlpr/protocol/gameserver/outbound/P409_Unknown.java | 758 |
package gwlpr.protocol.gameserver.outbound;
import gwlpr.protocol.serialization.GWMessage;
/**
* Auto-generated by PacketCodeGen.
*
*/
public final class P409_Unknown
extends GWMessage
{
private short unknown1;
private long unknown2;
@Override
public short getHeader() {
return 409;
}
public void setUnknown1(short unknown1) {
this.unknown1 = unknown1;
}
public void setUnknown2(long unknown2) {
this.unknown2 = unknown2;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("P409_Unknown[");
sb.append("unknown1=").append(this.unknown1).append(",unknown2=").append(this.unknown2).append("]");
return sb.toString();
}
}
| bsd-3-clause |
wcpan/gondola | core/src/main/java/com/yahoo/gondola/Shard.java | 7485 | /*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.gondola;
import com.yahoo.gondola.core.CoreMember;
import com.yahoo.gondola.core.Peer;
import com.yahoo.gondola.core.Stats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
* The type Shard.
*/
public class Shard implements Stoppable {
final static Logger logger = LoggerFactory.getLogger(Shard.class);
final Gondola gondola;
final Config config;
final Stats stats;
final String shardId;
final List<Peer> peers = new ArrayList<>();
final List<Member> members = new ArrayList<>();
Member localMember;
CoreMember cmember;
public Shard(Gondola gondola, String shardId) throws GondolaException {
this.gondola = gondola;
this.shardId = shardId;
config = gondola.getConfig();
stats = gondola.getStats();
List<Config.ConfigMember> configMembers = config.getMembersInShard(shardId);
List<Integer> peerIds = configMembers.stream()
.filter(cm -> !cm.hostId.equals(gondola.getHostId()))
.map(cm -> cm.memberId).collect(Collectors.toList());
// First create the local member, because it's needed when creating the remote members.
for (int i = 0; i < configMembers.size(); i++) {
Config.ConfigMember cm = configMembers.get(i);
if (gondola.getHostId().equals(cm.hostId)) {
// Local member
boolean isPrimary = i == 0;
cmember = new CoreMember(gondola, this, cm.memberId, peerIds, isPrimary);
localMember = new Member(gondola, cmember, null);
members.add(localMember);
break;
}
}
if (cmember == null) {
throw new IllegalStateException(String.format("Host id %s not found in %d", config.getIdentifier()));
}
// Create list of peers
for (Peer p : cmember.peers) {
members.add(new Member(gondola, cmember, p));
}
}
public void start() throws GondolaException {
cmember.start();
}
public boolean stop() {
return cmember.stop();
}
/******************** methods *********************/
/**
* Returns the cluster as provided in the constructor. See Cluster().
*
* @return non-null cluster id.
*/
public String getShardId() {
return shardId;
}
/**
* Returns the member with the specified id.
*
* @return null if the member id is not known.
*/
public Member getMember(int id) {
for (Member m : members) {
if (m.getMemberId() == id) {
return m;
}
}
return null;
}
/**
* @return non-null list of members in this cluster.
*/
public List<Member> getMembers() {
return members;
}
/**
* Returns the local member of this cluster. The local member is the actual process running on this host. The remote
* members are proxies of members running on other hosts.
*
* @return non-null local member.
*/
public Member getLocalMember() {
return localMember;
}
/**
* Returns the list of non-local members.
*
* @return non-null list of non-local members.
*/
public List<Member> getRemoteMembers() {
return members.stream().filter(m -> !m.isLocal()).collect(Collectors.toList());
}
/**
* Returns the current leader.
*
* @return null if the leader is not known.
*/
public Member getLeader() {
return getMember(cmember.getLeaderId());
}
/**
* Forces the local member of this cluster to become the leader. Blocks until this member becomes the leader.
*
* @param timeout -1 means there is no timeout.
*/
public void forceLeader(int timeout) {
long start = System.currentTimeMillis();
while (!cmember.isLeader()) {
try {
cmember.forceLeader();
if (timeout >= 0 && System.currentTimeMillis() - start > timeout) {
break;
}
Thread.sleep(1000);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
public Role getLocalRole() {
return cmember.getRole();
}
/**
* Returns the last saved index for this cluster. Waits until the storage is settled if necessary.
*/
public int getLastSavedIndex() throws InterruptedException {
return cmember.getSavedIndex();
}
/**
* ******************* commands ******************
*/
// TODO: move pool to Gondola, like message pool
Queue<Command> pool = new ConcurrentLinkedQueue<>();
/**
* Retrieves a command object from the command pool. Blocks until there are commands in the pool.
*
* @return non-null command object
*/
public Command checkoutCommand() throws InterruptedException {
Command command = pool.poll();
if (command == null) {
command = new Command(gondola, this, cmember);
}
return command;
}
/**
* Returns the command back into the command pool.
*
* @param command non-null command that is no longer used.
*/
void checkinCommand(Command command) {
pool.add(command);
}
/**
* Equivalent to getCommittedCommand(index, -1);
*
* @param index must be > 0.
* @return the non-null Command at index.
*/
public Command getCommittedCommand(int index) throws InterruptedException, GondolaException, TimeoutException {
return getCommittedCommand(index, -1);
}
/**
* Returns the command at the specified index. This method blocks until index has been committed. An empty command
* can be returned. This is an artifact of the Raft protocol to avoid deadlock when used with a finite thread pool.
* Empty commands will be inserted right after a leader election when the new leader discovers that it has
* uncommitted commands. The leader inserts an empty command to commit these immediately.
*
* @param index Must be > 0.
* @param timeout Returns after timeout milliseconds, even if the command is not yet available. -1 means there is no
* timeout.
* @return non-null Command
*/
public Command getCommittedCommand(int index, int timeout)
throws GondolaException, InterruptedException, TimeoutException {
if (index <= 0) {
throw new IllegalStateException(String.format("Index %d must be > 0", index));
}
Command command = checkoutCommand();
cmember.getCommittedLogEntry(command.ccmd, index, timeout);
try {
cmember.getCommittedLogEntry(command.ccmd, index, timeout);
return command;
} catch (GondolaException e) {
command.release();
throw new GondolaException(e);
}
}
/**
* Returns commitIndex.
*/
public int getCommitIndex() {
return cmember.getCommitIndex();
}
}
| bsd-3-clause |
xchrdw/nxparser | src/main/java/org/semanticweb/yars/nx/cli/Clean.java | 2583 | package org.semanticweb.yars.nx.cli;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URISyntaxException;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.semanticweb.yars.nx.clean.Cleaner;
import org.semanticweb.yars.nx.parser.NxParser;
public class Clean {
public static void main (String[] args) throws URISyntaxException, IOException{
Option inputO = new Option("i", "name of file to read, - for stdin");
inputO.setArgs(1);
Option outputO = new Option("o", "name of file to write, - for stdout");
outputO.setArgs(1);
Option helpO = new Option("h", "print help");
Option elementO = new Option("e", "check that all entries have x elements, will skip other entries");
elementO.setArgs(1);
Option datatypeO = new Option("d", "perform datatype normalisation (eperimental!)");
Options options = new Options();
options.addOption(inputO);
options.addOption(outputO);
options.addOption(helpO);
options.addOption(elementO);
options.addOption(datatypeO);
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("***ERROR: " + e.getClass() + ": " + e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options );
return;
}
if (cmd.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options );
return;
}
InputStream in = System.in;
PrintStream out = System.out;
int elements = -1;
if (cmd.hasOption("i")) {
if (cmd.getOptionValue("i").equals("-")) {
in = System.in;
} else {
in = new FileInputStream(cmd.getOptionValue("i"));
}
}
if (cmd.hasOption("o")) {
if (cmd.getOptionValue("o").equals("-")) {
out = System.out;
} else {
out = new PrintStream(new FileOutputStream(cmd.getOptionValue("o")));
}
}
if (cmd.hasOption("e")) {
elements = Integer.parseInt(cmd.getOptionValue("e"));
}
boolean datatype = false;
if (cmd.hasOption("d")) {
datatype = true;
}
NxParser nqp = new NxParser(in,false);
Cleaner.clean(nqp, out, elements, datatype);
}
}
| bsd-3-clause |
endlessm/chromium-browser | components/embedder_support/android/java/src/org/chromium/components/embedder_support/browser_context/BrowserContextHandle.java | 631 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.embedder_support.browser_context;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* An interface that provides access to a native BrowserContext.
*/
@JNINamespace("browser_context")
public interface BrowserContextHandle {
/** @return A pointer to the native BrowserContext that this object wraps. */
@CalledByNative
long getNativeBrowserContextPointer();
}
| bsd-3-clause |
wangxin39/xstat | XStatAPI/src/org/xsaas/xstat/po/GradeStdInfo.java | 1538 | package org.xsaas.xstat.po;
import java.io.Serializable;
/**
* ÆÀ·Ö±ê×¼ÐÅÏ¢±í
* @author ÍõöÎ
* ÆÀ·Ö±ê׼ʵÌå
*/
public class GradeStdInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3955013732011110988L;
/**
* ÆÀ·Ö±ê×¼±àºÅ
*/
private Long gradeStdID = null;
/**
* µ÷²éÎʾí±àºÅ
*/
private Long inquisitionID = null;
/**
* ±êÌâ
*/
private String title = null;
/**
* ÃèÊö
*/
private String description = null;
/**
* ״̬
* 1£ºÕý³£
* 2£ºÉ¾³ý
*/
private Integer status = null;
public Long getGradeStdID() {
return gradeStdID;
}
public void setGradeStdID(Long gradeStdID) {
this.gradeStdID = gradeStdID;
}
public Long getInquisitionID() {
return inquisitionID;
}
public void setInquisitionID(Long inquisitionID) {
this.inquisitionID = inquisitionID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public GradeStdInfo(String description, Long gradeStdID,
Long inquisitionID, Integer status, String title) {
super();
this.description = description;
this.gradeStdID = gradeStdID;
this.inquisitionID = inquisitionID;
this.status = status;
this.title = title;
}
public GradeStdInfo() {
super();
}
}
| bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/iploadbalancing/OvhDefinedFarm.java | 211 | package net.minidev.ovh.api.iploadbalancing;
/**
* a list of { type => [ Farm ids ] }
*/
public class OvhDefinedFarm {
/**
* canBeNull
*/
public Long id;
/**
* canBeNull
*/
public String type;
}
| bsd-3-clause |
NCIP/cagrid2 | cagrid-proxy-trust/src/main/java/org/cagrid/security/ssl/proxy/trust/ProxyPolicy.java | 5405 | /*
* Portions of this file Copyright 1999-2005 University of Chicago
* Portions of this file Copyright 1999-2005 The University of Southern California.
*
* This file or a portion of this file is licensed under the
* terms of the Globus Toolkit Public License, found at
* http://www.globus.org/toolkit/download/license.html.
* If you redistribute this file, with or without
* modifications, you must include this notice in the file.
*/
package org.cagrid.security.ssl.proxy.trust;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
/**
* Represents the policy part of the ProxyCertInfo extension. <BR>
*
* <PRE>
* ProxyPolicy ::= SEQUENCE {
* policyLanguage OBJECT IDENTIFIER,
* policy OCTET STRING OPTIONAL }
* </PRE>
*/
public class ProxyPolicy implements DEREncodable {
/** Impersonation proxy OID */
public static final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier(
"1.3.6.1.5.5.7.21.1");
/** Independent proxy OID */
public static final DERObjectIdentifier INDEPENDENT = new DERObjectIdentifier(
"1.3.6.1.5.5.7.21.2");
/** Limited proxy OID */
public static final DERObjectIdentifier LIMITED = new DERObjectIdentifier(
"1.3.6.1.4.1.3536.1.1.1.9");
private DERObjectIdentifier policyLanguage;
private DEROctetString policy;
/**
* Creates a new instance of the ProxyPolicy object from given ASN1Sequence
* object.
*
* @param seq
* ASN1Sequence object to create the instance from.
*/
public ProxyPolicy(ASN1Sequence seq) {
if (seq.size() < 1) {
throw new IllegalArgumentException("Invalid sequence");
}
this.policyLanguage = (DERObjectIdentifier) seq.getObjectAt(0);
if (seq.size() > 1) {
DEREncodable obj = seq.getObjectAt(1);
if (obj instanceof DERTaggedObject) {
obj = ((DERTaggedObject) obj).getObject();
}
this.policy = (DEROctetString) obj;
}
checkConstraints();
}
/**
* Returns the DER-encoded ASN.1 representation of proxy policy.
*
* @return <code>DERObject</code> the encoded representation of the proxy
* policy.
*/
public DERObject getDERObject() {
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(this.policyLanguage);
if (this.policy != null) {
vec.add(this.policy);
}
return new DERSequence(vec);
}
/**
* Creates a new instance of the ProxyPolicy object.
*
* @param policyLanguage
* the language policy Oid.
* @param policy
* the policy.
*/
public ProxyPolicy(DERObjectIdentifier policyLanguage, byte[] policy) {
if (policyLanguage == null) {
throw new IllegalArgumentException("Policy langauge oid required");
}
this.policyLanguage = policyLanguage;
if (policy != null) {
this.policy = new DEROctetString(policy);
}
checkConstraints();
}
/**
* Creates a new instance of the ProxyPolicy object.
*
* @param policyLanguageOid
* the language policy Oid.
* @param policy
* the policy.
*/
public ProxyPolicy(String policyLanguageOid, byte[] policy) {
if (policyLanguageOid == null) {
throw new IllegalArgumentException("Policy langauge oid required");
}
this.policyLanguage = new DERObjectIdentifier(policyLanguageOid);
if (policy != null) {
this.policy = new DEROctetString(policy);
}
checkConstraints();
}
/**
* Creates a new instance of the ProxyPolicy object.
*
* @param policyLanguage
* the language policy Oid.
* @param policy
* the policy.
*/
public ProxyPolicy(DERObjectIdentifier policyLanguage, String policy) {
this(policyLanguage, (policy != null) ? policy.getBytes() : null);
}
/**
* Creates a new instance of the ProxyPolicy object with no policy.
*
* @param policyLanguage
* the language policy Oid.
*/
public ProxyPolicy(DERObjectIdentifier policyLanguage) {
this(policyLanguage, (byte[]) null);
}
protected void checkConstraints() {
if ((this.policyLanguage.equals(IMPERSONATION) || this.policyLanguage
.equals(INDEPENDENT)) && this.policy != null) {
throw new IllegalArgumentException("Constrains violation.");
}
}
/**
* Returns the actual policy embedded in the ProxyPolicy object.
*
* @return the policy in bytes. Might be null.
*/
public byte[] getPolicy() {
return (this.policy != null) ? this.policy.getOctets() : null;
}
/**
* Returns the actual policy embedded in the ProxyPolicy object.
*
* @return the policy as String. Might be null.
*/
public String getPolicyAsString() {
return (this.policy != null) ? new String(this.policy.getOctets())
: null;
}
/**
* Returns the policy language of the ProxyPolicy.
*
* @return the policy language Oid.
*/
public DERObjectIdentifier getPolicyLanguage() {
return this.policyLanguage;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("ProxyPolicy: ");
buf.append(this.policyLanguage.getId());
if (this.policy != null) {
buf.append(System.getProperty("line.separator"));
buf.append(getPolicyAsString());
}
return buf.toString();
}
}
| bsd-3-clause |
kurbatovmax/javaCoursePracticStepan | Projects/PushCalculator/src/im/kmg/pc/ExceptionNoPlugins.java | 225 | package im.kmg.pc;
/**
* Created with IntelliJ IDEA.
* User: maxim
* Date: 9/14/13
* Time: 8:12 PM
*/
public class ExceptionNoPlugins extends Exception {
ExceptionNoPlugins() {
super("No commands");
}
}
| bsd-3-clause |
genome-vendor/apollo | src/java/apollo/gui/genomemap/ApolloPanel.java | 45866 | package apollo.gui.genomemap;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import apollo.config.Config;
import apollo.gui.ControlledObjectI;
import apollo.gui.Selection;
import apollo.gui.SelectionManager;
import apollo.gui.StatusBar;
import apollo.gui.Controller;
import apollo.gui.drawable.Drawable;
import apollo.gui.drawable.DrawableSeqFeature;
import apollo.gui.menus.*;
import apollo.gui.event.*;
import apollo.gui.event.MouseButtonEvent;
import apollo.gui.synteny.GuiCurationState;
import apollo.datamodel.*;
import apollo.seq.io.*;
import apollo.util.*;
import apollo.dataadapter.*;
import gov.sandia.postscript.*;
//used for dynamic loading of DataAdapters
import java.lang.reflect.*;
import org.apache.log4j.*;
/**
* This class is a container to hold and manage the various Views
* which are needed by Apollo. It holds all the views from both strands.
*/
public class ApolloPanel extends JPanel implements
ApolloPanelI,
BaseFocusListener,
ControlledObjectI,
FeatureSelectionListener,
KeyListener,
MouseInputListener,
MouseWheelListener,
DataLoadListener,
RubberbandListener,
//TypesChangedListener,
ViewListener {
// -----------------------------------------------------------------------
// Class/static variables
// -----------------------------------------------------------------------
protected final static Logger logger = LogManager.getLogger(ApolloPanel.class);
// -----------------------------------------------------------------------
// Instance variables
// -----------------------------------------------------------------------
protected Image backBuffer;
protected int backBufferWidth = 0;
protected int backBufferHeight = 0;
private Vector views; // ViewI vector
protected Vector linearViews; // ViewI viector
protected Vector pickViews; // pickViewI vector
private ScaleView scaleView; // SZAP will set this so we can access it here
protected ApolloLayoutManager layout_manager;
protected Controller controller;
protected ViewI focus;
protected String name;
protected boolean syncLimits = false;
protected RubberbandRectangle rubberband;
protected boolean inDrag = false;
protected MouseEvent pressEvent = null;
protected boolean inTierDrag = false;
protected TierViewI dragTierView = null;
protected StatusBar statusBar;
protected Rectangle layoutBounds;
protected boolean invalid = true;
protected boolean allowsMovement = true;
protected boolean showEdgeMatches = true;
//private boolean realRemove = true;
private MouseManager mouseManager;
private SelectionManager selectionManager;
private GuiCurationState curationState;
//private boolean loadInProgress=false; // not used anymore - but should it be?
ApolloPanel(String name,GuiCurationState curationState) {
// Basic setup
setName(name);
this.curationState = curationState;
setSelectionManager(curationState.getSelectionManager());
// vectors to hold views and view subsets
views = new Vector();
linearViews = new Vector();
pickViews = new Vector();
// Add mouse and keyboard listeners (there is no addMouseInputListener())
addMouseMotionListener(this);
addMouseListener (this);
addMouseWheelListener (this);
addKeyListener (this);
// Add rubberband
rubberband = new RubberbandRectangle(this);
rubberband.setActive(true);
rubberband.addListener(this);
//new MousePositionReporter(this);
// Setup panel graphics properties
setOpaque(false);
}
/** This gets called by gui machinery when panel is removed from parent,
overrides Component.removeNotify() - this was setup to clear() ApolloPanel
on remove, but now that szaps and apollo panels are not be recreated with
every load we actually want to never clear() - i think this means we dont
need clear anymore either */
// public void removeNotify() {
// // logger.debug("Remove notify for " + getName());
// if (realRemove)
// clear();
// super.removeNotify();
// realRemove = true;
// }
// public void setRealRemove(boolean state) {
// realRemove = state;
// }
// /** clears out and removes listeners and views and sets them to null */
// void clear() {
// if (rubberband != null) {
// rubberband.removeListener(this);
// removeMouseListener((MouseListener)rubberband);
// removeMouseMotionListener((MouseMotionListener)rubberband);
// }
// removeMouseMotionListener(this);
// removeMouseListener(this);
// removeKeyListener(this);
// clearViews(false); // false - remove views from view vectors
// rubberband = null;
// controller = null;
// layout_manager = null;
// if (views != null) {
// views.removeAllElements();
// }
// linearViews.removeAllElements();
// pickViews.removeAllElements();
// views = null;
// focus = null;
// pressEvent = null;
// }
/**
If just features then just takes features out of views,
otherwise gets rid of views - if its true that we dont need clear() anymore
than the boolean can be taken out
*/
private void clearViews(boolean justFeatures) {
if (views == null) {
return;
}
ArrayList featViews = getFeatureViews();
for (int i=0; i<featViews.size(); i++) {
FeatureView fv = (FeatureView) featViews.get(i);
if (justFeatures) fv.clearFeatures();
else fv.clear(); // wipes everything out
}
if (!justFeatures)
for (int i=0; i<views.size(); i++)
remove((ViewI)views.elementAt(i));
}
/** Helper function to get feature views that goes through ContainerViewI's in
in views vector */
private ArrayList getFeatureViews() {
if (views == null) {
return null;
}
ArrayList featViews = new ArrayList(4);
for (int i=0; i<views.size(); i++) {
ViewI view = (ViewI)views.elementAt(i);
if (view instanceof FeatureView) featViews.add(views.elementAt(i));
if (view instanceof ContainerViewI) {
Vector fViews =
((ContainerViewI)view).getViewsOfClass(apollo.gui.genomemap.FeatureView.class);
featViews.addAll(fViews);
}
}
return featViews;
}
/** Empties out the views but keeps the empty views (clearViews(true)) */
void clearFeatures() {
clearViews(true);
}
static final Object ALOCK = new ApolloTreeLock();
static class ApolloTreeLock {}
public synchronized final Object getApolloLock() {
return ALOCK;
}
/**
* Add a View to the views. This no longer does an invalidate/validate trigerring
* a layout. This is now the responsibility of the caller to do. This is more efficient
* for the case when you are adding many things, you only need to do the validate/layout
* after adding everything, not for each add. Also the intermediate layouts would
* screw up scroll bar values on revcomp.
*/
public void add(ViewI view,Object constraints) {
views.addElement(view);
if (view instanceof ViewI && !(view instanceof DragViewI)) {
linearViews.addElement(view);
}
if (view instanceof PickViewI && !(view instanceof DragViewI)) {
pickViews.addElement(view);
}
if (layout_manager != null) {
layout_manager.addLayoutView(view,constraints);
}
view.addViewListener(this);
// This validate causes a layout to occur before all the views have been added
// which can alter the scrollbar values on a revcomp since a layout will occur
// with not all the views so the view will be given a lot more real estate
// szap now calls validate after all the views have been added - its more efficient
// and it doenst create funny inbetween states that screw up the scrollbars
}
public void add(ViewI view) {
add(view,null);
}
// Called by SZAP so we can access scaleView from here when we need to.
public void setScaleView(ScaleView scale) {
scaleView = scale;
}
/**
* Set the Apollo specific layout manager for this Panel
*/
public void setLayout(ApolloLayoutManager manager) {
super.setLayout(manager);
this.layout_manager = manager;
invalidate();
validate();
}
/**
* Remove a View from the views
*
*
*/
public void remove(ViewI view) {
boolean found = false;
if (views.contains(view)) {
views.removeElement(view);
found = true;
}
if (linearViews.contains(view)) {
linearViews.removeElement(view);
}
if (pickViews.contains(view)) {
pickViews.removeElement(view);
}
if (layout_manager != null) {
layout_manager.removeLayoutView(view);
}
if (found) {
invalidate();
validate();
}
}
// Need this here because we need to do this from places where we only have
// access to ApolloPanel, not StrandedZoomableApolloPanel
public void putVerticalScrollbarsAtStart() {
for (int i=0;i<linearViews.size();i++) {
ViewI lv = ((ViewI)linearViews.elementAt(i));
if (lv instanceof ResultView)
((ResultView)lv).putScrollAtStart();
else if (lv instanceof AnnotationView)
((AnnotationView)lv).putScrollAtStart();
}
}
/**
* Sets flag indicating whether to synchronise the limits on all
* the LinearViews. This is necessary for the OverviewPanel, but
* not desirable for the FineEditor panel.
*/
public void setSyncLimits(boolean state) {
this.syncLimits = state;
if (this.syncLimits) {
syncViewLimits(-1, -1); // no range provided
}
}
public void setSyncLimits(boolean state, int reglow, int reghigh) {
this.syncLimits = state;
if (this.syncLimits) {
syncViewLimits(reglow, reghigh);
}
}
/**
* Gets flag indicating whether to synchronise the limits on all
* the LinearViews.
*/
public boolean isSynced() {
return this.syncLimits;
}
/**
* Actually do the view limit synchronisation
* This actually adds a 1/100 of seq length as padding to each end,
* and updates all the views with these limits. This means that
* limits != sequence start and end.
*/
protected void syncViewLimits(int reglow, int reghigh) {
int [] globalLimits = new int [2];
if (reglow < 0) {
for (int i=0;i<linearViews.size();i++) {
ViewI lv = ((ViewI)linearViews.elementAt(i));
if (lv.areLimitsSet()) {
if (i == 0 || lv.getLimits()[0] < globalLimits[0]) {
globalLimits[0] = lv.getLimits()[0];
}
if (i == 0 || lv.getLimits()[1] > globalLimits[1]) {
globalLimits[1] = lv.getLimits()[1];
}
}
}
}
// Original approach resulted in huge limits because some XML files have features
// that extend way beyond the range of the sequence itself.
// Why not just use the start/end of the sequence as limits? Users will still
// be able to see features that extend beyond it if they zoom out.
// Because quite often there is no sequence (gff files etc.) so the
// limits end up screwed. One way round this might be to make a dummy
// sequence which pretends to have the same limits as the features
// Note this didn't work because it assumed all ranges start at 0 which they don't
else {
// Leave some space on both sides so features don't slam against the left and right edges
int hspace = (reghigh-reglow)/100;
globalLimits[0] = reglow - hspace;
globalLimits[1] = reghigh + hspace;
}
for (int i=0;i<linearViews.size();i++) {
ViewI lv = (ViewI) linearViews.elementAt(i);
lv.setLimits(globalLimits);
lv.setZoomFactor(1.0);
}
setLinearCentre((int)(globalLimits[1]+globalLimits[0])/2);
}
/**
* Sets the linear centre for the focused view, or
* all LinearViews depending on syncLimits flag
*/
public void setLinearCentre(int Position) {
if (allowsMovement) {
if (isSynced()) {
for (int i=0;i<linearViews.size();i++) {
ViewI lv = ((ViewI)linearViews.elementAt(i));
lv.setCentre(Position);
}
} else {
focus.setCentre(Position);
}
}
repaint();
}
public void setMovementAllowed(boolean state) {
allowsMovement = state;
}
public int getLinearCentre() {
if (isSynced()) {
return ((ViewI)linearViews.elementAt(0)).getCentre();
} else {
return focus.getCentre();
}
}
public int getLinearMinimum() {
if (isSynced()) {
return ((ViewI)linearViews.elementAt(0)).getMinimum();
} else {
return focus.getMinimum();
}
}
public int getLinearMaximum() {
if (isSynced())
return ((ViewI)linearViews.elementAt(0)).getMaximum();
else
return focus.getMaximum();
}
public void setVisible(boolean state) {
super.setVisible(state);
backBuffer = createImage(1,1);
}
/** This returns the width of the panel in base pairs NOT pixels.
Is the linear part of the method name suppose to connote this?
If so it is not obvious. It should probably be renamed
getBasePairWidth or getCoordinateWidth if we dont want to
assume base pairs.
Its returning start and end base pair that is currently visible.
Loops through linear views and uses first visible one.
*/
public int getVisibleBasepairWidth() {
int lv_width = -1;
if (isSynced()) {
// 0th view is site view which doesnt have width until visible - ???
ViewI lv = null;
for (int i = 0; i < linearViews.size() && lv == null; i++) {
lv = (((ViewI)linearViews.elementAt(i)).isVisible() ?
(ViewI) linearViews.elementAt (i) : null);
}
if (lv != null) {
int [] lims = lv.getVisibleRange();
lv_width = (lims[1]-lims[0]);
}
} else {
int [] lims = focus.getVisibleRange();
lv_width = (lims[1]-lims[0]);
}
return lv_width;
}
/**
* Set zoom factor on all views
*/
public void setZoomFactor(double xFactor, double yFactor) {
if (isSynced()) {
for (int i=0;i<linearViews.size();i++) {
ViewI lv = ((ViewI)linearViews.elementAt(i));
if (xFactor > 0.0)
lv.setZoomFactor(xFactor);
}
}
repaint();
}
/**
* Set X zoom factor on all views
*/
public void setZoomFactorX(double xFactor) {
setZoomFactor(xFactor,-1.0);
}
/**
* Set Y zoom factor on all views
*/
public void setZoomFactorY(double yFactor) {
setZoomFactor(-1.0,yFactor);
}
/**
* Sets the event controller for the panel. This is for controlling
* the dispatch of Apollo specific (Feature) events. All the components
* dealling with apollo data should register with a single controller,
* which will notify them when changes, selections, moves... occur.
*/
public void setController(Controller controller) {
logger.debug("setController called for " + getName());
this.controller = controller;
controller.addListener(this);
for (int i=0; i<views.size(); i++) {
if (views.elementAt(i) instanceof ControlledObjectI) {
ControlledObjectI cti = (ControlledObjectI) views.elementAt(i);
cti.setController(controller);
}
}
}
/** Controller for selection */
private void setSelectionManager(SelectionManager sm) {
selectionManager = sm;
//selectionManager.setApolloPanel(this); // for now - eventually shouldnt need this
mouseManager = new MouseManager(this,getCurationState());
}
private GuiCurationState getCurationState() { return curationState; }
public Selection getSelection() {
return selectionManager.getSelection();
}
/**
* Gets the apollo event controller for the panel.
*/
public Controller getController() {
return this.controller;
}
public Object getControllerWindow() {
return SwingMissingUtil.getWindowAncestor(this);
}
public boolean needsAutoRemoval() {
return true;
}
public void print(File file, String orientation, String scale) {
try {
PrintWriter fw = new PrintWriter(new FileWriter(file));
Graphics psg = new PSGr2(fw);
double scaleVal = 1.0;
try {
scaleVal = new Double(scale).doubleValue();
} catch (Exception e) {
logger.error("Invalid scale factor", e);
return;
}
if (orientation.equals("landscape")) {
fw.println("-30 30 translate");
fw.println("90 rotate");
//fw.println("30 -642 translate");
fw.println("" + ((int)(30.0*scaleVal)) + " " + ((int)(-822.0*scaleVal)) + " translate");
fw.println("" + scale + " " + scale + " scale");
} else {
fw.println("-30 30 translate");
int yOffset = (int)(762.0 - 792.0*scaleVal );
fw.println("30 " + yOffset + " translate");
fw.println("" + scale + " " + scale + " scale");
}
for (int i=0; i<views.size(); i++) {
((ViewI)views.elementAt(i)).setInvalidity(true);
}
psg.setClip(new Rectangle(0,0,getSize().width,getSize().height));
paintComponent(psg);
psg.dispose();
fw.close();
} catch (Exception e) {
logger.error("Failed printing to file " + file, e);
}
}
/**
* Overidden paintComponent to draw any views requiring a repaint
*/
public void paintComponent(Graphics g) {
// The load in progress paint supression needs to be better
// The views should paint - but just there backrounds - no features
// even better the views should dump their old features at load time
//if (loadInProgress) return;//this isnt set anywhere,was it ever,should it be?
Rectangle clipRect = null;
Vector damagedViews = null;
// long timestamp;
// set the graphics to the back graphics
// get the damaged rectangle
Rectangle damage = g.getClipBounds();
// find the overlapping views
damagedViews = getViews(damage);
Graphics fg;
// SMJS If we're printing just send the PSGr2 graphics around,
// don't wrap it in a FastClippingGraphics
if (Config.useFastClipGraphics() && !(g instanceof PSGr2)) {
fg = new FastClippingGraphics(g);
} else {
fg = g;
}
fg.setFont(Config.getDefaultFont());
for (int i=0;i<damagedViews.size();i++) {
// redraw those views
ViewI v = ((ViewI)damagedViews.elementAt(i));
if (!v.isInvalid()) {
v.setGraphics(fg);
clipRect = v.getBounds().intersection(damage);
fg.setClip(clipRect);
v.paintView();
}
}
fg.setClip(damage);
// If not drawn then check if view has been set to invalid. If so
// it needs update for some other reason eg. rescaling, relayout,
// resizing.
for (int i=0;i<views.size();i++) {
ViewI v = ((ViewI)views.elementAt(i));
if (v.isInvalid() && !(v instanceof DragViewI) && v.isVisible()) {
v.setGraphics(fg);
fg.setClip(v.getBounds());
v.paintView();
damage = damage.union(v.getBounds());
v.setInvalidity(false);
}
}
// After all normal views drawn draw any dragging views.
for (int i=0;i<views.size();i++) {
ViewI v = ((ViewI)views.elementAt(i));
if (v instanceof DragViewI) {
Rectangle draggyBounds = new Rectangle(v.getBounds());
Rectangle panelBounds = getBounds();
if (draggyBounds.x < 0) draggyBounds.x = 0;
if (draggyBounds.y < 0) draggyBounds.y = 0;
if (draggyBounds.x > panelBounds.width) draggyBounds.x = panelBounds.width;
if (draggyBounds.y > panelBounds.height) draggyBounds.y = panelBounds.height;
if (draggyBounds.x+draggyBounds.width > panelBounds.width) draggyBounds.width = panelBounds.width-draggyBounds.x;
if (draggyBounds.y+draggyBounds.height > panelBounds.height) draggyBounds.height = panelBounds.height-draggyBounds.y;
fg.setClip(draggyBounds);
v.setGraphics(fg);
v.paintView();
damage = damage.union(v.getBounds());
v.setInvalidity(false);
}
}
fg.setClip(damage);
}
/**
* Overidden doLayout to handle View layout
*/
int count = 0;
public void doLayout() {
count++;
logger.debug("doLayout called, count = " + count);
if (count < 3) {
// This code is here to stop relayout when just the status bar is updated.
boolean isInvalid = false;
for (int i=0; i<views.size() && !isInvalid; i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v.isInvalid() && v.isVisible()) {
isInvalid = true;
logger.debug("View " + v.getName() + " is invalid");
}
}
isInvalid = isInvalid || invalid;
// Layout is not done if the bounds haven't changed unless one or more visible
// views are invalid or the panel has been set invalid.
if (layout_manager != null
&& (!getBounds().equals(layoutBounds) || isInvalid)) {
layout_manager.layoutViews(this);
layout_manager.layoutContainer(this);
layoutBounds = new Rectangle(getBounds());
}
logger.debug("end layout");
count--;
} else {
logger.warn("recursive doLayout() call.");
count = 0;
}
}
/**
* Set the Graphics to draw to.
*
* @param g The new graphics to draw to.
*/
public void setViewGraphics(Graphics g) {}
/** Causes views to layout if this.doLayout is called */
public void setInvalidity(boolean state) {
invalid = state;
}
/**
* Get the Graphics to draw to.
*
* @param g The new graphics to draw to.
*/
public Graphics getViewGraphics() {
return null;
}
public Image getBackBuffer() {
return backBuffer;
}
/**
* Returns the name of the panel.
*/
public String getName() {
return this.name;
}
/**
* Sets the name of the panel - is this used at all?
*
* @param name The name of the panel.
*/
public void setName(String name) {
this.name = new String(name);
}
/**
* Get the View at a specified location in the Panel
*/
protected ViewI getViewAt(Point p) {
ViewI retview = null;
for (int i=0;i<views.size();i++) {
ViewI v = ((ViewI)views.elementAt(i));
if (!(v instanceof DragViewI)) {
if (v.getBounds().contains(p) && v.isVisible()) {
if (v instanceof ContainerViewI) {
v = ((ContainerViewI)v).getContainedViewAt(p);
}
if (retview!=null) {
logger.warn("Overlapping non drag views (" + v.getName() + " and " + retview.getName() + ") in getViewAt()");
}
retview = v;
}
}
}
return retview;
}
/**
* Sets the view which has 'focus'
*/
protected void setFocusView(ViewI focus) {
this.focus = focus;
}
// Used by ScaleView
public ViewI getFocus() {
return focus;
}
// Handle the events
// Clearing the selection when a TypesChangedEvent occurs is very conservative.
// It stops selections in types which have become invisible, but could be
// annoying to the user - we'll see.
// public boolean handleTypesChangedEvent(TypesChangedEvent evt) {
// // Clearing selections here inadvertently causes a bug -
// // when TiersMenu is brought up for the 1st time the ShowMenu
// // calls up the hidden tiers for their colors, PropertyScheme create
// // new FeatureProperty and notifies TypesObserver Observer
// // TypesObserver calls Controller.handleTypesChangedEvent which
// // calls this method and the selection gets deselected and cant be
// // used for things in the menu like output to fasta - this only
// // happens on 1st selection to get the hidden tier stuff
// return true;
// }
public boolean handleDataLoadEvent(DataLoadEvent evt) {
clearSelection();
updateSelection();
return true;
}
private void updateSelection() {
fireFeatureSelectionEvent(getSelection());
repaint();
}
private void fireFeatureSelectionEvent (Selection sel) {
FeatureSelectionEvent evt = new FeatureSelectionEvent(this,sel);
controller.handleFeatureSelectionEvent(evt);
}
public boolean handleViewEvent(ViewEvent evt) {
if (evt.getType() == ViewEvent.LIMITS_CHANGED) {
if (isSynced()) {
syncViewLimits(-1,-1);
}
}
return true;
}
public boolean handleBaseFocusEvent (BaseFocusEvent evt) {
// redundant - szap.handleBFE->setCentreBase
// setLinearCentre(evt.getFocus());
return true;
}
/**
* FeatureSelectionListener - should this scroll to the selection?
* YES
* This sets Selection selection to the features in the selection event
* that are found in the views. When feature gets added to Selection,
* Selection tells it its selected. Repaint is called and features will
* paint themselves selected if they are so.
*/
public boolean handleFeatureSelectionEvent(FeatureSelectionEvent evt) {
boolean alreadyProcessed = false;
/* if source is from a FeatureView then it's from ourself essentially and
has already been dealt with (by attaching drawables as
selectionListeners)
This should get set to true if we've single-clicked an intron
(double-clicking an intron shouldn't do anything; instead,
it's ending up throwing an exception) */
if (evt.getSource() == this)
alreadyProcessed = true;
if (!alreadyProcessed) {
for (int i=0; i<views.size(); i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v instanceof SelectViewI && v.isVisible()) {
SelectViewI sv = (SelectViewI)v;
sv.select(evt.getSelection());
// The object that is the ContainerViewI should also be a SelectViewI
} else if (v instanceof ContainerViewI) {
Vector svs = ((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.SelectViewI.class);
for (int j=0; j<svs.size(); j++) {
SelectViewI sv = (SelectViewI)svs.elementAt(j);
sv.select(evt.getSelection());
}
}
}
}
processSelection(evt.getSelection());
getStrandedZoomableApolloPanel().scrollToSelection();
//highlightEdges(evt.getSelection(),true);
//repaint();
return true;
}
/** Notice this is the same iteration as in handleFeatureSelectionEvent
* sv.verticalScrollToSelection used to be part of handleFeatureSelectionEvent
* but the vertical scroll cant happen until zoom has happened, as zoom changes
* the view, and zoom has to wait for the whole selection to be over.
* It would be nice if we didnt have to iterate through the views to
* dig up the selection. If the feature itself was capable of adding itself
* to view.
*/
void verticalScrollToSelection(/*FeatureSelectionEvent evt*/) {
for (int i=0; i<views.size(); i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v instanceof SelectViewI && v.isVisible()) {
SelectViewI sv = (SelectViewI)v;
sv.verticalScrollToSelection();
//Selection newPick = sv.findSelected(evt);
//if (newPick.size() > 0)sv.verticalScrollToSelection(newPick);
}
else if (v instanceof ContainerViewI) {
Vector svs =
((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.SelectViewI.class);
for (int j=0; j<svs.size(); j++) {
SelectViewI sv = (SelectViewI)svs.elementAt(j);
sv.verticalScrollToSelection();
}
}
}
}
// These events are fired through the controller and onto other components
private void fireBaseFocusEvent(int focus) {
BaseFocusEvent evt = new BaseFocusEvent(this,focus,null);
controller.handleBaseFocusEvent(evt);
}
/**
* I believe this highlights edges in other views that line up with
* the edges in the selection
*/
public void highlightEdges(Selection sel, boolean state) {
if (showEdgeMatches) {
clearEdges();
for (int i=0; i<views.size() ; i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v instanceof FeatureView) {
((FeatureView)v).setMatchingEdges(sel,state);
} else if (v instanceof ContainerViewI) {
Vector fvs = ((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.FeatureView.class);
for (int j=0; j<fvs.size(); j++) {
((FeatureView)fvs.elementAt(j)).setMatchingEdges(sel,state);
}
}
}
}
}
public void setEdgeMatching(boolean state) {
showEdgeMatches = state;
if (state == true) {
highlightEdges(getSelection(),true);
} else {
clearEdges();
}
repaint();
}
public boolean isShowingEdgeMatches() {
return showEdgeMatches;
}
public void clearEdges() {
for (int i=0; i<views.size() ; i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v instanceof FeatureView) {
((FeatureView)v).clearEdges();
} else if (v instanceof ContainerViewI) {
Vector fvs = ((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.FeatureView.class);
for (int j=0; j<fvs.size(); j++) {
((FeatureView)fvs.elementAt(j)).clearEdges();
}
}
}
}
public void mouseWheelMoved(MouseWheelEvent evt) {
if (focus != null && focus instanceof TierView) {
TierView tv = (TierView)focus;
tv.moveScrollbarByWheelAmount(evt.getWheelRotation());
}
}
/**
* MouseInputListener routines
*/
public void mouseEntered(MouseEvent evt) {
requestFocusInWindow();
}
public void mouseExited(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {
// Middle button: center on selection
if (MouseButtonEvent.isMiddleMouseClickNoShift(evt)) {
doMiddleClick(evt);
}
// For left button, check that the View under mouse is selectable
// and do selection
else if (MouseButtonEvent.isLeftMouseClick(evt)) {
doLeftClick(evt);
/*
The result of a mouse-click is that we need to run a features
selection on ourselves. Since we are the event source, this
amounts to making sure aligning features are highlighted,
and repainting ourselves. */
processSelection(getSelection()); // should this be in MouseManager?
}
// Right click is handled in mousePressed, for some reason.
}
/** If a selection has occurred highlighting of edges and a repaint have to
take place. This is for either internal or external selection to use.
Anything else that has to happen with a selection should be put here.
This is called by internal selection (mouse click and rubberbanding),
and external selection (handleFeatureSelectionEvent)
*/
private void processSelection(Selection selection) {
highlightEdges(selection,true);// light up lined up edges in other views
repaint();
}
private void doLeftClick(MouseEvent evt) {
mouseManager.doLeftClick(evt);
}
/** If focus is selectable its an instance of PickViewI */
boolean focusIsSelectable() {
return focus instanceof PickViewI;
}
/** If focus is a pick focus, returns the PickViewI */
public PickViewI getPickViewFocus() {
if (!focusIsSelectable())
return null;
return
(PickViewI)focus;
}
protected void doMiddleClick(MouseEvent evt) {
Point base;
ViewI v;
if ((v = findVisibleLinearView()) != null) {
base = v.getTransform().toUser(evt.getX(),evt.getY());
} else {
logger.warn("No visible linearViews");
base = ((ViewI)linearViews.elementAt(0)).getTransform().toUser(evt.getX(),evt.getY());
}
setLinearCentre(base.x);
fireBaseFocusEvent(base.x);
}
private ViewI findVisibleLinearView() {
ViewI v = null;
for (int i=0;i<linearViews.size() && v == null; i++) {
ViewI tmp = (ViewI)linearViews.elementAt(i);
if (tmp.isVisible()) {
v = tmp;
if (v instanceof ContainerViewI) {
Vector lvs = ((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.ViewI.class);
if (lvs.size() != 0) {
v = (ViewI)lvs.elementAt(0);
}
}
}
}
return v;
}
/**
* When the mouse button comes down (but is not released) it
* may be either the right mouse button or the left. The
* middle mouse button is for clicks only. If it is the
* right button then popup a menu. If it is the left button
* then select and start dragging.
* @param evt
*/
public void mousePressed(MouseEvent evt) {
// Clear rubberband in ScaleView
scaleView.clear();
if (MouseButtonEvent.isRightMouseClickNoShift(evt)) {
ViewI view = getViewAt(new Point(evt.getX(),evt.getY()));
if (view instanceof PopupViewI) {
if (getSelection().size() == 0)
doLeftClick(evt);
((PopupViewI)view).showPopupMenu(evt);
}
}
else if (MouseButtonEvent.isLeftMouseClick(evt)) {
// Save location of press in case a drag begins without a selection being
// made. In this case we want to make the selection where the mouse
// started the drag which is where the press occurred.
if (getSelection().size() == 0) {
// I dont think we need this select - if no dragging mouseClicked
// will call doLeftClick, if dragging mouseDragged calls doViewDrag
// which call mouseClicked which calls doLeftClick.
// Otherwise this causes 2 doLeftClicks for one left click
// in otherwords its a redundant call - MG
//doLeftClick(evt);
}
pressEvent = evt;
}
}
public void mouseReleased(MouseEvent evt) {
if (MouseButtonEvent.isLeftMouseClick(evt)) {
if (inDrag) {
endViewDrag(evt);
}
}
// If it was shift-right mouse, end tier drag
else if (MouseButtonEvent.isRightMouseClickWithShift(evt)) {
if (inTierDrag) {
endTierDrag(evt);
}
}
// NOTE: middle done by rubberband.
}
private MouseEvent correctForShift(MouseEvent evt, DragViewI dv) {
if ((evt.getModifiers() & Event.SHIFT_MASK) != 0) {
return evt;
}
Point dropPosition = new Point(evt.getPoint());
dropPosition.x = dv.getOriginPosition().x;
return new MouseEvent((Component)evt.getSource(),0,evt.getWhen(),
evt.getModifiers(),
dropPosition.x, dropPosition.y,
evt.getClickCount(),
evt.isPopupTrigger());
}
public void endViewDrag(MouseEvent evt) {
// For left check that the mouse is over a drag receipient
// and drop on view.
if (inDrag) {
DragViewI dv = getDragView();
MouseEvent evt2 = correctForShift(evt,dv);
Point dropPosition = new Point(evt2.getPoint());
setFocusView(getViewAt(dropPosition));
boolean dropSuccessful = false;
if (focus instanceof DropTargetViewI) {
dropSuccessful = ((DropTargetViewI)focus).interpretDrop(dv,evt2);
} else {
logger.error("Can't drop in " + focus);
}
if (dv instanceof DragView) {
((DragView)dv).clear();
}
remove((ViewI)dv);
if (dropSuccessful)
clearSelection();
inDrag = false;
if (statusBar != null) {
statusBar.setActionPane("");
}
repaint();
}
}
public void endTierDrag(MouseEvent evt) {
if (inTierDrag) {
dragTierView.endTierDrag(evt);
inTierDrag = false;
repaint();
}
}
/**
* There are 2 types of dragging - tierDrag and viewDrag.
* Tier drag (shift-right mouse) moves the tier to a new place.
* "ViewDrag" (left mouse or shift left mouse) lets you drag results into
* the annotation area to create new genes or exons.
* Shift-dragging adds an exon to an existing gene (?).
*/
public void mouseDragged(MouseEvent evt) {
// Shift-right is tier drag
if (MouseButtonEvent.isRightMouseClickWithShift(evt)) {
logger.debug("mouseDragged: tier drag event");
doTierDrag(evt);
}
// For left check that the create new view (source view does this) and
// adds it to this panel as a DragView. Then redraw.
else if (MouseButtonEvent.isLeftMouseClick(evt)) {
doViewDrag(evt);
}
}
protected void doTierDrag(MouseEvent evt) {
if (!inTierDrag) {
// set focus
mouseMoved(evt);
if (focus instanceof TierViewI) {
TierViewI tv = (TierViewI)focus;
if (tv.allowsTierDrags()) {
if (tv.beginTierDrag(evt)) {
dragTierView = tv;
inTierDrag = true;
}
}
}
}
if (inTierDrag) {
// Drag the tier
dragTierView.updateTierDrag(evt);
repaint();
}
}
protected void doViewDrag(MouseEvent evt) {
if (!inDrag) {
if (focus instanceof TierViewI) {
TierViewI drag_view = (TierViewI) focus;
Selection selections = drag_view.getViewSelection(getSelection());
if (selections.size() != 0) {
DragViewI dvi = drag_view.createDragView(evt, selections);
if (dvi != null) {
add((ViewI)dvi,ApolloLayoutManager.NONE);
inDrag = true;
} else {
clearSelection();
}
} else {
// If nothing selected try to select (we should get another
// drag after this)
if (pressEvent != null) {
mouseClicked(pressEvent); // this will do a select
pressEvent = null;
mouseDragged(evt);
}
}
}
}
if (inDrag) {
DragViewI dv = getDragView();
// Drag the view.
MouseEvent evt2 = correctForShift(evt,dv);
Point newLocation = new Point(evt2.getPoint());
dv.setLocation(newLocation);
mouseMoved(evt2);
if (focus instanceof DropTargetViewI && statusBar != null) {
StringBuffer action = new StringBuffer();
// This method will set up the string buffer
((DropTargetViewI)focus).interpretDrop(dv,evt2,false,action);
if (dv instanceof DragView) {
DragView dfv = (DragView) dv;
dfv.setInHotspot(!action.toString().equals("No action"));
dfv.setHotspotType(action.toString().equals("Add evidence") ?
DragView.EVIDENCE_HOTSPOT :
DragView.OTHER_HOTSPOT);
}
statusBar.setActionPane(action.toString());
}
repaint();
}
// Update status
}
/** Gets features under mouse and puts name and position in status bar */
public void mouseMoved(MouseEvent evt) {
setFocusView(getViewAt(new Point(evt.getX(),evt.getY())));
FeatureList newPick = null;
if (focus instanceof FeatureView) {
if (focus instanceof SiteView) {
SiteView siteFocus = (SiteView)focus;
newPick = siteFocus.findFeatures(evt.getPoint());
} else {
FeatureView featFocus = (FeatureView)focus;
newPick = featFocus.findFeatures(evt.getPoint());
}
}
if (statusBar != null) {
if (newPick != null && newPick.size() != 0) {
SeqFeatureI sf = newPick.getFeature(0);
// was sf.getName()
// all idiosyncrasies of naming and label are held
// in nameadapter (NOT seq feature util which must
// not have any gui dependencies)
StringBuffer barText
= new StringBuffer(Config.getDisplayPrefs().getPublicName(sf));
if (newPick.size() > 1) {
barText.append(" + others");
}
statusBar.setFeaturePane(barText.toString());
} else {
statusBar.setFeaturePane("");
}
}
if (statusBar != null && focus != null) {
int pos = focus.getTransform().toUser(evt.getPoint()).x;
statusBar.setPositionPane(new String((new Integer(pos+1)).toString()));
}
}
public void changeTierHeights(int change) {
for (int i=0; i<views.size(); i++) {
ViewI v = (ViewI)views.elementAt(i);
if (v instanceof TierViewI) {
TierViewI tv = (TierViewI)v;
if (change > 0) {
tv.incrementTierHeight();
} else {
tv.decrementTierHeight();
}
tv.setInvalidity(true);
} else if (v instanceof ContainerViewI) {
Vector tvs = ((ContainerViewI)v).getViewsOfClass(apollo.gui.genomemap.TierViewI.class);
for (int j=0; j<tvs.size(); j++) {
TierViewI tv = (TierViewI)tvs.elementAt(j);
if (change > 0) {
tv.incrementTierHeight();
} else {
tv.decrementTierHeight();
}
tv.setInvalidity(true);
}
}
}
layout_manager.layoutViews(this);
repaint();
}
/**
* Keyboard event listeners
*/
public void keyPressed(KeyEvent evt) {
char keyChar = evt.getKeyChar();
if (keyChar == '-') {
logger.debug("Reducing yspace");
changeTierHeights(-1);
} else if (keyChar == '+') {
logger.debug("Increasing yspace");
changeTierHeights(1);
} else if (keyChar == 'r') {
logger.info("reverse complementing");
controller.handleReverseComplementEvent(new ReverseComplementEvent(this));
} else if (keyChar == 'o') {
logger.info("changing y orientation");
controller.handleOrientationEvent(new OrientationEvent(this));
}
if (focus instanceof KeyViewI) {
((KeyViewI)focus).keyPressed(evt);
}
}
public void keyReleased(KeyEvent evt) {}
public void keyTyped(KeyEvent evt) {}
/**
* Rubberband related methods
*/
public RubberbandRectangle getRubberband() {
return this.rubberband;
}
public boolean handleRubberbandEvent(RubberbandEvent evt) {
Rubberband rb = (Rubberband) evt.getSource();
Selection newSelection = new Selection();
// Should we return if not this component? what other component could it be?
if (rb.getComponent() == this) {
// Get the pickable views in the rectangle
Vector viewVector = getPickViews(evt.getBounds());
// Do a pick in each view
for (int i=0;i<viewVector.size();i++) {
PickViewI pv = ((PickViewI)viewVector.elementAt(i));
Selection viewSelection = pv.findFeaturesForSelection(evt.getBounds());
newSelection.add (viewSelection);
}
}
// If no shift key exclusive selection (deselect others)
boolean exclusiveSelection = false;
if ((rb.getModifiers() & Event.SHIFT_MASK) == 0) {
exclusiveSelection = true;
}
// fires FeatureSelectionEvent, edges and repaint done on receiving event
selectionManager.select(newSelection,exclusiveSelection,this);
processSelection(getSelection());
return true;
}
/**
* get the views Vector
*/
public Vector getViews() {
return this.views;
}
/**
* find pick views which are at least partly within a specified rectangle
*/
public Vector getPickViews(Rectangle bounds) {
return getViews(bounds,pickViews);
}
/**
* find non drag views which are at least partly within a specified rectangle
*/
public Vector getViews(Rectangle bounds) {
return getViews(bounds,views);
}
public Vector getViews(Rectangle bounds,Vector viewVector) {
Vector retviews = new Vector();
for (int i = 0; i < viewVector.size(); i++) {
ViewI v = ((ViewI)viewVector.elementAt(i));
if (!(v instanceof DragViewI)) {
if (v.getBounds().intersects(bounds) && v.isVisible()) {
retviews.addElement(v);
}
}
}
return retviews;
}
public Vector getDragViews() {
Vector retviews = new Vector();
for (int i=0;i<views.size();i++) {
ViewI v = ((ViewI)views.elementAt(i));
if (v instanceof DragViewI) {
retviews.addElement(v);
}
}
return retviews;
}
public DragViewI getDragView() {
Vector dvs = getDragViews();
if (dvs.size() > 1) {
logger.warn("Multiple drag views!!!");
}
DragViewI dv = ((DragViewI)dvs.elementAt(0));
return dv;
}
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
public void clearSelection() {
getSelection().clear();
clearEdges();
}
/** Returns a 2 element int array, 0th element is start, 1st element is end.
* Units are in basepairs. Returns lowest low and highest high of selection
* Changed from long[] to int[] to be consistent with everything.
* ints go up to 2 billion which should be plenty for biology - isnt it?
*/
int[] getSelectionLimits() {
int [] limits = new int[2];
limits[0] = 1000000000;
limits[1] = -1000000000;
//Vector features = getSelection().getSelectedData();
FeatureList features = getSelection().getSelectedData();
for (int i=0; i<features.size(); i++) {
SeqFeatureI sf = features.getFeature(i);
if (sf.getLow() < limits[0]) {
limits[0] = sf.getLow();
}
if (sf.getHigh() > limits[1]) {
limits[1] = sf.getHigh();
}
}
return limits;
}
public void setStatusBar(StatusBar sb) {
statusBar = sb;
}
public StatusBar getStatusBar() {
return statusBar;
}
public void finalize() {
logger.debug("Finalized ApolloPanel " + getName());
}
// not used
// void setLoadInProgress(boolean inProgress) {
// loadInProgress = inProgress;
// }
public StrandedZoomableApolloPanel getStrandedZoomableApolloPanel(){
StrandedZoomableApolloPanel panel =
(StrandedZoomableApolloPanel)
javax.swing.SwingUtilities.getAncestorOfClass(StrandedZoomableApolloPanel.class, this);
return panel;
}
}
| bsd-3-clause |
jzy3d/jzy3d-api-0.8.4 | src/api/org/jzy3d/plot3d/primitives/textured/ITranslucent.java | 119 | package org.jzy3d.plot3d.primitives.textured;
public interface ITranslucent {
public void setAlphaFactor(float a);
}
| bsd-3-clause |
MaddTheSane/MacPaf | src/com/redbugz/maf/gdbi/GdbiDocument.java | 10642 | /**
*
*/
package com.redbugz.maf.gdbi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
//import org.gdbi.db.pgvcgi.PgvcgiDatabase;
import com.apple.cocoa.foundation.NSObject;
import com.redbugz.maf.Family;
import com.redbugz.maf.Header;
import com.redbugz.maf.Individual;
import com.redbugz.maf.MafDocument;
import com.redbugz.maf.Multimedia;
import com.redbugz.maf.Note;
import com.redbugz.maf.Repository;
import com.redbugz.maf.Source;
import com.redbugz.maf.Submission;
import com.redbugz.maf.Submitter;
/**
* @author logan
*
*/
public class GdbiDocument extends Observable implements Observer, MafDocument{
public GdbiDocument() {
super();
try {
// PgvcgiDatabase.udebug.debug_println("test");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addFamily(com.redbugz.maf.Family)
*/
public void addFamily(Family newFamily) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addIndividual(com.redbugz.maf.Individual)
*/
public void addIndividual(Individual newIndividual) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addMultimedia(com.redbugz.maf.Multimedia)
*/
public void addMultimedia(Multimedia newMultimedia) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addNote(com.redbugz.maf.Note)
*/
public void addNote(Note newNote) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addObserver(java.util.Observer)
*/
public void addObserver(Observer observer) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addRepository(com.redbugz.maf.Repository)
*/
public void addRepository(Repository newRepository) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addSource(com.redbugz.maf.Source)
*/
public void addSource(Source newSource) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#addSubmitter(com.redbugz.maf.Submitter)
*/
public void addSubmitter(Submitter newSubmitter) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#chooseNewPrimaryIndividual()
*/
public void chooseNewPrimaryIndividual() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewFamily()
*/
public Family createAndInsertNewFamily() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewIndividual()
*/
public Individual createAndInsertNewIndividual() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewMultimedia()
*/
public Multimedia createAndInsertNewMultimedia() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewNote()
*/
public Note createAndInsertNewNote() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewRepository()
*/
public Repository createAndInsertNewRepository() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewSource()
*/
public Source createAndInsertNewSource() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#createAndInsertNewSubmitter()
*/
public Submitter createAndInsertNewSubmitter() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#endSuppressUpdates()
*/
public void endSuppressUpdates() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getFamiliesMap()
*/
public Map getFamiliesMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getFamily(java.lang.String)
*/
public Family getFamily(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getHeader()
*/
public Header getHeader() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getIndividual(java.lang.String)
*/
public Individual getIndividual(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getIndividualsMap()
*/
public Map getIndividualsMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getMultimedia(java.lang.String)
*/
public Multimedia getMultimedia(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getMultimediaMap()
*/
public Map getMultimediaMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableFamilyId()
*/
public int getNextAvailableFamilyId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableIndividualId()
*/
public int getNextAvailableIndividualId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableMultimediaId()
*/
public int getNextAvailableMultimediaId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableNoteId()
*/
public int getNextAvailableNoteId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableRepositoryId()
*/
public int getNextAvailableRepositoryId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableSourceId()
*/
public int getNextAvailableSourceId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNextAvailableSubmitterId()
*/
public int getNextAvailableSubmitterId() {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNote(java.lang.String)
*/
public Note getNote(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getNotesMap()
*/
public Map getNotesMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getPrimaryIndividual()
*/
public Individual getPrimaryIndividual() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getRepositoriesMap()
*/
public Map getRepositoriesMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getRepository(java.lang.String)
*/
public Repository getRepository(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getSource(java.lang.String)
*/
public Source getSource(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getSourcesMap()
*/
public Map getSourcesMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getSubmission()
*/
public Submission getSubmission() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getSubmitter(java.lang.String)
*/
public Submitter getSubmitter(String id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#getSubmittersMap()
*/
public Map getSubmittersMap() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#importFromDocument(com.redbugz.maf.MafDocument)
*/
public void importFromDocument(MafDocument importDocument) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#importGedcom(java.io.File, com.apple.cocoa.foundation.NSObject)
*/
public void importGedcom(File importFile, NSObject progress) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#outputToGedcom(java.io.OutputStream)
*/
public void outputToGedcom(OutputStream outputStream) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#outputToTempleReady(java.io.FileOutputStream)
*/
public void outputToTempleReady(FileOutputStream stream) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#outputToXML(java.io.OutputStream)
*/
public void outputToXML(OutputStream outputStream) throws IOException {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#removeFamily(com.redbugz.maf.Family)
*/
public void removeFamily(Family familyToRemove) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#removeIndividual(com.redbugz.maf.Individual)
*/
public void removeIndividual(Individual individualToRemove) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#removeSubmitter(com.redbugz.maf.Submitter)
*/
public void removeSubmitter(Submitter submitterToRemove) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#setPrimaryIndividual(com.redbugz.maf.Individual)
*/
public void setPrimaryIndividual(Individual newPrimaryIndividual) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.redbugz.maf.MafDocument#startSuppressUpdates()
*/
public void startSuppressUpdates() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
}
| bsd-3-clause |
jason-p-pickering/dhis2-core | dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/common/ImportOptions.java | 14695 | package org.hisp.dhis.dxf2.common;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.google.common.base.MoreObjects;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdSchemes;
import org.hisp.dhis.common.MergeMode;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.system.notification.NotificationLevel;
/**
* The idScheme is a general setting which will apply to all objects. The idSchemes
* can also be defined for specific objects such as dataElementIdScheme. The
* general setting will override specific settings.
*
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public class ImportOptions
{
private static final ImportOptions DEFAULT_OPTIONS = new ImportOptions().setImportStrategy( ImportStrategy.NEW_AND_UPDATES );
private IdSchemes idSchemes = new IdSchemes();
private boolean dryRun;
private Boolean preheatCache;
private boolean async;
private ImportStrategy importStrategy = ImportStrategy.CREATE_AND_UPDATE;
private MergeMode mergeMode = MergeMode.REPLACE;
private boolean skipExistingCheck;
private boolean sharing;
private boolean skipNotifications;
private boolean datasetAllowsPeriods;
private boolean strictPeriods;
private boolean strictCategoryOptionCombos;
private boolean strictAttributeOptionCombos;
private boolean strictOrganisationUnits;
private boolean requireCategoryOptionCombo;
private boolean requireAttributeOptionCombo;
private String filename;
private NotificationLevel notificationLevel;
//--------------------------------------------------------------------------
// Constructors
//--------------------------------------------------------------------------
public ImportOptions()
{
}
//--------------------------------------------------------------------------
// Logic
//--------------------------------------------------------------------------
public ImportOptions instance()
{
ImportOptions options = new ImportOptions();
options.idSchemes = this.idSchemes;
options.dryRun = this.dryRun;
options.preheatCache = this.preheatCache;
options.async = this.async;
options.importStrategy = this.importStrategy;
options.mergeMode = this.mergeMode;
options.skipExistingCheck = this.skipExistingCheck;
options.sharing = this.sharing;
options.skipNotifications = this.skipNotifications;
options.datasetAllowsPeriods = this.datasetAllowsPeriods;
options.strictPeriods = this.strictPeriods;
options.strictCategoryOptionCombos = this.strictCategoryOptionCombos;
options.strictAttributeOptionCombos = this.strictAttributeOptionCombos;
options.strictOrganisationUnits = this.strictOrganisationUnits;
options.requireCategoryOptionCombo = this.requireCategoryOptionCombo;
options.requireAttributeOptionCombo = this.requireAttributeOptionCombo;
options.filename = this.filename;
options.notificationLevel = this.notificationLevel;
return options;
}
public static ImportOptions getDefaultImportOptions()
{
return DEFAULT_OPTIONS;
}
/**
* Indicates whether to heat cache. Default is true.
*/
public boolean isPreheatCache()
{
return preheatCache == null ? true : preheatCache;
}
/**
* Indicates whether to heat cache. Default is false.
*/
public boolean isPreheatCacheDefaultFalse()
{
return preheatCache == null ? false : preheatCache;
}
/**
* Returns the notification level, or if not specified, returns the given
* default notification level.
*
* @param defaultLevel the default notification level.
* @return the notification level.
*/
public NotificationLevel getNotificationLevel( NotificationLevel defaultLevel )
{
return notificationLevel != null ? notificationLevel : defaultLevel;
}
//--------------------------------------------------------------------------
// Get methods
//--------------------------------------------------------------------------
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public IdSchemes getIdSchemes()
{
return idSchemes;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isDryRun()
{
return dryRun;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Boolean getPreheatCache()
{
return preheatCache;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isAsync()
{
return async;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isDatasetAllowsPeriods()
{
return datasetAllowsPeriods;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public ImportStrategy getImportStrategy()
{
return importStrategy != null ? importStrategy : ImportStrategy.NEW_AND_UPDATES;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public MergeMode getMergeMode()
{
return mergeMode;
}
public void setMergeMode( MergeMode mergeMode )
{
this.mergeMode = mergeMode;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isSkipExistingCheck()
{
return skipExistingCheck;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isSharing()
{
return sharing;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isSkipNotifications()
{
return skipNotifications;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isStrictPeriods()
{
return strictPeriods;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isStrictCategoryOptionCombos()
{
return strictCategoryOptionCombos;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isStrictAttributeOptionCombos()
{
return strictAttributeOptionCombos;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isStrictOrganisationUnits()
{
return strictOrganisationUnits;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isRequireCategoryOptionCombo()
{
return requireCategoryOptionCombo;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isRequireAttributeOptionCombo()
{
return requireAttributeOptionCombo;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getFilename()
{
return filename;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public NotificationLevel getNotificationLevel()
{
return notificationLevel;
}
//--------------------------------------------------------------------------
// Set methods
//--------------------------------------------------------------------------
public ImportOptions setIdSchemes( IdSchemes idSchemes )
{
this.idSchemes = idSchemes;
return this;
}
public ImportOptions setIdScheme( String idScheme )
{
idSchemes.setIdScheme( idScheme );
return this;
}
public ImportOptions setDataElementIdScheme( String idScheme )
{
idSchemes.setDataElementIdScheme( idScheme );
return this;
}
public ImportOptions setDatasetAllowsPeriods( boolean datasetAllowsPeriods )
{
this.datasetAllowsPeriods = datasetAllowsPeriods;
return this;
}
public ImportOptions setCategoryOptionComboIdScheme( String idScheme )
{
idSchemes.setCategoryOptionComboIdScheme( idScheme );
return this;
}
public ImportOptions setCategoryOptionIdScheme( String idScheme )
{
idSchemes.setCategoryOptionIdScheme( idScheme );
return this;
}
public ImportOptions setOrgUnitIdScheme( String idScheme )
{
idSchemes.setOrgUnitIdScheme( idScheme );
return this;
}
public ImportOptions setProgramIdScheme( String idScheme )
{
idSchemes.setProgramIdScheme( idScheme );
return this;
}
public ImportOptions setProgramStageIdScheme( String idScheme )
{
idSchemes.setProgramStageIdScheme( idScheme );
return this;
}
public ImportOptions setTrackedEntityIdScheme( String idScheme )
{
idSchemes.setTrackedEntityIdScheme( idScheme );
return this;
}
public ImportOptions setTrackedEntityAttributeIdScheme( String idScheme )
{
idSchemes.setTrackedEntityAttributeIdScheme( idScheme );
return this;
}
public ImportOptions setEventIdScheme( String idScheme )
{
idSchemes.setProgramStageInstanceIdScheme( idScheme );
return this;
}
public ImportOptions setDryRun( boolean dryRun )
{
this.dryRun = dryRun;
return this;
}
public ImportOptions setPreheatCache( Boolean preheatCache )
{
this.preheatCache = preheatCache;
return this;
}
public ImportOptions setAsync( boolean async )
{
this.async = async;
return this;
}
public ImportOptions setStrategy( ImportStrategy strategy )
{
this.importStrategy = strategy != null ? strategy : null;
return this;
}
public ImportOptions setImportStrategy( ImportStrategy strategy )
{
this.importStrategy = strategy != null ? strategy : null;
return this;
}
public ImportOptions setSkipExistingCheck( boolean skipExistingCheck )
{
this.skipExistingCheck = skipExistingCheck;
return this;
}
public ImportOptions setSharing( boolean sharing )
{
this.sharing = sharing;
return this;
}
public ImportOptions setSkipNotifications( boolean skipNotifications )
{
this.skipNotifications = skipNotifications;
return this;
}
public ImportOptions setStrictPeriods( boolean strictPeriods )
{
this.strictPeriods = strictPeriods;
return this;
}
public ImportOptions setStrictCategoryOptionCombos( boolean strictCategoryOptionCombos )
{
this.strictCategoryOptionCombos = strictCategoryOptionCombos;
return this;
}
public ImportOptions setStrictAttributeOptionCombos( boolean strictAttributeOptionCombos )
{
this.strictAttributeOptionCombos = strictAttributeOptionCombos;
return this;
}
public ImportOptions setStrictOrganisationUnits( boolean strictOrganisationUnits )
{
this.strictOrganisationUnits = strictOrganisationUnits;
return this;
}
public ImportOptions setRequireCategoryOptionCombo( boolean requireCategoryOptionCombo )
{
this.requireCategoryOptionCombo = requireCategoryOptionCombo;
return this;
}
public ImportOptions setRequireAttributeOptionCombo( boolean requireAttributeOptionCombo )
{
this.requireAttributeOptionCombo = requireAttributeOptionCombo;
return this;
}
public ImportOptions setFilename( String filename )
{
this.filename = filename;
return this;
}
public ImportOptions setNotificationLevel( NotificationLevel notificationLevel )
{
this.notificationLevel = notificationLevel;
return this;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper( this )
.add( "idSchemes", idSchemes )
.add( "dryRun", dryRun )
.add( "preheatCache", preheatCache )
.add( "async", async )
.add( "importStrategy", importStrategy )
.add( "mergeMode", mergeMode )
.add( "skipExistingCheck", skipExistingCheck )
.add( "sharing", sharing )
.add( "skipNotifications", skipNotifications )
.add( "datasetAllowsPeriods", datasetAllowsPeriods )
.add( "strictPeriods", strictPeriods )
.add( "strictCategoryOptionCombos", strictCategoryOptionCombos )
.add( "strictAttributeOptionCombos", strictAttributeOptionCombos )
.add( "strictOrganisationUnits", strictOrganisationUnits )
.add( "requireCategoryOptionCombo", requireCategoryOptionCombo )
.add( "requireAttributeOptionCombo", requireAttributeOptionCombo )
.toString();
}
}
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/tests/unit/caTissueSuite_Client/src/edu/wustl/catissuecore/api/testcases/AdminTestCases.java | 36328 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.api.testcases;
import edu.wustl.catissuecore.caties.util.CaTIESConstants;
import edu.wustl.catissuecore.domain.CancerResearchGroup;
import edu.wustl.catissuecore.domain.Capacity;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Department;
import edu.wustl.catissuecore.domain.DistributionProtocol;
import edu.wustl.catissuecore.domain.FluidSpecimen;
import edu.wustl.catissuecore.domain.ContainerPosition;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.SpecimenArray;
import edu.wustl.catissuecore.domain.SpecimenArrayType;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.StorageType;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.TissueSpecimen;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.domain.deintegration.ParticipantRecordEntry;
import edu.wustl.catissuecore.domain.pathology.DeidentifiedSurgicalPathologyReport;
import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport;
import edu.wustl.catissuecore.domain.pathology.ReportSection;
import edu.wustl.catissuecore.domain.pathology.TextContent;
import edu.wustl.common.lookup.DefaultLookupResult;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.system.applicationservice.ApplicationException;
import gov.nih.nci.system.query.SDKQuery;
import gov.nih.nci.system.query.SDKQueryResult;
import gov.nih.nci.system.query.example.InsertExampleQuery;
import gov.nih.nci.system.query.example.SearchExampleQuery;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.apache.commons.lang.StringUtils;
/**
* @author Ion C. Olaru
* */
public class AdminTestCases extends AbstractCaCoreApiTestCasesWithRegularAuthentication {
public AdminTestCases() {
super();
}
public void testAddInstitution() throws ApplicationException {
Institution i = new Institution();
i.setName("Some Inst. Name - 01" + UniqueKeyGeneratorUtil.getUniqueKey());
assertNull(i.getId());
i = insert(i);
assertNotNull(i);
assertTrue(i.getId() > 0);
}
public void testAddParticipantAlone() throws ApplicationException {
Participant p = new Participant();
p.setLastName("Malkovich");
p.setFirstName("John");
p.setActivityStatus("Active");
p = insert(p);
assertNotNull(p.getId());
assertTrue(p.getId() > 0);
}
public void testAddParticipantWithCPR() {
try {
Participant participant = BaseTestCaseUtility.initParticipant();
CollectionProtocol cp = getCollectionProtocolByShortTitle(PropertiesLoader.getCPShortTitleForAddParticipantWithCPR());
User user = getUserByLoginName(PropertiesLoader.getAdminUsername());
CollectionProtocolRegistration cpr = BaseTestCaseUtility.initCollectionProtocolRegistration(participant, cp, user);
Collection<CollectionProtocolRegistration> collectionProtocolRegistrationCollection = new HashSet<CollectionProtocolRegistration>();
collectionProtocolRegistrationCollection.add(cpr);
participant.setCollectionProtocolRegistrationCollection(collectionProtocolRegistrationCollection);
participant = insert(participant);
assertTrue("Participant inserted successfully." + participant.getId(), true);
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to insert Participant.", true);
}
}
public void testAddParticipantWithMedicalIdentifiers() {
try {
Participant p = BaseTestCaseUtility.initParticipant();
Collection<ParticipantMedicalIdentifier> pmis = new ArrayList<ParticipantMedicalIdentifier>();
ParticipantMedicalIdentifier pmi = new ParticipantMedicalIdentifier();
pmi.setMedicalRecordNumber("MRN-01-ABC-" + UniqueKeyGeneratorUtil.getUniqueKey());
pmi.setParticipant(p);
pmi.setSite(new Site());
pmi.getSite().setId((long) 1);
pmi.getSite().setName("In Transit");
pmis.add(pmi);
p.setParticipantMedicalIdentifierCollection(pmis);
p = insert(p);
assertTrue("Participant inserted successfully." + p.getId(), true);
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to insert Participant.", true);
}
}
public void testAddParticipantWithRecordEntries() {
try {
Participant p = BaseTestCaseUtility.initParticipant();
Collection<ParticipantRecordEntry> pres = new HashSet<ParticipantRecordEntry>();
ParticipantRecordEntry pre = new ParticipantRecordEntry();
pre.setParticipant(p);
pre.setActivityStatus("Active");
pres.add(pre);
p.setParticipantRecordEntryCollection(pres);
p = insert(p);
assertTrue("Participant inserted successfully." + p.getId(), true);
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to insert Participant.", true);
}
}
public void testUpdateParticipant() {
Participant participant = BaseTestCaseUtility.initParticipant();
try {
CollectionProtocol cp = getCollectionProtocolByShortTitle(PropertiesLoader.getCPTitleForUpdateParticipant());
User user = getUserByLoginName(PropertiesLoader.getAdminUsername());
CollectionProtocolRegistration cpr = BaseTestCaseUtility.initCollectionProtocolRegistration(participant, cp, user);
Collection<CollectionProtocolRegistration> cprCollection = new HashSet<CollectionProtocolRegistration>();
cprCollection.add(cpr);
participant.setCollectionProtocolRegistrationCollection(cprCollection);
} catch (ParseException e) {
e.printStackTrace();
assertFalse("Failed to generate the mock data", true);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse("Failed to generate the mock data", true);
}
try {
participant = insert(participant);
BaseTestCaseUtility.updateParticipant(participant);
Participant updatedParticipant = update(participant);
Collection<CollectionProtocolRegistration> cprs = updatedParticipant.getCollectionProtocolRegistrationCollection();
if (updatedParticipant != null
&& updatedParticipant.getRaceCollection().contains("Unknown")
&& updatedParticipant.getRaceCollection().contains("Black or African American") && cprs != null
&& cprs.size() > 0) {
assertTrue("Participant updated successfully", true);
}
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to update participant: " + participant.getId(), true);
}
}
public void testUpdateCPRWithBarcode() {
Participant participant = BaseTestCaseUtility.initParticipant();
try {
CollectionProtocol cp = getCollectionProtocolByShortTitle(PropertiesLoader.getCPTitleForUpdateParticipantWithBarcodeinCPR());
User user = getUserByLoginName(PropertiesLoader.getAdminUsername());
CollectionProtocolRegistration cpr = BaseTestCaseUtility.initCollectionProtocolRegistration(participant, cp, user);
Collection<CollectionProtocolRegistration> cprs = new HashSet<CollectionProtocolRegistration>();
cprs.add(cpr);
participant.setCollectionProtocolRegistrationCollection(cprs);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse("Failed to generate the mock data", true);
} catch (ParseException e) {
e.printStackTrace();
assertFalse("Failed to generate the mock data", true);
}
try {
participant = insert(participant);
BaseTestCaseUtility.updateParticipant(participant);
CollectionProtocolRegistration cpr1 = participant.getCollectionProtocolRegistrationCollection().iterator().next();
String barcode = "PATICIPANT" + UniqueKeyGeneratorUtil.getUniqueKey();
cpr1.setBarcode(barcode);
Participant updatedParticipant = update(participant);
CollectionProtocolRegistration cpr2 = updatedParticipant.getCollectionProtocolRegistrationCollection().iterator().next();
if (!barcode.equals(cpr2.getBarcode())) {
assertFalse("Failed to update participant for setting CPR having barcode value as " + barcode, true);
}
assertTrue("Domain object successfully updated ---->" + updatedParticipant, true);
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to update participant for setting CPR having barcode value", true);
}
}
public void testMatchingParticipant() throws ApplicationException {
Participant p1 = new Participant();
p1.setLastName("Micheal");
p1.setFirstName("Johnson");
p1.setActivityStatus("Active");
p1.setGender("Male Gender");
p1.setVitalStatus("Alive");
p1 = insert(p1);
Participant participant = new Participant();
//participant.setFirstName(PropertiesLoader.getFirstNameForMatchingParticipant());
participant.setLastName("Micheal");
participant.setFirstName("Johnson");
participant.setActivityStatus("Active");
participant.setGender("Male Gender");
participant.setVitalStatus("Alive");
try {
List<Object> resultList = getApplicationService().getParticipantMatchingObects(participant);
log.info("list size :: "+resultList.size());
if(resultList!=null && resultList.isEmpty())
{
log.info("list is Empty");
throw new ApplicationException();
}
for (Object object : resultList) {
if (object instanceof Participant || object instanceof DefaultLookupResult) {
Participant result = null;
if (object instanceof DefaultLookupResult) {
DefaultLookupResult d = (DefaultLookupResult) object;
result = (Participant) d.getObject();
log.info("Matching Participant Info :: ");
log.info("First Name :: "+result.getFirstName());
log.info("Last Name :: "+result.getLastName());
log.info("Vital Status :: "+result.getVitalStatus());
log.info("Gender :: "+result.getGender());
} else {
result = (Participant) object;
}
if (!StringUtils.contains(result.getFirstName(), PropertiesLoader.getFirstNameForMatchingParticipant())) {
assertFalse("Failed to retrieve matching participants having first name value as " + PropertiesLoader.getFirstNameForMatchingParticipant(), true);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
assertFalse("Failed to retrieve matching participants having first name value as " + PropertiesLoader.getFirstNameForMatchingParticipant(), true);
}
}
public void testSearchParticipantByExample() {
String gender = PropertiesLoader.getGenderForSearchParticipantByExample();
Participant participant = new Participant();
participant.setGender(gender);
List<Participant> result = null;
try {
result = searchByExample(Participant.class, participant);
for (Participant p : result) {
if (!gender.equals(p.getGender())) {
assertFalse("Failed to retrieve matching participants having gender value as " + PropertiesLoader.getGenderForSearchParticipantByExample(), true);
break;
}
}
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse("Failed to retrieve matching participants having gender value as " + PropertiesLoader.getGenderForSearchParticipantByExample(), true);
}
}
private CollectionProtocol getCollectionProtocolByShortTitle(String shortTitle) throws ApplicationException {
CollectionProtocol cp = new CollectionProtocol();
cp.setShortTitle(shortTitle);
List<CollectionProtocol> collectionProtocols = searchByExample(CollectionProtocol.class, cp);
CollectionProtocol result = null;
if (collectionProtocols != null && !collectionProtocols.isEmpty()) {
result = collectionProtocols.get(0);
}
return result;
}
private User getUserByLoginName(String loginName) throws ApplicationException {
User user = new User();
user.setLoginName(loginName);
List<User> users = searchByExample(User.class, user);
User result = null;
if (users != null && !users.isEmpty()) {
result = users.get(0);
}
return result;
}
public void testInsertParticipant() throws Exception {
Participant p = new Participant();
assertNull(p.getId());
p.setFirstName("Jane");
p.setLastName("Doe");
p.setActivityStatus("Active");
SDKQuery query = new InsertExampleQuery(p);
SDKQueryResult result = applicationService.executeQuery(query);
p = (Participant) result.getObjectResult();
assertNotNull(p.getId());
}
public void testSearchByExampleUsingInterfaceSearch() throws Exception {
Participant p = new Participant();
p.setFirstName("Alice");
List<Participant> result = searchByExample(Participant.class, p);
assertEquals(2, result.size());
}
public void testSearchByExampleUsingSDKQuery() throws Exception {
Participant p = new Participant();
p.setFirstName("Alice");
SDKQuery sQuery = new SearchExampleQuery(p);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(2, c.size());
}
public void testInsertCollectionProtocol() throws ApplicationException {
String key = UniqueKeyGeneratorUtil.getUniqueKey();
CollectionProtocol cp = new CollectionProtocol();
cp.setActivityStatus("Active");
cp.setTitle("CP Title - " + key);
cp.setShortTitle("CP Short Title - " + key);
cp.setStartDate(new Date());
cp.setConsentsWaived(true);
User user = getUserByLoginName(PropertiesLoader.getAdminUsername());
cp.setPrincipalInvestigator(user);
cp.setCoordinatorCollection(new HashSet());
cp = insert(cp);
System.out.println(">>> CP Inserted: " + cp.getId());
}
public void testSearchSpecimenWithBarcode()
{
try{
SpecimenCollectionGroup scg = new SpecimenCollectionGroup();
scg.setId(Long.valueOf(PropertiesLoader.getSCGID()));
scg = searchById(SpecimenCollectionGroup.class,scg);
Specimen specimenObj = (Specimen) BaseTestCaseUtility.initTissueSpecimen();
specimenObj.setSpecimenCollectionGroup(scg);
specimenObj = insert(specimenObj);
String barcode = specimenObj.getBarcode();
Specimen specimen = new Specimen();
// String barcode = PropertiesLoader.getProperty("admin.specimen.barcode");
specimen.setBarcode(barcode);
List<Specimen> spList = searchByExample(Specimen.class, specimen);
if(spList != null)
{
assertEquals(1, spList.size());
for (Specimen specimen2 : spList)
{
assertEquals(barcode, specimen2.getBarcode());
}
}
else
assertFalse(
"Failed to retrieve Specimens with barcode :"+ barcode,
true);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testSearchTissueSpecimen()
{
DetachedCriteria criteria = DetachedCriteria.forClass(TissueSpecimen.class);
criteria.add(Property.forName("id").isNotNull());
List<Object> result = null;
try {
result = getApplicationService().query(criteria);
boolean failed = false;
for (Object o : result) {
if (!(o instanceof TissueSpecimen)) {
failed = true;
break;
}
}
if (failed || result.size() < 1) {
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testSearchSpecimen()
{
try{
SpecimenCollectionGroup scg = new SpecimenCollectionGroup();
scg.setId(Long.valueOf(PropertiesLoader.getSCGID()));
scg = searchById(SpecimenCollectionGroup.class,scg);
System.out.println(scg);
Specimen specimenObj = (Specimen) BaseTestCaseUtility.initTissueSpecimen();
specimenObj.setSpecimenCollectionGroup(scg);
specimenObj = insert(specimenObj);
String label = specimenObj.getLabel();
DetachedCriteria criteria = DetachedCriteria.forClass(TissueSpecimen.class);
criteria.add(Property.forName("id").isNotNull());
List<Object> result = null;
result = getApplicationService().query(criteria);
boolean failed = false;
for (Object o : result) {
System.out.println(o.getClass());
if (!(o instanceof TissueSpecimen)) {
failed = true;
break;
}
}
if (failed || result.size() < 1) {
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testSearchSpecimenCollectionGroup()
{
try {
SpecimenCollectionGroup scga = new SpecimenCollectionGroup();
scga.setId(Long.valueOf(PropertiesLoader.getSCGID()));
scga = searchById(SpecimenCollectionGroup.class,scga);
System.out.println(scga);
SpecimenCollectionGroup scg = new SpecimenCollectionGroup();
String scgName = scga.getName();
scg.setName(scgName);
List<SpecimenCollectionGroup> spList = searchByExample(SpecimenCollectionGroup.class, scg);
if(spList != null)
{
assertEquals(1, spList.size());
for (SpecimenCollectionGroup specimen2 : spList)
{
assertEquals(scgName, specimen2.getName());
}
}
else
assertFalse(
"Failed to retrieve SCG with name :"+scgName,
true);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testSearchScgWithBarcode()
{
try {
SpecimenCollectionGroup scga = new SpecimenCollectionGroup();
scga.setId(Long.valueOf(PropertiesLoader.getSCGID()));
scga = searchById(SpecimenCollectionGroup.class,scga);
System.out.println(scga);
SpecimenCollectionGroup scg = new SpecimenCollectionGroup();
String barcode = scga.getBarcode();//PropertiesLoader.getProperty("admin.scg.barcode");
scg.setBarcode(barcode);
List<SpecimenCollectionGroup> spList = searchByExample(SpecimenCollectionGroup.class, scg);
if(spList != null)
{
assertEquals(1, spList.size());
for (SpecimenCollectionGroup specimen2 : spList)
{
assertEquals(barcode, specimen2.getBarcode());
}
}
else
assertFalse(
"Failed to retrieve SCG with barcode : "+barcode,
true);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testInsertSpecimen()
{
try {
SpecimenCollectionGroup scga = new SpecimenCollectionGroup();
scga.setId(Long.valueOf(PropertiesLoader.getSCGID()));
scga = searchById(SpecimenCollectionGroup.class,scga);
System.out.println(scga);
Specimen fSp = (Specimen)BaseTestCaseUtility.initFluidSpecimen();
fSp.setSpecimenCollectionGroup(scga);
Specimen tSp = (Specimen)BaseTestCaseUtility.initTissueSpecimen();
tSp.setSpecimenCollectionGroup(scga);
Specimen cSp = (Specimen)BaseTestCaseUtility.initCellSpecimen();
cSp.setSpecimenCollectionGroup(scga);
Specimen mSp = (Specimen)BaseTestCaseUtility.initMolecularSpecimen();
mSp.setSpecimenCollectionGroup(scga);
insert(fSp);
insert(tSp);
insert(cSp);
insert(mSp);
} catch (ApplicationException e) {
e.printStackTrace();
assertFalse(
"Failed to retrieve Fuild Specimens for condition of id not null",
true);
}
}
public void testSearchInstitution() throws Exception {
Institution institution = new Institution();
institution.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(institution);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchDepartmet() throws Exception {
Department department = new Department();
department.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(department);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchCancerResearchGrp() throws Exception {
CancerResearchGroup crg = new CancerResearchGroup();
crg.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(crg);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchUser() throws Exception {
User user = new User();
user.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(user);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchSite() throws Exception {
Site site = new Site();
site.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(site);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchCollectionProtocol() throws Exception {
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(collectionProtocol);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testCollectionProtocolWithConsentWaived() throws Exception {
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setConsentsWaived(true);
SDKQuery sQuery = new SearchExampleQuery(collectionProtocol);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchDistributionProtocol() throws Exception {
DistributionProtocol distributionProtocol = new DistributionProtocol();
distributionProtocol.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(distributionProtocol);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchDeidentifiedSurgicalPathologyReport() throws Exception
{
DeidentifiedSurgicalPathologyReport deidentifiedSurgicalPathologyReport=new DeidentifiedSurgicalPathologyReport();
IdentifiedSurgicalPathologyReport spr = new IdentifiedSurgicalPathologyReport();
SDKQuery sQuery = new SearchExampleQuery(spr);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=(IdentifiedSurgicalPathologyReport)c.iterator().next();
deidentifiedSurgicalPathologyReport.setIsFlagForReview(new Boolean(false));
deidentifiedSurgicalPathologyReport.setReportStatus(CaTIESConstants.PENDING_FOR_XML);
deidentifiedSurgicalPathologyReport.setActivityStatus("Active");
deidentifiedSurgicalPathologyReport.setSpecimenCollectionGroup(identifiedSurgicalPathologyReport.getSpecimenCollectionGroup());
TextContent textContent = new TextContent();
String data="Report is de-identified \n"+identifiedSurgicalPathologyReport.getTextContent().getData();
textContent.setData(data);
textContent.setSurgicalPathologyReport(deidentifiedSurgicalPathologyReport);
deidentifiedSurgicalPathologyReport.setTextContent(textContent);
DeidentifiedSurgicalPathologyReport deIdentifiedSurgicalPathologyReport1=insert(deidentifiedSurgicalPathologyReport);
identifiedSurgicalPathologyReport.setDeIdentifiedSurgicalPathologyReport(deIdentifiedSurgicalPathologyReport1);
identifiedSurgicalPathologyReport = (IdentifiedSurgicalPathologyReport) update(identifiedSurgicalPathologyReport);
// spr = new DeidentifiedSurgicalPathologyReport();
DeidentifiedSurgicalPathologyReport spr1 = new DeidentifiedSurgicalPathologyReport();
sQuery = new SearchExampleQuery(spr1);
result = applicationService.executeQuery(sQuery);
c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchIdentifiedSurgicalPathologyReport() throws Exception
{
IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=new IdentifiedSurgicalPathologyReport();
identifiedSurgicalPathologyReport.setActivityStatus("Active");
identifiedSurgicalPathologyReport.setCollectionDateTime(new Date());
identifiedSurgicalPathologyReport.setIsFlagForReview(new Boolean(false));
identifiedSurgicalPathologyReport.setReportStatus(CaTIESConstants.PENDING_FOR_DEID);
// identifiedSurgicalPathologyReport.setReportSource((Site)BizTestCaseUtility.getObjectMap(Site.class));
TextContent textContent=new TextContent();
String data="[FINAL DIAGNOSIS]\n" +
"This is the Final Diagnosis Text" +
"\n\n[GROSS DESCRIPTION]" +
"The specimen is received unfixed labeled hernia sac and consists of a soft, pink to yellow segment of fibrous and fatty tissue measuring 7.5cm in length x 3.2 x 0.9cm with a partly defined lumen. Representative tissue submitted labeled 1A.";
textContent.setData(data);
textContent.setSurgicalPathologyReport(identifiedSurgicalPathologyReport);
Set reportSectionCollection=new HashSet();
ReportSection reportSection1=new ReportSection();
reportSection1.setName("GDT");
reportSection1.setDocumentFragment("The specimen is received unfixed labeled hernia sac and consists of a soft, pink to yellow segment of fibrous and fatty tissue measuring 7.5cm in length x 3.2 x 0.9cm with a partly defined lumen. Representative tissue submitted labeled 1A.");
reportSection1.setTextContent(textContent);
ReportSection reportSection2=new ReportSection();
reportSection2.setName("FIN");
reportSection2.setDocumentFragment("This is the Final Diagnosis Text");
reportSection2.setTextContent(textContent);
reportSectionCollection.add(reportSection1);
reportSectionCollection.add(reportSection2);
textContent.setReportSectionCollection(reportSectionCollection);
identifiedSurgicalPathologyReport.setTextContent(textContent);
SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
specimenCollectionGroup.setId(1L);
SDKQuery sQuery = new SearchExampleQuery(specimenCollectionGroup);
SDKQueryResult result = applicationService.executeQuery(sQuery);
Collection c = result.getCollectionResult();
specimenCollectionGroup =(SpecimenCollectionGroup)c.iterator().next();
specimenCollectionGroup.setSurgicalPathologyNumber("SPN"+UniqueKeyGeneratorUtil.getUniqueKey());
identifiedSurgicalPathologyReport.setSpecimenCollectionGroup(specimenCollectionGroup);
specimenCollectionGroup=update(specimenCollectionGroup);
identifiedSurgicalPathologyReport=insert(identifiedSurgicalPathologyReport);
IdentifiedSurgicalPathologyReport spr = new IdentifiedSurgicalPathologyReport();
sQuery = new SearchExampleQuery(spr);
result = applicationService.executeQuery(sQuery);
c = result.getCollectionResult();
assertEquals(1, c.size());
}
public void testSearchStorageType() throws ApplicationException
{
StorageType storagetype = new StorageType();
storagetype.setDefaultTemperatureInCentigrade(-80.0);
storagetype.setName("Type"+UniqueKeyGeneratorUtil.getUniqueKey());
Capacity capacity=new Capacity();
capacity.setOneDimensionCapacity(10);
capacity.setTwoDimensionCapacity(10);
storagetype.setCapacity(capacity);
storagetype.setOneDimensionLabel("Rows");
storagetype.setTwoDimensionLabel("Columns");
storagetype=insert(storagetype);
log.info(" searching domain object");
StorageType type=new StorageType();
type.setId(storagetype.getId());
try {
List resultList = searchByExample(StorageType.class,type);
StorageType storageType= (StorageType) resultList.get(0);
log.info(" Domain Object is successfully Found ----> :: " + storageType.getName());
}
catch (Exception e) {
e.printStackTrace();
assertFalse("Does not find Domain Object", true);
}
}
public void testSearchStorageContainer() throws ApplicationException
{
log.info(" searching domain object");
StorageContainer container=new StorageContainer();
container.setId(new Long(1));
try {
List resultList = searchByExample(StorageContainer.class,container);
StorageContainer containerFromResult= (StorageContainer) resultList.get(0);
log.info(" Domain Object is successfully Found ----> :: " + containerFromResult.getName());
}
catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Does not find Domain Object", true);
}
}
public void testSearchStorageContainerWithCaseSensitiveBarcode() throws ApplicationException
{
StorageContainer st=new StorageContainer();
Capacity capacity=new Capacity();
capacity.setOneDimensionCapacity(10);
capacity.setTwoDimensionCapacity(10);
st.setCapacity(capacity);
StorageType sType=new StorageType();
sType.setId(new Long(3));
st.setStorageType(sType);
Site site=new Site();
site.setId(new Long(1));
st.setSite(site);
st.setActivityStatus("Active");
st.setFull(false);
st.setBarcode(PropertiesLoader.getCaseSensitiveBarcodeForContainer());
st=insert(st);
boolean found=false;
log.info(" searching domain object");
StorageContainer container=new StorageContainer();
container.setBarcode(PropertiesLoader.getCaseSensitiveBarcodeForContainer());
try {
List resultList = searchByExample(StorageContainer.class,container);
for (int i = 0; i < resultList.size(); i++)
{
StorageContainer containerFromResult= (StorageContainer) resultList.get(i);
if(container.getBarcode().equals(containerFromResult.getBarcode()))
{
log.info(" Domain Object is successfully Found with given barcode ----> :: " + containerFromResult.getBarcode());
found=true;
break;
}
}
if(!found)
{
throw new Exception("Storage Container not available with given barcode.");
}
}
catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Does not find Domain Object", true);
}
}
public void testSearchSpecimenArrayType() throws ApplicationException
{
SpecimenArrayType specimenArrayType=new SpecimenArrayType();
specimenArrayType=BaseTestCaseUtility.initSpecimenSpecimenArrayType();
specimenArrayType=insert(specimenArrayType);
log.info("Domain object successfully inserted "+specimenArrayType.getName());
log.info(" searching domain object");
SpecimenArrayType specArrayType=new SpecimenArrayType();
specArrayType.setName(specimenArrayType.getName());
try {
List resultList = searchByExample(SpecimenArrayType.class,specArrayType);
SpecimenArrayType specArrayTypeFromResult= (SpecimenArrayType) resultList.get(0);
log.info(" Domain Object is successfully Found with given barcode ----> :: " + specArrayTypeFromResult.getName());
}
catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Does not find Domain Object", true);
}
}
/**
* Search Container which is located at given position of parent container
*
*/
public void testSearchStorageContainerLocatedAtPosition()
{
try
{
StorageContainer parentContainer=new StorageContainer();
parentContainer.setName(PropertiesLoader.getParentContainerName());
StorageContainer containerToFind = new StorageContainer();
containerToFind.setId(parentContainer.getId());
ContainerPosition conPosition = new ContainerPosition();
conPosition.setPositionDimensionOne(PropertiesLoader.getPositionDimensionOneInParentContainer());
conPosition.setPositionDimensionTwo(PropertiesLoader.getPositionDimensionTwoInParentContainer());
conPosition.setParentContainer(parentContainer);
List result = searchByExample(ContainerPosition.class, conPosition);
log.info(result);
if(result.size()>1||result.size()<1)
{
assertFalse("Could not find Storage Container Object", true);
}
assertTrue("Storage Container successfully found. Size:" +result.size(), true);
}
catch(Exception e)
{
Logger.out.error(e.getMessage(),e);
System.out
.println("StorageContainerTestCases.testSearchStorageContainerLocatedAtPosition()");
System.out.println(e.getMessage());
e.printStackTrace();
assertFalse("Could not find Storage Container Object", true);
}
}
public void testSearchSpecimenArray()
{
SpecimenArray specArray=new SpecimenArray();
specArray.setId(new Long(1));
try {
List resultList = searchByExample(SpecimenArray.class,specArray);
SpecimenArray specArrayFromResult= (SpecimenArray) resultList.get(0);
log.info(" Domain Object is successfully Found ----> :: " + specArrayFromResult.getName());
}
catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
assertFalse("Does not find Domain Object", true);
}
}
}
| bsd-3-clause |
all-of-us/workbench | api/src/integration/java/org/pmiops/workbench/google/CloudResourceManagerServiceImplIntegrationTest.java | 2079 | package org.pmiops.workbench.google;
import static com.google.common.truth.Truth.assertThat;
import com.google.api.services.cloudresourcemanager.model.Project;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.pmiops.workbench.BaseIntegrationTest;
import org.pmiops.workbench.db.model.DbUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
public class CloudResourceManagerServiceImplIntegrationTest extends BaseIntegrationTest {
@Autowired private CloudResourceManagerService service;
@TestConfiguration
@ComponentScan(basePackageClasses = CloudResourceManagerServiceImpl.class)
@Import({CloudResourceManagerServiceImpl.class, BaseIntegrationTest.Configuration.class})
static class Configuration {}
// This is a single hand created user in the fake-research-aou.org gsuite.
// It has one project that has been shared with it, AoU CRM Integration Test
// in the firecloud dev domain.
private final String SINGLE_WORKSPACE_TEST_USER_EMAIL =
"cloud-resource-manager-integration-test@fake-research-aou.org";
// This user was hand-created in the test environment and has never signed in.
private final String NEVER_SIGNED_IN_TEST_USER_EMAIL =
"cloud-resource-manager-integration-test-no-sign-in@fake-research-aou.org";
@Test
public void testGetAllProjectsForUserSingleWorkspaceUser() throws Exception {
DbUser testUser = new DbUser();
testUser.setUsername(SINGLE_WORKSPACE_TEST_USER_EMAIL);
List<Project> projectList = service.getAllProjectsForUser(testUser);
assertThat(projectList.size()).isEqualTo(1);
}
@Test
public void testGetAllProjectsForUserNeverSignedInUser() throws Exception {
DbUser testUser = new DbUser();
testUser.setUsername(NEVER_SIGNED_IN_TEST_USER_EMAIL);
List<Project> projectList = service.getAllProjectsForUser(testUser);
assertThat(projectList).isEmpty();
}
}
| bsd-3-clause |
aic-sri-international/aic-praise | src/main/java/com/sri/ai/praise/core/representation/interfacebased/factor/core/expression/core/UAIModelToExpressionFactorNetwork.java | 8356 | package com.sri.ai.praise.core.representation.interfacebased.factor.core.expression.core;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.praise.core.representation.classbased.table.core.uai.UAIUtil.constructGenericTableExpressionUsingEqualities;
import static com.sri.ai.praise.core.representation.classbased.table.core.uai.UAIUtil.convertGenericTableToInstance;
import static com.sri.ai.praise.core.representation.interfacebased.factor.core.expression.core.ExpressionFactorNetwork.expressionFactorNetwork;
import static com.sri.ai.util.Util.mapIntoSet;
import static com.sri.ai.util.Util.println;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.api.Type;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.Context;
import com.sri.ai.grinder.api.Theory;
import com.sri.ai.grinder.helper.GrinderUtil;
import com.sri.ai.grinder.helper.UniquelyNamedConstantIncludingBooleansAndNumbersPredicate;
import com.sri.ai.grinder.theory.compound.CompoundTheory;
import com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory;
import com.sri.ai.grinder.theory.equality.EqualityTheory;
import com.sri.ai.grinder.theory.linearrealarithmetic.LinearRealArithmeticTheory;
import com.sri.ai.grinder.theory.propositional.PropositionalTheory;
import com.sri.ai.praise.core.representation.classbased.expressionbased.api.ExpressionBasedModel;
import com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable;
import com.sri.ai.praise.core.representation.classbased.table.core.uai.UAIModel;
import com.sri.ai.praise.core.representation.classbased.table.core.uai.parsing.UAIModelReader;
import com.sri.ai.praise.core.representation.interfacebased.factor.api.Factor;
import com.sri.ai.praise.core.representation.interfacebased.factor.core.expression.api.ExpressionFactor;
import com.sri.ai.praise.core.representation.translation.ciaranframework.core.uai.UAI_to_ExpressionBased_Translator;
import com.sri.ai.util.base.IdentityWrapper;
public class UAIModelToExpressionFactorNetwork {
public static ExpressionFactorNetwork convert(UAIModel uaiModel) {
return convert(uaiModel,null);
}
public static ExpressionFactorNetwork convert(UAIModel uaiModel,Theory theory) {
List<Expression> factorsRepresentedAsExpressions =
createListOfExpressionsrepresentingTheFactorsFromAUAIModel(uaiModel);
if (theory == null) {
theory =
new CompoundTheory(
new EqualityTheory(false, true),
new DifferenceArithmeticTheory(false, true),
new LinearRealArithmeticTheory(false, true),
new PropositionalTheory());
}
//Add variables in the factors to the context...
ExpressionBasedModel factorsAndTypes = new UAI_to_ExpressionBased_Translator(factorsRepresentedAsExpressions, uaiModel);
//Context
Context context = fillingContext(theory, factorsAndTypes);
ExpressionFactorNetwork result = expressionFactorNetwork(factorsRepresentedAsExpressions, context);
return result;
}
private static Context fillingContext(Theory theory, ExpressionBasedModel factorsAndTypes) {
LinkedHashMap<String, String> mapFromRandomVariableNameToTypeName = new LinkedHashMap<>(factorsAndTypes.getMapFromRandomVariableNameToTypeName());
Map<String, String> mapFromSymbolNameToTypeName= new LinkedHashMap<>(mapFromRandomVariableNameToTypeName);
mapFromSymbolNameToTypeName.putAll(factorsAndTypes.getMapFromNonUniquelyNamedConstantNameToTypeName());
mapFromSymbolNameToTypeName.putAll(factorsAndTypes.getMapFromUniquelyNamedConstantNameToTypeName());
Map<String, String> mapFromCategoricalTypeNameToSizeString = new LinkedHashMap<>(factorsAndTypes.getMapFromCategoricalTypeNameToSizeString());
Set<Expression> uniquelyNamedConstants = mapIntoSet(factorsAndTypes.getMapFromUniquelyNamedConstantNameToTypeName().keySet(), Expressions::parse);
uniquelyNamedConstants.add(parse("and"));
uniquelyNamedConstants.add(parse("not"));
uniquelyNamedConstants.add(parse("'if . then . else .'"));
UniquelyNamedConstantIncludingBooleansAndNumbersPredicate isUniquelyNamedConstantPredicate =
new UniquelyNamedConstantIncludingBooleansAndNumbersPredicate(uniquelyNamedConstants);
LinkedList<Type> additionalTypes = new LinkedList<Type>(theory.getNativeTypes()); // add needed types that may not be the type of any variable
additionalTypes.addAll(factorsAndTypes.getAdditionalTypes());
Context context =
GrinderUtil.makeContext(
mapFromSymbolNameToTypeName,
mapFromCategoricalTypeNameToSizeString,
additionalTypes,
isUniquelyNamedConstantPredicate,
theory
);
return context;
}
private static List<Expression> createListOfExpressionsrepresentingTheFactorsFromAUAIModel(UAIModel uaiModel){
/* This is similar to the way They do in the UAIMARSolver.
* However, I think it is easier to understand in my way(below, uncommented).
* This code used the fact that one same factor can appear many times (e.g. to factors phi_i and phi_j
* having the same table).
* The UAI model Contains the following maps
* -1 map that links a index to it's table (tableInstanceIdxToTable)
* -one map that does the inverse operation (uniqueTableToTableInstanceIdxs).
* Because a table can be used more than once, it links a FunctionTable to a list of indexes
* -one map that each table to a unique index (sort of a id of each unique table)(getUniqueFunctionTable).
* My code only uses the 1st one, while the commented one uses the 2nd and third tables
*
List<Expression> factorsRepresentedAsExpressions = new ArrayList<>();
for (int i = 0; i < uaiModel.numberUniqueFunctionTables(); i++) {
FunctionTable table = uaiModel.getUniqueFunctionTable(i);
Expression genericTableExpression;
genericTableExpression = constructGenericTableExpressionUsingEqualities(table);
for (int tableIdx : uaiModel.getTableIndexes(i)) {
Expression instanceTableExpression =
convertGenericTableToInstance(table, genericTableExpression, uaiModel.getVariableIndexesForTable(tableIdx));
factorsRepresentedAsExpressions.add(instanceTableExpression);
}
}
return factorsRepresentedAsExpressions;*/
List<Expression> factorsRepresentedAsExpressions = new ArrayList<>();
for (int i = 0; i < uaiModel.numberTables(); i++) {
FunctionTable table = uaiModel.getTable(i);
Expression genericTableExpression =
constructGenericTableExpressionUsingEqualities(table);
Expression instanceTableExpression =
convertGenericTableToInstance(table, genericTableExpression, uaiModel.getVariableIndexesForTable(i));
factorsRepresentedAsExpressions.add(instanceTableExpression);
}
return factorsRepresentedAsExpressions;
}
public static void main(String[] args) {
try {
// Importing the file and reading it
FileReader modelFile = new FileReader(new File("").getAbsolutePath()+"/UAITests/BN_0.uai" );
UAIModel model = UAIModelReader.read(modelFile);
// Converting the network
ExpressionFactorNetwork network = convert(model, null);
// Printing the factors
for(IdentityWrapper<Factor> fwrapped : network.getAs()) {
ExpressionFactor f = (ExpressionFactor) fwrapped.getObject();
println(f);
}
/*// This seems to be OK! But when we analyze the connections between the factors:
IdentityWrapper<Factor> f = network.getAs().iterator().next();
println("Printing one of the factors of the network:\n\t "+f);
println("Printing this factor's connections:\n\t" + network.getBsOfA(f));
println("This shows that there is something wrong\n"
+ "In fact the connections in the graph are made based on the 'freeVariables' of a factor");
println("freeVariables of f: "+Expressions.freeVariables((ExpressionFactor)f.getObject(),((ExpressionFactor)f.getObject()).getContext()));
println("\nWe can check that those 'abnomalies' are indeed variables on the network:");
for(Variable v:network.getBs()) {
System.out.print(v + ", ");
}*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
| bsd-3-clause |
burtcorp/jmespath-java | jmespath-core/src/main/java/io/burt/jmespath/node/FlattenArrayNode.java | 944 | package io.burt.jmespath.node;
import java.util.List;
import java.util.LinkedList;
import io.burt.jmespath.Adapter;
import io.burt.jmespath.JmesPathType;
public class FlattenArrayNode<T> extends Node<T> {
public FlattenArrayNode(Adapter<T> runtime) {
super(runtime);
}
@Override
public T search(T input) {
if (runtime.typeOf(input) == JmesPathType.ARRAY) {
List<T> elements = runtime.toList(input);
List<T> flattened = new LinkedList<>();
for (T element : elements) {
if (runtime.typeOf(element) == JmesPathType.ARRAY) {
flattened.addAll(runtime.toList(element));
} else {
flattened.add(element);
}
}
return runtime.createArray(flattened);
} else {
return runtime.createNull();
}
}
@Override
protected boolean internalEquals(Object o) {
return true;
}
@Override
protected int internalHashCode() {
return 19;
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-madvoc/src/testInt/java/jodd/madvoc/TagActionTest.java | 1347 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.madvoc;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TagActionTest {
@BeforeClass
public static void beforeClass() {
MadvocSuite.startTomcat();
}
@AfterClass
public static void afterClass() {
MadvocSuite.stopTomcat();
}
@Test
public void testDisableTag() {
HttpResponse response = HttpRequest
.get("localhost:8173/tag/disable/123")
.send();
assertEquals("disable-Tag{123:jodd}", response.bodyText().trim());
}
@Test
public void testDeleteTag() {
HttpResponse response = HttpRequest
.get("localhost:8173/tag/delete/123")
.send();
assertEquals("delete-Tag{123:jodd}", response.bodyText().trim());
}
@Test
public void testEditTag() {
HttpResponse response = HttpRequest
.get("localhost:8173/tag/edit/123")
.query("tag.name", "ddoj")
.send();
assertEquals("edit-Tag{123:ddoj}", response.bodyText().trim());
}
@Test
public void testSaveTag() {
HttpResponse response = HttpRequest
.get("localhost:8173/tag/save/123")
.query("tag.name", "JODD")
.send();
assertEquals("save-Tag{123:JODD}", response.bodyText().trim());
}
} | bsd-3-clause |
shankari/e-mission-data-collection | src/android/DataCollectionPlugin.java | 9032 | package edu.berkeley.eecs.emission.cordova.tracker;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.preference.PreferenceManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationRequest;
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import edu.berkeley.eecs.emission.*;
import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineService;
import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineForegroundService;
import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineReceiver;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.ConsentConfig;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.LocationTrackingConfig;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.StatsEvent;
import edu.berkeley.eecs.emission.cordova.tracker.verification.SensorControlForegroundDelegate;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log;
import edu.berkeley.eecs.emission.cordova.usercache.BuiltinUserCache;
public class DataCollectionPlugin extends CordovaPlugin {
public static final String TAG = "DataCollectionPlugin";
private SensorControlForegroundDelegate mControlDelegate = null;
@Override
public void pluginInitialize() {
mControlDelegate = new SensorControlForegroundDelegate(this, cordova);
final Activity myActivity = cordova.getActivity();
BuiltinUserCache.getDatabase(myActivity).putMessage(R.string.key_usercache_client_nav_event,
new StatsEvent(myActivity, R.string.app_launched));
TripDiaryStateMachineReceiver.initOnUpgrade(myActivity);
}
@Override
public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException {
if (action.equals("launchInit")) {
Log.d(cordova.getActivity(), TAG, "application launched, init is nop on android");
callbackContext.success();
return true;
} else if (action.equals("markConsented")) {
Log.d(cordova.getActivity(), TAG, "marking consent as done");
Context ctxt = cordova.getActivity();
JSONObject newConsent = data.getJSONObject(0);
ConsentConfig cfg = new Gson().fromJson(newConsent.toString(), ConsentConfig.class);
ConfigManager.setConsented(ctxt, cfg);
TripDiaryStateMachineForegroundService.startProperly(cordova.getActivity().getApplication());
// Now, really initialize the state machine
// Note that we don't call initOnUpgrade so that we can handle the case where the
// user deleted the consent and re-consented, but didn't upgrade the app
mControlDelegate.checkAndPromptPermissions();
// ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize));
// TripDiaryStateMachineReceiver.restartCollection(ctxt);
callbackContext.success();
return true;
} else if (action.equals("storeBatteryLevel")) {
Context ctxt = cordova.getActivity();
TripDiaryStateMachineReceiver.saveBatteryAndSimulateUser(ctxt);
callbackContext.success();
} else if (action.equals("getConfig")) {
Context ctxt = cordova.getActivity();
LocationTrackingConfig cfg = ConfigManager.getConfig(ctxt);
// Gson.toJson() represents a string and we are expecting an object in the interface
callbackContext.success(new JSONObject(new Gson().toJson(cfg)));
return true;
} else if (action.equals("setConfig")) {
Context ctxt = cordova.getActivity();
JSONObject newConfig = data.getJSONObject(0);
LocationTrackingConfig cfg = new Gson().fromJson(newConfig.toString(), LocationTrackingConfig.class);
ConfigManager.updateConfig(ctxt, cfg);
TripDiaryStateMachineReceiver.restartCollection(ctxt);
callbackContext.success();
return true;
} else if (action.equals("getState")) {
Context ctxt = cordova.getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctxt);
String state = prefs.getString(ctxt.getString(R.string.curr_state_key), ctxt.getString(R.string.state_start));
callbackContext.success(state);
return true;
} else if (action.equals("forceTransition")) {
// we want to run this in a background thread because it might sometimes wait to get
// the current location
final String generalTransition = data.getString(0);
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Context ctxt = cordova.getActivity();
Map<String, String> transitionMap = getTransitionMap(ctxt);
if (transitionMap.containsKey(generalTransition)) {
String androidTransition = transitionMap.get(generalTransition);
ctxt.sendBroadcast(new ExplicitIntent(ctxt, androidTransition));
callbackContext.success(androidTransition);
} else {
callbackContext.error(generalTransition + " not supported, ignoring");
}
}
});
return true;
} else if (action.equals("handleSilentPush")) {
throw new UnsupportedOperationException("silent push handling not supported for android");
} else if (action.equals("getAccuracyOptions")) {
JSONObject retVal = new JSONObject();
retVal.put("PRIORITY_HIGH_ACCURACY", LocationRequest.PRIORITY_HIGH_ACCURACY);
retVal.put("PRIORITY_BALANCED_POWER_ACCURACY", LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
retVal.put("PRIORITY_LOW_POWER", LocationRequest.PRIORITY_LOW_POWER);
retVal.put("PRIORITY_NO_POWER", LocationRequest.PRIORITY_NO_POWER);
callbackContext.success(retVal);
return true;
}
return false;
}
private static Map<String, String> getTransitionMap(Context ctxt) {
Map<String, String> retVal = new HashMap<String, String>();
retVal.put("INITIALIZE", ctxt.getString(R.string.transition_initialize));
retVal.put("EXITED_GEOFENCE", ctxt.getString(R.string.transition_exited_geofence));
retVal.put("STOPPED_MOVING", ctxt.getString(R.string.transition_stopped_moving));
retVal.put("STOP_TRACKING", ctxt.getString(R.string.transition_stop_tracking));
retVal.put("START_TRACKING", ctxt.getString(R.string.transition_start_tracking));
return retVal;
}
@Override
public void onNewIntent(Intent intent) {
Context mAct = cordova.getActivity();
Log.d(mAct, TAG, "onNewIntent(" + intent.getAction() + ")");
Log.d(mAct, TAG, "Found extras " + intent.getExtras());
// this is will be NOP if we are not handling the right intent
mControlDelegate.onNewIntent(intent);
// This is where we can add other intent handlers
}
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
// This will be a NOP if we are not requesting the right permission
mControlDelegate.onRequestPermissionResult(requestCode, permissions, grantResults);
// This is where we can add other permission callbacks
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
Log.d(cordova.getActivity(), TAG, "received onActivityResult(" + requestCode + "," +
resultCode + "," + "null data" + ")");
} else {
Log.d(cordova.getActivity(), TAG, "received onActivityResult("+requestCode+","+
resultCode+","+data.getDataString()+")");
}
// This will be a NOP if we are not handling the correct activity intent
mControlDelegate.onActivityResult(requestCode, resultCode, data);
/*
This is where we would handle other cases for activity results
switch (requestCode) {
default:
Log.d(cordova.getActivity(), TAG, "Got unsupported request code "+requestCode+ " , ignoring...");
}
*/
}
}
| bsd-3-clause |
mattunderscorechampion/rated-executor | src/test/java/com/mattunderscore/executor/stubs/CountingTask.java | 1817 | /* Copyright © 2013 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package com.mattunderscore.executor.stubs;
/**
* Simple runnable task to execute. Increments a counter.
*
* @author Matt Champion
* @since 0.0.1
*/
public final class CountingTask implements Runnable
{
public volatile int count = 0;
@Override
public void run()
{
count++;
}
} | bsd-3-clause |
octacode/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/quizGen/shasha/videocollectiontemplate/Constants.java | 806 | package org.quizGen.shasha.videocollectiontemplate;
import org.quizGen.shasha.videocollectiontemplate.data.VideoContract;
/**
* @brief Constants used in video collection template's simulator relating databases.
* <p/>
*/
public class Constants {
public static final String[] VIDEO_COLUMNS = {
VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
VideoContract.Videos.TITLE,
VideoContract.Videos.DESCRIPTION,
VideoContract.Videos.LINK,
VideoContract.Videos.THUMBNAIL_URL
};
public static final int COL_TITLE = 1;
public static final int COL_DESCRIPTION = 2;
public static final int COL_LINK = 3;
public static final int COL_THUMBNAIL_URL = 4;
public static String XMLFileName = "video_content.xml";
}
| bsd-3-clause |
michelafrinic/WHOIS | whois-commons/src/main/java/net/ripe/db/whois/common/profiles/WhoisProfile.java | 795 | package net.ripe.db.whois.common.profiles;
public class WhoisProfile {
public static final String ENDTOEND = "ENDTOEND";
public static final String TEST = "TEST";
public static final String DEPLOYED = "DEPLOYED";
private static boolean deployed, endtoend;
public static boolean isDeployed() {
return deployed;
}
public static void setDeployed() {
WhoisProfile.deployed = true;
WhoisProfile.endtoend = false;
System.setProperty("spring.profiles.active", DEPLOYED);
}
public static boolean isEndtoend() {
return endtoend;
}
public static void setEndtoend() {
WhoisProfile.deployed = false;
WhoisProfile.endtoend = true;
System.setProperty("spring.profiles.active", ENDTOEND);
}
}
| bsd-3-clause |
vactowb/jbehave-core | jbehave-core/src/test/java/org/jbehave/core/steps/StepCreatorBehaviour.java | 25027 | package org.jbehave.core.steps;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_END;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_START;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.beans.IntrospectionException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.failures.BeforeOrAfterFailed;
import org.jbehave.core.failures.UUIDExceptionWrapper;
import org.jbehave.core.model.Meta;
import org.jbehave.core.parsers.RegexStepMatcher;
import org.jbehave.core.parsers.StepMatcher;
import org.jbehave.core.reporters.StoryReporter;
import org.jbehave.core.steps.AbstractStepResult.Failed;
import org.jbehave.core.steps.AbstractStepResult.Ignorable;
import org.jbehave.core.steps.AbstractStepResult.Pending;
import org.jbehave.core.steps.AbstractStepResult.Skipped;
import org.jbehave.core.steps.AbstractStepResult.Successful;
import org.jbehave.core.steps.StepCreator.ParameterNotFound;
import org.jbehave.core.steps.StepCreator.ParameterisedStep;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import com.thoughtworks.paranamer.BytecodeReadingParanamer;
import com.thoughtworks.paranamer.CachingParanamer;
public class StepCreatorBehaviour {
private ParameterConverters parameterConverters = mock(ParameterConverters.class);
@Before
public void setUp() throws Exception {
when(parameterConverters.convert("shopping cart", String.class)).thenReturn("shopping cart");
when(parameterConverters.convert("book", String.class)).thenReturn("book");
when(parameterConverters.newInstanceAdding(Matchers.<ParameterConverters.ParameterConverter> anyObject()))
.thenReturn(parameterConverters);
}
@Test
public void shouldHandleTargetInvocationFailureInBeforeOrAfterStep() throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
MostUsefulConfiguration configuration = new MostUsefulConfiguration();
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(configuration, stepsInstance);
StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory,
configuration.parameterConverters(), new ParameterControls(), null, new SilentStepMonitor());
// When
Method method = SomeSteps.methodFor("aFailingBeforeScenarioMethod");
StepResult stepResult = stepCreator.createBeforeOrAfterStep(method, Meta.EMPTY).perform(null);
// Then
assertThat(stepResult, instanceOf(Failed.class));
assertThat(stepResult.getFailure(), instanceOf(UUIDExceptionWrapper.class));
Throwable cause = stepResult.getFailure().getCause();
assertThat(cause, instanceOf(BeforeOrAfterFailed.class));
assertThat(
cause.getMessage(),
org.hamcrest.Matchers
.equalTo("Method aFailingBeforeScenarioMethod (annotated with @BeforeScenario in class org.jbehave.core.steps.SomeSteps) failed: java.lang.RuntimeException"));
}
@Test
public void shouldDescribeStepToReporterBeforeExecutingParametrisedStep() throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(new MostUsefulConfiguration(), stepsInstance);
StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory, null,
new ParameterControls(), null, new SilentStepMonitor());
StoryReporter storyReporter = mock(StoryReporter.class);
// When
Method method = SomeSteps.methodFor("aMethod");
((ParameterisedStep) stepCreator.createParametrisedStep(method, "When I run", "I run", null)).describeTo(storyReporter);
// Then
verify(storyReporter).beforeStep("When I run");
}
@Test
public void shouldHandleTargetInvocationFailureInParametrisedStep() throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(new MostUsefulConfiguration(), stepsInstance);
StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory, null,
new ParameterControls(), null, new SilentStepMonitor());
// When
Method method = SomeSteps.methodFor("aFailingMethod");
StepResult stepResult = stepCreator.createParametrisedStep(method, "When I fail", "I fail", null).perform(null);
// Then
assertThat(stepResult, instanceOf(Failed.class));
}
@Test
public void shouldHandleFailureInParametrisedStep() throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(new MostUsefulConfiguration(), stepsInstance);
StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory, null,
new ParameterControls(), null, new SilentStepMonitor());
// When
Method method = null;
StepResult stepResult = stepCreator.createParametrisedStep(method, "When I fail", "I fail", null).perform(null);
// Then
assertThat(stepResult, instanceOf(Failed.class));
}
@Test(expected = ParameterNotFound.class)
public void shouldFailIfMatchedParametersAreNotFound() throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepMatcher stepMatcher = mock(StepMatcher.class);
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(new MostUsefulConfiguration(), stepsInstance);
StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory, new ParameterConverters(),
new ParameterControls(), stepMatcher, new SilentStepMonitor());
// When
when(stepMatcher.parameterNames()).thenReturn(new String[] {});
stepCreator.matchedParameter("unknown");
// Then .. fail as expected
}
@Test
public void shouldCreatePendingAndIgnorableAsStepResults() throws IntrospectionException {
// When
Step ignorableStep = StepCreator.createIgnorableStep("!-- ignore me");
Step pendingStep = StepCreator.createPendingStep("When I'm pending", null);
// Then
assertThat(ignorableStep.perform(null), instanceOf(Ignorable.class));
assertThat(ignorableStep.doNotPerform(null), instanceOf(Ignorable.class));
assertThat(pendingStep.perform(null), instanceOf(Pending.class));
assertThat(pendingStep.doNotPerform(null), instanceOf(Pending.class));
}
@Test
public void shouldCreateParametrisedStepWithParsedParametersValues() throws Exception {
assertThatParametrisedStepHasMarkedParsedParametersValues("shopping cart", "book");
assertThatParametrisedStepHasMarkedParsedParametersValues("bookreading", "book");
assertThatParametrisedStepHasMarkedParsedParametersValues("book", "bookreading");
}
private void assertThatParametrisedStepHasMarkedParsedParametersValues(String firstParameterValue,
String secondParameterValue) throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepMatcher stepMatcher = new RegexStepMatcher(StepType.WHEN, "I use parameters $theme and $variant", Pattern.compile("When I use parameters (.*) and (.*)"), new String[]{"theme", "variant"});
StepCreator stepCreator = stepCreatorUsing(stepsInstance, stepMatcher, new ParameterControls());
Map<String, String> parameters = new HashMap<String, String>();
// When
StepResult stepResult = stepCreator.createParametrisedStep(SomeSteps.methodFor("aMethodWithANamedParameter"),
"When I use parameters "+firstParameterValue+" and " + secondParameterValue, "When I use parameters "+firstParameterValue+" and " + secondParameterValue, parameters)
.perform(null);
// Then
assertThat(stepResult, instanceOf(Successful.class));
String expected = "When I use parameters " + PARAMETER_VALUE_START + firstParameterValue + PARAMETER_VALUE_END
+ " and " + PARAMETER_VALUE_START + secondParameterValue + PARAMETER_VALUE_END;
assertThat(stepResult.parametrisedStep(), equalTo(expected));
}
@Test
public void shouldCreateParametrisedStepWithNamedParametersValues() throws Exception {
assertThatParametrisedStepHasMarkedNamedParameterValues("shopping cart", "book");
assertThatParametrisedStepHasMarkedNamedParameterValues("bookreading", "book");
assertThatParametrisedStepHasMarkedNamedParameterValues("book", "bookreading");
}
private void assertThatParametrisedStepHasMarkedNamedParameterValues(String firstParameterValue,
String secondParameterValue) throws IntrospectionException {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepMatcher stepMatcher = mock(StepMatcher.class);
StepCreator stepCreator = stepCreatorUsing(stepsInstance, stepMatcher, new ParameterControls());
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("theme", firstParameterValue);
parameters.put("variant", secondParameterValue);
// When
when(stepMatcher.parameterNames()).thenReturn(parameters.keySet().toArray(new String[parameters.size()]));
when(stepMatcher.parameter(1)).thenReturn(parameters.get(firstParameterValue));
when(stepMatcher.parameter(2)).thenReturn(parameters.get(secondParameterValue));
StepResult stepResult = stepCreator.createParametrisedStep(SomeSteps.methodFor("aMethodWithANamedParameter"),
"When I use parameters <theme> and <variant>", "I use parameters <theme> and <variant>", parameters)
.perform(null);
// Then
assertThat(stepResult, instanceOf(Successful.class));
String expected = "When I use parameters " + PARAMETER_VALUE_START + firstParameterValue + PARAMETER_VALUE_END
+ " and " + PARAMETER_VALUE_START + secondParameterValue + PARAMETER_VALUE_END;
assertThat(stepResult.parametrisedStep(), equalTo(expected));
}
@Test
public void shouldInvokeBeforeOrAfterStepMethodWithExpectedParametersFromMeta() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
Properties properties = new Properties();
properties.put("theme", "shopping cart");
properties.put("variant", "book");
// When
Step stepWithMeta = stepCreator.createBeforeOrAfterStep(SomeSteps.methodFor("aMethodWithANamedParameter"),
new Meta(properties));
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat(stepsInstance.args, instanceOf(Map.class));
@SuppressWarnings("unchecked")
Map<String, String> methodArgs = (Map<String, String>) stepsInstance.args;
assertThat(methodArgs.get("variant"), is("book"));
assertThat(methodArgs.get("theme"), is("shopping cart"));
}
@Test
public void shouldInvokeBeforeOrAfterStepMethodWithMetaUsingParanamer() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
stepCreator.useParanamer(new CachingParanamer(new BytecodeReadingParanamer()));
Properties properties = new Properties();
properties.put("theme", "shopping cart");
// When
Step stepWithMeta = stepCreator.createBeforeOrAfterStep(SomeSteps.methodFor("aMethodWithoutNamedAnnotation"),
new Meta(properties));
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat((String) stepsInstance.args, is("shopping cart"));
}
@Test
public void shouldHandleFailureInBeforeOrAfterStepWithMeta() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
// When
Method method = SomeSteps.methodFor("aFailingMethod");
StepResult stepResult = stepCreator.createBeforeOrAfterStep(method, Meta.EMPTY).perform(null);
// Then
assertThat(stepResult, instanceOf(Failed.class));
assertThat(stepResult.getFailure(), instanceOf(UUIDExceptionWrapper.class));
assertThat(stepResult.getFailure().getCause(), instanceOf(BeforeOrAfterFailed.class));
}
@Test
public void shouldInvokeAfterStepUponAnyOutcomeMethodWithExpectedParametersFromMeta() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
Properties properties = new Properties();
properties.put("theme", "shopping cart");
properties.put("variant", "book");
// When
Step stepWithMeta = stepCreator.createAfterStepUponOutcome(SomeSteps.methodFor("aMethodWithANamedParameter"),
AfterScenario.Outcome.ANY, new Meta(properties));
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat(stepsInstance.args, instanceOf(Map.class));
@SuppressWarnings("unchecked")
Map<String, String> methodArgs = (Map<String, String>) stepsInstance.args;
assertThat(methodArgs.get("variant"), is("book"));
assertThat(methodArgs.get("theme"), is("shopping cart"));
}
@Test
public void shouldNotInvokeAfterStepUponSuccessOutcomeMethodIfFailureOccurred() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
// When
Step stepWithMeta = stepCreator.createAfterStepUponOutcome(SomeSteps.methodFor("aFailingMethod"),
AfterScenario.Outcome.SUCCESS, mock(Meta.class));
StepResult stepResult = stepWithMeta.doNotPerform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
}
@Test
public void shouldInvokeAfterStepUponSuccessOutcomeMethodIfNoFailureOccurred() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
Properties properties = new Properties();
properties.put("theme", "shopping cart");
properties.put("variant", "book");
// When
Step stepWithMeta = stepCreator.createAfterStepUponOutcome(SomeSteps.methodFor("aMethodWithANamedParameter"),
AfterScenario.Outcome.SUCCESS, new Meta(properties));
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat(stepsInstance.args, instanceOf(Map.class));
@SuppressWarnings("unchecked")
Map<String, String> methodArgs = (Map<String, String>) stepsInstance.args;
assertThat(methodArgs.get("variant"), is("book"));
assertThat(methodArgs.get("theme"), is("shopping cart"));
}
@Test
public void shouldNotInvokeAfterStepUponFailureOutcomeMethodIfNoFailureOccurred() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
// When
Step stepWithMeta = stepCreator.createAfterStepUponOutcome(SomeSteps.methodFor("aFailingMethod"),
AfterScenario.Outcome.FAILURE, mock(Meta.class));
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
}
@Test
public void shouldInvokeAfterStepUponFailureOutcomeMethodIfFailureOccurred() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
Properties properties = new Properties();
properties.put("theme", "shopping cart");
properties.put("variant", "book");
// When
Step stepWithMeta = stepCreator.createAfterStepUponOutcome(SomeSteps.methodFor("aMethodWithANamedParameter"),
AfterScenario.Outcome.FAILURE, new Meta(properties));
StepResult stepResult = stepWithMeta.doNotPerform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat(stepsInstance.args, instanceOf(Map.class));
@SuppressWarnings("unchecked")
Map<String, String> methodArgs = (Map<String, String>) stepsInstance.args;
assertThat(methodArgs.get("variant"), is("book"));
assertThat(methodArgs.get("theme"), is("shopping cart"));
}
@Test
public void shouldInvokeBeforeOrAfterStepMethodWithExpectedConvertedParametersFromMeta() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
stepCreator.useParanamer(new CachingParanamer(new BytecodeReadingParanamer()));
// When
Date aDate = new Date();
when(parameterConverters.convert(anyString(), eq(Date.class))).thenReturn(aDate);
Step stepWithMeta = stepCreator.createBeforeOrAfterStep(SomeSteps.methodFor("aMethodWithDate"), new Meta());
StepResult stepResult = stepWithMeta.perform(null);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat((Date) stepsInstance.args, is(aDate));
}
@Test
public void shouldInjectExceptionThatHappenedIfTargetMethodExpectsIt() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
parameterConverters = new ParameterConverters();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
// When
Step stepWithMeta = stepCreator.createBeforeOrAfterStep(
SomeSteps.methodFor("aMethodThatExpectsUUIDExceptionWrapper"), mock(Meta.class));
UUIDExceptionWrapper occurredFailure = new UUIDExceptionWrapper();
StepResult stepResult = stepWithMeta.perform(occurredFailure);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat((UUIDExceptionWrapper) stepsInstance.args, is(occurredFailure));
}
@Test
public void shouldInjectNoFailureIfNoExceptionHappenedAndTargetMethodExpectsIt() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
parameterConverters = new ParameterConverters();
StepCreator stepCreator = stepCreatorUsing(stepsInstance, mock(StepMatcher.class), new ParameterControls());
// When
Step stepWithMeta = stepCreator.createBeforeOrAfterStep(
SomeSteps.methodFor("aMethodThatExpectsUUIDExceptionWrapper"), mock(Meta.class));
UUIDExceptionWrapper occurredFailure = new UUIDExceptionWrapper();
StepResult stepResult = stepWithMeta.perform(occurredFailure);
// Then
assertThat(stepResult, instanceOf(Skipped.class));
assertThat((UUIDExceptionWrapper) stepsInstance.args, is(occurredFailure));
}
@Test
public void shouldMatchParametersByDelimitedNameWithNoNamedAnnotations() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
parameterConverters = new ParameterConverters();
StepMatcher stepMatcher = mock(StepMatcher.class);
ParameterControls parameterControls = new ParameterControls().useDelimiterNamedParameters(true);
StepCreator stepCreator = stepCreatorUsing(stepsInstance, stepMatcher, parameterControls);
Map<String, String> params = Collections.singletonMap("param", "value");
when(stepMatcher.parameterNames()).thenReturn(params.keySet().toArray(new String[params.size()]));
when(stepMatcher.parameter(1)).thenReturn("<param>");
// When
Step step = stepCreator.createParametrisedStep(SomeSteps.methodFor("aMethodWithoutNamedAnnotation"),
"When a parameter <param> is set", "a parameter <param> is set", params);
step.perform(null);
// Then
assertThat((String) stepsInstance.args, equalTo("value"));
}
@SuppressWarnings("unchecked")
@Test
public void shouldMatchParametersByDelimitedNameWithDistinctNamedAnnotations() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
parameterConverters = new ParameterConverters();
StepMatcher stepMatcher = mock(StepMatcher.class);
ParameterControls parameterControls = new ParameterControls().useDelimiterNamedParameters(true);
StepCreator stepCreator = stepCreatorUsing(stepsInstance, stepMatcher, parameterControls);
Map<String, String> params = new HashMap<String, String>();
params.put("t", "distinct theme");
params.put("v", "distinct variant");
when(stepMatcher.parameterNames()).thenReturn(params.keySet().toArray(new String[params.size()]));
when(stepMatcher.parameter(1)).thenReturn("<t>");
when(stepMatcher.parameter(2)).thenReturn("<v>");
// When
Step step = stepCreator.createParametrisedStep(SomeSteps.methodFor("aMethodWithANamedParameter"),
"When I use parameters <t> and <v>", "I use parameters <t> and <v>", params);
step.perform(null);
// Then
Map<String, String> results = (Map<String, String>) stepsInstance.args;
assertThat(results.get("theme"), equalTo("distinct theme"));
assertThat(results.get("variant"), equalTo("distinct variant"));
}
@SuppressWarnings("unchecked")
@Test
public void shouldMatchParametersByNamedAnnotationsIfConfiguredToNotUseDelimiterNamedParamters() throws Exception {
// Given
SomeSteps stepsInstance = new SomeSteps();
parameterConverters = new ParameterConverters();
StepMatcher stepMatcher = mock(StepMatcher.class);
ParameterControls parameterControls = new ParameterControls().useDelimiterNamedParameters(false);
StepCreator stepCreator = stepCreatorUsing(stepsInstance, stepMatcher, parameterControls);
Map<String, String> params = new HashMap<String, String>();
params.put("theme", "a theme");
params.put("variant", "a variant");
when(stepMatcher.parameterNames()).thenReturn(params.keySet().toArray(new String[params.size()]));
when(stepMatcher.parameter(1)).thenReturn("<t>");
when(stepMatcher.parameter(2)).thenReturn("<v>");
// When
Step step = stepCreator.createParametrisedStep(SomeSteps.methodFor("aMethodWithANamedParameter"),
"When I use parameters <t> and <v>", "I use parameters <t> and <v>", params);
step.perform(null);
// Then
Map<String, String> results = (Map<String, String>) stepsInstance.args;
assertThat(results.get("theme"), equalTo("a theme"));
assertThat(results.get("variant"), equalTo("a variant"));
}
private StepCreator stepCreatorUsing(SomeSteps stepsInstance, StepMatcher stepMatcher, ParameterControls parameterControls) {
InjectableStepsFactory stepsFactory = new InstanceStepsFactory(new MostUsefulConfiguration(), stepsInstance);
return new StepCreator(stepsInstance.getClass(), stepsFactory, parameterConverters, parameterControls,
stepMatcher, new SilentStepMonitor());
}
}
| bsd-3-clause |
thgriefers/mastercard-api-java | src/main/java/com/mastercard/api/partnerwallet/domain/switchapi/AuthorizePairingRequest.java | 7180 |
package com.mastercard.api.partnerwallet.domain.switchapi;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AuthorizePairingRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AuthorizePairingRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="PairingDataTypes" type="{}PairingDataTypes"/>
* <element name="OAuthToken" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="MerchantCheckoutId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ConsumerWalletId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="WalletId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ExpressCheckout" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="ConsumerCountry" type="{}Country"/>
* <element name="SilentPairing" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ExtensionPoint" type="{}ExtensionPoint" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlRootElement(name="AuthorizePairingRequest")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AuthorizePairingRequest", propOrder = {
"pairingDataTypes",
"oAuthToken",
"merchantCheckoutId",
"consumerWalletId",
"walletId",
"expressCheckout",
"consumerCountry",
"silentPairing",
"extensionPoint"
})
public class AuthorizePairingRequest {
@XmlElement(name = "PairingDataTypes", required = true)
protected PairingDataTypes pairingDataTypes;
@XmlElement(name = "OAuthToken", required = true)
protected String oAuthToken;
@XmlElement(name = "MerchantCheckoutId", required = true)
protected String merchantCheckoutId;
@XmlElement(name = "ConsumerWalletId", required = true)
protected String consumerWalletId;
@XmlElement(name = "WalletId", required = true)
protected String walletId;
@XmlElement(name = "ExpressCheckout")
protected boolean expressCheckout;
@XmlElement(name = "ConsumerCountry", required = true)
protected Country consumerCountry;
@XmlElement(name = "SilentPairing")
protected Boolean silentPairing;
@XmlElement(name = "ExtensionPoint")
protected ExtensionPoint extensionPoint;
/**
* Gets the value of the pairingDataTypes property.
*
* @return
* possible object is
* {@link PairingDataTypes }
*
*/
public PairingDataTypes getPairingDataTypes() {
return pairingDataTypes;
}
/**
* Sets the value of the pairingDataTypes property.
*
* @param value
* allowed object is
* {@link PairingDataTypes }
*
*/
public void setPairingDataTypes(PairingDataTypes value) {
this.pairingDataTypes = value;
}
/**
* Gets the value of the oAuthToken property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOAuthToken() {
return oAuthToken;
}
/**
* Sets the value of the oAuthToken property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOAuthToken(String value) {
this.oAuthToken = value;
}
/**
* Gets the value of the merchantCheckoutId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMerchantCheckoutId() {
return merchantCheckoutId;
}
/**
* Sets the value of the merchantCheckoutId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMerchantCheckoutId(String value) {
this.merchantCheckoutId = value;
}
/**
* Gets the value of the consumerWalletId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsumerWalletId() {
return consumerWalletId;
}
/**
* Sets the value of the consumerWalletId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsumerWalletId(String value) {
this.consumerWalletId = value;
}
/**
* Gets the value of the walletId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWalletId() {
return walletId;
}
/**
* Sets the value of the walletId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWalletId(String value) {
this.walletId = value;
}
/**
* Gets the value of the expressCheckout property.
*
*/
public boolean isExpressCheckout() {
return expressCheckout;
}
/**
* Sets the value of the expressCheckout property.
*
*/
public void setExpressCheckout(boolean value) {
this.expressCheckout = value;
}
/**
* Gets the value of the consumerCountry property.
*
* @return
* possible object is
* {@link Country }
*
*/
public Country getConsumerCountry() {
return consumerCountry;
}
/**
* Sets the value of the consumerCountry property.
*
* @param value
* allowed object is
* {@link Country }
*
*/
public void setConsumerCountry(Country value) {
this.consumerCountry = value;
}
/**
* Gets the value of the silentPairing property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isSilentPairing() {
return silentPairing;
}
/**
* Sets the value of the silentPairing property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setSilentPairing(Boolean value) {
this.silentPairing = value;
}
/**
* Gets the value of the extensionPoint property.
*
* @return
* possible object is
* {@link ExtensionPoint }
*
*/
public ExtensionPoint getExtensionPoint() {
return extensionPoint;
}
/**
* Sets the value of the extensionPoint property.
*
* @param value
* allowed object is
* {@link ExtensionPoint }
*
*/
public void setExtensionPoint(ExtensionPoint value) {
this.extensionPoint = value;
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.tourguide/src/main/java/org/caleydo/view/tourguide/spi/compute/IComputedStratificationScore.java | 1407 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.tourguide.spi.compute;
import org.caleydo.view.tourguide.spi.algorithm.IComputeElement;
import org.caleydo.view.tourguide.spi.algorithm.IComputeScoreFilter;
import org.caleydo.view.tourguide.spi.algorithm.IStratificationAlgorithm;
import org.caleydo.view.tourguide.spi.score.IRegisteredScore;
import org.caleydo.view.tourguide.spi.score.IScore;
/**
* declares that the given {@link IScore} must be computed on a stratification base
*
* @author Samuel Gratzl
*
*/
public interface IComputedStratificationScore extends IRegisteredScore {
/**
* already in the cache?
*
* @param a
* @return
*/
boolean contains(IComputeElement a);
/**
* put the result in the cache
*
* @param a
* @param value
*/
void put(IComputeElement a, double value);
/**
* returns the algorithm to compute this score
*
* @return
*/
IStratificationAlgorithm getAlgorithm();
/**
* returns the filter apply for skipping invalid combination pairs
*
* @return
*/
IComputeScoreFilter getFilter();
}
| bsd-3-clause |
etecture/dynamic-repositories | dynamic-repositories-remote-neo4j/src/test/java/de/etecture/opensource/dynamicrepositories/technologies/Actor.java | 2028 | /*
* This file is part of the ETECTURE Open Source Community Projects.
*
* Copyright (c) 2013 by:
*
* ETECTURE GmbH
* Darmstädter Landstraße 112
* 60598 Frankfurt
* Germany
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the author nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package de.etecture.opensource.dynamicrepositories.technologies;
import java.util.List;
/**
* represents a sample entity for test purposes.
*
* @author rhk
*/
public interface Actor {
String getName();
List<String> getRoles();
Movie getInitialMovie();
List<Movie> getMovies();
}
| bsd-3-clause |
datagr4m/org.datagr4m | datagr4m-application/src/main/java/org/datagr4m/application/designer/toolbars/search/ISearchEngineListener.java | 243 | package org.datagr4m.application.designer.toolbars.search;
import java.util.List;
import org.datagr4m.drawing.model.items.IBoundedItem;
public interface ISearchEngineListener {
public void searchFinished(List<IBoundedItem> results);
}
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/CTRPInstitutionAction.java | 2317 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.action;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.CTRPInstitutionForm;
import edu.wustl.catissuecore.ctrp.COPPAServiceClient;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.coppa.po.Organization;
import edu.wustl.catissuecore.util.global.Constants;
public class CTRPInstitutionAction extends BaseAction {
/**
* logger.
*/
private transient final Logger logger = Logger
.getCommonLogger(CTRPInstitutionAction.class);
/**
* Overrides the executeSecureAction method of SecureAction class.
*
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response
* : response obj
* @throws Exception
* generic exception
* @return ActionForward : ActionForward
*/
@Override
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
CTRPInstitutionForm ctrpInstitutionForm = (CTRPInstitutionForm) form;
System.out.println("Request Param:"+request.getParameter("operation"));
Organization[] organizationList = null;
organizationList = new COPPAServiceClient()
.searchOrganization(ctrpInstitutionForm.getEntityName());
if (organizationList != null && organizationList.length > 0) {
request.setAttribute("COPPA_MATCH_FOUND", "true");
request.getSession().setAttribute("COPPA_ORGANIZATIONS",
organizationList);
}
return mapping.findForward("displayMatches");
}
}
| bsd-3-clause |
NCIP/caarray | qa/software/API_Test_Suite/src/caarray/client/test/search/BiomaterialKeywordSearch.java | 1017 | //======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package caarray.client.test.search;
import gov.nih.nci.caarray.external.v1_0.query.BiomaterialKeywordSearchCriteria;
/**
* @author vaughng
* Jul 9, 2009
*/
public class BiomaterialKeywordSearch extends CriteriaSearch
{
private BiomaterialKeywordSearchCriteria searchCriteria;
/**
*
*/
public BiomaterialKeywordSearch()
{
super();
}
public BiomaterialKeywordSearchCriteria getSearchCriteria()
{
return searchCriteria;
}
public void setSearchCriteria(BiomaterialKeywordSearchCriteria searchCriteria)
{
this.searchCriteria = searchCriteria;
}
}
| bsd-3-clause |
westnorth/weibo_zy | weibo_cm/createTable.java | 4258 | import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class createTable {
private static String DATABASE_CONNECTION = "jdbc:sqlite:weibo.db";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createTable();
}
});
}
private static void createTable(){
Connection conn;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(DATABASE_CONNECTION);
// 建立事务机制,禁止自动提交,设置回滚点
conn.setAutoCommit(false);
Statement stat = conn.createStatement();
// User{weibo=null, id=2438418282, name='心情慵懒',
// screenName='心情慵懒', location='甘肃 陇南', description='',
// profileImageUrl='http://tp3.sinaimg.cn/2438418282/50/5612515360/1',
// province='62', city='26', domain ='', gender ='m',
// url='',
// allowAllActMsg=false,
// followersCount=1,
// friendsCount=40, createdAt=Sun Oct 02 00:00:00 CST 2011,
// favouritesCount=0, following=false, statusesCount=0,
// geoEnabled=false,
// voiderified=false,
// status=null}
stat.executeUpdate("create table userInfo ("
+ "id PRIMARY KEY NOT NULL,"// 用户UID",主键
+ "screenName,"// 微博昵称
+ "name,"// 友好显示名称,同微博昵称
+ "province,"// 省份编码(参考省份编码表)
+ "city,"// 城市编码(参考城市编码表)
+ "location,"// 地址
+ "description,"// 个人描述
+ "url,"// 用户博客地址
+ "profileImageUrl,"// 自定义图像
+ "domain,"// 用户个性化URL
+ "gender,"// 性别,m--男,f--女,n--未知
+ "followersCount,"// 粉丝数
+ "friendsCount,"// 关注数
+ "statusesCount,"// 微博数
+ "favouritesCount,"// 收藏数
+ "createdAt,"// 创建时间
+ "following,"// 是否已关注(此特性暂不支持)
+ "verified,"// 加V标示,是否微博认证用户
+ "status,"// 状态,由取回的字符中提取,意义不明
+ "geoEnabled,"// 地理状态信息
+ "allowAllActMsg,"// 由取回的字符中提取,意义不明
+ "weibo,"// 由取回的字符中提取,意义不明
+ "access_token,"// 访问Token
+ "access_secret)");// 访问密钥
// [createdAt=Sat Oct 01 23:51:54 CST 2011,
// id=3363835379243442, text=养生之道,首在养气。,
// source=<a href="http://mail.sina.com.cn"
// rel="nofollow">新浪免费邮箱</a>,
// isTruncated=false, inReplyToStatusId=-1, inReplyToUserId=-1,
// isFavorited=false, inReplyToScreenName=,
// latitude=-1.0,
// longitude=-1.0,
// thumbnail_pic=, bmiddle_pic=,
// original_pic=,
// mid=3363835379243442,
// user=null,
// retweeted_status=null]}
stat.executeUpdate("create table statusInfo (" + "created_at,"// 创建时间
+ "id PRIMARY KEY NOT NULL,"// 微博ID,主键
+ "text,"// 微博信息内容
+ "source,"// 微博来源
+ "favorited,"// 是否已收藏
+ "truncated,"// 是否被截断
+ "in_reply_to_status_id,"// 回复ID
+ "in_reply_to_user_id,"// 回复人UID
+ "in_reply_to_screen_name,"// 回复人昵称
+ "thumbnail_pic,"// 缩略图
+ "bmiddle_pic,"// 中型图片
+ "original_pic,"// 原始图片
+ "user,"// 作者信息
+ "retweeted_status)");// 转发的博文,内容为status,如果不是转发,则没有此字段
// stat.executeUpdate("insert into people values ('Gandhi', 'politics');");
// stat.executeUpdate("insert into people values ('Turing', 'computers');");
// stat.executeUpdate("insert into people values ('Wittgenstein', 'smartypants');");
conn.commit();
//
// ResultSet rs = stat.executeQuery("select * from people;");
// while (rs.next()) {
// System.out.println("name = " + rs.getString("name"));
// System.out
// .println("occupation = " + rs.getString("occupation"));
// }
// rs.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.println("create table error");
e.printStackTrace();
}
}
} | bsd-3-clause |
vivo-project/Vitro | api/src/test/java/edu/cornell/mannlib/vitro/webapp/utils/json/JacksonUtilsTest.java | 1980 | /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.json;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* quotes,\, \r, \n, \b, \f, \t and other control characters.
*
*
*/
public class JacksonUtilsTest extends AbstractTestClass {
// ----------------------------------------------------------------------
// Tests for quote()
// quotes,\, \r, \n, \b, \f, \t and other control characters.
// Originally written as direct comparisons to the net.sf.json version.
// ----------------------------------------------------------------------
@Test
public void quoteNull() {
assertJacksonQuoted(null, "");
// assertNetSfJsonQuoted(null, "");
}
@Test
public void quoteQuote() {
assertJacksonQuoted("\"", "\\\"");
// assertNetSfJsonQuoted("\"", "\\\"");
}
@Test
public void quoteBackslash() {
assertJacksonQuoted("\\", "\\\\");
// assertNetSfJsonQuoted("\\", "\\\\");
}
@Test
public void quoteReturn() {
assertJacksonQuoted("\r", "\\r");
// assertNetSfJsonQuoted("\r", "\\r");
}
@Test
public void quoteUnicode() {
assertJacksonQuoted("\u0007", "\\u0007");
// assertNetSfJsonQuoted("\u0007", "\\u0007");
}
@Test
public void quoteAssorted() {
assertJacksonQuoted("\n\b\f\t", "\\n\\b\\f\\t");
// assertNetSfJsonQuoted("\n\b\f\t", "\\n\\b\\f\\t");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertJacksonQuoted(String raw, String expected) {
String actual = JacksonUtils.quote(raw);
assertEquals("\"" + expected + "\"", actual);
}
// private void assertNetSfJsonQuoted(String raw, String expected) {
// String actual = net.sf.json.util.JSONUtils.quote(raw);
// assertEquals("\"" + expected + "\"", actual);
// }
}
| bsd-3-clause |
wahidcse/school-management-system | src/main/java/org/sms/entity/ClassInfo.java | 891 | package org.sms.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class ClassInfo {
@Id
@GeneratedValue
private int id;
private String subjectName;
private String levelNo;
private String section;
private String dayName;
@Temporal(TemporalType.TIMESTAMP)
@Column(columnDefinition="TIMESTAMP")
private Date classTime;
private int teacherId;
@OneToMany(mappedBy = "classinfo", cascade = CascadeType.REMOVE)
private List<ClassGroup> classGroup;
@ManyToMany(mappedBy = "classinfo")
private List<Student> students;
}
| bsd-3-clause |
JulianSchuette/ConDroid | src/symbolic/java/acteve/symbolic/integer/UnaryDoubleExpression.java | 2138 | /*
Copyright (c) 2011,2012,
Saswat Anand (saswat@gatech.edu)
Mayur Naik (naik@cc.gatech.edu)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
package acteve.symbolic.integer;
public class UnaryDoubleExpression extends DoubleExpression
{
Expression operand;
UnaryOperator op;
public UnaryDoubleExpression(UnaryOperator o, Expression operand)
{
this.operand = operand;
this.op = o;
}
public String toString ()
{
return "(" + op.toString() + " " + operand.toString() + ")";
}
public String toYicesString()
{
return super.toYicesString(op.toYicesString(operand.exprString()));
}
}
| bsd-3-clause |
UCDenver-ccp/ccp-nlp | ccp-nlp-wrapper-conceptmapper/src/main/java/edu/ucdenver/ccp/nlp/wrapper/conceptmapper/ConceptMapperAggregateFactory.java | 5235 | /**
*
*/
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper;
/*
* #%L
* Colorado Computational Pharmacology's nlp module
* %%
* Copyright (C) 2012 - 2014 Regents of the University of Colorado
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.io.File;
import java.io.IOException;
import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.conceptMapper.support.stemmer.Stemmer;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.metadata.OperationalProperties;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.ConceptMapperFactory.SearchStrategyParamValue;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.ConceptMapperFactory.TokenNormalizerConfigParam.CaseMatchParamValue;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.tokenizer.OffsetTokenizerFactory;
/**
* @author Center for Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
public class ConceptMapperAggregateFactory {
/**
* Returns an aggregate description for a UIMA pipeline containing the OffsetTokenizer followed
* by the ConceptMapper
*
* @param tsd
* @param dictionaryFile
* @param caseMatchParamValue
* @param searchStrategyParamValue
* @param spanFeatureStructureClass
* commonly edu.ucdenver.ccp.nlp.ext.uima.types.Sentence
* @param stemmerClass
* optional, leave null if not desired
* @param stopwordList
* @param orderIndependentLookup
* @param findAllMatches
* @param replaceCommaWithAnd
* @return
* @throws UIMAException
* @throws IOException
*/
public static AnalysisEngineDescription getOffsetTokenizerConceptMapperAggregateDescription(
TypeSystemDescription tsd, File dictionaryFile, CaseMatchParamValue caseMatchParamValue,
SearchStrategyParamValue searchStrategyParamValue, Class<? extends Annotation> spanFeatureStructureClass,
Class<? extends Stemmer> stemmerClass, String[] stopwordList, boolean orderIndependentLookup,
boolean findAllMatches, boolean replaceCommaWithAnd) throws UIMAException, IOException {
/* Init the tokenizer */
Object[] tokenizerConfigData = null;
if (stemmerClass == null) {
tokenizerConfigData = OffsetTokenizerFactory.buildConfigurationData(caseMatchParamValue);
} else {
tokenizerConfigData = OffsetTokenizerFactory.buildConfigurationData(caseMatchParamValue, stemmerClass);
}
AnalysisEngineDescription offsetTokenizerDescription = OffsetTokenizerFactory.buildOffsetTokenizerDescription(
tsd, tokenizerConfigData);
OperationalProperties operationalProperties = offsetTokenizerDescription.getAnalysisEngineMetaData()
.getOperationalProperties();
// offsetTokenizerDescription.setImplementationName("offset tokenizer");
// System.out.println(offsetTokenizerDescription.getAnalysisEngineMetaData().getOperationalProperties().isMultipleDeploymentAllowed());
/* Init the concept mapper */
AnalysisEngineDescription conceptMapperDescription = ConceptMapperFactory.buildConceptMapperDescription(tsd,
dictionaryFile, caseMatchParamValue, searchStrategyParamValue, stemmerClass, stopwordList,
orderIndependentLookup, findAllMatches, replaceCommaWithAnd, spanFeatureStructureClass,
offsetTokenizerDescription);
if (offsetTokenizerDescription.getAnalysisEngineMetaData().getOperationalProperties() == null) {
offsetTokenizerDescription.getAnalysisEngineMetaData().setOperationalProperties(operationalProperties);
}
return AnalysisEngineFactory.createAggregateDescription(offsetTokenizerDescription, conceptMapperDescription);
}
}
| bsd-3-clause |
GameRevision/GWLP-R | protocol/src/main/java/gwlpr/protocol/gameserver/outbound/P040_MessageOfTheDay.java | 602 |
package gwlpr.protocol.gameserver.outbound;
import gwlpr.protocol.serialization.GWMessage;
/**
* Auto-generated by PacketCodeGen.
*
*/
public final class P040_MessageOfTheDay
extends GWMessage
{
private String text;
@Override
public short getHeader() {
return 40;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("P040_MessageOfTheDay[");
sb.append("text=").append(this.text.toString()).append("]");
return sb.toString();
}
}
| bsd-3-clause |
wangxin39/xstat | ManageSystem/src/org/xsaas/xstat/web/action/manage/list/ListHeaderAction.java | 8334 | package org.xsaas.xstat.web.action.manage.list;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xsaas.xstat.web.conf.QuestionTypeConstants;
import org.xsaas.xstat.web.conf.SmgkConstants;
import org.xsaas.xstat.web.util.PaginationUtil;
import org.xsaas.xstat.business.IInquisitionHeaderInfoService;
import org.xsaas.xstat.business.IInquisitionInfoService;
import org.xsaas.xstat.business.IOptionTemplateInfoService;
import org.xsaas.xstat.business.IQuestionInfoService;
import org.xsaas.xstat.po.InquisitionHeaderInfo;
import org.xsaas.xstat.po.InquisitionInfo;
import org.xsaas.xstat.po.OptionTemplateInfo;
import org.xsaas.xstat.po.QuestionInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ListHeaderAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 8154573800306729423L;
private static Log logger = LogFactory.getLog(ListHeaderAction.class);
private IInquisitionHeaderInfoService inquisitionHeaderInfoService = null;
private IInquisitionInfoService inquisitionInfoService = null;
private IQuestionInfoService questionInfoService = null;
private IOptionTemplateInfoService optionTemplateInfoService = null;
private List<String> questionList = new LinkedList<String>();
private List<String> inquisitionList = new LinkedList<String>();
private List<String> isinputList = new LinkedList<String>();
private List<String> typeList = new LinkedList<String>();
private Long inquisitionID = null;
private Long headerID = null;
private Integer num = null;
private List<InquisitionHeaderInfo> pageList = null;
private PaginationUtil pu = null;
@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
try{
String username = (String)ActionContext.getContext().getSession().get("LOGINUSERNAME");
String password = (String)ActionContext.getContext().getSession().get("LOGINPASSWORD");
if(username == null || password == null) {
return LOGIN;
}
int page = 1;
if(num != null){
page = num.intValue();
}
List<InquisitionInfo> iList = inquisitionInfoService.getInquisitionInfoList();
//先添加调查问卷
long selectInquisitionID = 0;
if(inquisitionID != null) {
selectInquisitionID = inquisitionID.longValue();
}else{
//客户信息不为空
if(iList.size() >0) {
InquisitionInfo ci = iList.get(0);
selectInquisitionID = ci.getInquisitionID();
}
}
ActionContext.getContext().getSession().put("INQUISITIONSELECT",iList);
ActionContext.getContext().getSession().put("GLOBALINQUISITIONID",selectInquisitionID);
int total = 0;
if(selectInquisitionID != 0)
{
total = inquisitionHeaderInfoService.getInquisitionHeaderInfoTotal(selectInquisitionID);
}else{
total = inquisitionHeaderInfoService.getInquisitionHeaderInfoTotal();
}
pu = new PaginationUtil(total,page,SmgkConstants.PAGE_MAX_RESULT);
if(selectInquisitionID != 0) {
pageList = inquisitionHeaderInfoService.findInquisitionHeaderInfoByPage(selectInquisitionID,pu.getStartRecord(),SmgkConstants.PAGE_MAX_RESULT);
}else{
pageList = inquisitionHeaderInfoService.findInquisitionHeaderInfoByPage(pu.getStartRecord(),SmgkConstants.PAGE_MAX_RESULT);
}
Map<Long,String> iqMap = new java.util.HashMap<Long, String>();
for(InquisitionInfo info:iList)
{
if(info.getInquisitionID() != null) {
iqMap.put(info.getInquisitionID(), ""+info.getTitle());
}
}
for(InquisitionHeaderInfo info:pageList){
if(info.getQuestionID() != null) {
QuestionInfo qInfo = questionInfoService.getQuestionInfo(info.getQuestionID());
questionList.add(""+qInfo.getQuestion());
}else{
questionList.add("");
}
if(info.getIsinput() != null) {
isinputList.add(""+QuestionTypeConstants.IsinputTypeDict.get(info.getIsinput()));
}else{
isinputList.add("");
}
if(info.getQuestionType() != null) {
typeList.add(""+QuestionTypeConstants.QuestionTypeDict.get(info.getQuestionType()));
}else{
typeList.add("");
}
}
}catch(Exception e) {
logger.error(""+e.getMessage(),e.getCause());
}
return SUCCESS;
}
public String detail() throws Exception {
String username = (String)ActionContext.getContext().getSession().get("LOGINUSERNAME");
String password = (String)ActionContext.getContext().getSession().get("LOGINPASSWORD");
try{
if(username == null || password == null) {
return LOGIN;
}
if(headerID == null) {
this.addActionError("编号为空!");
return ERROR;
}
InquisitionHeaderInfo info = inquisitionHeaderInfoService.getInquisitionHeaderInfo(headerID);
if(info != null){
ActionContext.getContext().put("HEADEREDIT",info);
}
InquisitionInfo ii = inquisitionInfoService.getInquisitionInfo(info.getInquisitionID());
QuestionInfo qi = questionInfoService.getQuestionInfo(info.getQuestionID());
if(qi != null && qi.getQuestion() != null) {
ActionContext.getContext().put("QUESTIONLIST",qi.getQuestion());
}
if(ii != null && ii.getTitle() != null) {
ActionContext.getContext().put("INQUISITIONLIST",ii.getTitle());
}
if(info != null && info.getIsinput() != null) {
ActionContext.getContext().put("ISINPUTLIST",QuestionTypeConstants.IsinputTypeDict.get(info.getIsinput()));
}
if(info != null && info.getQuestionType() != null) {
ActionContext.getContext().put("TYPELIST",QuestionTypeConstants.QuestionTypeDict.get(info.getQuestionType()));
}
if(info != null && info.getSelectType() != null) {
ActionContext.getContext().put("SELECTLIST",QuestionTypeConstants.SelectDict.get(info.getSelectType()));
}
if(info != null && info.getOptionTemplateID() != null && info.getSelectType() != null && info.getSelectType() == 1) {
OptionTemplateInfo oti = optionTemplateInfoService.getOptionTemplateInfo(info.getOptionTemplateID());
if(oti != null) {
ActionContext.getContext().put("OPTIONTEMPLATE", ""+oti.getTitle());
}else{
ActionContext.getContext().put("OPTIONTEMPLATE", "");
}
}
}catch(Exception e) {
logger.error(e.getMessage(),e.getCause());
}
return SUCCESS;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public void setInquisitionHeaderInfoService(
IInquisitionHeaderInfoService inquisitionHeaderInfoService) {
this.inquisitionHeaderInfoService = inquisitionHeaderInfoService;
}
public void setQuestionInfoService(IQuestionInfoService questionInfoService) {
this.questionInfoService = questionInfoService;
}
public List<String> getQuestionList() {
return questionList;
}
public Long getInquisitionID() {
return inquisitionID;
}
public void setInquisitionID(Long inquisitionID) {
this.inquisitionID = inquisitionID;
}
public void setQuestionList(List<String> questionList) {
this.questionList = questionList;
}
public List<String> getInquisitionList() {
return inquisitionList;
}
public void setInquisitionList(List<String> inquisitionList) {
this.inquisitionList = inquisitionList;
}
public void setInquisitionInfoService(
IInquisitionInfoService inquisitionInfoService) {
this.inquisitionInfoService = inquisitionInfoService;
}
public List<String> getIsinputList() {
return isinputList;
}
public void setIsinputList(List<String> isinputList) {
this.isinputList = isinputList;
}
public List<InquisitionHeaderInfo> getPageList() {
return pageList;
}
public void setPageList(List<InquisitionHeaderInfo> pageList) {
this.pageList = pageList;
}
public PaginationUtil getPu() {
return pu;
}
public List<String> getTypeList() {
return typeList;
}
public void setTypeList(List<String> typeList) {
this.typeList = typeList;
}
public Long getHeaderID() {
return headerID;
}
public void setHeaderID(Long headerID) {
this.headerID = headerID;
}
public void setOptionTemplateInfoService(
IOptionTemplateInfoService optionTemplateInfoService) {
this.optionTemplateInfoService = optionTemplateInfoService;
}
}
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/domain/ccts/Notification.java | 5787 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.domain.ccts;
// Generated Jan 28, 2011 10:47:34 AM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import edu.wustl.common.domain.AbstractDomainObject;
/**
* Represents a CCTS notification message received by caTissue from iHub.
*/
public class Notification extends AbstractDomainObject {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private Application application;
private EventType eventType;
private ObjectIdType objectIdType;
private ProcessingStatus processingStatus;
private Date dateSent;
private Date dateReceived;
private String objectIdValue;
private Set<NotificationProcessingLog> processingLog = new HashSet<NotificationProcessingLog>();
/**
* @return the id
*/
public final Long getId() {
return id;
}
/**
* @param id the id to set
*/
public final void setId(Long id) {
this.id = id;
}
/**
* @return the application
*/
public final Application getApplication() {
return application;
}
/**
* @param application the application to set
*/
public final void setApplication(Application application) {
this.application = application;
}
/**
* @return the eventType
*/
public final EventType getEventType() {
return eventType;
}
/**
* @param eventType the eventType to set
*/
public final void setEventType(EventType eventType) {
this.eventType = eventType;
}
/**
* @return the objectType
*/
public final ObjectIdType getObjectIdType() {
return objectIdType;
}
/**
* @param objectType the objectType to set
*/
public final void setObjectIdType(ObjectIdType objectType) {
this.objectIdType = objectType;
}
/**
* @return the processingStatus
*/
public final ProcessingStatus getProcessingStatus() {
return processingStatus;
}
/**
* @param processingStatus the processingStatus to set
*/
public final void setProcessingStatus(ProcessingStatus processingStatus) {
this.processingStatus = processingStatus;
}
/**
* @return the objectIdValue
*/
public final String getObjectIdValue() {
return objectIdValue;
}
/**
* @param objectIdValue the objectIdValue to set
*/
public final void setObjectIdValue(String objectIdValue) {
this.objectIdValue = objectIdValue;
}
/**
* @return the processingLog
*/
public final Set<NotificationProcessingLog> getProcessingLog() {
return processingLog;
}
/**
* @param processingLog the processingLog to set
*/
public final void setProcessingLog(Set<NotificationProcessingLog> processingLog) {
this.processingLog = processingLog;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Notification [id=" + id + ", application=" + application
+ ", eventType=" + eventType + ", objectIdType=" + objectIdType
+ ", processingStatus=" + processingStatus + ", dateSent="
+ dateSent + ", dateReceived=" + dateReceived
+ ", objectIdValue=" + objectIdValue + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Notification)) {
return false;
}
Notification other = (Notification) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
/**
* @return the dateSent
*/
public final Date getDateSent() {
return dateSent;
}
/**
* @param dateSent the dateSent to set
*/
public final void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}
/**
* @return the dateReceived
*/
public final Date getDateReceived() {
return dateReceived;
}
/**
* @param dateReceived the dateReceived to set
*/
public final void setDateReceived(Date dateReceived) {
this.dateReceived = dateReceived;
}
/**
* @return
*/
public Date getDateOfLastProcessingAttempt() {
Date date = null;
if (CollectionUtils.isNotEmpty(getProcessingLog())) {
date = getProcessingLog().iterator().next().getDateTime();
}
return date;
}
/**
* Creates a successful processing log entry.
* @param payload
*/
public void addSuccess(String payload) {
NotificationProcessingLog log = new NotificationProcessingLog();
log.setDateTime(new Date());
log.setNotification(this);
log.setPayload(payload);
log.setProcessingResult(ProcessingResult.SUCCESS);
getProcessingLog().add(log);
}
/**
* Creates an unsuccessful processing log entry.
* @param errorMessage
*/
public void addFailure(String errorMessage) {
NotificationProcessingLog log = new NotificationProcessingLog();
log.setDateTime(new Date());
log.setNotification(this);
log.setErrorCode(StringUtils.left(errorMessage,255));
log.setProcessingResult(ProcessingResult.FAILURE);
getProcessingLog().add(log);
}
}
| bsd-3-clause |
spals/appbuilder | monitor-core-test/src/test/java/net/spals/appbuilder/monitor/core/TracerProviderTest.java | 1831 | package net.spals.appbuilder.monitor.core;
import io.opentracing.NoopTracer;
import io.opentracing.NoopTracerFactory;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import org.testng.annotations.Test;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link TracerProvider}
*
* @author tkral
*/
public class TracerProviderTest {
@Test
public void testNoopDefault() {
final TracerPlugin tracerPlugin = mock(TracerPlugin.class);
when(tracerPlugin.createTracer(anyMap())).thenReturn(NoopTracerFactory.create());
final TracerProvider tracerProvider = new TracerProvider(
Collections.singletonMap("noop", tracerPlugin),
Collections.<String, TracerTag>emptyMap()
);
assertThat(tracerProvider.get(), instanceOf(NoopTracer.class));
}
// Run after testNoopDefault because only one GlobalTracer is allowed
@Test(dependsOnMethods = "testNoopDefault")
public void testGlobalTracerRegistration() {
final Tracer tracer = mock(Tracer.class);
final TracerPlugin tracerPlugin = mock(TracerPlugin.class);
when(tracerPlugin.createTracer(anyMap())).thenReturn(tracer);
final TracerProvider tracerProvider = new TracerProvider(
Collections.singletonMap("myTracer", tracerPlugin),
Collections.<String, TracerTag>emptyMap()
);
tracerProvider.tracingSystem = "myTracer";
tracerProvider.get();
assertThat(GlobalTracer.isRegistered(), is(true));
}
}
| bsd-3-clause |
NCIP/cacore-sdk | sdk-toolkit/iso-example-project/junit/src/test/xml/data/M2MBidirectionalXMLDataTest.java | 5055 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC, SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk/LICENSE.txt for details.
*/
package test.xml.data;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.util.Assert;
import gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Employee;
import gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Project;
import gov.nih.nci.iso21090.Ii;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
public class M2MBidirectionalXMLDataTest extends SDKXMLDataTestBase
{
public static String getTestCaseName()
{
return "Many to Many Bidirectional XML Data Test Case";
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch1() throws Exception
{
Employee searchObject = new Employee();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Employee",searchObject );
assertNotNull(results);
assertEquals(10,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Employee result = (Employee)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Employee result2 = (Employee)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch2() throws Exception
{
Project searchObject = new Project();
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Project",searchObject );
assertNotNull(results);
assertEquals(10,results.size());
for(Iterator i = results.iterator();i.hasNext();)
{
Project result = (Project)i.next();
toXML(result);
validateClassElements(result);
validateIso90210Element(result, "id", "extension", result.getId().getExtension());
validateIso90210Element(result, "name", "value", result.getName().getValue());
assertTrue(validateXMLData(result, searchObject.getClass()));
Project result2 = (Project)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* erifies that the associated object is null
*
* @throws Exception
*/
public void testZeroAssociatedObjectsNestedSearch1() throws Exception
{
Employee searchObject = new Employee();
Ii ii = new Ii();
ii.setExtension("7");
searchObject.setId(ii);
Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Employee",searchObject );
assertNotNull(results);
assertEquals(1,results.size());
Iterator i = results.iterator();
Employee result = (Employee)i.next();
toXML(result);
Employee result2 = (Employee)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
Collection projectCollection = result2.getProjectCollection();
assertNull(projectCollection);
}
public void testAssociationNestedSearchHQL1() throws Exception {
HQLCriteria hqlCriteria = new HQLCriteria(
"from gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Employee where id='7'");
Collection results = search(hqlCriteria,
"gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.Employee");
assertNotNull(results);
assertEquals(1,results.size());
Iterator i = results.iterator();
Employee result = (Employee)i.next();
toXML(result);
Employee result2 = (Employee)fromXML(result);
assertNotNull(result2);
assertNotNull(result2.getId().getExtension());
assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
assertNotNull(result2.getName());
Collection projectCollection = result2.getProjectCollection();
assertNull(projectCollection);
}
}
| bsd-3-clause |
digicyc/TinyDiskUI | src/org/msblabs/tinydisk/Radix64.java | 5373 | /*
* Radix64
*
* Handles Base64 encoding and decoding. Aslo PGP/GPG Ascii armour files
* that will be used to hide meta files. Hence the CRC24 checksum used by PGP/GPG
*
*/
package org.msblabs.tinydisk;
/**
*
* @author acidus
*/
public class Radix64 {
private final static byte[] alphabet =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'+', (byte)'/'
};
public static byte [] encode(byte[] in ) {
int iLen = in.length;
int oDataLen = ( iLen * 4 + 2 ) / 3;// output length without padding
int oLen = ( ( iLen + 2 ) / 3 ) * 4;// output length including padding
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
int i0;
int i1;
int i2;
int o0;
int o1;
int o2;
int o3;
while ( ip < iLen ) {
i0 = in[ip++] & 0xff;
i1 = ip < iLen ? in[ip++] & 0xff : 0;
i2 = ip < iLen ? in[ip++] & 0xff : 0;
o0 = i0 >>> 2;
o1 = ( ( i0 & 3 ) << 4 ) | ( i1 >>> 4 );
o2 = ( ( i1 & 0xf ) << 2 ) | ( i2 >>> 6 );
o3 = i2 & 0x3F;
out[op++] = alphabet [o0];
out[op++] = alphabet [o1];
out[op] = op < oDataLen ? alphabet [o2] : (byte) '=';
op++;
out[op] = op < oDataLen ? alphabet [o3] : (byte) '=';
op++;
}
return out;
}
//compute the CRC24 Radix checksum, and base64 it
//ported from C code in RFC2440
public static byte[] checksum (byte [] unencoded) {
long crc = (long) 0xB704CE; //init it
for(int ptr =0; ptr < unencoded.length; ptr++) {
crc ^= (unencoded[ptr]) << 16;
for(int i = 0; i < 8; i++) {
crc <<= 1;
if ( (crc & 0x1000000) > 0)
crc ^= (long) 0x1864CFB; //CRC poly
}
}
//grab the bottom 24 bits
crc = crc & (long) 0xffffff;
//form our bytes to base64
byte [] in = new byte[3];
in[0] = (byte) ((crc >>> 16) & 0xFF);
in[1] = (byte) ((crc >>> 8) & 0xFF);
in[2] = (byte) ((crc) & 0xFF);
return encode(in);
}
public static byte[] decode( byte[] in)
{
int iLen = in.length;
int oLen = (iLen * 3 ) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while ( ip < iLen ) {
//System.out.println("--- " + ip + " of " + iLen);
int concat2 = (mapFrom(in[ip]) << 18) |
(mapFrom(in[ip + 1]) << 12);
if(in[ip + 2] != '=') {
concat2 = concat2 | (mapFrom(in[ip + 2]) << 6);
}
if(in[ip + 3] != '=') {
concat2 = concat2 | (mapFrom(in[ip + 3]));
}
ip += 4;
out[op] = (byte)(((concat2 >> 16) & 0xFF));
//System.out.println("\'" + (char) out[op] + "\'");
out[op + 1] = (byte)(((concat2 >> 8) & 0xFF));
//System.out.println("\'" + (char) out[op + 1] + "\'");
out[op + 2] = (byte)((concat2 & 0xFF));
//System.out.println("\'" + (char) out[op + 2] + "\'");
op += 3;
}
//take care of anything the padding did
//check for chopping off 2 empty array elements because of ==
if(in[in.length -2 ] == '=') {
byte [] tmp = new byte[out.length - 2];
System.arraycopy(out,0, tmp,0,out.length - 2);
out = tmp;
}
//check for chopping off 1 empty array element because of =
else if(in[in.length - 1 ] == '=') {
byte [] tmp = new byte[out.length - 1];
System.arraycopy(out,0, tmp,0,out.length - 1);
out = tmp;
}
return out;
}
//Get Base64 char code from ASCII code
static int mapFrom(int val) {
if(val == '/') {
return 63;
} else if(val == '+') {
return 62;
} else if((val >= '0') && (val <= '9')){
return 52 + val - '0';
} else if((val >= 'A') && (val <= 'Z')) {
return val - 'A';
} else if((val >= 'a') && (val <= 'z')) {
return 26 + val - 'a';
} else {
System.out.println("Not a possible six-bit value");
System.exit(0);
}
return -1;
}//end mapFrom
}
| bsd-3-clause |
luttero/Maud | src/it/unitn/ing/rista/diffr/absorption/NoneAbsorption.java | 2504 | /*
* @(#)NoneAbsorption.java created 07/01/1999 Pergine Vals.
*
* Copyright (c) 1998 Luca Lutterotti All Rights Reserved.
*
* This software is the research result of Luca Lutterotti and it is
* provided as it is as confidential and proprietary information.
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Luca Lutterotti.
*
* THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package it.unitn.ing.rista.diffr.absorption;
import java.lang.*;
import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.awt.*;
import it.unitn.ing.rista.util.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
/**
* The NoneAbsorption is a class
*
*
* @version $Revision: 1.5 $, $Date: 2005/05/06 18:07:25 $
* @author Luca Lutterotti
* @since JDK1.1
*/
public class NoneAbsorption extends Absorption {
public static String[] diclistc = {};
public static String[] diclistcrm = {};
public static String[] classlistc = {};
public static String[] classlistcs = {};
public NoneAbsorption(XRDcat aobj, String alabel) {
super(aobj, alabel);
initXRD();
identifier = "none abs";
IDlabel = "none abs";
description = "none absorption model";
}
public NoneAbsorption(XRDcat aobj) {
this(aobj, "none abs");
}
public NoneAbsorption() {
identifier = "none abs";
IDlabel = "none abs";
description = "none absorption model";
}
public void initConstant() {
Nstring = 0;
Nstringloop = 0;
Nparameter = 0;
Nparameterloop = 0;
Nsubordinate = 0;
Nsubordinateloop = 0;
}
public void initDictionary() {
for (int i = 0; i < totsubordinateloop; i++)
diclist[i] = diclistc[i];
System.arraycopy(diclistcrm, 0, diclistRealMeaning, 0, totsubordinateloop);
for (int i = 0; i < totsubordinateloop - totsubordinate; i++)
classlist[i] = classlistc[i];
for (int i = 0; i < totsubordinate - totparameterloop; i++)
classlists[i] = classlistcs[i];
}
public void initParameters() {
super.initParameters();
}
}
| bsd-3-clause |
delivered/BulkScanDownloader | src/main/java/iris/ShredDownloadedItemResponse.java | 5074 | /**
* ShredDownloadedItemResponse.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package iris;
public class ShredDownloadedItemResponse implements java.io.Serializable {
private iris.OpRequestBillingStatus billingStatus;
private java.lang.Boolean shouldRetry;
public ShredDownloadedItemResponse() {
}
public ShredDownloadedItemResponse(
iris.OpRequestBillingStatus billingStatus,
java.lang.Boolean shouldRetry) {
this.billingStatus = billingStatus;
this.shouldRetry = shouldRetry;
}
/**
* Gets the billingStatus value for this ShredDownloadedItemResponse.
*
* @return billingStatus
*/
public iris.OpRequestBillingStatus getBillingStatus() {
return billingStatus;
}
/**
* Sets the billingStatus value for this ShredDownloadedItemResponse.
*
* @param billingStatus
*/
public void setBillingStatus(iris.OpRequestBillingStatus billingStatus) {
this.billingStatus = billingStatus;
}
/**
* Gets the shouldRetry value for this ShredDownloadedItemResponse.
*
* @return shouldRetry
*/
public java.lang.Boolean getShouldRetry() {
return shouldRetry;
}
/**
* Sets the shouldRetry value for this ShredDownloadedItemResponse.
*
* @param shouldRetry
*/
public void setShouldRetry(java.lang.Boolean shouldRetry) {
this.shouldRetry = shouldRetry;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ShredDownloadedItemResponse)) return false;
ShredDownloadedItemResponse other = (ShredDownloadedItemResponse) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.billingStatus==null && other.getBillingStatus()==null) ||
(this.billingStatus!=null &&
this.billingStatus.equals(other.getBillingStatus()))) &&
((this.shouldRetry==null && other.getShouldRetry()==null) ||
(this.shouldRetry!=null &&
this.shouldRetry.equals(other.getShouldRetry())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getBillingStatus() != null) {
_hashCode += getBillingStatus().hashCode();
}
if (getShouldRetry() != null) {
_hashCode += getShouldRetry().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ShredDownloadedItemResponse.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("uri:iris", ">ShredDownloadedItemResponse"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("billingStatus");
elemField.setXmlName(new javax.xml.namespace.QName("uri:iris", "BillingStatus"));
elemField.setXmlType(new javax.xml.namespace.QName("uri:iris", "OpRequestBillingStatus"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("shouldRetry");
elemField.setXmlName(new javax.xml.namespace.QName("uri:iris", "ShouldRetry"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| bsd-3-clause |
knopflerfish/knopflerfish.org | osgi/bundles_opt/jini/jinidriver/src/org/knopflerfish/bundle/jini/JiniServiceFactory.java | 5497 | /*
* Copyright (c) 2003-2004, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.bundle.jini;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscovery;
import net.jini.lookup.LookupCache;
import net.jini.lookup.ServiceDiscoveryManager;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.jini.JiniDriver;
import java.io.IOException;
import java.util.Dictionary;
/**
* DOCUMENT ME!
*
* @author Nico Goeminne
*/
public class JiniServiceFactory implements org.osgi.framework.ServiceFactory,
org.osgi.service.cm.ManagedService {
static ServiceDiscoveryManager serviceDiscoveryManager = null;
LookupDiscovery lookupDiscovery = null;
String[] lusImportGroups = LookupDiscovery.ALL_GROUPS;
/**
* Creates a new JiniServiceFactory object.
*
* @throws Exception DOCUMENT ME!
*/
public JiniServiceFactory() throws Exception {
// Needed to spawn in order to find the right classes.
Thread curThread = Thread.currentThread();
ClassLoader oldClassLoader = curThread.getContextClassLoader();
curThread.setContextClassLoader(Activator.class.getClassLoader());
lookupDiscovery = new LookupDiscovery(getLusImportGroups());
serviceDiscoveryManager = new ServiceDiscoveryManager(lookupDiscovery,
null);
ServiceTemplate registrarTemplate = new ServiceTemplate(null,
new Class[] { ServiceRegistrar.class }, null);
LookupCache registrarCache = serviceDiscoveryManager.createLookupCache(registrarTemplate,
null, new Listener(ServiceRegistrar.class));
curThread.setContextClassLoader(oldClassLoader);
oldClassLoader = null;
curThread = null;
}
/**
* DOCUMENT ME!
*
* @param bundle DOCUMENT ME!
* @param registration DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Object getService(Bundle bundle, ServiceRegistration registration) {
JiniDriverImpl jiniDriverImpl = new JiniDriverImpl();
Debug.printDebugInfo(10,
"JiniDriver Requested by " + bundle.getBundleId());
return jiniDriverImpl;
}
/**
* DOCUMENT ME!
*
* @param bundle DOCUMENT ME!
* @param registration DOCUMENT ME!
* @param service DOCUMENT ME!
*/
public void ungetService(Bundle bundle, ServiceRegistration registration,
Object service) {
Debug.printDebugInfo(10,
"JiniDriver Released by " + bundle.getBundleId());
JiniDriverImpl jiniDriverImpl = (JiniDriverImpl) service;
jiniDriverImpl.ungetServices();
}
/**
* DOCUMENT ME!
*/
public void terminate() {
serviceDiscoveryManager.terminate();
lookupDiscovery.terminate();
}
// When CM config changes
public void updated(Dictionary props) {
String[] exportGroups = (String[]) props.get(JiniDriver.CM_LUS_EXPORT_GROUPS);
Osgi2Jini.setCMLusExportGroups(exportGroups);
String[] importGroups = (String[]) props.get(JiniDriver.CM_LUS_IMPORT_GROUPS);
importGroups = (importGroups != null) ? importGroups
: LookupDiscovery.ALL_GROUPS;
setLusImportGroups(importGroups);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String[] getLusImportGroups() {
return lusImportGroups;
}
/**
* DOCUMENT ME!
*
* @param lusImportGroups DOCUMENT ME!
*/
public void setLusImportGroups(String[] lusImportGroups) {
this.lusImportGroups = lusImportGroups;
try {
lookupDiscovery.setGroups(lusImportGroups);
} catch (IOException ex) {
}
}
}
| bsd-3-clause |
motech/MOTECH-Mobile | motech-mobile-core/src/main/java/org/motechproject/mobile/core/model/GatewayResponseImpl.java | 7600 | /**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.mobile.core.model;
import org.motechproject.mobile.core.util.MotechIDGenerator;
import java.io.Serializable;
import java.util.Date;
/**
* Date :Jul 24, 2009
* @author Joseph Djomeda (joseph@dreamoval.com)
*/
public class GatewayResponseImpl implements GatewayResponse, Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private GatewayRequest gatewayRequest;
private String gatewayMessageId;
private String recipientNumber;
private MStatus messageStatus;
private String responseText;
// private Set<Transition> transitions = new HashSet<Transition>();
private String requestId;
private Date dateCreated;
private Date lastModified;
public GatewayResponseImpl() {
this.id = MotechIDGenerator.generateID();
}
public GatewayResponseImpl(String gatewayMessageId, String recipientNumber, MStatus messageStatus) {
this();
this.gatewayMessageId = gatewayMessageId;
this.recipientNumber = recipientNumber;
this.messageStatus = messageStatus;
}
private int version = -1;
/*
* @return the version
*/
public int getVersion() {
return version;
}
/*
* @param version the version to set
*/
public void setVersion(int version) {
this.version = version;
}
/*
* @return the messageId
*/
public GatewayRequest getGatewayRequest() {
return gatewayRequest;
}
/*
* @param messageId the messageId to set
*/
public void setGatewayRequest(GatewayRequest gatewayRequest) {
this.gatewayRequest = gatewayRequest;
}
/*
* @return the gatewayMessageId
*/
public String getGatewayMessageId() {
return gatewayMessageId;
}
/*
* @param gatewayMessageId the gatewayMessageId to set
*/
public void setGatewayMessageId(String gatewayMessageId) {
this.gatewayMessageId = gatewayMessageId;
}
/*
* @return the recipientNumber
*/
public String getRecipientNumber() {
return recipientNumber;
}
/*
* @param recipientNumber the recipientNumber to set
*/
public void setRecipientNumber(String recipientNumber) {
this.recipientNumber = recipientNumber;
}
/*
* @return the messageStatus
*/
public MStatus getMessageStatus() {
return messageStatus;
}
/*
* @param messageStatus the messageStatus to set
*/
public void setMessageStatus(MStatus messageStatus) {
this.messageStatus = messageStatus;
}
public String getResponseText() {
return responseText;
}
public void setResponseText(String responseText) {
this.responseText = responseText;
}
/*
* @return the requestId
*/
public String getRequestId() {
return requestId;
}
/*
* @param requestId the requestId to set
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/*
* @return the dateCreated
*/
public Date getDateCreated() {
return dateCreated;
}
/*
* @param dateCreated the dateCreated to set
*/
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/*
* @return the lastModified
*/
public Date getLastModified() {
return lastModified;
}
/*
* @param lastModified the lastModified to set
*/
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
String newLine = System.getProperty("line.separator");
if (this != null) {
sb.append((this.getId() != null) ? "key=Id value=" + this.getId().toString() : "Id is null ");
sb.append(newLine);
sb.append((this.gatewayRequest != null) ? "key=gatewayRequest.Id value=" + this.gatewayRequest.getId() : "gatewayRequest.Id is null ");
sb.append(newLine);
sb.append((this.requestId != null) ? "key=requestId value=" + this.requestId : "requestId is null ");
sb.append(newLine);
sb.append((this.gatewayMessageId != null) ? "key=gatewayMessageID value=" + this.gatewayMessageId : "gatewayMessageId is null ");
sb.append(newLine);
sb.append((this.recipientNumber != null) ? "key=recipientNumber value=" + this.recipientNumber : "recipientNumber is null ");
sb.append(newLine);
sb.append((this.responseText != null) ? "key=tryNumber.Id value=" + this.responseText : "responseText is null ");
sb.append(newLine);
sb.append((this.dateCreated != null) ? "key=dateSent value=" + this.dateCreated.toString() : "dateCreate is null ");
sb.append(newLine);
sb.append((this.lastModified != null) ? "key=lastModified value=" + this.lastModified.toString() : "lastModified is null ");
sb.append(newLine);
sb.append((this.messageStatus != null) ? "key=messageStatus value=" + this.messageStatus.toString() : "messageStatus is null ");
sb.append(newLine);
return sb.toString();
} else {
return "Object is null";
}
}
/*
* @return the id
*/
public Long getId() {
return id;
}
/*
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
}
| bsd-3-clause |
hjwylde/rivers | app/src/main/java/com/hjwylde/rivers/ui/activities/licenses/LicensesActivity.java | 582 | package com.hjwylde.rivers.ui.activities.licenses;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hjwylde.rivers.ui.activities.BaseActivity;
@UiThread
public class LicensesActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new LicensesFragment())
.commit();
}
}
| bsd-3-clause |
saghm/ItsTwitterTime | mobile/src/main/java/me/saghm/itstwittertime/GetUserTask.java | 889 | package me.saghm.itstwittertime;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;
/**
* Created by saghm on 9/21/14.
*/
public class GetUserTask extends AsyncTask<Start, Void, Void> {
protected Void doInBackground(Start...s) {
try {
final Start start = s[0];
start.twitter.setOAuthAccessToken(s[0].accessToken);
final String user = s[0].twitter.getScreenName();
start.runOnUiThread(new Runnable() {
@Override
public void run() {
start.textView.setText("Logged in as " + user);
}
});
} catch(Exception e) {
Log.i("exception", ExceptionParser.parse(e));
}
return null;
}
}
| bsd-3-clause |
DevMine/parsers | java/src/main/java/ch/devmine/javaparser/structures/UnaryExpression.java | 1204 | /*
* Copyright 2014-2015 The DevMine Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package ch.devmine.javaparser.structures;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author lweingart
*/
public class UnaryExpression extends Expr {
private static final String UNARY = "UNARY";
@Getter @SerializedName(value = "expression_name")
private final String expressionName = UNARY;
@Getter @Setter
private String operator;
@Getter @Setter
private Expr operand;
public UnaryExpression() {}
public UnaryExpression(String operator, Expr operand) {
this.operator = operator;
this.operand = operand;
}
@Override
public String toString() {
String e = this.expressionName;
String op1 = this.operator != null ? this.operator : "null";
String op2 = this.operand != null ? this.operand.toString() : "null";
return "Expression name : ".concat(e)
.concat(", operator : ").concat(op1)
.concat(", operand : " ).concat(op2);
}
}
| bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/ReservedValueSetting.java | 2739 | /*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity;
import android.database.Cursor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.common.CoreObject;
import org.hisp.dhis.android.core.common.ObjectWithUidInterface;
@AutoValue
public abstract class ReservedValueSetting implements CoreObject, ObjectWithUidInterface {
@Nullable
public abstract String uid();
@Nullable
public abstract Integer numberOfValuesToReserve();
@NonNull
public static ReservedValueSetting create(Cursor cursor) {
return AutoValue_ReservedValueSetting.createFromCursor(cursor);
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_ReservedValueSetting.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(Long id);
public abstract Builder uid(String uid);
public abstract Builder numberOfValuesToReserve(Integer numberOfValuesToReserve);
public abstract ReservedValueSetting build();
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-lagarto-web/src/main/java/jodd/htmlstapler/HtmlStaplerException.java | 480 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.htmlstapler;
import jodd.exception.UncheckedException;
/**
* HTML stapler exception.
*/
public class HtmlStaplerException extends UncheckedException {
public HtmlStaplerException(Throwable t) {
super(t);
}
public HtmlStaplerException(String message) {
super(message);
}
public HtmlStaplerException(String message, Throwable t) {
super(message, t);
}
} | bsd-3-clause |
FuseMCNetwork/ZSurvivalGames | src/main/java/me/michidk/zsurvivalgames/modules/TNTListener.java | 2948 | package me.michidk.zsurvivalgames.modules;
import me.johnking.jlib.protocol.util.EntityUtilities;
import me.michidk.zsurvivalgames.Main;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.HashMap;
/**
* Copyright by michidk
* Date: 05.10.13
* Time: 13:47
*/
public class TNTListener implements Listener {
private static HashMap<Integer, String> list = new HashMap<>();
public TNTListener() {
Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
}
//canceling destroying tnt
@EventHandler
public void onBlockDestroy(BlockBreakEvent e) {
if (e.getBlock().getType().equals(Material.TNT)) {
e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent e) {
Player p = e.getPlayer();
if (!(e.getBlock().getType() == Material.TNT)) {
return;
}
e.getBlock().setType(Material.AIR);
Location loc = e.getBlock().getLocation();
loc.add(0.5D, 0.5D, 0.5D);
//cast not necessary, but good to know
TNTPrimed tnt = (TNTPrimed) p.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT);
tnt.setFuseTicks(tnt.getFuseTicks() - 30); //recude fuse time by 1.5 seconds
list.put(tnt.getEntityId(), p.getName());
e.setCancelled(false);
}
@EventHandler
public void onExplode(EntityExplodeEvent e) {
if (!(e.getEntity().getType() == EntityType.PRIMED_TNT)) {
return;
}
int EID = e.getEntity().getEntityId();
if (!list.containsKey(EID)) {
return;
}
e.setCancelled(true);
Location l = e.getLocation();
l.getWorld().createExplosion(l.getX(), l.getY(), l.getZ(), 2F, false, false); //normal TNT: 4F
}
@EventHandler
public void onDamage(EntityDamageByEntityEvent e) {
if (e.getCause() != EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) return;
if (!(e.getEntity() instanceof Player || e.getDamager() instanceof Player)) return;
if (e.getEntity().getType() != EntityType.PLAYER) {
e.setCancelled(true);
}
Player damager = Bukkit.getPlayerExact(list.get(e.getDamager().getEntityId()));
EntityUtilities.setKiller((LivingEntity) e.getEntity(), damager, 20 * 10);
}
}
| bsd-3-clause |
rlgomes/dtf | src/java/com/yahoo/dtf/actions/component/Component.java | 4628 | package com.yahoo.dtf.actions.component;
import java.util.ArrayList;
import com.yahoo.dtf.actions.Action;
import com.yahoo.dtf.actions.flowcontrol.Sequence;
import com.yahoo.dtf.actions.protocol.Lock;
import com.yahoo.dtf.components.ComponentHook;
import com.yahoo.dtf.components.ComponentReturnHook;
import com.yahoo.dtf.components.ComponentUnlockHook;
import com.yahoo.dtf.exception.DTFException;
import com.yahoo.dtf.exception.ParseException;
import com.yahoo.dtf.state.DTFState;
/**
* @dtf.tag component
*
* @dtf.since 1.0
* @dtf.author Rodney Gomes
*
* @dtf.tag.desc This tag encapsulates the remote tags that are to be executed
* on components that have been locked and identified by the
* {@dtf.link Lockcomponent} tag. The children tags specified
* within this tag are executed on the component identified by the
* id attribute and all of the events thrown by those children
* tags are replayed back on the runner as if the actions had
* occurred localy so you can record them as you would any local
* activities.
*
* @dtf.tag.example
* <component id="DTFA1">
* <echo>***********************************</echo>
* <echo>This is being printed from the dtfx</echo>
* <echo>***********************************</echo>
* </component>
*
* @dtf.tag.example
* <component id="DTFA2">
* <sleep time="3s"/>
* <echo>This is being printed from the dtfx</echo>
* </component>
*/
public class Component extends Action {
/**
* @dtf.attr id
* @dtf.attr.desc The unique identifier of a component already locked with
* the {@dtf.link Lockcomponent} tag.
*/
private String id = null;
public Component() { }
private static ArrayList<ComponentHook> _hooks =
new ArrayList<ComponentHook>();
private static ArrayList<ComponentReturnHook> _rhooks =
new ArrayList<ComponentReturnHook>();
private static ArrayList<ComponentUnlockHook> _uhooks =
new ArrayList<ComponentUnlockHook>();
public static void registerComponentHook(ComponentHook hook) {
_hooks.add(hook);
}
public static ArrayList<ComponentHook> getComponentHooks() {
return _hooks;
}
public static void registerComponentReturnHook(ComponentReturnHook hook) {
_rhooks.add(hook);
}
public static ArrayList<ComponentReturnHook> getComponentReturnHooks() {
return _rhooks;
}
public static void registerComponentUnlockHook(ComponentUnlockHook hook) {
_uhooks.add(hook);
}
public static ArrayList<ComponentUnlockHook> getComponentUnlockHooks() {
return _uhooks;
}
public void execute() throws DTFException {
execute(true);
}
public void execute(boolean withhooks) throws DTFException {
DTFState state = getState();
Lock lock = state.getComponents().getComponent(getId());
Sequence sequence = new Sequence();
String id = getId();
state.disableReplace();
try {
/*
* We can't try to do handleComponent work on the DTFC, that is
* pointless and will most likely result in some unpredictable
* error.
*/
if ( withhooks ) {
for (int i = 0; i < _hooks.size(); i++) {
long start = System.currentTimeMillis();
ArrayList<Action> others =
_hooks.get(i).handleComponent(id);
sequence.addActions(others);
long stop = System.currentTimeMillis();
if ( Action.getLogger().isDebugEnabled() ) {
Action.getLogger().
debug(_hooks.get(i).getClass().getSimpleName() +
" took " + (stop-start) + "ms.");
}
}
}
sequence.addActions(children());
Action result = getComm().sendActionToCaller(lock.getId(), sequence);
if ( result != null ) result.execute();
} catch (DTFException e) {
e.setComponent(getId());
throw e;
} finally {
state.enableReplace();
}
}
public String getId() throws ParseException { return replaceProperties(id); }
public void setId(String id) { this.id = id; }
}
| bsd-3-clause |
intarsys/runtime | src/de/intarsys/tools/tlv/common/TlvElement.java | 2636 | package de.intarsys.tools.tlv.common;
import de.intarsys.tools.hex.HexTools;
/**
* A TLV element is a "tag, length, value" data structure. First, an identifier
* is expected, followed by a length, followed by the data itself.
* <p>
* This abstract implementation does not imply anything about the encoding of
* the identifier, length or value field. This is deferred to a concrete
* implementation, e.g. a ASN.1 DER implementation.
* <p>
* The TLV element is parsed from an associated {@link TlvInputStream}.
*
*/
abstract public class TlvElement {
protected final int identifier;
protected final byte[] buffer;
protected final int offset;
protected final int length;
protected TlvElement(int identifier, byte[] buffer) {
this(identifier, buffer, 0, buffer.length);
}
protected TlvElement(int identifier, byte[] buffer, int offset, int length) {
assert (buffer != null);
assert (buffer.length >= offset + length);
this.identifier = identifier;
this.buffer = buffer;
this.offset = offset;
this.length = length;
}
abstract public TlvInputStream createTlvInputStream(byte[] pBytes,
int pOffset, int pLength);
/**
* The data part within the TLV element.
*
* @return The data part within the TLV element.
*/
public byte[] getContent() {
byte[] data = new byte[length];
System.arraycopy(buffer, offset, data, 0, length);
return data;
}
/**
* The whole, encoded TLV element.
*
* @return The whole, encoded TLV element.
*/
abstract public byte[] getEncoded();
/**
* The identifier for this TLV element.
* <p>
* An identifier may be made up of different components, see ASN.1.
*
* @return The identifier for this TLV element.
*/
public int getIdentifier() {
return identifier;
}
/**
* The length of the TLV elements data
*
* @return The length of the TLV elements data
*/
public int getLength() {
return length;
}
/**
* A composite {@link TlvElement} contains other {@link TlvElement}
* instances in form of a {@link TlvTemplate}.
*
* @return The contained {@link TlvTemplate} if available.
* @throws TlvFormatException
*/
public TlvTemplate getTemplate() throws TlvFormatException {
return new TlvTemplate(createTlvInputStream(buffer, offset, length));
}
/**
* <code>true</code> if this element contains TLV data itself.
*
* @return <code>true</code> if this element contains TLV data itself.
*/
abstract public boolean isComposite();
@Override
public String toString() {
return "0x" + Integer.toHexString(getIdentifier()) + ":"
+ HexTools.bytesToHexString(buffer, offset, length, true);
}
}
| bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/xdsl/xdslmodemconfig/OvhChannelModeEnum.java | 293 | package net.minidev.ovh.api.xdsl.xdslmodemconfig;
/**
* How the WiFi channel is selected
*/
public enum OvhChannelModeEnum {
Auto("Auto"),
Manual("Manual");
final String value;
OvhChannelModeEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| bsd-3-clause |
NCIP/cab2b | software/dependencies/dynamicextensions/caB2B_2009_JUN_02/src/edu/common/dynamicextensions/ui/webui/action/SelectControlAction.java | 4113 | /*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
/*
* Created on Nov 14, 2006
* @author
*
*/
package edu.common.dynamicextensions.ui.webui.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.common.dynamicextensions.domaininterface.userinterface.ContainerInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.common.dynamicextensions.processor.LoadFormControlsProcessor;
import edu.common.dynamicextensions.processor.ProcessorConstants;
import edu.common.dynamicextensions.ui.util.ControlsUtility;
import edu.common.dynamicextensions.ui.webui.actionform.ControlsForm;
import edu.common.dynamicextensions.ui.webui.util.WebUIManager;
import edu.common.dynamicextensions.util.global.Constants;
/**
* @author preeti_munot
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class SelectControlAction extends BaseDynamicExtensionsAction
{
/**
* @param mapping ActionMapping mapping
* @param form ActionForm form
* @param request HttpServletRequest request
* @param response HttpServletResponse response
* @return ActionForward forward to next action
* @throws DynamicExtensionsApplicationException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws DynamicExtensionsApplicationException
{
try
{
//Get controls form
ControlsForm controlsForm = (ControlsForm) form;
ContainerInterface containerInterface = WebUIManager.getCurrentContainer(request);
if((controlsForm!=null)&&(containerInterface!=null))
{
ControlsUtility.reinitializeSequenceNumbers(containerInterface.getControlCollection(),controlsForm.getControlsSequenceNumbers());
}
//Action can be either add sub-form or add control to form
if (isAddSubFormAction(controlsForm.getUserSelectedTool()))
{
String operationMode = request.getParameter("operationMode");
request.setAttribute("operationMode", operationMode);
return mapping.findForward(Constants.ADD_SUB_FORM);
}
else
{
//Add form control
addControlToForm(containerInterface, controlsForm);
request.setAttribute("controlsList",controlsForm.getChildList());
return mapping.findForward(Constants.SUCCESS);
}
}
catch (Exception e)
{
String actionForwardString = catchException(e, request);
if((actionForwardString==null)||(actionForwardString.equals("")))
{
return mapping.getInputForward();
}
return (mapping.findForward(actionForwardString));
}
}
/**
* @param controlsForm
* @throws DynamicExtensionsApplicationException
* @throws DynamicExtensionsSystemException
*/
private void addControlToForm(ContainerInterface containerInterface, ControlsForm controlsForm) throws DynamicExtensionsSystemException,
DynamicExtensionsApplicationException
{
String oldControlOperation = controlsForm.getControlOperation();
controlsForm.setControlOperation(ProcessorConstants.OPERATION_ADD);
LoadFormControlsProcessor loadFormControlsProcessor = LoadFormControlsProcessor.getInstance();
loadFormControlsProcessor.loadFormControls(controlsForm, containerInterface);
controlsForm.setControlOperation(oldControlOperation);
}
/**
* @param userSelectedTool
* @return
*/
private boolean isAddSubFormAction(String userSelectedTool)
{
if ((userSelectedTool != null) && (userSelectedTool.equals(ProcessorConstants.ADD_SUBFORM_CONTROL)))
{
return true;
}
return false;
}
} | bsd-3-clause |
tsungtingkuo/diffusion | src/similarity/TopicSimilarity.java | 5238 | package similarity;
import java.util.*;
import utility.*;
public class TopicSimilarity {
final public static int UNKNOWN = -1;
final public static int ALLONE = 0;
final public static int RANDOM = 1;
final public static int JACCARD = 2;
final public static int LDA = 3;
final public static int CATEGORY = 4;
int type = UNKNOWN;
String sim = null;
String dataset = null;
String valid = null;
int[] topicList = null;
int[] trainList = null;
int[] testList = null;
double[][] similarities = null;
public TopicSimilarity(String dataset, String valid, String topicListFileName, String trainListFileName, String testListFileName, String similarityFileName) throws Exception {
this(UNKNOWN, dataset, valid, topicListFileName, trainListFileName, testListFileName, "");
this.similarities = Utility.loadDouble2DArray(similarityFileName);
}
public TopicSimilarity(int type, String dataset, String valid, String topicListFileName, String trainListFileName, String testListFileName, String sim) throws Exception {
super();
this.sim = sim;
this.type = type;
this.dataset = dataset;
this.valid = valid;
this.topicList = Utility.loadIntegerArray(topicListFileName);
this.trainList = Utility.loadIntegerArray(trainListFileName);
this.testList = Utility.loadIntegerArray(testListFileName);
}
public void computeSimilarities() throws Exception {
this.similarities = new double[this.topicList.length][this.topicList.length];
switch(this.type) {
case ALLONE:
this.computeAllOneSimilarities();
break;
case RANDOM:
this.computeRandomSimilarities();
break;
case JACCARD:
this.computeJaccardSimilarities();
break;
case LDA:
this.computeLDASimilarities();
break;
case CATEGORY:
this.computeCategorySimilarities();
break;
}
}
public void computeCategorySimilarities() throws Exception {
TreeMap<Integer, Integer> topicToCategory = Utility.loadIntegerToIntegerTreeMap("list/all_category.txt");
for(int i=0; i<this.topicList.length; i++) {
for(int j=0; j<this.topicList.length; j++) {
if(topicToCategory.get(topicList[i]) == topicToCategory.get(topicList[j])) {
this.similarities[i][j] = 1.0;
}
else {
this.similarities[i][j] = 0.0;
}
}
}
}
public void computeLDASimilarities() throws Exception {
double[][] lda = Utility.loadDouble2DArray("topic/" + this.sim + ".txt");
for(int i=0; i<this.topicList.length; i++) {
for(int j=0; j<this.topicList.length; j++) {
this.similarities[i][j] = Utility.computeCosine(lda[i], lda[j]);
//for(int k=0; k<lda[0].length; k++) {
// this.similarities[i][j] += lda[i][k]*lda[j][k];
//}
}
}
}
public void computeAllOneSimilarities() throws Exception {
for(int i=0; i<this.topicList.length; i++) {
for(int j=0; j<this.topicList.length; j++) {
this.similarities[i][j] = 1.0;
}
}
}
public void computeRandomSimilarities() throws Exception {
Random r = new Random();
for(int i=0; i<this.topicList.length; i++) {
for(int j=0; j<this.topicList.length; j++) {
this.similarities[i][j] = r.nextDouble();
}
}
}
public void computeJaccardSimilarities() throws Exception {
for(int i=0; i<this.topicList.length; i++) {
int ti = this.topicList[i];
long[] ai = null;
if(Utility.firstIndexOfIntegerArray(trainList, ti) != -1) {
ai = Utility.loadLongArray("data/" + this.dataset + "_iii/" + this.valid + "train/aggresive_" + ti + "_train.txt");
}
else {
ai = Utility.loadLongArray("data/" + this.dataset + "_iii/" + this.valid + "test/aggresive_" + ti + "_test.txt");
}
for(int j=0; j<this.topicList.length; j++) {
int tj = this.topicList[j];
long[] aj = null;
if(Utility.firstIndexOfIntegerArray(trainList, tj) != -1) {
aj = Utility.loadLongArray("data/" + this.dataset + "_iii/" + this.valid + "train/aggresive_" + tj + "_train.txt");
}
else {
aj = Utility.loadLongArray("data/" + this.dataset + "_iii/" + this.valid + "test/aggresive_" + tj + "_test.txt");
}
this.similarities[i][j] = Utility.computeJaccard(ai, aj);
}
}
}
public void saveSimilarities(String fileName) throws Exception {
Utility.saveDouble2DArray(fileName, this.similarities);
}
public void computeAndSaveSimilarities(String fileName) throws Exception {
this.computeSimilarities();
this.saveSimilarities(fileName);
}
public double getSimilarity(int topic1, int topic2) {
int index1 = Utility.firstIndexOfIntegerArray(this.topicList, topic1);
int index2 = Utility.firstIndexOfIntegerArray(this.topicList, topic2);
return this.similarities[index1][index2];
}
public double getNormalizedSimilarity(int topic1, int topic2) {
int index1 = Utility.firstIndexOfIntegerArray(this.topicList, topic1);
int index2 = Utility.firstIndexOfIntegerArray(this.topicList, topic2);
double[] normalized = Utility.getNormalizedSumScoreArray(this.similarities[index1]);
return normalized[index2];
}
/**
* @return the similarities
*/
public double[][] getSimilarities() {
return similarities;
}
}
| bsd-3-clause |
Parrot-Developers/libARUtils | gen/JNI/java/com/parrot/arsdk/arutils/ARUTILS_FTP_TYPE_ENUM.java | 3682 | /*
Copyright (C) 2014 Parrot SA
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Parrot nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/*
* GENERATED FILE
* Do not modify this file, it will be erased during the next configure run
*/
package com.parrot.arsdk.arutils;
import java.util.HashMap;
/**
* Java copy of the eARUTILS_FTP_TYPE enum
*/
public enum ARUTILS_FTP_TYPE_ENUM {
/** Dummy value for all unknown cases */
eARUTILS_FTP_TYPE_UNKNOWN_ENUM_VALUE (Integer.MIN_VALUE, "Dummy value for all unknown cases"),
ARUTILS_FTP_TYPE_GENERIC (0),
ARUTILS_FTP_TYPE_UPDATE (1),
ARUTILS_FTP_TYPE_FLIGHTPLAN (2),
ARUTILS_FTP_TYPE_MAX (3);
private final int value;
private final String comment;
static HashMap<Integer, ARUTILS_FTP_TYPE_ENUM> valuesList;
ARUTILS_FTP_TYPE_ENUM (int value) {
this.value = value;
this.comment = null;
}
ARUTILS_FTP_TYPE_ENUM (int value, String comment) {
this.value = value;
this.comment = comment;
}
/**
* Gets the int value of the enum
* @return int value of the enum
*/
public int getValue () {
return value;
}
/**
* Gets the ARUTILS_FTP_TYPE_ENUM instance from a C enum value
* @param value C value of the enum
* @return The ARUTILS_FTP_TYPE_ENUM instance, or null if the C enum value was not valid
*/
public static ARUTILS_FTP_TYPE_ENUM getFromValue (int value) {
if (null == valuesList) {
ARUTILS_FTP_TYPE_ENUM [] valuesArray = ARUTILS_FTP_TYPE_ENUM.values ();
valuesList = new HashMap<Integer, ARUTILS_FTP_TYPE_ENUM> (valuesArray.length);
for (ARUTILS_FTP_TYPE_ENUM entry : valuesArray) {
valuesList.put (entry.getValue (), entry);
}
}
ARUTILS_FTP_TYPE_ENUM retVal = valuesList.get (value);
if (retVal == null) {
retVal = eARUTILS_FTP_TYPE_UNKNOWN_ENUM_VALUE;
}
return retVal; }
/**
* Returns the enum comment as a description string
* @return The enum description
*/
public String toString () {
if (this.comment != null) {
return this.comment;
}
return super.toString ();
}
}
| bsd-3-clause |
motech/MOTECH-Mobile | motech-mobile-modemgw/src/main/java/org/motechproject/mobile/modemgw/ModemGatewayMessageHandlerImpl.java | 4080 | /**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.mobile.modemgw;
import org.motechproject.mobile.core.manager.CoreManager;
import org.motechproject.mobile.core.model.GatewayRequest;
import org.motechproject.mobile.core.model.GatewayResponse;
import org.motechproject.mobile.core.model.MStatus;
import org.motechproject.mobile.omp.manager.GatewayMessageHandler;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ModemGatewayMessageHandlerImpl implements GatewayMessageHandler {
CoreManager coreManager;
MStatus defaultStatus = MStatus.PENDING;
MStatus defaultResponse = MStatus.SCHEDULED;
Map<String, MStatus> responseMap;
Map<String, MStatus> statusMap;
public CoreManager getCoreManager() {
return coreManager;
}
public void setCoreManager(CoreManager coreManager) {
this.coreManager = coreManager;
}
public void setResponseMap(Map<String, MStatus> responseMap) {
this.responseMap = responseMap;
}
public MStatus lookupResponse(String responseCode) {
MStatus responseStatus = responseMap.get(responseCode);
return responseStatus != null ? responseStatus : defaultResponse;
}
public void setStatusMap(Map<String, MStatus> statusMap) {
this.statusMap = statusMap;
}
public MStatus lookupStatus(String statusCode) {
MStatus status = responseMap.get(statusCode);
return status != null ? status : defaultStatus;
}
@SuppressWarnings("unchecked")
public Set<GatewayResponse> parseMessageResponse(GatewayRequest msg,
String gatewayResponse) {
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
GatewayResponse response = coreManager.createGatewayResponse();
// Use the gateway request id as gateway message id
response.setGatewayMessageId(msg.getRequestId());
response.setGatewayRequest(msg);
response.setRecipientNumber(msg.getRecipientsNumber());
response.setRequestId(msg.getRequestId());
response.setResponseText(gatewayResponse);
response.setMessageStatus(lookupStatus(gatewayResponse));
response.setDateCreated(new Date());
responses.add(response);
return responses;
}
public MStatus parseMessageStatus(String gatewayResponse) {
return lookupStatus(gatewayResponse);
}
}
| bsd-3-clause |
act262/freeline | freeline-runtime/src/main/java/com/antfortune/freeline/router/schema/GetSyncTicketSchema.java | 1223 | package com.antfortune.freeline.router.schema;
import android.text.TextUtils;
import android.util.Log;
import com.antfortune.freeline.FreelineCore;
import com.antfortune.freeline.router.ISchemaAction;
import com.antfortune.freeline.server.EmbedHttpServer;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Created by hejie on 17/4/17
*/
public class GetSyncTicketSchema implements ISchemaAction {
private static final String TAG = "Freeline.GetSyncTicket";
@Override
public String getDescription() {
return "getSyncTicket";
}
@Override
public void handle(String method, String path, HashMap<String, String> headers, Map<String, String> queries, InputStream input, EmbedHttpServer.ResponseOutputStream response) throws Exception {
long apkBuildFlag = FreelineCore.getApkBuildFlag();
long lastSync = FreelineCore.getLastDynamicSyncId() + apkBuildFlag;
Log.i(TAG, "apkBuildFlag: " + apkBuildFlag);
Log.i(TAG, "lastSync: " + lastSync);
String result = "{'apkBuildFlag':"+apkBuildFlag+",'lastSync':"+lastSync+"}";
response.setContentTypeText();
response.write(result.getBytes("utf-8"));
}
}
| bsd-3-clause |