repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/administrative/domain/ContainerActivityLog.java | 2061 | package com.krishagni.catissueplus.core.administrative.domain;
import java.util.Date;
import org.hibernate.envers.Audited;
import com.krishagni.catissueplus.core.biospecimen.domain.BaseEntity;
@Audited
public class ContainerActivityLog extends BaseEntity {
private StorageContainer container;
private ScheduledContainerActivity activity;
private ContainerTask task;
private User performedBy;
private Date activityDate;
private Integer timeTaken;
private String comments;
private String activityStatus;
public StorageContainer getContainer() {
return container;
}
public void setContainer(StorageContainer container) {
this.container = container;
}
public ScheduledContainerActivity getActivity() {
return activity;
}
public void setActivity(ScheduledContainerActivity activity) {
this.activity = activity;
}
public ContainerTask getTask() {
return task;
}
public void setTask(ContainerTask task) {
this.task = task;
}
public User getPerformedBy() {
return performedBy;
}
public void setPerformedBy(User performedBy) {
this.performedBy = performedBy;
}
public Date getActivityDate() {
return activityDate;
}
public void setActivityDate(Date activityDate) {
this.activityDate = activityDate;
}
public Integer getTimeTaken() {
return timeTaken;
}
public void setTimeTaken(Integer timeTaken) {
this.timeTaken = timeTaken;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getActivityStatus() {
return activityStatus;
}
public void setActivityStatus(String activityStatus) {
this.activityStatus = activityStatus;
}
public void update(ContainerActivityLog other) {
setContainer(other.getContainer());
setActivity(other.getActivity());
setTask(other.getTask());
setPerformedBy(other.getPerformedBy());
setActivityDate(other.getActivityDate());
setTimeTaken(other.getTimeTaken());
setComments(other.getComments());
setActivityStatus(other.getActivityStatus());
}
}
| bsd-3-clause |
chrlembeck/codegen | codegen-generator/src/main/java/de/chrlembeck/codegen/generator/lang/ObjectCallSource.java | 1049 | package de.chrlembeck.codegen.generator.lang;
/**
* Referenz auf ein Objekt, dessen Attribut ausgelesen soll oder dessen Methode aufgerufen werden soll.
*
* @author Christoph Lembeck
*/
public class ObjectCallSource implements CallSource {
/**
* Enthaltenes Objekt mit dazugehörigem Typ für die Auswertung zur Template-Generator-Laufzeit.
*/
private ObjectWithType<?> objectWithType;
/**
* Erzeugt ein neues Wrapper-Objekt mit dem übergebenen Objekt als Quelle.
*
* @param objectRef
* Objekt, dessen Attribut ausgelesen soll oder dessen Methode aufgerufen werden soll.
*/
public ObjectCallSource(final ObjectWithType<?> objectRef) {
this.objectWithType = objectRef;
}
/**
* Gibt das Objekt zurück, dass als Quelle für den Aufruf verwendet werden soll.
*
* @return Objekt, dessen Attribut ausgelesen soll oder dessen Methode aufgerufen werden soll.
*/
public Object getObjectRef() {
return objectWithType.getObject();
}
} | bsd-3-clause |
fdicerbo/fiware-dba | src/main/java/com/sap/dpre/mySQL/MySQLQueryExecutor_Util.java | 7368 | /*******************************************************************************
* Copyright (c) 2013, SAP AG
* 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 SAP AG 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.
******************************************************************************/
package com.sap.dpre.mySQL;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import com.sap.dpre.log.MyLogger;
import com.sap.dpre.ws.DBA_utils;
public class MySQLQueryExecutor_Util {
/**
* Reads the DB dump and store the data into the database using the passed statement stmt. The gid is used to create the table name
* @param dbDump
* @param stmt
* @param gid
* @return
* @throws IOException
* @throws SQLException
*/
static String parseAndApplyTransaction (InputStream dbDump, Statement stmt, long gid) throws IOException, SQLException {
MyLogger logger = MyLogger.getInstance();
logger.writeLog(Level.ALL,"Method parseAndApplyTransaction");
BufferedInputStream inputStream = new BufferedInputStream(dbDump);
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream));
String bufferString ="", tmpString ="";
int currentIndex=-1, previousIndex=0;
String dumpTableName = "";
String dbTableName = "";
String createStatement = "CREATE TABLE `";
String insertStatement = "INSERT INTO `";
while ((tmpString = inputStreamReader.readLine())!= null) {
if (tmpString.indexOf("--", previousIndex) == 0) {
// this line is a comment! let's forget about it
// bufferString = "";
} else if (tmpString.length() != 0) {
// we look for ';', that means end of SQL statement
if(tmpString.startsWith("CREATE TABLE") && dumpTableName.equals("")){
boolean startTableName = false;
for(int i=0; i<tmpString.length(); i++){
if(tmpString.charAt(i) == '`'){
startTableName = !startTableName;
if(!startTableName) break;
}
if(startTableName && tmpString.charAt(i) != '`')
dumpTableName = dumpTableName+tmpString.charAt(i);
}
dbTableName = createNewName(dumpTableName, gid);
MySQLConnection.getInstance().setMyTableName(dbTableName);
}
if(!dumpTableName.equals("")){
bufferString += tmpString;
currentIndex=bufferString.indexOf(";", previousIndex);
// we ensure that a valid SQL command is contained into
// bufferString, i.e., the String must contain at least a ";"
while (currentIndex - previousIndex <= 0) {
tmpString += inputStreamReader.readLine();
if (tmpString.contains(";")) {
bufferString = tmpString;
currentIndex=bufferString.indexOf(";", previousIndex);
}
}
// at this point, in previousIndex there is the last location where
// SQL statement started, and in currentIndex there is the current
// ';' location
// this function manages all the ";" that are found on the
// bufferString
if(tmpString.startsWith(createStatement+dumpTableName+"`") || tmpString.startsWith(insertStatement+dumpTableName+"`"))
parseSQLStatementsInString(bufferString.replaceFirst(dumpTableName, dbTableName), stmt, gid);
previousIndex =0;
bufferString="";
}
}
}
return dbTableName;
}
/**
* Creates the name of the table where the DB dump has to be stored
* @param tableName
* @param gid
* @return Table name
*/
public static String createNewName(String tableName, long gid) {
MyLogger logger = MyLogger.getInstance();
logger.writeLog(Level.ALL, "Method createNewName, tableName:"+tableName+", gid:"+gid);
String compositeTableName = tableName+gid;
int hash = compositeTableName.hashCode();
if(hash < 0) hash = -1 * hash;
String newTableName = tableName+"_"+hash;
return newTableName;
}
/**
* this function manages all the ";" that are found on the bufferString
* @param bufferString
* @param previousIndex
* @param currentIndex
* @param stmt
* @return
* @throws SQLException
*/
public static String[] parseSQLStatementsInString(String bufferString, Statement stmt, long gid) throws SQLException {
MyLogger logger = MyLogger.getInstance();
logger.writeLog(Level.ALL, "Start method parseSQLStatementsInString," +
" gid:"+gid+
" bufferString:"+bufferString+
", thread number:"+
Thread.currentThread().getId());
int currentIndex = bufferString.length()-1;
int previousIndex = 0;
Vector<String> returnArray = new Vector<String>();
int j=0;
while (bufferString.contains(";")) {
if (previousIndex != currentIndex) {
String currentSQLStatement = null;
try{
currentSQLStatement = bufferString.substring(previousIndex, currentIndex+1);
}catch(StringIndexOutOfBoundsException e){
logger.writeLog(Level.ALL, "Error:"+e.getLocalizedMessage());
logger.writeLog(Level.ALL, "bufferString:"+bufferString +
"previousIndex:"+previousIndex +
"currentIndex:"+currentIndex);
}
// execute query
if (stmt != null) {
stmt.execute(currentSQLStatement);
}
returnArray.add(currentSQLStatement);
// adjust any remainder data
bufferString = bufferString.substring(currentIndex+1);
}
// we check if there are still ";" in the bufferString,
// that in case can be parsed now
currentIndex = bufferString.indexOf(";");
previousIndex =0;
}
String [] toReturn = new String[returnArray.size()];
int i =0;
for (Iterator iterator = returnArray.iterator(); iterator.hasNext();) {
toReturn[i++]= (String) iterator.next();
}
logger.writeLog(Level.ALL, "End method parseSQLStatementsInString");
return toReturn;
}
}
| bsd-3-clause |
sfhsfembot/RecycledRushDriveTrain | src/org/usfirst/frc692/RecycledRushDriveTrain/RobotMap.java | 4711 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc692.RecycledRushDriveTrain;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.PIDSource.PIDSourceParameter;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.TalonSRX;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static SpeedController driveTrainleftFrontTalon0;
public static SpeedController driveTrainleftBackTalon1;
public static SpeedController driveTrainrightFrontTalon2;
public static SpeedController driveTrainrightBackTalon3;
public static RobotDrive driveTrainRobotDrive;
public static Gyro driveTraingyro;
public static Encoder driveTrainleftFrontEncoder;
public static Encoder driveTrainleftBackEncoder;
public static Encoder driveTrainrightFrontEncoder;
public static Encoder driveTrainrightBackEncoder;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static void init() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driveTrainleftFrontTalon0 = new TalonSRX(0);
LiveWindow.addActuator("DriveTrain", "leftFrontTalon0", (TalonSRX) driveTrainleftFrontTalon0);
driveTrainleftBackTalon1 = new TalonSRX(1);
LiveWindow.addActuator("DriveTrain", "leftBackTalon1", (TalonSRX) driveTrainleftBackTalon1);
driveTrainrightFrontTalon2 = new TalonSRX(2);
LiveWindow.addActuator("DriveTrain", "rightFrontTalon2", (TalonSRX) driveTrainrightFrontTalon2);
driveTrainrightBackTalon3 = new TalonSRX(3);
LiveWindow.addActuator("DriveTrain", "rightBackTalon3", (TalonSRX) driveTrainrightBackTalon3);
driveTrainRobotDrive = new RobotDrive(driveTrainleftFrontTalon0, driveTrainleftBackTalon1,
driveTrainrightFrontTalon2, driveTrainrightBackTalon3);
driveTrainRobotDrive.setSafetyEnabled(true);
driveTrainRobotDrive.setExpiration(0.1);
driveTrainRobotDrive.setSensitivity(0.5);
driveTrainRobotDrive.setMaxOutput(1.0);
driveTraingyro = new Gyro(0);
LiveWindow.addSensor("DriveTrain", "gyro", driveTraingyro);
driveTraingyro.setSensitivity(0.007);
driveTrainleftFrontEncoder = new Encoder(17, 18, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "leftFrontEncoder", driveTrainleftFrontEncoder);
driveTrainleftFrontEncoder.setDistancePerPulse(1.0);
driveTrainleftFrontEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
driveTrainleftBackEncoder = new Encoder(19, 20, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "leftBackEncoder", driveTrainleftBackEncoder);
driveTrainleftBackEncoder.setDistancePerPulse(1.0);
driveTrainleftBackEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
driveTrainrightFrontEncoder = new Encoder(21, 22, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "rightFrontEncoder", driveTrainrightFrontEncoder);
driveTrainrightFrontEncoder.setDistancePerPulse(1.0);
driveTrainrightFrontEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
driveTrainrightBackEncoder = new Encoder(23, 24, false, EncodingType.k4X);
LiveWindow.addSensor("DriveTrain", "rightBackEncoder", driveTrainrightBackEncoder);
driveTrainrightBackEncoder.setDistancePerPulse(1.0);
driveTrainrightBackEncoder.setPIDSourceParameter(PIDSourceParameter.kRate);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
}
| bsd-3-clause |
mafagafogigante/dungeon | src/main/java/org/mafagafogigante/dungeon/world/LuminosityVisibilityCriterion.java | 885 | package org.mafagafogigante.dungeon.world;
import org.mafagafogigante.dungeon.entity.Luminosity;
import org.mafagafogigante.dungeon.entity.creatures.Observer;
import org.mafagafogigante.dungeon.io.Version;
import java.io.Serializable;
/**
* A visibility criterion based on luminosity.
*/
public class LuminosityVisibilityCriterion implements Serializable, VisibilityCriterion {
private static final long serialVersionUID = Version.MAJOR;
private final Luminosity minimumLuminosity;
public LuminosityVisibilityCriterion(Luminosity minimumLuminosity) {
this.minimumLuminosity = minimumLuminosity;
}
@Override
public boolean isMetBy(Observer observer) {
double observerLuminosity = observer.getObserverLocation().getLuminosity().toPercentage().toDouble();
return Double.compare(observerLuminosity, minimumLuminosity.toPercentage().toDouble()) >= 0;
}
}
| bsd-3-clause |
lockss/lockss-daemon | src/org/lockss/protocol/BlockingStreamComm.java | 74623 | /*
* $Id$
*/
/*
Copyright (c) 2000-2014 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.protocol;
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import java.util.*;
import org.apache.commons.collections.*;
import org.apache.commons.collections.bag.TreeBag; // needed to disambiguate
import EDU.oswego.cs.dl.util.concurrent.*;
import org.lockss.util.*;
import org.lockss.util.Queue;
import org.lockss.config.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
import org.lockss.app.*;
import org.lockss.poller.*;
/**
* BlockingStreamComm implements the streaming mesaage protocol using
* blocking sockets.
*/
public class BlockingStreamComm
extends BaseLockssDaemonManager
implements ConfigurableManager, LcapStreamComm, PeerMessage.Factory {
static Logger log = Logger.getLogger("SComm");
public static final String SERVER_NAME = "StreamComm";
/** Use V3 over SSL **/
public static final String PARAM_USE_V3_OVER_SSL = PREFIX + "v3OverSsl";
public static final boolean DEFAULT_USE_V3_OVER_SSL = false;
/** Use client authentication for SSL **/
public static final String PARAM_USE_SSL_CLIENT_AUTH =
PREFIX + "sslClientAuth";
public static final boolean DEFAULT_USE_SSL_CLIENT_AUTH = true;
/** Name of managed keystore to use for both my private key and peers'
* public keys (see org.lockss.keyMgr.keystore.<i>id</i>.name). Set
* either this, or both sslPrivateKeystoreName and
* sslPublicKeystoreName. */
public static final String PARAM_SSL_KEYSTORE_NAME =
PREFIX + "sslKeystoreName";
/** Name of managed keystore to use for my private key (see
* org.lockss.keyMgr.keystore.<i>id</i>.name). */
public static final String PARAM_SSL_PRIVATE_KEYSTORE_NAME =
PREFIX + "sslPrivateKeystoreName";
/** Name of managed keystore in which to look for peers' public keys (see
* org.lockss.keyMgr.keystore.<i>id</i>.name). */
public static final String PARAM_SSL_PUBLIC_KEYSTORE_NAME =
PREFIX + "sslPublicKeystoreName";
/** An SSLContext that supports this protocol will be obtained. Note
* that this is just passed to <code>SSLContent.getInstance()</code>;
* sockets obtained from resulting factory will likely support other
* protocols. To ensure that other protocols are not used they should be
* included in <code>org.lockss.scomm.disableSslServerProtocols</code>
* and <code>org.lockss.scomm.disableSslClientProtocols</code> */
public static final String PARAM_SSL_PROTOCOL = PREFIX + "sslProtocol";
public static final String DEFAULT_SSL_PROTOCOL = "TLSv1.2";
/** SSL protocols to disable in server sockets. */
public static final String PARAM_DISABLE_SSL_SERVER_PROTOCOLS =
PREFIX + "disableSslServerProtocols";
public static final List DEFAULT_DISABLE_SSL_SERVER_PROTOCOLS =
ListUtil.list("SSLv3", "SSLv2Hello");
/** SSL protocols to disable in client sockets. */
public static final String PARAM_DISABLE_SSL_CLIENT_PROTOCOLS =
PREFIX + "disableSslClientProtocols";
public static final List DEFAULT_DISABLE_SSL_CLIENT_PROTOCOLS =
ListUtil.list("SSLv3", "SSLv2Hello");
/** If true, listen socket will be bound only to the configured local IP
* address **/
public static final String PARAM_BIND_TO_LOCAL_IP_ONLY =
PREFIX + "bindToLocalIpOnly";
public static final boolean DEFAULT_BIND_TO_LOCAL_IP_ONLY = false;
/** If true, when the listen socket is bound to the local IP address,
* outgoing connections will also be made from that address. Should
* normally be true; some testing situations require special behavior. */
public static final String PARAM_SEND_FROM_BIND_ADDR =
PREFIX + "sendFromBindAddr";
public static final boolean DEFAULT_SEND_FROM_BIND_ADDR = true;
/** Max peer channels. Only affects outgoing messages; incoming
* connections are always accepted. */
public static final String PARAM_MAX_CHANNELS =
PREFIX + "maxChannels";
public static final int DEFAULT_MAX_CHANNELS = 50;
/** Min threads in channel thread pool */
public static final String PARAM_CHANNEL_THREAD_POOL_MIN =
PREFIX + "threadPool.min";
public static final int DEFAULT_CHANNEL_THREAD_POOL_MIN = 3;
/** Max threads in channel thread pool */
public static final String PARAM_CHANNEL_THREAD_POOL_MAX =
PREFIX + "threadPool.max";
public static final int DEFAULT_CHANNEL_THREAD_POOL_MAX = 3 * DEFAULT_MAX_CHANNELS;
/** Duration after which idle threads will be terminated.. -1 = never */
public static final String PARAM_CHANNEL_THREAD_POOL_KEEPALIVE =
PREFIX + "threadPool.keepAlive";
public static final long DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE =
10 * Constants.MINUTE;
/** Connect timeout */
public static final String PARAM_CONNECT_TIMEOUT =
PREFIX + "timeout.connect";
public static final long DEFAULT_CONNECT_TIMEOUT = 2 * Constants.MINUTE;
/** Data timeout (SO_TIMEOUT), channel is aborted if read times out.
* This should be disabled (zero) because the read side of a channel may
* legitimately be idle for a long time (if the channel is sending), and
* interrupted reads apparently cannot reliably be resumed. If the
* channel is truly idle, the send side should close it. */
public static final String PARAM_DATA_TIMEOUT =
PREFIX + "timeout.data";
public static final long DEFAULT_DATA_TIMEOUT = 0;
/** Data timeout (SO_TIMEOUT) during SSL negotiation (if any). Channel
* isn't fully set up yet and idle timeout isn't in effect. Data timeout
* ({@value PARAM_DATA_TIMEOUT} may be zero, but SSL negotiation should
* always have a timeout. */
public static final String PARAM_SSL_HANDSHAKE_TIMEOUT =
PREFIX + "timeout.sslHandshake";
public static final long DEFAULT_SSL_HANDSHAKE_TIMEOUT = 5 * Constants.MINUTE;
/** Enable SO_KEEPALIVE if true */
public static final String PARAM_SOCKET_KEEPALIVE =
PREFIX + "socketKeepAlive";
public static final boolean DEFAULT_SOCKET_KEEPALIVE = true;
/** Enable TCP_NODELAY if true */
public static final String PARAM_TCP_NODELAY = PREFIX + "tcpNoDelay";
public static final boolean DEFAULT_TCP_NODELAY = true;
/** Time after which idle channel will be closed */
public static final String PARAM_CHANNEL_IDLE_TIME =
PREFIX + "channelIdleTime";
public static final long DEFAULT_CHANNEL_IDLE_TIME = 2 * Constants.MINUTE;
/** Time channel remains in DRAIN_INPUT state before closing */
public static final String PARAM_DRAIN_INPUT_TIME =
PREFIX + "drainInputTime";
public static final long DEFAULT_DRAIN_INPUT_TIME = 10 * Constants.SECOND;
/** Interval at which send thread checks idle timer */
public static final String PARAM_SEND_WAKEUP_TIME =
PREFIX + "sendWakeupTime";
public static final long DEFAULT_SEND_WAKEUP_TIME = 1 * Constants.MINUTE;
/** Interval before message expiration time at which to retry */
public static final String PARAM_RETRY_BEFORE_EXPIRATION =
PREFIX + "retryBeforeExpiration";
public static final long DEFAULT_RETRY_BEFORE_EXPIRATION =
1 * Constants.MINUTE;
/** Max time to wait and retry connection to unresponsive peer. May
* happen sooner if queued messages will expire sooner */
public static final String PARAM_MAX_PEER_RETRY_INTERVAL =
PREFIX + "maxPeerRetryInterval";
public static final long DEFAULT_MAX_PEER_RETRY_INTERVAL =
30 * Constants.MINUTE;
/** Min time to wait and retry connection to unresponsive peer. */
public static final String PARAM_MIN_PEER_RETRY_INTERVAL =
PREFIX + "minPeerRetryInterval";
public static final long DEFAULT_MIN_PEER_RETRY_INTERVAL =
30 * Constants.SECOND;
/** Min time to wait between retry attempts (channel start interval) */
public static final String PARAM_RETRY_DELAY =
PREFIX + "retryDelay";
public static final long DEFAULT_RETRY_DELAY = 5 * Constants.SECOND;
/** FilePeerMessage will be used for messages larger than this, else
* MemoryPeerMessage */
public static final String PARAM_MIN_FILE_MESSAGE_SIZE =
PREFIX + "minFileMessageSize";
public static final int DEFAULT_MIN_FILE_MESSAGE_SIZE = 1024;
/** Maximum allowable received message size */
public static final String PARAM_MAX_MESSAGE_SIZE =
PREFIX + "maxMessageSize";
public static final long DEFAULT_MAX_MESSAGE_SIZE = 1024 * 1024 * 1024;
/** Per-peer message send rate limit. Messages queued for send in excess
* of this rate will be discarded and counted */
public static final String PARAM_PEER_SEND_MESSAGE_RATE_LIMIT =
PREFIX + "peerSendMessageRateLimit";
public static final String DEFAULT_PEER_SEND_MESSAGE_RATE_LIMIT =
"unlimited";
/** Per-peer message receive rate limit. Messages received in excess of
* this rate will be discarded and counted */
public static final String PARAM_PEER_RECEIVE_MESSAGE_RATE_LIMIT =
PREFIX + "peerReceiveMessageRateLimit";
public static final String DEFAULT_PEER_RECEIVE_MESSAGE_RATE_LIMIT =
"unlimited";
/** Rough transmission speed will be measured for messages at least this
* large, reported at debug level */
public static final String PARAM_MIN_MEASURED_MESSAGE_SIZE =
PREFIX + "minMeasuredMessageSize";
public static final long DEFAULT_MIN_MEASURED_MESSAGE_SIZE = 5 * 1024 * 1024;
/** Dir for PeerMessage data storage */
public static final String PARAM_DATA_DIR = PREFIX + "messageDataDir";
/** Default is PlatformInfo.getSystemTempDir() */
public static final String DEFAULT_DATA_DIR = "Platform tmp dir";
/** Wrap Socket OutputStream in BufferedOutputStream? */
public static final String PARAM_IS_BUFFERED_SEND = PREFIX + "bufferedSend";
public static final boolean DEFAULT_IS_BUFFERED_SEND = true;
/** Amount of time BlockingStreamComm.stopService() should wait for
* worker threads to exit. Zero disables wait. */
public static final String PARAM_WAIT_EXIT = PREFIX + "waitExit";
public static final long DEFAULT_WAIT_EXIT = 2 * Constants.SECOND;
/** If true, associated channels that refuse messages will be immediately
* dissociated */
public static final String PARAM_DISSOCIATE_ON_NO_SEND =
PREFIX + "dissociateOnNoSend";
public static final boolean DEFAULT_DISSOCIATE_ON_NO_SEND = true;
/** If true, stopChannel() will dissociate unconditionally, matching the
* previous behavior. If false it will dissociate only if it changes the
* state to CLOSING. */
public static final String PARAM_DISSOCIATE_ON_EVERY_STOP =
PREFIX + "dissociateOnEveryStop";
public static final boolean DEFAULT_DISSOCIATE_ON_EVERY_STOP = false;
/** If true, unknown peer messages opcodes cause the channel to abort */
public static final String PARAM_ABORT_ON_UNKNOWN_OP =
PREFIX + "abortOnUnknownOp";
public static final boolean DEFAULT_ABORT_ON_UNKNOWN_OP = true;
static final String WDOG_PARAM_SCOMM = "SComm";
static final long WDOG_DEFAULT_SCOMM = 1 * Constants.HOUR;
static final String PRIORITY_PARAM_SCOMM = "SComm";
static final int PRIORITY_DEFAULT_SCOMM = -1;
static final String PRIORITY_PARAM_SLISTEN = "SListen";
static final int PRIORITY_DEFAULT_SLISTEN = -1;
static final String WDOG_PARAM_CHANNEL = "Channel";
static final long WDOG_DEFAULT_CHANNEL = 30 * Constants.MINUTE;
static final String PRIORITY_PARAM_CHANNEL = "Channel";
static final int PRIORITY_DEFAULT_CHANNEL = -1;
static final String WDOG_PARAM_RETRY = "SRetry";
static final long WDOG_DEFAULT_RETRY = 1 * Constants.HOUR;
static final String PRIORITY_PARAM_RETRY = "SRetry";
static final int PRIORITY_DEFAULT_RETRY = -1;
private boolean paramUseV3OverSsl = DEFAULT_USE_V3_OVER_SSL;
private boolean paramSslClientAuth = DEFAULT_USE_SSL_CLIENT_AUTH;
private String paramSslPrivateKeyStoreName;
private String paramSslPublicKeyStoreName;
private String paramSslProtocol = DEFAULT_SSL_PROTOCOL;
private List<String> paramDisableSslServerProtocols =
DEFAULT_DISABLE_SSL_SERVER_PROTOCOLS;
private List<String> paramDisableSslClientProtocols =
DEFAULT_DISABLE_SSL_CLIENT_PROTOCOLS;
private int paramMinFileMessageSize = DEFAULT_MIN_FILE_MESSAGE_SIZE;
private long paramMaxMessageSize = DEFAULT_MAX_MESSAGE_SIZE;
private long paramMinMeasuredMessageSize =
DEFAULT_MIN_MEASURED_MESSAGE_SIZE;
private File dataDir = null;
private int paramBacklog = DEFAULT_LISTEN_BACKLOG;
private int paramMaxChannels = DEFAULT_MAX_CHANNELS;
private int paramMinPoolSize = DEFAULT_CHANNEL_THREAD_POOL_MIN;
private int paramMaxPoolSize = DEFAULT_CHANNEL_THREAD_POOL_MAX;
private long paramPoolKeepaliveTime = DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE;
private long paramConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
private long paramSoTimeout = DEFAULT_DATA_TIMEOUT;
private long paramSslHandshakeTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT;
private boolean paramSoKeepAlive = DEFAULT_SOCKET_KEEPALIVE;
private boolean paramIsTcpNoDelay = DEFAULT_TCP_NODELAY;
private long paramSendWakeupTime = DEFAULT_SEND_WAKEUP_TIME;
private long paramRetryBeforeExpiration = DEFAULT_RETRY_BEFORE_EXPIRATION;
private long paramMaxPeerRetryInterval = DEFAULT_MAX_PEER_RETRY_INTERVAL;
private long paramMinPeerRetryInterval = DEFAULT_MIN_PEER_RETRY_INTERVAL;
private long paramRetryDelay = DEFAULT_RETRY_DELAY;
protected long paramChannelIdleTime = DEFAULT_CHANNEL_IDLE_TIME;
private long paramDrainInputTime = DEFAULT_DRAIN_INPUT_TIME;
private boolean paramIsBufferedSend = DEFAULT_IS_BUFFERED_SEND;
private long paramWaitExit = DEFAULT_WAIT_EXIT;
private boolean paramAbortOnUnknownOp = DEFAULT_ABORT_ON_UNKNOWN_OP;
private long lastHungCheckTime = 0;
private PooledExecutor pool;
protected SSLSocketFactory sslSocketFactory = null;
protected SSLServerSocketFactory sslServerSocketFactory = null;
private boolean paramDissociateOnNoSend = DEFAULT_DISSOCIATE_ON_NO_SEND;
private boolean paramDissociateOnEveryStop =
DEFAULT_DISSOCIATE_ON_EVERY_STOP;
private boolean enabled = DEFAULT_ENABLED;
private boolean running = false;
private String bindAddr;
private boolean sendFromBindAddr;
private SocketFactory sockFact;
private ServerSocket listenSock;
private PeerIdentity myPeerId;
private PeerAddress.Tcp myPeerAddr;
private IdentityManager idMgr;
protected LockssKeyStoreManager keystoreMgr;
private OneShot configShot = new OneShot();
private FifoQueue rcvQueue; // PeerMessages received from channels
private ReceiveThread rcvThread;
private ListenThread listenThread;
private RetryThread retryThread;
// Synchronization lock for rcv thread, listen thread manipulations
private Object threadLock = new Object();
// Map holds channels and queue associated with each Peer
Map<PeerIdentity,PeerData> peers = new HashMap<PeerIdentity,PeerData>();
Comparator ROC = new RetryOrderComparator();
TreeSet<PeerData> peersToRetry = new TreeSet<PeerData>(ROC);
// Record of draining channels (no longer associated with peer) so stats
// can find them
Set<BlockingPeerChannel> drainingChannels = new HashSet();
private Vector messageHandlers = new Vector(); // Vector is synchronized
private boolean anyRateLimited;
private RateLimiter.LimiterMap sendRateLimiters =
new RateLimiter.LimiterMap(PARAM_PEER_SEND_MESSAGE_RATE_LIMIT,
DEFAULT_PEER_SEND_MESSAGE_RATE_LIMIT);
private RateLimiter.LimiterMap receiveRateLimiters =
new RateLimiter.LimiterMap(PARAM_PEER_RECEIVE_MESSAGE_RATE_LIMIT,
DEFAULT_PEER_RECEIVE_MESSAGE_RATE_LIMIT);
int nPrimary = 0;
int nSecondary = 0;
int maxPrimary = 0;
int maxSecondary = 0;
int maxDrainingChannels = 0;
Object ctrLock = new Object(); // lock for above counters
// Counts number of successful messages with N retries
Bag retryHist = new TreeBag();
// Counts number of discarded messages with N retries
Bag retryErrHist = new TreeBag();
ChannelStats globalStats = new ChannelStats();
public BlockingStreamComm() {
sockFact = null;
}
class PeerData {
PeerIdentity pid;
BlockingPeerChannel primary;
BlockingPeerChannel secondary;
Queue sendQueue = null; // Non-null only when there are queued
// messages for a peer that has no active
// primary channel.
PeerMessage earliestMsg; // Needed until we have separate channel
// for each poll
long lastRetry = 0;
long nextRetry = TimeBase.MAX; // Time at which we should try again to
// connect and send held msgs.
private int origCnt = 0; // Number of connect attempts
private int failCnt = 0; // Number of connect failures
private int acceptCnt = 0; // Number of incoming connections
int msgsSent = 0;
int sendRateLimited = 0;
int rcvRateLimited = 0;
int msgsRcvd = 0;
int lastSendRpt = 0;
PeerData(PeerIdentity pid) {
this.pid = pid;
}
PeerIdentity getPid() {
return pid;
}
BlockingPeerChannel getPrimaryChannel() {
return primary;
}
BlockingPeerChannel getSecondaryChannel() {
return secondary;
}
int getSendQueueSize() {
Queue q = sendQueue;
return q == null ? 0 : q.size();
}
long getLastRetry() {
return lastRetry;
}
long getNextRetry() {
return nextRetry;
}
long getFirstExpiration() {
if (sendQueue == null || sendQueue.isEmpty()) {
return TimeBase.MAX;
}
PeerMessage msg = earliestMsg;
if (msg == null) {
return TimeBase.MAX;
}
return msg.getExpiration();
}
int getOrigCnt() {
return origCnt;
}
int getFailCnt() {
return failCnt;
}
int getAcceptCnt() {
return acceptCnt;
}
int getMsgsSent() {
return msgsSent;
}
int getMsgsRcvd() {
return msgsRcvd;
}
void sentMsg() {
msgsSent++;
}
void rcvdMsg() {
msgsRcvd++;
}
int getSendRateLimited() {
return sendRateLimited;
}
int getRcvRateLimited() {
return rcvRateLimited;
}
void rcvRateLimited() {
rcvRateLimited++;
anyRateLimited = true;
}
void countPrimary(boolean incr) {
synchronized (ctrLock) {
if (incr) {
nPrimary++;
if (nPrimary > maxPrimary) maxPrimary = nPrimary;
} else {
nPrimary--;
}
}
}
void countSecondary(boolean incr) {
synchronized (ctrLock) {
if (incr) {
nSecondary++;
if (nSecondary > maxSecondary) maxSecondary = nSecondary;
} else {
nSecondary--;
}
}
}
synchronized void associateChannel(BlockingPeerChannel chan) {
acceptCnt++;
if (primary == null) {
primary = chan;
countPrimary(true);
handOffQueuedMsgs(primary);
if (log.isDebug2()) log.debug2("Associated " + chan);
} else if (primary == chan) {
log.warning("Redundant peer-channel association (" + chan + ")");
} else {
if (secondary == null) {
secondary = chan; // normal secondary association
countSecondary(true);
if (log.isDebug2()) log.debug2("Associated secondary " + chan);
} else if (secondary == chan) {
log.debug("Redundant secondary peer-channel association(" +
chan +")");
} else {
// maybe should replace if new working and old not. but old will
// eventually timeout and close anyway
log.warning("Conflicting peer-channel association(" + chan +
"), was " + primary);
}
}
}
// This may be called more than once by the same channel, from its
// multiple worker threads. Redundant calls must be harmless.
synchronized void dissociateChannel(BlockingPeerChannel chan) {
if (primary == chan) {
globalStats.add(primary.getStats());
primary = null;
countPrimary(false);
if (log.isDebug2()) log.debug2("Removed: " + chan);
}
if (secondary == chan) {
globalStats.add(secondary.getStats());
secondary = null;
countSecondary(false);
if (log.isDebug2()) log.debug2("Removed secondary: " + chan);
}
synchronized (drainingChannels) {
if (chan.isState(BlockingPeerChannel.ChannelState.DRAIN_INPUT)
&& chan.getPeer() != null) {
// If this channel is draining, remember it so can include in stats
if (log.isDebug2()) log.debug2("Add to draining: " + chan);
drainingChannels.add(chan);
maxDrainingChannels = Math.max(maxDrainingChannels,
drainingChannels.size());
} else {
// else ensure it's gone
if (drainingChannels.remove(chan)) {
if (log.isDebug2()) log.debug2("Del from draining: " + chan);
}
}
}
}
synchronized void send(PeerMessage msg) throws IOException {
RateLimiter limiter = getSendRateLimiter(pid);
if (limiter != null) {
if (!limiter.isEventOk()) {
sendRateLimited++;
anyRateLimited = true;
log.debug2("Pkt rate limited");
return;
} else {
limiter.event();
}
}
if (sendQueue != null) {
// If queue exists, we're already waiting for connection retry.
if (primary != null) {
log.error("send: sendQueue and primary channel both exist: " +
primary);
}
enqueueHeld(msg, false );
return;
}
// A closing channel might refuse the message (return false), in which
// case it will have dissociated itself so try again with a new
// channel.
BlockingPeerChannel last = null;
int rpt = 0;
boolean retry = true;
while (rpt++ <= 3) {
lastSendRpt = rpt;
BlockingPeerChannel chan = findOrMakeChannel();
if (chan == null) {
break;
}
if (last == chan)
throw new IllegalStateException("Got same channel as last time: "
+ chan);
if (chan.send(msg)) {
return;
}
if (chan.isUnusedOriginatingChannel()) {
log.warning("Couldn't start channel " + chan);
retry = chan.shouldRetry();
break;
}
last = chan;
if (paramDissociateOnNoSend) {
dissociateChannel(chan);
}
}
log.error("Couldn't enqueue msg to channel after "
+ rpt + " tries: " + msg);
if (retry && msg.isRequeueable()) {
// This counts as a connect failure, as the queue was empty when we
// entered
failCnt++;
// XXX Not counting this as a retry causes unpredictable test results
enqueueHeld(msg, true);
}
}
synchronized BlockingPeerChannel findOrMakeChannel() {
if (primary != null) {
return primary;
}
if (secondary != null) {
// found secondary, no primary. promote secondary to primary
primary = secondary;
secondary = null;
countPrimary(true);
countSecondary(false);
log.debug2("Promoted " + primary);
handOffQueuedMsgs(primary);
return primary;
}
// new primary channel, if we have room
if (nPrimary < paramMaxChannels) {
try {
BlockingPeerChannel chan =
getSocketFactory().newPeerChannel(BlockingStreamComm.this, pid);
if (log.isDebug2()) log.debug2("Created " + chan);
try {
handOffQueuedMsgs(chan);
lastRetry = TimeBase.nowMs();
chan.startOriginate();
origCnt++;
primary = chan;
countPrimary(true);
return primary;
} catch (IOException e) {
log.warning("Can't start channel " + chan, e);
return null;
}
} catch (IOException e) {
log.warning("Can't create channel " + pid, e);
return null;
}
}
return null;
}
synchronized void enqueueHeld(PeerMessage msg, boolean isRetry) {
if (sendQueue == null) {
sendQueue = new FifoQueue();
}
if (log.isDebug3()) log.debug3("enqueuing held "+ msg);
BlockingPeerChannel chan = primary;
if (chan != null && !chan.isState(enqueueHeldPrimaryOkStates)) {
log.error("enqueueHeld: primary channel exists: " + primary);
}
sendQueue.put(msg);
if (isRetry) {
msg.incrRetryCount();
}
long retry = calcNextRetry(msg, isRetry);
if (retry < nextRetry) {
synchronized (peersToRetry) {
peersToRetry.remove(this);
earliestMsg = msg;
nextRetry = retry;
if (log.isDebug3()) {
log.debug3("Retry " + pid + " at "
+ Deadline.at(nextRetry).shortString());
}
peersToRetry.add(this);
if (this == peersToRetry.first()) {
retryThread.recalcNext();
}
}
}
}
synchronized void handOffQueuedMsgs(BlockingPeerChannel chan) {
if (sendQueue != null) {
if (log.isDebug2()) {
log.debug2("Handing off " + sendQueue.size() + " msgs to " + chan);
}
chan.enqueueMsgs(sendQueue);
sendQueue = null;
synchronized (peersToRetry) {
peersToRetry.remove(this);
}
nextRetry = TimeBase.MAX;
earliestMsg = null;
}
}
/**
* If channel aborts with unsent messages, queue them to try again later.
*/
synchronized void drainQueue(PeerData pdata,
Queue queue,
boolean shouldRetry) {
// Don't cause trouble if shutting down (happens in unit tests).
if (!isRunning() || queue == null || queue.isEmpty()) {
return;
}
failCnt++;
if (shouldRetry) {
requeueUnsentMsgs(queue);
} else {
deleteMsgs(queue);
}
}
void requeueUnsentMsgs(Queue queue) {
PeerMessage msg;
try {
int requeued = 0;
int deleted = 0;
while ((msg = (PeerMessage)queue.get(Deadline.EXPIRED)) != null) {
if (msg.isRequeueable() && !msg.isExpired()
&& msg.getRetryCount() < msg.getRetryMax()) {
enqueueHeld(msg, true);
requeued++;
} else {
countMessageErrRetries(msg);
msg.delete();
deleted++;
}
}
if (log.isDebug2()) {
log.debug2("Requeued " + requeued + ", deleted " + deleted);
}
} catch (InterruptedException e) {
// can't happen (get doesn't wait)
}
}
void deleteMsgs(Queue queue) {
PeerMessage msg;
try {
while ((msg = (PeerMessage)queue.get(Deadline.EXPIRED)) != null) {
msg.delete();
}
} catch (InterruptedException e) {
// can't happen (get doesn't wait)
}
}
// Called by retry thread when we're the first item in peersToRetry
synchronized boolean retryIfNeeded() {
if (!isRetryNeeded()) {
synchronized (peersToRetry) {
peersToRetry.remove(this);
}
return false;
}
if (primary != null) {
return false;
}
if (TimeBase.nowMs() < getNextRetry()) {
return false;
}
BlockingPeerChannel chan = findOrMakeChannel();
if (chan != null) {
return true;
} else {
log.error("retry: couldn't create channel " + pid);
return false;
}
}
boolean isRetryNeeded() {
if (sendQueue == null) {
return false;
}
if (sendQueue.isEmpty()) {
log.error("Empty send queue " + pid);
return false;
}
return true;
}
long calcNextRetry(PeerMessage msg, boolean isRetry) {
long last = msg.getLastRetry();
long target = TimeBase.MAX;
if (msg.getExpiration() > 0) {
target = msg.getExpiration() - paramRetryBeforeExpiration;
}
long intr = msg.getRetryInterval();
if (intr > 0) {
target = Math.min(target, last + intr);
}
log.debug3("last: " + last
+ ", intr: " + intr
+ ", target: " + target
+ ", minPeer: " + paramMinPeerRetryInterval);
long retry =
Math.max(Math.min(target,
lastRetry + paramMaxPeerRetryInterval),
lastRetry + paramMinPeerRetryInterval);
return retry;
}
synchronized void abortChannels() {
if (primary != null) {
primary.abortChannel();
}
if (secondary != null) {
secondary.abortChannel();
}
}
synchronized void waitChannelsDone(Deadline timeout) {
if (primary != null) {
primary.waitThreadsExited(timeout);
}
if (secondary != null) {
secondary.waitThreadsExited(timeout);
}
}
synchronized void checkHung() {
if (primary != null) {
primary.checkHung();
}
if (secondary != null) {
secondary.checkHung();
}
}
public String toString() {
StringBuilder sb = new StringBuilder(50);
sb.append("[CP: ");
sb.append(pid);
if (nextRetry != TimeBase.MAX) {
sb.append(", ");
sb.append(Deadline.restoreDeadlineAt(nextRetry).shortString());
}
sb.append("]");
return sb.toString();
}
}
static BlockingPeerChannel.ChannelState[] enqueueHeldPrimaryOkStates = {
BlockingPeerChannel.ChannelState.DISSOCIATING,
BlockingPeerChannel.ChannelState.CLOSING};
/**
* start the stream comm manager.
*/
public void startService() {
super.startService();
LockssDaemon daemon = getDaemon();
idMgr = daemon.getIdentityManager();
keystoreMgr = daemon.getKeystoreManager();
resetConfig();
anyRateLimited = false;
try {
myPeerId = getLocalPeerIdentity();
} catch (Exception e) {
log.critical("No V3 identity, not starting stream comm", e);
enabled = false;
return;
}
log.debug("Local V3 peer: " + myPeerId);
PeerAddress pad = myPeerId.getPeerAddress();
if (pad instanceof PeerAddress.Tcp) {
myPeerAddr = (PeerAddress.Tcp)pad;
} else {
log.error("Disabling stream comm; no local TCP peer address: " + pad);
enabled = false;
}
if (enabled) {
start();
StatusService statSvc = daemon.getStatusService();
statSvc.registerStatusAccessor(getStatusAccessorName("SCommChans"),
new ChannelStatus());
statSvc.registerStatusAccessor(getStatusAccessorName("SCommPeers"),
new PeerStatus());
}
}
protected String getStatusAccessorName(String base) {
return base;
}
/**
* stop the stream comm manager
* @see org.lockss.app.LockssManager#stopService()
*/
public void stopService() {
StatusService statSvc = getDaemon().getStatusService();
statSvc.unregisterStatusAccessor(getStatusAccessorName("SCommChans"));
statSvc.unregisterStatusAccessor(getStatusAccessorName("SCommPeers"));
if (isRunning()) {
stop();
}
super.stopService();
}
/**
* Set communication parameters from configuration, once only.
* Some aspects of this service currently cannot be reconfigured.
* @param config the Configuration
*/
public void setConfig(Configuration config,
Configuration prevConfig,
Configuration.Differences changedKeys) {
// Instances of this manager are started incrementally in testing,
// after the daemon is running, so isDaemonInited() won't work here
if (isInited()) {
// one-time only init
if (configShot.once()) {
configure(config, prevConfig, changedKeys);
}
// the following params can be changed on the fly
if (changedKeys.contains(PREFIX)) {
if (enabled && isRunning() &&
!config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED)) {
stopService();
}
paramMinFileMessageSize = config.getInt(PARAM_MIN_FILE_MESSAGE_SIZE,
DEFAULT_MIN_FILE_MESSAGE_SIZE);
paramMaxMessageSize = config.getLong(PARAM_MAX_MESSAGE_SIZE,
DEFAULT_MAX_MESSAGE_SIZE);
paramMinMeasuredMessageSize =
config.getLong(PARAM_MIN_MEASURED_MESSAGE_SIZE,
DEFAULT_MIN_MEASURED_MESSAGE_SIZE);
paramIsBufferedSend = config.getBoolean(PARAM_IS_BUFFERED_SEND,
DEFAULT_IS_BUFFERED_SEND);
paramIsTcpNoDelay = config.getBoolean(PARAM_TCP_NODELAY,
DEFAULT_TCP_NODELAY);
paramWaitExit = config.getTimeInterval(PARAM_WAIT_EXIT,
DEFAULT_WAIT_EXIT);
String paramDataDir = config.get(PARAM_DATA_DIR,
PlatformUtil.getSystemTempDir());
File dir = new File(paramDataDir);
if (FileUtil.ensureDirExists(dir)) {
if (!dir.equals(dataDir)) {
dataDir = dir;
log.debug2("Message data dir: " + dataDir);
}
} else {
log.warning("No message data dir: " + dir);
dataDir = null;
}
paramMaxChannels = config.getInt(PARAM_MAX_CHANNELS,
DEFAULT_MAX_CHANNELS);
paramConnectTimeout = config.getTimeInterval(PARAM_CONNECT_TIMEOUT,
DEFAULT_CONNECT_TIMEOUT);
paramSoTimeout = config.getTimeInterval(PARAM_DATA_TIMEOUT,
DEFAULT_DATA_TIMEOUT);
paramSslHandshakeTimeout =
config.getTimeInterval(PARAM_SSL_HANDSHAKE_TIMEOUT,
DEFAULT_SSL_HANDSHAKE_TIMEOUT);
paramDisableSslServerProtocols =
config.getList(PARAM_DISABLE_SSL_SERVER_PROTOCOLS,
DEFAULT_DISABLE_SSL_SERVER_PROTOCOLS);
paramDisableSslClientProtocols =
config.getList(PARAM_DISABLE_SSL_CLIENT_PROTOCOLS,
DEFAULT_DISABLE_SSL_CLIENT_PROTOCOLS);
paramSoKeepAlive = config.getBoolean(PARAM_SOCKET_KEEPALIVE,
DEFAULT_SOCKET_KEEPALIVE);
paramSendWakeupTime = config.getTimeInterval(PARAM_SEND_WAKEUP_TIME,
DEFAULT_SEND_WAKEUP_TIME);
paramChannelIdleTime =
config.getTimeInterval(PARAM_CHANNEL_IDLE_TIME,
DEFAULT_CHANNEL_IDLE_TIME);
paramDrainInputTime = config.getTimeInterval(PARAM_DRAIN_INPUT_TIME,
DEFAULT_DRAIN_INPUT_TIME);
paramDissociateOnNoSend =
config.getBoolean(PARAM_DISSOCIATE_ON_NO_SEND,
DEFAULT_DISSOCIATE_ON_NO_SEND);
paramDissociateOnEveryStop =
config.getBoolean(PARAM_DISSOCIATE_ON_EVERY_STOP,
DEFAULT_DISSOCIATE_ON_EVERY_STOP);
paramRetryBeforeExpiration =
config.getTimeInterval(PARAM_RETRY_BEFORE_EXPIRATION,
DEFAULT_RETRY_BEFORE_EXPIRATION);
paramMaxPeerRetryInterval =
config.getTimeInterval(PARAM_MAX_PEER_RETRY_INTERVAL,
DEFAULT_MAX_PEER_RETRY_INTERVAL);
paramMinPeerRetryInterval =
config.getTimeInterval(PARAM_MIN_PEER_RETRY_INTERVAL,
DEFAULT_MIN_PEER_RETRY_INTERVAL);
paramRetryDelay =
config.getTimeInterval(PARAM_RETRY_DELAY, DEFAULT_RETRY_DELAY);
paramAbortOnUnknownOp = config.getBoolean(PARAM_ABORT_ON_UNKNOWN_OP,
DEFAULT_ABORT_ON_UNKNOWN_OP);
if (changedKeys.contains(PARAM_PEER_SEND_MESSAGE_RATE_LIMIT)) {
sendRateLimiters.resetRateLimiters(config);
}
if (changedKeys.contains(PARAM_PEER_RECEIVE_MESSAGE_RATE_LIMIT)) {
receiveRateLimiters.resetRateLimiters(config);
}
}
}
}
/** One-time startup configuration */
private void configure(Configuration config,
Configuration prevConfig,
Configuration.Differences changedKeys) {
enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
if (!enabled) {
return;
}
paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN,
DEFAULT_CHANNEL_THREAD_POOL_MIN);
paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX,
DEFAULT_CHANNEL_THREAD_POOL_MAX);
paramPoolKeepaliveTime =
config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE,
DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE);
if (config.getBoolean(PARAM_BIND_TO_LOCAL_IP_ONLY,
DEFAULT_BIND_TO_LOCAL_IP_ONLY)) {
bindAddr = config.get(IdentityManager.PARAM_LOCAL_IP);
}
sendFromBindAddr = config.getBoolean(PARAM_SEND_FROM_BIND_ADDR,
DEFAULT_SEND_FROM_BIND_ADDR);
if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) {
paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL,
DEFAULT_USE_V3_OVER_SSL);
sockFact = null;
// XXX shut down old listen socket, do exponential backoff
// XXX on bind() to bring up new listen socket
// XXX then move this to the "change on the fly" above
}
if (!paramUseV3OverSsl)
return;
log.info("Using SSL");
// We're trying to use SSL
if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) {
paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH,
DEFAULT_USE_SSL_CLIENT_AUTH);
sockFact = null;
}
if (sslServerSocketFactory != null && sslSocketFactory != null) {
// already initialized
return;
}
if (changedKeys.contains(PARAM_SSL_KEYSTORE_NAME)
|| changedKeys.contains(PARAM_SSL_PRIVATE_KEYSTORE_NAME)
|| changedKeys.contains(PARAM_SSL_PUBLIC_KEYSTORE_NAME)) {
String name = getOrNull(config, PARAM_SSL_KEYSTORE_NAME);
String priv = getOrNull(config, PARAM_SSL_PRIVATE_KEYSTORE_NAME);
String pub = getOrNull(config, PARAM_SSL_PUBLIC_KEYSTORE_NAME);
if (!StringUtil.isNullString(name)) {
paramSslPrivateKeyStoreName = name;
paramSslPublicKeyStoreName = name;
}
if (priv != null) {
if (name != null && !priv.equals(name)) {
log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name +
" with " + PARAM_SSL_PRIVATE_KEYSTORE_NAME + ": " + priv);
}
paramSslPrivateKeyStoreName = priv;
}
if (pub != null) {
if (name != null && !pub.equals(name)) {
log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name +
" with " + PARAM_SSL_PUBLIC_KEYSTORE_NAME + ": " + pub);
}
paramSslPublicKeyStoreName = pub;
}
if (StringUtil.equalStrings(paramSslPublicKeyStoreName,
paramSslPrivateKeyStoreName)) {
// so can use == later
paramSslPrivateKeyStoreName = paramSslPublicKeyStoreName;
log.debug("Using keystore " + paramSslPrivateKeyStoreName);
} else {
log.debug("Using private keystore " + paramSslPrivateKeyStoreName
+ ", public keystore " + paramSslPublicKeyStoreName);
}
sockFact = null;
}
if (changedKeys.contains(PARAM_SSL_PROTOCOL)) {
paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
sockFact = null;
}
KeyManagerFactory kmf =
keystoreMgr.getKeyManagerFactory(paramSslPrivateKeyStoreName, "LCAP");
if (kmf == null) {
throw new IllegalArgumentException("Keystore not found: "
+ paramSslPrivateKeyStoreName);
}
KeyManager[] kma = kmf.getKeyManagers();
TrustManagerFactory tmf =
keystoreMgr.getTrustManagerFactory(paramSslPublicKeyStoreName, "LCAP");
if (tmf == null) {
throw new IllegalArgumentException("Keystore not found: "
+ paramSslPublicKeyStoreName);
}
TrustManager[] tma = tmf.getTrustManagers();
// Now create an SSLContext from the KeyManager
SSLContext sslContext = null;
try {
RandomManager rmgr = getDaemon().getRandomManager();
SecureRandom rng = rmgr.getSecureRandom();
sslContext = SSLContext.getInstance(paramSslProtocol);
sslContext.init(kma, tma, rng);
// Now create the SSL socket factories from the context
sslServerSocketFactory = sslContext.getServerSocketFactory();
sslSocketFactory = sslContext.getSocketFactory();
log.info("SSL init successful");
} catch (NoSuchAlgorithmException ex) {
log.error("Creating SSL context threw " + ex);
sslContext = null;
} catch (NoSuchProviderException ex) {
log.error("Creating SSL context threw " + ex);
sslContext = null;
} catch (KeyManagementException ex) {
log.error("Creating SSL context threw " + ex);
sslContext = null;
}
}
String getOrNull(Configuration config, String param) {
String val = config.get(param);
return "".equals(val) ? null : val;
}
// private debug output of keystore
private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) {
log.debug3("start of key store");
try {
for (Enumeration en = ks.aliases(); en.hasMoreElements(); ) {
String alias = (String) en.nextElement();
log.debug3("Next alias " + alias);
if (ks.isCertificateEntry(alias)) {
log.debug3("About to Certificate");
java.security.cert.Certificate cert = ks.getCertificate(alias);
if (cert == null) {
log.debug3(alias + " null cert chain");
} else {
log.debug3("Cert for " + alias + " is " + cert.toString());
}
} else if (ks.isKeyEntry(alias)) {
log.debug3("About to getKey");
Key privateKey = ks.getKey(alias, privateKeyPassWord);
log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat());
} else {
log.debug3(alias + " neither key nor cert");
}
}
log.debug3("end of key store");
} catch (Exception ex) {
log.error("logKeyStore() threw " + ex);
}
}
/** Return true iff all connections are authenticated; <i>ie</i>, we only
* talk to known peers */
public boolean isTrustedNetwork() {
return paramUseV3OverSsl && paramSslClientAuth;
}
// overridable for testing
protected PeerIdentity getLocalPeerIdentity() {
return idMgr.getLocalPeerIdentity(Poll.V3_PROTOCOL);
}
PeerIdentity findPeerIdentity(String idkey)
throws IdentityManager.MalformedIdentityKeyException {
return idMgr.findPeerIdentity(idkey);
}
PeerIdentity getMyPeerId() {
return myPeerId;
}
Queue getReceiveQueue() {
return rcvQueue;
}
SocketFactory getSocketFactory() {
if (sockFact == null)
if (paramUseV3OverSsl) {
sockFact = new SslSocketFactory();
} else {
sockFact = new NormalSocketFactory();
}
return sockFact;
}
long getConnectTimeout() {
return paramConnectTimeout;
}
long getSoTimeout() {
return paramSoTimeout;
}
long getSendWakeupTime() {
return paramSendWakeupTime;
}
long getChannelIdleTime() {
return paramChannelIdleTime;
}
long getDrainInputTime() {
return paramDrainInputTime;
}
long getChannelHungTime() {
return paramChannelIdleTime + 1000;
}
long getMaxMessageSize() {
return paramMaxMessageSize;
}
long getMinMeasuredMessageSize() {
return paramMinMeasuredMessageSize;
}
boolean isBufferedSend() {
return paramIsBufferedSend;
}
boolean isTcpNoDelay() {
return paramIsTcpNoDelay;
}
boolean getAbortOnUnknownOp() {
return paramAbortOnUnknownOp;
}
boolean getDissociateOnEveryStop() {
return paramDissociateOnEveryStop;
}
/**
* Called by channel when it learns its peer's identity
*/
void associateChannelWithPeer(BlockingPeerChannel chan, PeerIdentity peer) {
PeerData pdata = findPeerData(peer);
pdata.associateChannel(chan);
}
/**
* Called by channel when closing
*/
void dissociateChannelFromPeer(BlockingPeerChannel chan, PeerIdentity peer,
Queue sendQueue) {
// Do nothing if channel has no peer. E.g., incoming connection, on
// which no PeerId msg received.
if (peer != null) {
PeerData pdata = getPeerData(peer);
// No action if no PeerData
if (pdata != null) {
pdata.dissociateChannel(chan);
if (sendQueue != null) {
pdata.drainQueue(pdata, sendQueue, chan.shouldRetry());
}
}
}
}
/**
* Return an existing PeerData for the peer or create a new one
*/
PeerData findPeerData(PeerIdentity pid) {
if (pid == null) {
log.error("findPeerData: null pid", new Throwable());
throw new RuntimeException("Null pid");
}
synchronized (peers) {
PeerData pdata = peers.get(pid);
if (pdata == null) {
log.debug2("new PeerData("+pid+")");
pdata = new PeerData(pid);
peers.put(pid, pdata);
}
return pdata;
}
}
PeerData getPeerData(PeerIdentity pid) {
synchronized (peers) {
return peers.get(pid);
}
}
void rcvRateLimited(PeerIdentity pid) {
PeerData pdata = getPeerData(pid);
if (pdata != null) {
pdata.rcvRateLimited();
}
}
/** Send a message to a peer.
* @param msg the message to send
* @param id the identity of the peer to which to send the message
* @throws IOException if message couldn't be queued
*/
public void sendTo(PeerMessage msg, PeerIdentity id)
throws IOException {
if (!isRunning()) throw new IllegalStateException("SComm not running");
if (msg == null) throw new NullPointerException("Null message");
if (id == null) throw new NullPointerException("Null peer");
if (log.isDebug3()) log.debug3("sending "+ msg +" to "+ id);
sendToChannel(msg, id);
}
protected void sendToChannel(PeerMessage msg, PeerIdentity id)
throws IOException {
PeerData pdata = findPeerData(id);
pdata.send(msg);
}
RateLimiter getSendRateLimiter(PeerIdentity id) {
return sendRateLimiters.getRateLimiter(id);
}
RateLimiter getReceiveRateLimiter(PeerIdentity id) {
return receiveRateLimiters.getRateLimiter(id);
}
BlockingPeerChannel findOrMakeChannel(PeerIdentity id) throws IOException {
PeerData pdata = findPeerData(id);
return pdata.findOrMakeChannel();
}
void countMessageRetries(PeerMessage msg) {
synchronized (retryHist) {
retryHist.add(msg.getRetryCount());
}
}
void countMessageErrRetries(PeerMessage msg) {
synchronized (retryErrHist) {
retryErrHist.add(msg.getRetryCount());
}
}
void start() {
pool = new PooledExecutor(paramMaxPoolSize);
pool.setMinimumPoolSize(paramMinPoolSize);
pool.setKeepAliveTime(paramPoolKeepaliveTime);
log.debug2("Channel thread pool min, max: " +
pool.getMinimumPoolSize() + ", " + pool.getMaximumPoolSize());
pool.abortWhenBlocked();
rcvQueue = new FifoQueue();
try {
int port = myPeerAddr.getPort();
if (!getDaemon().getResourceManager().reserveTcpPort(port,
SERVER_NAME)) {
throw new IOException("TCP port " + port + " unavailable");
}
if (bindAddr != null) {
log.debug("Listening on port " + port + " on " + bindAddr);
} else {
log.debug("Listening on port " + port);
}
listenSock =
getSocketFactory().newServerSocket(bindAddr, port, paramBacklog);
} catch (IOException e) {
log.critical("Can't create listen socket", e);
return;
}
ensureQRunner();
ensureRetryThread();
ensureListener();
running = true;
}
protected boolean isRunning() {
return running;
}
// stop all threads and channels
void stop() {
running = false;
Deadline timeout = null;
synchronized (threadLock) {
if (paramWaitExit > 0) {
timeout = Deadline.in(paramWaitExit);
}
stopThread(retryThread, timeout);
retryThread = null;
stopThread(listenThread, timeout);
listenThread = null;
stopThread(rcvThread, timeout);
rcvThread = null;
}
log.debug2("Shutting down pool");
if (pool != null) {
pool.shutdownNow();
}
log.debug2("pool shut down ");
}
List<PeerData> getAllPeerData() {
synchronized (peers) {
return new ArrayList<PeerData>(peers.values());
}
}
// stop all channels in channel map
void stopChannels(Map map, Deadline timeout) {
log.debug2("Stopping channels");
List<PeerData> lst = getAllPeerData();
for (PeerData pdata : lst) {
pdata.abortChannels();
}
// Wait until the threads have exited before proceeding. Useful in
// testing to keep debug output straight.
// Any channels that had already dissociated themselves are not waited
// for. It would take extra bookkeeping to handle those and they don't
// seem to cause nearly as much trouble.
if (timeout != null) {
for (PeerData pdata : lst) {
pdata.waitChannelsDone(timeout);
}
}
}
// poke channels that might have hung sender
void checkHungChannels() {
log.debug3("Doing hung check");
for (PeerData pdata : getAllPeerData()) {
pdata.checkHung();
}
}
/**
* Execute the runnable in a pool thread
* @param run the Runnable to be run
* @throws RuntimeException if no pool thread is available
*/
void execute(Runnable run) throws InterruptedException {
if (run == null)
log.warning("Executing null", new Throwable());
pool.execute(run);
}
/** Setup all socket options. Should be called before any read/write
* calls */
void setupOpenSocket(Socket sock) throws SocketException {
if (log.isDebug3()) {
log.debug3(sock + "SO_TIMEOUT: " + getSoTimeout()
+ ", TcpNoDelay: " + isTcpNoDelay()
+ ", KeepAlive: " + paramSoKeepAlive);
}
sock.setSoTimeout((int)getSoTimeout());
sock.setTcpNoDelay(isTcpNoDelay());
sock.setKeepAlive(paramSoKeepAlive);
}
// process a socket returned by accept()
// overridable for testing
void processIncomingConnection(Socket sock) throws IOException {
if (sock.isClosed()) {
// This should no longer happen
throw new SocketException("processIncomingConnection got closed socket");
}
// Setup socket (SO_TIMEOUT, etc.) before SSL handshake
setupOpenSocket(sock);
log.debug2("Accepted connection from " +
new IPAddr(sock.getInetAddress()));
// SSL handshake now performed by channel
BlockingPeerChannel chan = getSocketFactory().newPeerChannel(this, sock);
chan.startIncoming();
}
private void processReceivedPacket(PeerMessage msg) {
log.debug2("Received " + msg);
try {
runHandlers(msg);
} catch (ProtocolException e) {
log.warning("Cannot process incoming packet", e);
}
}
protected void runHandler(MessageHandler handler,
PeerMessage msg) {
try {
handler.handleMessage(msg);
} catch (Exception e) {
log.error("callback threw", e);
}
}
private void runHandlers(PeerMessage msg)
throws ProtocolException {
try {
int proto = msg.getProtocol();
MessageHandler handler;
if (proto >= 0 && proto < messageHandlers.size() &&
(handler = (MessageHandler)messageHandlers.get(proto)) != null) {
runHandler(handler, msg);
} else {
log.warning("Received message with unregistered protocol: " + proto);
}
} catch (RuntimeException e) {
log.warning("Unexpected error in runHandlers", e);
throw new ProtocolException(e.toString());
}
}
/**
* Register a {@link LcapStreamComm.MessageHandler}, which will be called
* whenever a message is received.
* @param protocol an int representing the protocol
* @param handler MessageHandler to add
*/
public void registerMessageHandler(int protocol, MessageHandler handler) {
synchronized (messageHandlers) {
if (protocol >= messageHandlers.size()) {
messageHandlers.setSize(protocol + 1);
}
if (messageHandlers.get(protocol) != null) {
throw
new RuntimeException("Protocol " + protocol + " already registered");
}
messageHandlers.set(protocol, handler);
}
}
/**
* Unregister a {@link LcapStreamComm.MessageHandler}.
* @param protocol an int representing the protocol
*/
public void unregisterMessageHandler(int protocol) {
if (protocol < messageHandlers.size()) {
messageHandlers.set(protocol, null);
}
}
// PeerMessage.Factory implementation
public PeerMessage newPeerMessage() {
return new MemoryPeerMessage();
}
public PeerMessage newPeerMessage(long estSize) {
if (estSize < 0) {
return newPeerMessage();
} else if (estSize > 0 &&
dataDir != null &&
estSize >= paramMinFileMessageSize) {
return new FilePeerMessage(dataDir);
} else {
return new MemoryPeerMessage();
}
}
// Make it easy to compare timeout values, where 0 = infinite.
long absTimeout(long timeout) {
return timeout == 0 ? Long.MAX_VALUE : timeout;
}
protected void handshake(SSLSocket s) throws SSLPeerUnverifiedException {
long oldTimeout = -2;
try {
oldTimeout = s.getSoTimeout();
if (absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) {
s.setSoTimeout((int)paramSslHandshakeTimeout);
}
} catch (SocketException e) {
log.warning("Couldn't save/set socket timeout before handshake", e);
}
try {
SSLSession session = s.getSession();
java.security.cert.Certificate[] certs = session.getPeerCertificates();
log.debug(session.getPeerHost() + " via " + session.getProtocol() + " verified");
} catch (SSLPeerUnverifiedException ex) {
log.error(s.getInetAddress() + ":" + s.getPort() + " not verified");
try {
s.close();
} catch (IOException ex2) {
log.error("Socket close threw " + ex2);
}
throw ex;
} finally {
if (!s.isClosed() &&
absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) {
try {
s.setSoTimeout((int)oldTimeout);
} catch (SocketException e) {
log.warning("Couldn't restore socket timeout after handshake", e);
}
}
}
}
protected void handshakeIfClientAuth(Socket sock)
throws SSLPeerUnverifiedException {
if (sock instanceof SSLSocket && paramSslClientAuth) {
// Ensure handshake is complete before doing anything else
handshake((SSLSocket)sock);
}
}
/** Sort retry list by time of next retry. Ensure never equal */
static class RetryOrderComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
PeerData pd1 = (PeerData)o1;
PeerData pd2 = (PeerData)o2;
long r1 = pd1.getNextRetry();
long r2 = pd2.getNextRetry();
int res = (r2 > r1 ? -1
: (r2 < r1 ? 1
: (System.identityHashCode(pd1)
- System.identityHashCode(pd2))));
return res;
}
}
void ensureQRunner() {
synchronized (threadLock) {
if (rcvThread == null) {
log.info("Starting receive thread");
rcvThread = new ReceiveThread("SCommRcv: " +
myPeerId.getIdString());
rcvThread.start();
rcvThread.waitRunning();
}
}
}
void ensureListener() {
synchronized (threadLock) {
if (listenThread == null) {
log.info("Starting listen thread");
listenThread = new ListenThread("SCommListen: " +
myPeerId.getIdString());
listenThread.start();
listenThread.waitRunning();
}
}
}
void ensureRetryThread() {
synchronized (threadLock) {
if (retryThread == null) {
log.info("Starting retry thread");
retryThread = new RetryThread("SCommRetry: " +
myPeerId.getIdString());
retryThread.start();
retryThread.waitRunning();
}
}
}
void stopThread(CommThread th, Deadline timeout) {
if (th != null) {
log.info("Stopping " + th.getName());
th.stopCommThread();
if (timeout != null) {
th.waitExited(timeout);
}
}
}
abstract class CommThread extends LockssThread {
abstract void stopCommThread();
CommThread(String name) {
super(name);
}
}
// Receive thread
private class ReceiveThread extends CommThread {
private volatile boolean goOn = true;
private Deadline timeout = Deadline.in(getChannelHungTime());
ReceiveThread(String name) {
super(name);
}
public void lockssRun() {
setPriority(PRIORITY_PARAM_SCOMM, PRIORITY_DEFAULT_SCOMM);
triggerWDogOnExit(true);
startWDog(WDOG_PARAM_SCOMM, WDOG_DEFAULT_SCOMM);
nowRunning();
while (goOn) {
pokeWDog();
try {
synchronized (timeout) {
if (goOn) {
timeout.expireIn(getChannelHungTime());
}
}
if (log.isDebug3()) log.debug3("rcvQueue.get(" + timeout + ")");
Object qObj = rcvQueue.get(timeout);
if (qObj != null) {
if (qObj instanceof PeerMessage) {
if (log.isDebug3()) log.debug3("Rcvd " + qObj);
processReceivedPacket((PeerMessage)qObj);
} else {
log.warning("Non-PeerMessage on rcv queue" + qObj);
}
}
if (TimeBase.msSince(lastHungCheckTime) >
getChannelHungTime()) {
checkHungChannels();
lastHungCheckTime = TimeBase.nowMs();
}
} catch (InterruptedException e) {
// just wake up and check for exit
} finally {
}
}
rcvThread = null;
}
void stopCommThread() {
synchronized (timeout) {
stopWDog();
triggerWDogOnExit(false);
goOn = false;
timeout.expire();
}
}
}
private void disableSelectedProtocols(SSLServerSocket sock) {
if (paramDisableSslServerProtocols == null) return;
Set<String> enaprotos = new HashSet<String>();
for (String s : sock.getEnabledProtocols()) {
if (paramDisableSslServerProtocols.contains(s)) {
continue;
}
enaprotos.add(s);
}
sock.setEnabledProtocols(enaprotos.toArray(new String[0]));
}
private void disableSelectedProtocols(SSLSocket sock) {
if (paramDisableSslClientProtocols == null) return;
Set<String> enaprotos = new HashSet<String>();
for (String s : sock.getEnabledProtocols()) {
if (paramDisableSslClientProtocols.contains(s)) {
continue;
}
enaprotos.add(s);
}
sock.setEnabledProtocols(enaprotos.toArray(new String[0]));
}
// Listen thread
private class ListenThread extends CommThread {
private volatile boolean goOn = true;
private ListenThread(String name) {
super(name);
}
public void lockssRun() {
setPriority(PRIORITY_PARAM_SLISTEN, PRIORITY_DEFAULT_SLISTEN);
triggerWDogOnExit(true);
// startWDog(WDOG_PARAM_SLISTEN, WDOG_DEFAULT_SLISTEN);
nowRunning();
String sockmsg =
(listenSock instanceof SSLServerSocket) ? "SSL Listener" : "Listener";
while (goOn) {
// pokeWDog();
log.debug3("accept()");
try {
Socket sock = listenSock.accept();
if (!goOn) {
break;
}
processIncomingConnection(sock);
} catch (SocketException e) {
if (goOn) {
log.warning(sockmsg, e);
}
} catch (Exception e) {
log.warning(sockmsg, e);
}
}
listenThread = null;
}
void stopCommThread() {
stopWDog();
triggerWDogOnExit(false);
goOn = false;
IOUtil.safeClose(listenSock);
this.interrupt();
}
}
// Outside thread so stat table can find it
// Must initialize (to mutable Deadline) in case recalcNext called before
// thread runs.
private volatile Deadline retryThreadNextRetry = Deadline.at(TimeBase.MAX);
// Retry thread
private class RetryThread extends CommThread {
private volatile boolean goOn = true;
private long soonest = 0;
RetryThread(String name) {
super(name);
}
public void lockssRun() {
setPriority(PRIORITY_PARAM_RETRY, PRIORITY_DEFAULT_RETRY);
triggerWDogOnExit(true);
startWDog(WDOG_PARAM_RETRY, WDOG_DEFAULT_RETRY);
nowRunning();
outer:
while (goOn) {
pokeWDog();
do {
retryThreadNextRetry = getNextRetry();
log.debug2("nextRetry: " + retryThreadNextRetry.shortString());
try {
retryThreadNextRetry.sleep();
} catch (InterruptedException e) {
// just wakeup and check for work
}
if (!goOn) {
break outer;
}
} while (TimeBase.nowMs() < soonest);
PeerData pdata = firstPeerToRetry();
if (pdata != null && pdata.retryIfNeeded()) {
soonest = TimeBase.nowMs() + paramRetryDelay;
} else {
soonest = 0;
}
}
retryThread = null;
}
Deadline getNextRetry() {
synchronized (peersToRetry) {
PeerData pdata = firstPeerToRetry();
if (log.isDebug3()) log.debug3("firstPeerToRetry: " + pdata);
if (pdata != null) {
log.debug3("pdata.getNextRetry(): " + pdata.getNextRetry());
return Deadline.at(Math.max(soonest, pdata.getNextRetry()));
} else {
return Deadline.at(TimeBase.MAX);
}
}
}
PeerData firstPeerToRetry() {
synchronized (peersToRetry) {
if (peersToRetry.isEmpty()) {
return null;
}
PeerData pdata = peersToRetry.first();
if (log.isDebug2()) {
log.debug2("First peer to retry: " + pdata.getPid());
}
return pdata;
}
}
void recalcNext() {
retryThreadNextRetry.expire();
}
void stopCommThread() {
synchronized (retryThreadNextRetry) {
stopWDog();
triggerWDogOnExit(false);
goOn = false;
retryThreadNextRetry.expire();
}
}
@Override
protected void threadHung() {
Deadline next = getNextRetry();
if (next.expired()) {
super.threadHung();
} else {
pokeWDog();
}
}
}
/** SocketFactory interface allows encapsulation of socket type details
(normal, SSL, etc.) and allows test code to use instrumented or mock
sockets and peer channels */
interface SocketFactory {
/** Return a listen socket of the appropriate type */
ServerSocket newServerSocket(String bindAddr, int port, int backlog)
throws IOException;
/** Return a socket of the appropriate type connected to the remote
* address, with its options set */
Socket newSocket(IPAddr addr, int port) throws IOException;
/** Overridable for testing */
BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
Socket sock)
throws IOException;
/** Overridable for testing */
BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
PeerIdentity peer)
throws IOException;
}
/** Normal socket factory creates real TCP Sockets */
class NormalSocketFactory implements SocketFactory {
public ServerSocket newServerSocket(String bindAddr, int port, int backlog)
throws IOException {
if (bindAddr != null) {
return new ServerSocket(port, backlog, InetAddress.getByName(bindAddr));
} else {
return new ServerSocket(port, backlog);
}
}
public Socket newSocket(IPAddr addr, int port) throws IOException {
Socket sock;
if (sendFromBindAddr && bindAddr != null) {
sock = new Socket(addr.getInetAddr(), port,
InetAddress.getByName(bindAddr), 0);
} else {
sock = new Socket(addr.getInetAddr(), port);
}
setupOpenSocket(sock);
return sock;
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
Socket sock)
throws IOException {
return new BlockingPeerChannel(comm, sock);
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
PeerIdentity peer)
throws IOException {
return new BlockingPeerChannel(comm, peer);
}
}
/** SSL socket factory */
class SslSocketFactory implements SocketFactory {
public ServerSocket newServerSocket(String bindAddr, int port, int backlog)
throws IOException {
if (sslServerSocketFactory == null) {
throw new IOException("no SSL server socket factory");
}
SSLServerSocket s;
if (bindAddr != null) {
s = (SSLServerSocket)
sslServerSocketFactory.createServerSocket(port, backlog,
InetAddress.getByName(bindAddr));
} else {
s = (SSLServerSocket)
sslServerSocketFactory.createServerSocket(port, backlog);
}
disableSelectedProtocols(s);
s.setNeedClientAuth(paramSslClientAuth);
log.debug("New SSL server socket: " + port + " backlog " + backlog +
" clientAuth " + paramSslClientAuth);
if (log.isDebug2()) logSSLSocketDetails(s);
return s;
}
public Socket newSocket(IPAddr addr, int port) throws IOException {
if (sslSocketFactory == null) {
throw new IOException("no SSL client socket factory");
}
SSLSocket s;
if (sendFromBindAddr && bindAddr != null) {
s = (SSLSocket)sslSocketFactory.createSocket(addr.getInetAddr(), port,
InetAddress.getByName(bindAddr), 0);
} else {
s = (SSLSocket)sslSocketFactory.createSocket(addr.getInetAddr(), port);
}
disableSelectedProtocols(s);
log.debug2("New SSL client socket: " + port + "@" + addr.toString());
// Setup socket (SO_TIMEOUT, etc.) before SSL handshake
setupOpenSocket(s);
if (paramSslClientAuth) {
handshake(s);
}
return s;
}
private void logSSLSocketDetails(SSLServerSocket s) {
log.debug2("Supported cipher suites: " +
ListUtil.fromArray(s.getSupportedCipherSuites()));
log.debug2("Enabled cipher suites: " +
ListUtil.fromArray(s.getEnabledCipherSuites()));
log.debug2("Supported protocols: " +
ListUtil.fromArray(s.getSupportedProtocols()));
log.debug2("Enabled protocols: " +
ListUtil.fromArray(s.getEnabledProtocols()));
log.debug2("Enable session creation: " + s.getEnableSessionCreation());
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
Socket sock)
throws IOException {
return new BlockingPeerChannel(comm, sock);
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
PeerIdentity peer)
throws IOException {
return new BlockingPeerChannel(comm, peer);
}
}
private static final List chanStatusColDescs =
ListUtil.list(
new ColumnDescriptor("Peer", "Peer",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("State", "State",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Flags", "Flags",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("SendQ", "SendQ",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Sent", "Msgs Sent",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Rcvd", "Msgs Rcvd",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("SentBytes", "Bytes Sent",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("RcvdBytes", "Bytes Rcvd",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("LastSend", "LastSend",
ColumnDescriptor.TYPE_TIME_INTERVAL),
new ColumnDescriptor("LastRcv", "LastRcv",
ColumnDescriptor.TYPE_TIME_INTERVAL),
new ColumnDescriptor("PrevStateChange", "Change",
ColumnDescriptor.TYPE_TIME_INTERVAL),
new ColumnDescriptor("PrevState", "PrevState",
ColumnDescriptor.TYPE_STRING)
);
private class ChannelStatus implements StatusAccessor {
long start;
public String getDisplayName() {
return "Comm Channels";
}
public boolean requiresKey() {
return false;
}
public void populateTable(StatusTable table) {
String key = table.getKey();
ChannelStats cumulative = new ChannelStats();
table.setColumnDescriptors(chanStatusColDescs);
table.setRows(getRows(key, cumulative));
cumulative.add(globalStats);
table.setSummaryInfo(getSummaryInfo(key, cumulative));
}
private List getSummaryInfo(String key, ChannelStats stats) {
List res = new ArrayList();
StringBuilder sb = new StringBuilder();
if (paramUseV3OverSsl) {
sb.append(paramSslProtocol);
if (paramSslClientAuth) {
sb.append(", Client Auth");
}
} else {
sb.append("No");
}
res.add(new StatusTable.SummaryInfo("SSL",
ColumnDescriptor.TYPE_STRING,
sb.toString()));
res.add(new StatusTable.SummaryInfo("Channels",
ColumnDescriptor.TYPE_STRING,
nPrimary + "/"
+ paramMaxChannels + ", "
+ maxPrimary + " max"));
res.add(new StatusTable.SummaryInfo("RcvChannels",
ColumnDescriptor.TYPE_STRING,
nSecondary + ", "
+ maxSecondary +" max"));
res.add(new StatusTable.SummaryInfo("Draining",
ColumnDescriptor.TYPE_STRING,
drainingChannels.size() + ", "
+ maxDrainingChannels + " max"));
ChannelStats.Count count = stats.getInCount();
res.add(new StatusTable.SummaryInfo("Msgs Sent",
ColumnDescriptor.TYPE_INT,
count.getMsgs()));
res.add(new StatusTable.SummaryInfo("Bytes Sent",
ColumnDescriptor.TYPE_INT,
count.getBytes()));
count = stats.getOutCount();
res.add(new StatusTable.SummaryInfo("Msgs Rcvd",
ColumnDescriptor.TYPE_INT,
count.getMsgs()));
res.add(new StatusTable.SummaryInfo("Bytes Rcvd",
ColumnDescriptor.TYPE_INT,
count.getBytes()));
return res;
}
private List getRows(String key, ChannelStats cumulative) {
List table = new ArrayList();
for (PeerData pdata : getAllPeerData()) {
BlockingPeerChannel primary = pdata.getPrimaryChannel();
if (primary != null) {
table.add(makeRow(primary, "", cumulative));
}
BlockingPeerChannel secondary = pdata.getSecondaryChannel();
if (secondary != null) {
table.add(makeRow(secondary, "", cumulative));
}
}
synchronized (drainingChannels) {
for (BlockingPeerChannel chan : drainingChannels) {
table.add(makeRow(chan, "D", cumulative));
}
}
return table;
}
private Map makeRow(BlockingPeerChannel chan,
String flags, ChannelStats cumulative) {
PeerIdentity pid = chan.getPeer();
Map row = new HashMap();
// Draining channels can sometimes have null peer
row.put("Peer", (pid == null) ? "???" : pid.getIdString());
row.put("State", chan.getState());
row.put("SendQ", chan.getSendQueueSize());
ChannelStats stats = chan.getStats();
cumulative.add(stats);
ChannelStats.Count count = stats.getInCount();
row.put("Sent", count.getMsgs());
row.put("SentBytes", count.getBytes());
count = stats.getOutCount();
row.put("Rcvd", count.getMsgs());
row.put("RcvdBytes", count.getBytes());
StringBuilder sb = new StringBuilder(flags);
if (chan.isOriginate()) sb.append("O");
if (chan.hasConnecter()) sb.append("C");
if (chan.hasReader()) sb.append("R");
if (chan.hasWriter()) sb.append("W");
row.put("Flags", sb.toString());
row.put("LastSend", lastTime(chan.getLastSendTime()));
row.put("LastRcv", lastTime(chan.getLastRcvTime()));
if (chan.getPrevState() != BlockingPeerChannel.ChannelState.NONE) {
row.put("PrevState", chan.getPrevState());
row.put("PrevStateChange", lastTime(chan.getLastStateChange()));
}
return row;
}
Long lastTime(long time) {
if (time <= 0) return null;
return TimeBase.msSince(time);
}
}
private static final List peerStatusColDescs =
ListUtil.list(
new ColumnDescriptor("Peer", "Peer",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Orig", "Orig",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Fail", "Fail",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Accept", "Accept",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Sent", "Msgs Sent",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Rcvd", "Msgs Rcvd",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Chan", "Chan",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("SendQ", "Send Q",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("LastRetry", "Last Attempt",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("NextRetry", "Next Retry",
ColumnDescriptor.TYPE_DATE)
);
private static final List rateLimitColDescs =
ListUtil.list(
new ColumnDescriptor("SendLimited", "Send Discard",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("RcvLimited", "Rcv Discard",
ColumnDescriptor.TYPE_STRING)
);
private static final List peerStatusSortRules =
ListUtil.list(new StatusTable.SortRule("Peer", true));
private class PeerStatus implements StatusAccessor {
long start;
public String getDisplayName() {
return "Comm Peer Data";
}
public boolean requiresKey() {
return false;
}
public void populateTable(StatusTable table) {
String key = table.getKey();
if (anyRateLimited) {
table.setColumnDescriptors(ListUtil.append(peerStatusColDescs,
rateLimitColDescs));
} else {
table.setColumnDescriptors(peerStatusColDescs);
}
table.setDefaultSortRules(peerStatusSortRules);
table.setRows(getRows(key));
table.setSummaryInfo(getSummaryInfo(key));
}
private List getRows(String key) {
List table = new ArrayList();
for (PeerData pdata : getAllPeerData()) {
table.add(makeRow(pdata));
}
return table;
}
private Map makeRow(PeerData pdata) {
PeerIdentity pid = pdata.getPid();
Map row = new HashMap();
row.put("Peer", (pid == null) ? "???" : pid.getIdString());
row.put("Orig", pdata.getOrigCnt());
row.put("Fail", pdata.getFailCnt());
row.put("Accept", pdata.getAcceptCnt());
row.put("Sent", pdata.getMsgsSent());
row.put("Rcvd", pdata.getMsgsRcvd());
if (anyRateLimited) {
row.put("SendLimited", pdata.getSendRateLimited());
row.put("RcvLimited", pdata.getRcvRateLimited());
}
StringBuilder sb = new StringBuilder(2);
if (pdata.getPrimaryChannel() != null) {
sb.append("P");
}
if (pdata.getSecondaryChannel() != null) {
sb.append("S");
}
if (sb.length() != 0) {
row.put("Chan", sb.toString());
}
int pq = pdata.getSendQueueSize();
if (pq != 0) {
row.put("SendQ", pq);
} else {
BlockingPeerChannel chan = pdata.getPrimaryChannel();
if (chan != null) {
row.put("SendQ", chan.getSendQueueSize());
}
}
row.put("LastRetry", pdata.getLastRetry());
if (pdata.getNextRetry() != TimeBase.MAX) {
row.put("NextRetry", pdata.getNextRetry());
}
return row;
}
private String histString(Bag hist) {
synchronized (hist) {
List lst = new ArrayList();
for (Integer cnt : ((Set<Integer>)hist.uniqueSet())) {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(cnt);
sb.append(",");
sb.append(hist.getCount(cnt));
sb.append("]");
lst.add(sb.toString());
}
return StringUtil.separatedString(lst, ",");
}
}
private List getSummaryInfo(String key) {
List res = new ArrayList();
res.add(new StatusTable.SummaryInfo("Msg Ok Retries",
ColumnDescriptor.TYPE_STRING,
histString(retryHist)));
res.add(new StatusTable.SummaryInfo("Msg Err Retries",
ColumnDescriptor.TYPE_STRING,
histString(retryErrHist)));
res.add(new StatusTable.SummaryInfo("Waiting Retry",
ColumnDescriptor.TYPE_INT,
peersToRetry.size()));
if (peersToRetry.size() != 0) {
res.add(new StatusTable.SummaryInfo("Next Retry",
ColumnDescriptor.TYPE_DATE,
retryThreadNextRetry));
}
return res;
}
}
}
| bsd-3-clause |
TATRC/KMR2 | Services/DisplayCalendarLib/src/main/java/gov/hhs/fha/nhinc/displaycalendarlib/CalendarAccessor.java | 4343 | /*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
* Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. 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 NHIN Connect 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.
*
* END OF TERMS AND CONDITIONS
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.hhs.fha.nhinc.displaycalendarlib;
import org.osaf.caldav4j.dialect.SogoCalDavDialect;
import java.io.IOException;
import net.fortuna.ical4j.model.Calendar;
import org.osaf.caldav4j.CalDAVCollection;
import org.osaf.caldav4j.CalDAVConstants;
import org.osaf.caldav4j.exceptions.CalDAV4JException;
import org.osaf.caldav4j.util.GenerateQuery;
import net.fortuna.ical4j.model.component.CalendarComponent;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osaf.caldav4j.credential.CaldavCredential;
import org.osaf.caldav4j.dialect.CalDavDialect;
import org.osaf.caldav4j.dialect.GoogleCalDavDialect;
/**
*
* @author nhin
*/
public class CalendarAccessor {
private CalendarInit init;
protected static final Log log = LogFactory.getLog(CalendarInit.class);
private CaldavCredential credential;
private CalDavDialect dialect;
public CalendarAccessor() throws Exception {
credential = new CaldavCredential();
dialect = new SogoCalDavDialect();
try {
init = new CalendarInit(credential, dialect);
} catch (IOException ioe) {
log.error("IO Exception creating CalendarAccessor");
ioe.printStackTrace();
}
}
public Calendar getCalendar(int userId, String type) {
CalResponse response = new CalResponse();
CalDAVCollection collection = createCalDAVCollection();
Calendar calendar = null;
try {
GenerateQuery gq = new GenerateQuery(null,
CalendarComponent.VEVENT + "UID==" + userId);
log.info(gq.prettyPrint());
calendar = collection.queryCalendar(init.getHttpClient(),
CalendarComponent.VEVENT, Integer.toString(userId), "test");
} catch (CalDAV4JException ce) {
ce.printStackTrace();
}
return calendar;
}
private CalDAVCollection createCalDAVCollection() {
CalDAVCollection calendarCollection = new CalDAVCollection(
init.getCollectionPath(), createHostConfiguration(credential), init.getMethodFactory(),
CalDAVConstants.PROC_ID_DEFAULT);
return calendarCollection;
}
public static HostConfiguration createHostConfiguration(CaldavCredential caldavCredential) {
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(caldavCredential.host, caldavCredential.port, caldavCredential.protocol);
return hostConfig;
}
}
| bsd-3-clause |
xebialabs/vijava | src/com/vmware/vim25/HostNetworkInfo.java | 4709 | /*================================================================================
Copyright (c) 2012 Steve Jin. 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 VMware, Inc. 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 VMWARE, INC. 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.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HostNetworkInfo extends DynamicData {
public HostVirtualSwitch[] vswitch;
public HostProxySwitch[] proxySwitch;
public HostPortGroup[] portgroup;
public PhysicalNic[] pnic;
public HostVirtualNic[] vnic;
public HostVirtualNic[] consoleVnic;
public HostDnsConfig dnsConfig;
public HostIpRouteConfig ipRouteConfig;
public HostIpRouteConfig consoleIpRouteConfig;
public HostIpRouteTableInfo routeTableInfo;
public HostDhcpService[] dhcp;
public HostNatService[] nat;
public Boolean ipV6Enabled;
public Boolean atBootIpV6Enabled;
public HostVirtualSwitch[] getVswitch() {
return this.vswitch;
}
public HostProxySwitch[] getProxySwitch() {
return this.proxySwitch;
}
public HostPortGroup[] getPortgroup() {
return this.portgroup;
}
public PhysicalNic[] getPnic() {
return this.pnic;
}
public HostVirtualNic[] getVnic() {
return this.vnic;
}
public HostVirtualNic[] getConsoleVnic() {
return this.consoleVnic;
}
public HostDnsConfig getDnsConfig() {
return this.dnsConfig;
}
public HostIpRouteConfig getIpRouteConfig() {
return this.ipRouteConfig;
}
public HostIpRouteConfig getConsoleIpRouteConfig() {
return this.consoleIpRouteConfig;
}
public HostIpRouteTableInfo getRouteTableInfo() {
return this.routeTableInfo;
}
public HostDhcpService[] getDhcp() {
return this.dhcp;
}
public HostNatService[] getNat() {
return this.nat;
}
public Boolean getIpV6Enabled() {
return this.ipV6Enabled;
}
public Boolean getAtBootIpV6Enabled() {
return this.atBootIpV6Enabled;
}
public void setVswitch(HostVirtualSwitch[] vswitch) {
this.vswitch=vswitch;
}
public void setProxySwitch(HostProxySwitch[] proxySwitch) {
this.proxySwitch=proxySwitch;
}
public void setPortgroup(HostPortGroup[] portgroup) {
this.portgroup=portgroup;
}
public void setPnic(PhysicalNic[] pnic) {
this.pnic=pnic;
}
public void setVnic(HostVirtualNic[] vnic) {
this.vnic=vnic;
}
public void setConsoleVnic(HostVirtualNic[] consoleVnic) {
this.consoleVnic=consoleVnic;
}
public void setDnsConfig(HostDnsConfig dnsConfig) {
this.dnsConfig=dnsConfig;
}
public void setIpRouteConfig(HostIpRouteConfig ipRouteConfig) {
this.ipRouteConfig=ipRouteConfig;
}
public void setConsoleIpRouteConfig(HostIpRouteConfig consoleIpRouteConfig) {
this.consoleIpRouteConfig=consoleIpRouteConfig;
}
public void setRouteTableInfo(HostIpRouteTableInfo routeTableInfo) {
this.routeTableInfo=routeTableInfo;
}
public void setDhcp(HostDhcpService[] dhcp) {
this.dhcp=dhcp;
}
public void setNat(HostNatService[] nat) {
this.nat=nat;
}
public void setIpV6Enabled(Boolean ipV6Enabled) {
this.ipV6Enabled=ipV6Enabled;
}
public void setAtBootIpV6Enabled(Boolean atBootIpV6Enabled) {
this.atBootIpV6Enabled=atBootIpV6Enabled;
}
} | bsd-3-clause |
davidpicard/jkernelmachines | src/main/java/net/jkernelmachines/projection/DoublePCA.java | 5987 | /*******************************************************************************
* Copyright (c) 2016, David Picard.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
*******************************************************************************/
package net.jkernelmachines.projection;
import static net.jkernelmachines.util.algebra.MatrixOperations.eig;
import static net.jkernelmachines.util.algebra.MatrixOperations.transi;
import static net.jkernelmachines.util.algebra.VectorOperations.add;
import static net.jkernelmachines.util.algebra.VectorOperations.dot;
import static net.jkernelmachines.util.algebra.VectorOperations.mul;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import net.jkernelmachines.threading.ThreadedMatrixOperator;
import net.jkernelmachines.type.TrainingSample;
/**
* Principal component analysis on double arrays.
* @author picard
*
*/
public class DoublePCA implements Serializable {
private static final long serialVersionUID = -6200080076438113052L;
double[][] projectors;
double[] whitening_coeff;
double[] mean;
/**
* Train the projectors on a given data-set.
* @param list the list of training samples
*/
public void train(final List<TrainingSample<double[]>> list) {
int dim = list.get(0).sample.length;
mean = new double[dim];
for(TrainingSample<double[]> t : list) {
mean = add(mean, 1, t.sample);
}
mean = mul(mean, 1./list.size());
// compute covariance matrix;
double[][] cov = new double[dim][dim];
ThreadedMatrixOperator factory = new ThreadedMatrixOperator() {
@Override
public void doLines(double[][] matrix, int from, int to) {
for(int i = from ; i < to ; i++) {
for(int j = 0 ; j < matrix.length ; j++) {
double sum = 0;
for(TrainingSample<double[]> t : list) {
sum += (t.sample[i]-mean[i]) * (t.sample[j]-mean[j]);
}
matrix[i][j] = sum/list.size();
}
}
}
};
cov = factory.getMatrix(cov);
// eigen decomposition
double[][][] eig = eig(cov);
//projectors are eigenvectors transposed
projectors = transi(eig[0]);
//coefficients are the square root of the eigenvalues
whitening_coeff = new double[dim];
for(int d = 0 ; d < dim ; d++) {
if(eig[1][d][d] > 0) {
whitening_coeff[d] = 1./Math.sqrt(eig[1][d][d]);
}
else {
whitening_coeff[d] = 0;
}
}
}
/**
* Project a single sample using the trained projectors.
* @param s the sample to project
* @return a new sample with the projected vector, and the same label
*/
public TrainingSample<double[]> project(TrainingSample<double[]> s) {
double[] px = new double[projectors.length];
for(int i = 0 ; i < projectors.length ; i++) {
px[i] = dot(projectors[i], add(s.sample, -1, mean));
}
return new TrainingSample<double[]>(px, s.label);
}
/**
* Project a single sample using the trained projectors with optional whitening (unitary
* covariance matrix).
* @param s the sample to project
* @param whitening option to perform a whitened projection
* @return a new sample with the projected vector and the same label
*/
public TrainingSample<double[]> project(TrainingSample<double[]> s, boolean whitening) {
double[] px = new double[projectors.length];
for(int i = 0 ; i < projectors.length ; i++) {
px[i] = dot(projectors[i], add(s.sample, -1, mean));
if(whitening) {
px[i] *= whitening_coeff[i];
}
}
return new TrainingSample<double[]>(px, s.label);
}
/**
* Performs the projection on a list of samples.
* @param list the list of input samples
* @return a new list with projected samples
*/
public List<TrainingSample<double[]>> projectList(final List<TrainingSample<double[]>> list) {
List<TrainingSample<double[]>> out = new ArrayList<TrainingSample<double[]>>();
for(TrainingSample<double[]> t : list) {
out.add(project(t));
}
return out;
}
/**
* Performs the projection on a list of samples with optional whitening (unitary covariance matrix).
* @param list the list of input samples
* @param whitening option to perform a whitened projection
* @return a new list with projected samples
*/
public List<TrainingSample<double[]>> projectList(final List<TrainingSample<double[]>> list, boolean whitening) {
List<TrainingSample<double[]>> out = new ArrayList<TrainingSample<double[]>>();
for(TrainingSample<double[]> t : list) {
out.add(project(t, whitening));
}
return out;
}
}
| bsd-3-clause |
jingjidejuren/mongodb-orm | src/main/java/com/mongodb/orm/builder/statement/CommandStatement.java | 2461 | package com.mongodb.orm.builder.statement;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.mongodb.constant.ORM;
import com.mongodb.exception.StatementException;
import com.mongodb.orm.engine.Config;
import com.mongodb.orm.engine.config.CommandConfig;
import com.mongodb.orm.engine.entry.NodeEntry;
/**
* Transform SQL file for ORM, "command" node statement.
* @author: xiangping_yu
* @data : 2014-1-22
* @since : 1.5
*/
public class CommandStatement extends BaseStatement implements StatementHandler {
private String id;
/**
* Command node analyzes.
*/
@SuppressWarnings("serial")
private static final Map<String, NodeAnalyze<CommandConfig>> analyzes = new HashMap<String, NodeAnalyze<CommandConfig>>() {
{
put(ORM.NODE_QUERY, new QueryNodeAnalyze());
put(ORM.NODE_FIELD, new FieldNodeAnalyze());
}
};
public CommandStatement(String id) {
this.id = id;
}
@Override
public Config handler(Node node) {
CommandConfig command = new CommandConfig(id);
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node n = childNodes.item(i);
String nodeName = n.getNodeName();
NodeAnalyze<CommandConfig> analyze = analyzes.get(nodeName);
if (analyze == null) {
throw new StatementException("Error child node for 'command', id '" + id + "'.");
}
analyze.analyze(command, n);
}
logger.debug("Mongo config '" + id + "' has inited.");
return command;
}
private static class QueryNodeAnalyze implements NodeAnalyze<CommandConfig> {
@Override
public void analyze(CommandConfig config, Node node) {
if (config.getQuery() != null) {
throw new StatementException("Alias name conflict occurred. The node 'query' is already exists in '" + config.getId() + "'.");
}
NodeEntry entry = getQuery(config.getId(), node);
config.setQuery(entry);
}
}
private static class FieldNodeAnalyze implements NodeAnalyze<CommandConfig> {
@Override
public void analyze(CommandConfig config, Node node) {
if (config.getField() != null) {
throw new StatementException("Alias name conflict occurred. The node 'field' is already exists in '" + config.getId() + "'.");
}
NodeEntry entry = getField(config.getId(), node);
config.setField(entry);
}
}
}
| bsd-3-clause |
yegor256/ymock | ymock-mocks/mock-socket/src/main/java/com/ymock/mock/socket/DataBridge.java | 2113 | /**
* Copyright (c) 2011-2012, yMock.com
* 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 yMock.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
* 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.ymock.mock.socket;
import java.io.IOException;
/**
* Bridge between this component and {@link YMockClient}.
*
* @author Yegor Bugayenko (yegor@ymock.com)
* @version $Id$
*/
interface DataBridge {
/**
* Send message to {@link YMockClient}.
* @param message The message to send
* @throws IOException If something goes wrong
*/
void send(final String message) throws IOException;
/**
* Receive message from {@link YMockClient}.
* @return The message to send
*/
String receive();
}
| bsd-3-clause |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vma/src/generated/java/org/lwjgl/util/vma/VmaRecordSettings.java | 14303 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.util.vma;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Parameters for recording calls to VMA functions. To be used in {@link VmaAllocatorCreateInfo}{@code ::pRecordSettings}.
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VmaRecordSettings {
* VmaRecordFlags {@link #flags};
* char const * {@link #pFilePath};
* }</code></pre>
*/
public class VmaRecordSettings extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
FLAGS,
PFILEPATH;
static {
Layout layout = __struct(
__member(4),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
FLAGS = layout.offsetof(0);
PFILEPATH = layout.offsetof(1);
}
/**
* Creates a {@code VmaRecordSettings} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VmaRecordSettings(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** flags for recording. Must be:<br><table><tr><td>{@link Vma#VMA_RECORD_FLUSH_AFTER_CALL_BIT RECORD_FLUSH_AFTER_CALL_BIT}</td></tr></table> */
@NativeType("VmaRecordFlags")
public int flags() { return nflags(address()); }
/**
* path to the file that should be written by the recording.
*
* <p>Suggested extension: "csv". If the file already exists, it will be overwritten. It will be opened for the whole time {@code VmaAllocator} object is
* alive. If opening this file fails, creation of the whole allocator object fails.</p>
*/
@NativeType("char const *")
public ByteBuffer pFilePath() { return npFilePath(address()); }
/**
* path to the file that should be written by the recording.
*
* <p>Suggested extension: "csv". If the file already exists, it will be overwritten. It will be opened for the whole time {@code VmaAllocator} object is
* alive. If opening this file fails, creation of the whole allocator object fails.</p>
*/
@NativeType("char const *")
public String pFilePathString() { return npFilePathString(address()); }
/** Sets the specified value to the {@link #flags} field. */
public VmaRecordSettings flags(@NativeType("VmaRecordFlags") int value) { nflags(address(), value); return this; }
/** Sets the address of the specified encoded string to the {@link #pFilePath} field. */
public VmaRecordSettings pFilePath(@NativeType("char const *") ByteBuffer value) { npFilePath(address(), value); return this; }
/** Initializes this struct with the specified values. */
public VmaRecordSettings set(
int flags,
ByteBuffer pFilePath
) {
flags(flags);
pFilePath(pFilePath);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VmaRecordSettings set(VmaRecordSettings src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VmaRecordSettings} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VmaRecordSettings malloc() {
return wrap(VmaRecordSettings.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VmaRecordSettings} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VmaRecordSettings calloc() {
return wrap(VmaRecordSettings.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VmaRecordSettings} instance allocated with {@link BufferUtils}. */
public static VmaRecordSettings create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VmaRecordSettings.class, memAddress(container), container);
}
/** Returns a new {@code VmaRecordSettings} instance for the specified memory address. */
public static VmaRecordSettings create(long address) {
return wrap(VmaRecordSettings.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VmaRecordSettings createSafe(long address) {
return address == NULL ? null : wrap(VmaRecordSettings.class, address);
}
/**
* Returns a new {@link VmaRecordSettings.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VmaRecordSettings.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VmaRecordSettings.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VmaRecordSettings.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VmaRecordSettings.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VmaRecordSettings.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }
/**
* Returns a new {@code VmaRecordSettings} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VmaRecordSettings malloc(MemoryStack stack) {
return wrap(VmaRecordSettings.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VmaRecordSettings} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VmaRecordSettings calloc(MemoryStack stack) {
return wrap(VmaRecordSettings.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VmaRecordSettings.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VmaRecordSettings.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VmaRecordSettings.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #flags}. */
public static int nflags(long struct) { return UNSAFE.getInt(null, struct + VmaRecordSettings.FLAGS); }
/** Unsafe version of {@link #pFilePath}. */
public static ByteBuffer npFilePath(long struct) { return memByteBufferNT1(memGetAddress(struct + VmaRecordSettings.PFILEPATH)); }
/** Unsafe version of {@link #pFilePathString}. */
public static String npFilePathString(long struct) { return memASCII(memGetAddress(struct + VmaRecordSettings.PFILEPATH)); }
/** Unsafe version of {@link #flags(int) flags}. */
public static void nflags(long struct, int value) { UNSAFE.putInt(null, struct + VmaRecordSettings.FLAGS, value); }
/** Unsafe version of {@link #pFilePath(ByteBuffer) pFilePath}. */
public static void npFilePath(long struct, ByteBuffer value) {
if (CHECKS) { checkNT1(value); }
memPutAddress(struct + VmaRecordSettings.PFILEPATH, memAddress(value));
}
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param struct the struct to validate
*/
public static void validate(long struct) {
check(memGetAddress(struct + VmaRecordSettings.PFILEPATH));
}
// -----------------------------------
/** An array of {@link VmaRecordSettings} structs. */
public static class Buffer extends StructBuffer<VmaRecordSettings, Buffer> implements NativeResource {
private static final VmaRecordSettings ELEMENT_FACTORY = VmaRecordSettings.create(-1L);
/**
* Creates a new {@code VmaRecordSettings.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VmaRecordSettings#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VmaRecordSettings getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link VmaRecordSettings#flags} field. */
@NativeType("VmaRecordFlags")
public int flags() { return VmaRecordSettings.nflags(address()); }
/** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@link VmaRecordSettings#pFilePath} field. */
@NativeType("char const *")
public ByteBuffer pFilePath() { return VmaRecordSettings.npFilePath(address()); }
/** @return the null-terminated string pointed to by the {@link VmaRecordSettings#pFilePath} field. */
@NativeType("char const *")
public String pFilePathString() { return VmaRecordSettings.npFilePathString(address()); }
/** Sets the specified value to the {@link VmaRecordSettings#flags} field. */
public VmaRecordSettings.Buffer flags(@NativeType("VmaRecordFlags") int value) { VmaRecordSettings.nflags(address(), value); return this; }
/** Sets the address of the specified encoded string to the {@link VmaRecordSettings#pFilePath} field. */
public VmaRecordSettings.Buffer pFilePath(@NativeType("char const *") ByteBuffer value) { VmaRecordSettings.npFilePath(address(), value); return this; }
}
} | bsd-3-clause |
lockss/lockss-daemon | src/org/lockss/servlet/DaemonStatus.java | 31321 | /*
Copyright (c) 2000-2021 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.servlet;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import org.mortbay.html.*;
import org.w3c.dom.Document;
import org.lockss.config.*;
import org.lockss.daemon.status.*;
import org.lockss.plugin.PluginManager;
import org.lockss.util.*;
/**
* DaemonStatus servlet
*/
public class DaemonStatus extends LockssServlet {
private static final Logger log = Logger.getLogger(DaemonStatus.class);
/** Supported output formats */
static final int OUTPUT_HTML = 1;
static final int OUTPUT_TEXT = 2;
static final int OUTPUT_XML = 3;
static final int OUTPUT_CSV = 4;
private String tableName;
private String tableKey;
private String sortKey;
private StatusTable statTable;
private StatusService statSvc;
private int outputFmt;
private java.util.List rules;
private BitSet tableOptions;
private PluginManager pluginMgr;
protected void resetLocals() {
super.resetLocals();
rules = null;
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
statSvc = getLockssDaemon().getStatusService();
pluginMgr = getLockssDaemon().getPluginManager();
}
static final Set fixedParams =
SetUtil.set("text", "output", "options", "table", "key", "sort");
/**
* Handle a request
* @throws IOException
*/
public void lockssHandleRequest() throws IOException {
if (!StringUtil.isNullString(req.getParameter("isDaemonReady"))) {
if (pluginMgr.areAusStarted()) {
resp.setStatus(200);
PrintWriter wrtr = resp.getWriter();
resp.setContentType("text/plain");
wrtr.println("true");
} else {
PrintWriter wrtr = resp.getWriter();
resp.setContentType("text/plain");
wrtr.println("false");
resp.sendError(202, "Not ready");
}
return;
}
outputFmt = OUTPUT_HTML; // default output is html
String outputParam = req.getParameter("output");
if (!StringUtil.isNullString(outputParam)) {
if ("html".equalsIgnoreCase(outputParam)) {
outputFmt = OUTPUT_HTML;
} else if ("xml".equalsIgnoreCase(outputParam)) {
outputFmt = OUTPUT_XML;
} else if ("text".equalsIgnoreCase(outputParam)) {
outputFmt = OUTPUT_TEXT;
} else if ("csv".equalsIgnoreCase(outputParam)) {
outputFmt = OUTPUT_CSV;
} else {
log.warning("Unknown output format: " + outputParam);
}
}
String optionsParam = req.getParameter("options");
tableOptions = new BitSet();
if (isDebugUser()) {
log.debug2("Debug user. Setting OPTION_DEBUG_USER");
tableOptions.set(StatusTable.OPTION_DEBUG_USER);
}
for (Iterator iter = StringUtil.breakAt(optionsParam, ',').iterator();
iter.hasNext(); ) {
String s = (String)iter.next();
if ("norows".equalsIgnoreCase(s)) {
tableOptions.set(StatusTable.OPTION_NO_ROWS);
}
}
tableName = req.getParameter("table");
tableKey = req.getParameter("key");
if (StringUtil.isNullString(tableName)) {
tableName = statSvc.getDefaultTableName();
}
if (StringUtil.isNullString(tableKey)) {
tableKey = null;
}
sortKey = req.getParameter("sort");
if (StringUtil.isNullString(sortKey)) {
sortKey = null;
}
switch (outputFmt) {
case OUTPUT_HTML:
doHtmlStatusTable();
break;
case OUTPUT_XML:
try {
doXmlStatusTable();
} catch (XmlDomBuilder.XmlDomException xde) {
throw new IOException("Error building XML", xde);
}
break;
case OUTPUT_TEXT:
doTextStatusTable();
break;
case OUTPUT_CSV:
doCsvStatusTable();
break;
}
}
private Page newTablePage() throws IOException {
Page page = newPage();
addJavaScript(page);
if (!pluginMgr.areAusStarted()) {
page.add(ServletUtil.notStartedWarning());
}
// After resp.getWriter() has been called, throwing an exception will
// result in a blank page, so don't call it until the end.
// (HttpResponse.sendError() calls getOutputStream(), and only one of
// getWriter() or getOutputStream() may be called.)
// all pages but index get a select box to choose a different table
if (!isAllTablesTable()) {
Block centeredBlock = new Block(Block.Center);
centeredBlock.add(getSelectTableForm());
page.add(centeredBlock);
page.add(ServletUtil.removeElementWithId("dsSelectBox"));
}
// page.add("<center>");
// page.add(srvLink(SERVLET_DAEMON_STATUS, ".",
// concatParams("text=1", req.getQueryString())));
// page.add("</center><br><br>");
return page;
}
private void doHtmlStatusTable() throws IOException {
Page page = doHtmlStatusTable0();
endPage(page);
}
private void doTextStatusTable() throws IOException {
PrintWriter wrtr = resp.getWriter();
resp.setContentType("text/plain");
// String vPlatform = CurrentConfig.getParam(PARAM_PLATFORM_VERSION);
String vPlatform;
PlatformVersion pVer = ConfigManager.getPlatformVersion();
if (pVer != null) {
vPlatform = ", platform=" + StringUtil.ckvEscape(pVer.displayString());
} else {
vPlatform = "";
}
Date now = new Date();
Date startDate = getLockssDaemon().getStartDate();
wrtr.println("host=" + getLcapIPAddr() +
",time=" + now.getTime() +
",up=" + TimeBase.msSince(startDate.getTime()) +
",version=" + BuildInfo.getBuildInfoString() +
vPlatform);
doTextStatusTable(wrtr);
}
private StatusTable makeTable() throws StatusService.NoSuchTableException {
StatusTable table = new StatusTable(tableName, tableKey);
table.setOptions(tableOptions);
for (Enumeration en = req.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
if (!fixedParams.contains(name)) {
table.setProperty(name, req.getParameter(name));
}
}
statSvc.fillInTable(table);
return table;
}
// build and send an XML DOM Document of the StatusTable
private void doXmlStatusTable()
throws IOException, XmlDomBuilder.XmlDomException {
// By default, XmlDomBuilder will produce UTF-8. Must set content type
// *before* calling getWriter()
resp.setContentType("text/xml; charset=UTF-8");
PrintWriter wrtr = resp.getWriter();
try {
StatusTable statTable = makeTable();
XmlStatusTable xmlTable = new XmlStatusTable(statTable);
String over = req.getParameter("outputVersion");
if (over != null) {
try {
int ver = Integer.parseInt(over);
xmlTable.setOutputVersion(ver);
} catch (NumberFormatException e) {
log.warning("Illegal outputVersion: " + over + ": " + e.toString());
}
}
Document xmlTableDoc = xmlTable.getTableDocument();
XmlDomBuilder.serialize(xmlTableDoc, wrtr);
} catch (Exception e) {
XmlDomBuilder xmlBuilder =
new XmlDomBuilder(XmlStatusConstants.NS_PREFIX,
XmlStatusConstants.NS_URI,
"1.0");
Document errorDoc = XmlDomBuilder.createDocument();
org.w3c.dom.Element rootElem = xmlBuilder.createRoot(errorDoc,
XmlStatusConstants.ERROR);
if (e instanceof StatusService.NoSuchTableException) {
XmlDomBuilder.addText(rootElem, "No such table: " + e.toString());
} else {
String emsg = e.toString();
StringBuilder buffer = new StringBuilder("Error getting table: ");
buffer.append(emsg);
buffer.append("\n");
buffer.append(StringUtil.trimStackTrace(emsg,
StringUtil.stackTraceString(e)));
XmlDomBuilder.addText(rootElem, buffer.toString());
}
XmlDomBuilder.serialize(errorDoc, wrtr);
return;
}
}
private java.util.List getRowList(StatusTable statTable) {
java.util.List rowList;
if (sortKey != null) {
try {
rules = makeSortRules(statTable, sortKey);
rowList = statTable.getSortedRows(rules);
} catch (Exception e) {
// There are lots of ways a user-specified sort can fail if the
// table creator isn't careful. Fall back to default if that
// happens.
log.warning("Error sorting table by: " + rules, e);
// XXX should display some sort of error msg
rowList = statTable.getSortedRows();
rules = null; // prevent column titles from indicating
// the sort order that didn't work
}
} else {
rowList = statTable.getSortedRows();
}
return rowList;
}
// Build the table, adding elements to page
private Page doHtmlStatusTable0() throws IOException {
Page page;
try {
statTable = makeTable();
} catch (StatusService.NoSuchTableException e) {
page = newTablePage();
errMsg = "No such table: " + e.getMessage();
layoutErrorBlock(page);
return page;
} catch (Exception e) {
page = newTablePage();
errMsg = "Error getting table: " + e.toString();
layoutErrorBlock(page);
if (isDebugUser()) {
page.add("<br><pre> ");
page.add(StringUtil.trimStackTrace(e.toString(),
StringUtil.stackTraceString(e)));
page.add("</pre>");
}
return page;
}
java.util.List colList = statTable.getColumnDescriptors();
java.util.List rowList = getRowList(statTable);
String title0 = htmlEncode(statTable.getTitle());
String titleFoot = htmlEncode(statTable.getTitleFootnote());
page = newTablePage();
Table table = null;
// convert list of ColumnDescriptors to array of ColumnDescriptors
ColumnDescriptor cds[];
int cols;
if (colList != null) {
cds = (ColumnDescriptor [])colList.toArray(new ColumnDescriptor[0]);
cols = cds.length;
} else {
cds = new ColumnDescriptor[0];
cols = 1;
}
if (true || !rowList.isEmpty()) {
// if table not empty, output column headings
// Make the table. Make a narrow empty column between real columns,
// for spacing. Resulting table will have 2*cols-1 columns
table = new Table(0, "ALIGN=CENTER CELLSPACING=2 CELLPADDING=0");
String title = title0 + addFootnote(titleFoot);
table.newRow();
table.addHeading(title, "ALIGN=CENTER COLSPAN=" + (cols * 2 - 1));
table.newRow();
addSummaryInfo(table, statTable, cols);
if (colList != null) {
// output column headings
for (int ix = 0; ix < cols; ix++) {
ColumnDescriptor cd = cds[ix];
table.newCell("class=\"colhead\" valign=\"bottom\" align=\"" +
((cols == 1) ? "center" : getColAlignment(cd)) + "\"");
table.add(getColumnTitleElement(statTable, cd, rules));
if (ix < (cols - 1)) {
table.newCell("width=8");
table.add(" ");
}
}
}
}
// Create (but do not yet refer to) any footnotes that the table wants
// to be in a specific order
for (String orderedFoot : statTable.getOrderedFootnotes()) {
addFootnote(orderedFoot);
}
if (rowList != null) {
// output rows
for (Iterator rowIter = rowList.iterator(); rowIter.hasNext(); ) {
Map rowMap = (Map)rowIter.next();
if (rowMap.get(StatusTable.ROW_SEPARATOR) != null) {
table.newRow();
table.newCell("align=center colspan=" + (cols * 2 - 1));
table.add("<hr>");
}
table.newRow();
for (int ix = 0; ix < cols; ix++) {
ColumnDescriptor cd = cds[ix];
Object val = rowMap.get(cd.getColumnName());
table.newCell("valign=\"top\" align=\"" + getColAlignment(cd) + "\"");
table.add(getDisplayString(val, cd.getType()));
if (ix < (cols - 1)) {
table.newCell(); // empty column for spacing
}
}
}
}
if (table != null) {
Form frm = new Form(srvURL(myServletDescr()));
// use GET so user can refresh in browser
frm.method("GET");
frm.add(table);
page.add(frm);
page.add("<br>");
}
return page;
}
private String htmlEncode(String s) {
if (s == null) {
return null;
}
return HtmlUtil.htmlEncode(s);
}
/** Prepend table name to servlet-specfici part of page title */
protected String getTitleHeading() {
if (statTable == null) {
return super.getTitleHeading();
} else {
return statTable.getTitle() + " - " + super.getTitleHeading();
}
}
// Build the table, writing text to wrtr
private void doTextStatusTable(PrintWriter wrtr) throws IOException {
StatusTable statTable;
try {
statTable = makeTable();
} catch (StatusService.NoSuchTableException e) {
wrtr.println("No table: " + e.toString());
return;
} catch (Exception e) {
wrtr.println("Error getting table: " + e.toString());
return;
}
wrtr.println();
wrtr.print("table=" + StringUtil.ckvEscape(statTable.getTitle()));
if (tableKey != null) {
wrtr.print(",key=" + StringUtil.ckvEscape(tableKey));
}
java.util.List summary = statTable.getSummaryInfo();
if (summary != null && !summary.isEmpty()) {
for (Iterator iter = summary.iterator(); iter.hasNext(); ) {
StatusTable.SummaryInfo sInfo = (StatusTable.SummaryInfo)iter.next();
wrtr.print(",");
wrtr.print(sInfo.getTitle());
wrtr.print("=");
Object dispVal = getTextDisplayString(sInfo.getValue());
String valStr = dispVal != null ? dispVal.toString() : "(null)";
wrtr.print(StringUtil.ckvEscape(valStr));
}
}
wrtr.println();
java.util.List rowList = getRowList(statTable);
if (rowList != null) {
// output rows
for (Iterator rowIter = rowList.iterator(); rowIter.hasNext(); ) {
Map rowMap = (Map)rowIter.next();
for (Iterator iter = rowMap.keySet().iterator(); iter.hasNext(); ) {
Object o = iter.next();
if (!(o instanceof String)) {
// ignore special markers (eg, StatusTable.ROW_SEPARATOR)
continue;
}
String key = (String)o;
Object val = rowMap.get(key);
Object dispVal = getTextDisplayString(val);
String valStr = dispVal != null ? dispVal.toString() : "(null)";
wrtr.print(key + "=" + StringUtil.ckvEscape(valStr));
if (iter.hasNext()) {
wrtr.print(",");
} else {
wrtr.println();
}
}
}
}
}
// Build the table, writing csv to wrtr
private void doCsvStatusTable() throws IOException {
PrintWriter wrtr = resp.getWriter();
resp.setContentType("text/plain");
StatusTable statTable;
try {
statTable = makeTable();
} catch (StatusService.NoSuchTableException e) {
wrtr.println("No table: " + e.toString());
return;
} catch (Exception e) {
wrtr.println("Error getting table: " + e.toString());
return;
}
java.util.List<ColumnDescriptor> colList =
statTable.getColumnDescriptors();
java.util.List<Map> rowList = getRowList(statTable);
if (colList != null) {
for (Iterator colIter = colList.iterator(); colIter.hasNext(); ) {
ColumnDescriptor cd = (ColumnDescriptor)colIter.next();
wrtr.print(StringUtil.csvEncode(cd.getTitle()));
if (colIter.hasNext()) {
wrtr.print(",");
} else {
wrtr.println();
}
}
if (rowList != null) {
// output rows
for (Map rowMap : rowList) {
for (Iterator colIter = colList.iterator(); colIter.hasNext(); ) {
ColumnDescriptor cd = (ColumnDescriptor)colIter.next();
Object val = rowMap.get(cd.getColumnName());
Object dispVal = getTextDisplayString(val);
String valStr = dispVal != null ? dispVal.toString() : "(null)";
wrtr.print(StringUtil.csvEncode(valStr));
if (colIter.hasNext()) {
wrtr.print(",");
} else {
wrtr.println();
}
}
}
}
} else {
wrtr.println("(Empty table)");
}
}
static final Image UPARROW1 = ServletUtil.image("uparrow1blue.gif", 16, 16, 0,
"Primary sort column, ascending");
static final Image UPARROW2 = ServletUtil.image("uparrow2blue.gif", 16, 16, 0,
"Secondary sort column, ascending");
static final Image DOWNARROW1 = ServletUtil.image("downarrow1blue.gif", 16, 16, 0,
"Primary sort column, descending");
static final Image DOWNARROW2 = ServletUtil.image("downarrow2blue.gif", 16, 16, 0,
"Secondary sort column, descending");
/** Create a column heading element:<ul>
* <li> plain text if not sortable
* <li> if sortable, link with sortkey set to solumn name,
* descending if was previous primary ascending key
* <li> plus a possible secondary sort key set to previous sort column
* <li> if is current primary or secondary sort colume, display an up or
* down arrow.</ul>
* @param statTable
* @param cd
* @param rules the SortRules used to sort the currently displayed table
*/
Composite getColumnTitleElement(StatusTable statTable, ColumnDescriptor cd,
java.util.List rules) {
Composite elem = new Composite();
Image sortArrow = null;
boolean ascending = getDefaultSortAscending(cd);
String colTitle = cd.getTitle();
if (true && statTable.isResortable() && cd.isSortable()) {
String ruleParam;
if (rules != null && !rules.isEmpty()) {
StatusTable.SortRule rule1 = (StatusTable.SortRule)rules.get(0);
if (cd.getColumnName().equals(rule1.getColumnName())) {
// This column is the current primary sort; link to reverse order
ascending = !rule1.sortAscending();
// and display a primary arrow
sortArrow = rule1.sortAscending() ? UPARROW1 : DOWNARROW1;
if (rules.size() > 1) {
// keep same secondary sort key if there was one
StatusTable.SortRule rule2 = (StatusTable.SortRule)rules.get(1);
ruleParam = ruleParam(cd, ascending) + "," + ruleParam(rule2);
} else {
ruleParam = ruleParam(cd, ascending);
}
} else {
if (rules.size() > 1) {
StatusTable.SortRule rule2 = (StatusTable.SortRule)rules.get(1);
if (cd.getColumnName().equals(rule2.getColumnName())) {
// This is the secondary sort column; display secondary arrow
sortArrow = rule2.sortAscending() ? UPARROW2 : DOWNARROW2;
}
}
// primary sort is this column, secondary is previous primary
ruleParam = ruleParam(cd, ascending) + "," + ruleParam(rule1);
}
} else {
// no previous, sort by column
ruleParam = ruleParam(cd, ascending);
}
Link link = new Link(srvURL(myServletDescr(),
modifyParams("sort", ruleParam)),
colTitle);
link.attribute("class", "colhead");
elem.add(link);
String foot = cd.getFootnote();
if (foot != null) {
elem.add(addFootnote(foot));
}
if (sortArrow != null) {
elem.add(sortArrow);
}
} else {
elem.add(colTitle);
elem.add(addFootnote(cd.getFootnote()));
}
return elem;
}
String ruleParam(ColumnDescriptor cd, boolean ascending) {
return (ascending ? "A" : "D") + cd.getColumnName();
}
String ruleParam(StatusTable.SortRule rule) {
return (rule.sortAscending() ? "A" : "D") + rule.getColumnName();
}
java.util.List makeSortRules(StatusTable statTable, String sortKey) {
Map columnDescriptorMap = statTable.getColumnDescriptorMap();
java.util.List cols = StringUtil.breakAt(sortKey, ',');
java.util.List res = new ArrayList();
for (Iterator iter = cols.iterator(); iter.hasNext(); ) {
String spec = (String)iter.next();
boolean ascending = spec.charAt(0) == 'A';
String col = spec.substring(1);
StatusTable.SortRule defaultRule =
getDefaultRuleForColumn(statTable, col);
StatusTable.SortRule rule;
Comparator comparator = null;
if (columnDescriptorMap.containsKey(col)) {
ColumnDescriptor cd = (ColumnDescriptor)columnDescriptorMap.get(col);
comparator = cd.getComparator();
}
if (defaultRule != null && defaultRule.getComparator() != null) {
comparator = defaultRule.getComparator();
}
if (comparator != null) {
rule = new StatusTable.SortRule(col, comparator, ascending);
} else {
rule = new StatusTable.SortRule(col, ascending);
}
res.add(rule);
}
log.debug2("rules: " + res);
return res;
}
private StatusTable.SortRule getDefaultRuleForColumn(StatusTable statTable,
String col) {
java.util.List defaults = statTable.getDefaultSortRules();
for (Iterator iter = defaults.iterator(); iter.hasNext(); ) {
StatusTable.SortRule rule = (StatusTable.SortRule)iter.next();
if (col.equals(rule.getColumnName())) {
return rule;
}
}
return null;
}
private void addSummaryInfo(Table table, StatusTable statTable, int cols) {
java.util.List summary = statTable.getSummaryInfo();
if (summary != null && !summary.isEmpty()) {
for (Iterator iter = summary.iterator(); iter.hasNext(); ) {
StatusTable.SummaryInfo sInfo =
(StatusTable.SummaryInfo)iter.next();
table.newRow();
StringBuilder sb = null;
String stitle = sInfo.getTitle();
if (!StringUtil.isNullString(stitle)) {
sb = new StringBuilder();
sb.append("<b>");
sb.append(stitle);
if (sInfo.getHeaderFootnote() != null) {
sb.append(addFootnote(sInfo.getHeaderFootnote()));
}
sb.append("</b>: ");
}
table.newCell("COLSPAN=" + (cols * 2 - 1));
// make a 2 cell table for each row, so multiline values will be
// aligned
Table itemtab = new Table(0, "align=left cellspacing=0 cellpadding=0");
itemtab.newRow();
if (sb != null) {
itemtab.newCell("valign=top");
itemtab.add(sb.toString());
}
Object sval = sInfo.getValue();
if (sval != null) {
itemtab.newCell();
StringBuilder valSb = new StringBuilder();
valSb.append(getDisplayString(sval, sInfo.getType()));
if (sInfo.getValueFootnote() != null) {
valSb.append(addFootnote(sInfo.getValueFootnote()));
}
itemtab.add(valSb.toString());
}
table.add(itemtab);
}
table.newRow();
}
}
private String getColAlignment(ColumnDescriptor cd) {
switch (cd.getType()) {
case ColumnDescriptor.TYPE_STRING:
case ColumnDescriptor.TYPE_DATE:
case ColumnDescriptor.TYPE_IP_ADDRESS:
case ColumnDescriptor.TYPE_TIME_INTERVAL:
default:
return "left";
case ColumnDescriptor.TYPE_INT:
case ColumnDescriptor.TYPE_PERCENT:
case ColumnDescriptor.TYPE_AGREEMENT:
case ColumnDescriptor.TYPE_FLOAT: // tk - should align decimal points?
return "right";
}
}
private boolean getDefaultSortAscending(ColumnDescriptor cd) {
switch (cd.getType()) {
case ColumnDescriptor.TYPE_STRING:
case ColumnDescriptor.TYPE_IP_ADDRESS:
case ColumnDescriptor.TYPE_TIME_INTERVAL:
default:
return true;
case ColumnDescriptor.TYPE_INT:
case ColumnDescriptor.TYPE_PERCENT:
case ColumnDescriptor.TYPE_AGREEMENT:
case ColumnDescriptor.TYPE_FLOAT: // tk - should align decimal points?
case ColumnDescriptor.TYPE_DATE:
return false;
}
}
// Handle lists
private String getTextDisplayString(Object val) {
if (val == StatusTable.NO_VALUE) {
// Some, but not all text formats avoid calling this with NO_VALUE
return "";
}
Object aval = StatusTable.getActualValue(val);
if (aval instanceof Collection) {
StringBuilder sb = new StringBuilder();
for (Iterator iter = ((Collection)aval).iterator(); iter.hasNext(); ) {
sb.append(StatusTable.getActualValue(iter.next()));
}
return sb.toString();
} else {
return aval != null ? aval.toString() : "(null)";
}
}
// Handle lists
private String getDisplayString(Object val, int type) {
if (val instanceof Collection) {
return getCollectionDisplayString((Collection)val,
StatusTable.DisplayedValue.Layout.None,
type);
} else {
return getDisplayString0(val, type);
}
}
// Handle lists
private String getCollectionDisplayString(Collection coll,
StatusTable.DisplayedValue.Layout layout,
int type) {
StringBuilder sb = new StringBuilder();
for (Iterator iter = coll.iterator(); iter.hasNext(); ) {
sb.append(getDisplayString0(iter.next(), type));
switch (layout) {
case Column:
if (iter.hasNext()) {
sb.append("<br>");
}
default:
}
}
return sb.toString();
}
// Process References and other links
private String getDisplayString0(Object val, int type) {
if (val instanceof StatusTable.Reference) {
return getRefString((StatusTable.Reference)val, type);
} else if (val instanceof StatusTable.SrvLink) {
// Display as link iff user is allowed access to the target servlet
StatusTable.SrvLink slink = (StatusTable.SrvLink)val;
if (isServletRunnable(slink.getServletDescr())) {
return getSrvLinkString(slink, type);
} else {
return getDisplayString1(StatusTable.getActualValue(val), type);
}
} else if (val instanceof StatusTable.LinkValue) {
// A LinkValue type we don't know about. Just display its embedded
// value.
return getDisplayString1(StatusTable.getActualValue(val), type);
} else {
return getDisplayString1(val, type);
}
}
// turn References into html links
private String getRefString(StatusTable.Reference ref, int type) {
StringBuilder sb = new StringBuilder();
sb.append("table=");
sb.append(ref.getTableName());
String key = ref.getKey();
if (!StringUtil.isNullString(key)) {
sb.append("&key=");
sb.append(urlEncode(key));
}
Properties refProps = ref.getProperties();
if (refProps != null) {
for (Iterator iter = refProps.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry ent = (Map.Entry)iter.next();
sb.append("&");
sb.append(ent.getKey());
sb.append("=");
sb.append(urlEncode((String)ent.getValue()));
}
}
if (ref.getPeerId() != null) {
return srvAbsLink(ref.getPeerId(),
myServletDescr(),
getDisplayString(ref.getValue(), type),
sb.toString());
} else {
return srvLink(myServletDescr(),
getDisplayString(ref.getValue(), type),
sb.toString());
}
}
// turn UrlLink into html link
private String getSrvLinkString(StatusTable.SrvLink link, int type) {
return srvLink(link.getServletDescr(),
getDisplayString1(link.getValue(), type),
link.getArgs());
}
// add display attributes from a DisplayedValue
private String getDisplayString1(Object val, int type) {
if (val instanceof StatusTable.DisplayedValue) {
StatusTable.DisplayedValue dval = (StatusTable.DisplayedValue)val;
Object innerVal = dval.getValue();
if (innerVal instanceof Collection) {
return getCollectionDisplayString((Collection)innerVal,
dval.getLayout(),
type);
}
String str = dval.hasDisplayString()
? HtmlUtil.htmlEncode(dval.getDisplayString())
: getDisplayString1(innerVal, type);
String color = dval.getColor();
java.util.List<String> footnotes = dval.getFootnotes();
if (color != null) {
str = "<font color=" + color + ">" + str + "</font>";
}
if (dval.getBold()) {
str = "<b>" + str + "</b>";
}
boolean notFirst = false;
for (String foot : footnotes) {
str = str + addFootnote(foot, notFirst);
notFirst = true;
}
String hoverText = dval.getHoverText();
if (!StringUtil.isNullString(hoverText)) {
str = "<div title=\"" + hoverText + "\">" + str + "</div>";
}
return str;
} else {
String str = getDisplayConverter().convertDisplayString(val, type);
if (type == ColumnDescriptor.TYPE_STRING) {
str = HtmlUtil.htmlEncode(str);
}
return str;
}
}
DisplayConverter dispConverter;
private DisplayConverter getDisplayConverter() {
if (dispConverter == null) {
dispConverter = new DisplayConverter();
}
return dispConverter;
}
private static BitSet debugOptions = new BitSet();
static {
debugOptions.set(StatusTable.OPTION_DEBUG_USER);
}
/**
* Build a form with a select box that fetches a named table
* @return the Composite object
*/
private Composite getSelectTableForm() {
try {
StatusTable statTable =
statSvc.getTable(StatusService.ALL_TABLES_TABLE, null,
isDebugUser() ? debugOptions : null);
java.util.List colList = statTable.getColumnDescriptors();
java.util.List rowList = statTable.getSortedRows();
ColumnDescriptor cd = (ColumnDescriptor)colList.get(0);
Select sel = new Select("table", false);
sel.attribute("onchange", "this.form.submit()");
boolean foundIt = false;
for (Iterator rowIter = rowList.iterator(); rowIter.hasNext(); ) {
Map rowMap = (Map)rowIter.next();
Object val = rowMap.get(cd.getColumnName());
String display = StatusTable.getActualValue(val).toString();
if (val instanceof StatusTable.Reference) {
StatusTable.Reference ref = (StatusTable.Reference)val;
String key = ref.getTableName();
// select the current table
boolean isThis = (tableKey == null) && tableName.equals(key);
foundIt = foundIt || isThis;
sel.add(display, isThis, key);
} else {
sel.add(display, false);
}
}
// if not currently displaying a table in the list, select a blank entry
if (!foundIt) {
sel.add(" ", true, "");
}
Form frm = new Form(srvURL(myServletDescr()));
// use GET so user can refresh in browser
frm.method("GET");
frm.add(sel);
Input submit = new Input(Input.Submit, "foo", "Go");
submit.attribute("id", "dsSelectBox");
frm.add(submit);
return frm;
} catch (Exception e) {
// if this fails for any reason, just don't include this form
log.warning("Failed to build status table selector", e);
return new Composite();
}
}
protected boolean isAllTablesTable() {
return StatusService.ALL_TABLES_TABLE.equals(tableName);
}
// make me a link in nav table unless I'm displaying table of all tables
protected boolean linkMeInNav() {
return !isAllTablesTable();
}
}
| bsd-3-clause |
mattunderscorechampion/tree-root | tree-traversers/src/test/java/com/mattunderscore/trees/traversers/PostOrderIteratorTest.java | 5016 | /* Copyright © 2014 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.trees.traversers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mattunderscore.trees.linked.tree.Constructor;
import com.mattunderscore.trees.mutable.MutableSettableStructuredNode;
import com.mattunderscore.trees.spi.DefaultRemovalHandler;
import com.mattunderscore.trees.tree.Tree;
/**
* Tests for post-order iterator.
* @author Matt Champion on 03/09/14.
*/
public final class PostOrderIteratorTest {
private static Tree<String, MutableSettableStructuredNode<String>> tree;
private Iterator<? extends MutableSettableStructuredNode<String>> iterator;
private Iterator<String> elementIterator;
@BeforeClass
public static void setUpTree() {
final Constructor<String> constructor = new Constructor<>();
tree = constructor.build(
"f",
constructor.build(
"b",
constructor.build(
"a"),
constructor.build(
"d",
constructor.build(
"c"),
constructor.build(
"e")
)
),
constructor.build(
"i",
constructor.build(
"h",
constructor.build(
"g"))));
}
@Before
public void setUp() {
iterator = new PostOrderIterator<>(tree, new DefaultRemovalHandler<>());
elementIterator = new NodeToElementIterators<>(iterator);
}
@Test
public void nodeIterator() {
assertEquals("a", iterator.next().getElement());
assertEquals("c", iterator.next().getElement());
assertEquals("e", iterator.next().getElement());
assertEquals("d", iterator.next().getElement());
assertEquals("b", iterator.next().getElement());
assertEquals("g", iterator.next().getElement());
assertEquals("h", iterator.next().getElement());
assertEquals("i", iterator.next().getElement());
assertEquals("f", iterator.next().getElement());
assertFalse(iterator.hasNext());
}
@Test
public void elementIterator() {
assertEquals("a", elementIterator.next());
assertEquals("c", elementIterator.next());
assertEquals("e", elementIterator.next());
assertEquals("d", elementIterator.next());
assertEquals("b", elementIterator.next());
assertEquals("g", elementIterator.next());
assertEquals("h", elementIterator.next());
assertEquals("i", elementIterator.next());
assertEquals("f", elementIterator.next());
assertFalse(iterator.hasNext());
}
@Test(expected = UnsupportedOperationException.class)
public void prestartRemove() {
iterator.remove();
}
@Test(expected = UnsupportedOperationException.class)
public void remove() {
Assert.assertEquals("a", iterator.next().getElement());
iterator.remove();
}
@Test(expected = UnsupportedOperationException.class)
public void prestartElementRemove() {
elementIterator.remove();
}
@Test(expected = UnsupportedOperationException.class)
public void elementRemove() {
assertEquals("a", elementIterator.next());
elementIterator.remove();
}
}
| bsd-3-clause |
intarsys/runtime | src/de/intarsys/tools/functor/ConstantFunctor.java | 2102 | /*
* Copyright (c) 2007, intarsys consulting GmbH
*
* 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 intarsys 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.intarsys.tools.functor;
/**
* A common utility {@link IFunctor} returning a constant value.
*/
public class ConstantFunctor extends CommonFunctor {
private Object constant;
public ConstantFunctor(Object constant) {
this.constant = constant;
}
public Object getConstant() {
return constant;
}
/*
* (non-Javadoc)
*
* @see de.intarsys.tools.functor.IFunctor#perform(de.intarsys.tools.functor.IFunctorCall)
*/
public Object perform(IFunctorCall call) throws FunctorInvocationException {
return getConstant();
}
}
| bsd-3-clause |
DataBiosphere/terra-cli | src/main/java/bio/terra/cli/serialization/userfacing/input/GcsStorageClass.java | 1313 | package bio.terra.cli.serialization.userfacing.input;
import bio.terra.workspace.model.GcpGcsBucketDefaultStorageClass;
/**
* This enum defines the possible storage classes for buckets, and maps these classes to the
* corresponding {@link GcpGcsBucketDefaultStorageClass} enum in the WSM client library. The CLI
* defines its own version of this enum so that:
*
* <p>- The CLI syntax does not change when WSM API changes. In this case, the syntax affected is
* the structure of the user-provided JSON file to specify a lifecycle rule.
*
* <p>- The CLI can more easily control the JSON mapping behavior of the enum. In this case, the WSM
* client library version of the enum provides a @JsonCreator fromValue method that is case
* sensitive, and the CLI may want to allow case insensitive deserialization.
*/
public enum GcsStorageClass {
STANDARD(GcpGcsBucketDefaultStorageClass.STANDARD),
NEARLINE(GcpGcsBucketDefaultStorageClass.NEARLINE),
COLDLINE(GcpGcsBucketDefaultStorageClass.COLDLINE),
ARCHIVE(GcpGcsBucketDefaultStorageClass.ARCHIVE);
private GcpGcsBucketDefaultStorageClass wsmEnumVal;
GcsStorageClass(GcpGcsBucketDefaultStorageClass wsmEnumVal) {
this.wsmEnumVal = wsmEnumVal;
}
public GcpGcsBucketDefaultStorageClass toWSMEnum() {
return this.wsmEnumVal;
}
}
| bsd-3-clause |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkQueryPoolPerformanceCreateInfoKHR.java | 18937 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Structure specifying parameters of a newly created performance query pool.
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code queueFamilyIndex} <b>must</b> be a valid queue family index of the device</li>
* <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-performanceCounterQueryPools">{@code performanceCounterQueryPools}</a> feature <b>must</b> be enabled</li>
* <li>Each element of {@code pCounterIndices} <b>must</b> be in the range of counters reported by {@code vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR} for the queue family specified in {@code queueFamilyIndex}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code sType} <b>must</b> be {@link KHRPerformanceQuery#VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR}</li>
* <li>{@code pCounterIndices} <b>must</b> be a valid pointer to an array of {@code counterIndexCount} {@code uint32_t} values</li>
* <li>{@code counterIndexCount} <b>must</b> be greater than 0</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link KHRPerformanceQuery#vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR GetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR}</p>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkQueryPoolPerformanceCreateInfoKHR {
* VkStructureType {@link #sType};
* void const * {@link #pNext};
* uint32_t {@link #queueFamilyIndex};
* uint32_t {@link #counterIndexCount};
* uint32_t const * {@link #pCounterIndices};
* }</code></pre>
*/
public class VkQueryPoolPerformanceCreateInfoKHR extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
STYPE,
PNEXT,
QUEUEFAMILYINDEX,
COUNTERINDEXCOUNT,
PCOUNTERINDICES;
static {
Layout layout = __struct(
__member(4),
__member(POINTER_SIZE),
__member(4),
__member(4),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
STYPE = layout.offsetof(0);
PNEXT = layout.offsetof(1);
QUEUEFAMILYINDEX = layout.offsetof(2);
COUNTERINDEXCOUNT = layout.offsetof(3);
PCOUNTERINDICES = layout.offsetof(4);
}
/**
* Creates a {@code VkQueryPoolPerformanceCreateInfoKHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkQueryPoolPerformanceCreateInfoKHR(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** the type of this structure. */
@NativeType("VkStructureType")
public int sType() { return nsType(address()); }
/** {@code NULL} or a pointer to a structure extending this structure. */
@NativeType("void const *")
public long pNext() { return npNext(address()); }
/** the queue family index to create this performance query pool for. */
@NativeType("uint32_t")
public int queueFamilyIndex() { return nqueueFamilyIndex(address()); }
/** the length of the {@code pCounterIndices} array. */
@NativeType("uint32_t")
public int counterIndexCount() { return ncounterIndexCount(address()); }
/** a pointer to an array of indices into the {@link KHRPerformanceQuery#vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR EnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR}{@code ::pCounters} to enable in this performance query pool. */
@NativeType("uint32_t const *")
public IntBuffer pCounterIndices() { return npCounterIndices(address()); }
/** Sets the specified value to the {@link #sType} field. */
public VkQueryPoolPerformanceCreateInfoKHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the {@link KHRPerformanceQuery#VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR} value to the {@link #sType} field. */
public VkQueryPoolPerformanceCreateInfoKHR sType$Default() { return sType(KHRPerformanceQuery.VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR); }
/** Sets the specified value to the {@link #pNext} field. */
public VkQueryPoolPerformanceCreateInfoKHR pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; }
/** Sets the specified value to the {@link #queueFamilyIndex} field. */
public VkQueryPoolPerformanceCreateInfoKHR queueFamilyIndex(@NativeType("uint32_t") int value) { nqueueFamilyIndex(address(), value); return this; }
/** Sets the address of the specified {@link IntBuffer} to the {@link #pCounterIndices} field. */
public VkQueryPoolPerformanceCreateInfoKHR pCounterIndices(@NativeType("uint32_t const *") IntBuffer value) { npCounterIndices(address(), value); return this; }
/** Initializes this struct with the specified values. */
public VkQueryPoolPerformanceCreateInfoKHR set(
int sType,
long pNext,
int queueFamilyIndex,
IntBuffer pCounterIndices
) {
sType(sType);
pNext(pNext);
queueFamilyIndex(queueFamilyIndex);
pCounterIndices(pCounterIndices);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkQueryPoolPerformanceCreateInfoKHR set(VkQueryPoolPerformanceCreateInfoKHR src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkQueryPoolPerformanceCreateInfoKHR malloc() {
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkQueryPoolPerformanceCreateInfoKHR calloc() {
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance allocated with {@link BufferUtils}. */
public static VkQueryPoolPerformanceCreateInfoKHR create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, memAddress(container), container);
}
/** Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance for the specified memory address. */
public static VkQueryPoolPerformanceCreateInfoKHR create(long address) {
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkQueryPoolPerformanceCreateInfoKHR createSafe(long address) {
return address == NULL ? null : wrap(VkQueryPoolPerformanceCreateInfoKHR.class, address);
}
/**
* Returns a new {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
/**
* Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkQueryPoolPerformanceCreateInfoKHR malloc(MemoryStack stack) {
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkQueryPoolPerformanceCreateInfoKHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkQueryPoolPerformanceCreateInfoKHR calloc(MemoryStack stack) {
return wrap(VkQueryPoolPerformanceCreateInfoKHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkQueryPoolPerformanceCreateInfoKHR.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #sType}. */
public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.STYPE); }
/** Unsafe version of {@link #pNext}. */
public static long npNext(long struct) { return memGetAddress(struct + VkQueryPoolPerformanceCreateInfoKHR.PNEXT); }
/** Unsafe version of {@link #queueFamilyIndex}. */
public static int nqueueFamilyIndex(long struct) { return UNSAFE.getInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.QUEUEFAMILYINDEX); }
/** Unsafe version of {@link #counterIndexCount}. */
public static int ncounterIndexCount(long struct) { return UNSAFE.getInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.COUNTERINDEXCOUNT); }
/** Unsafe version of {@link #pCounterIndices() pCounterIndices}. */
public static IntBuffer npCounterIndices(long struct) { return memIntBuffer(memGetAddress(struct + VkQueryPoolPerformanceCreateInfoKHR.PCOUNTERINDICES), ncounterIndexCount(struct)); }
/** Unsafe version of {@link #sType(int) sType}. */
public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.STYPE, value); }
/** Unsafe version of {@link #pNext(long) pNext}. */
public static void npNext(long struct, long value) { memPutAddress(struct + VkQueryPoolPerformanceCreateInfoKHR.PNEXT, value); }
/** Unsafe version of {@link #queueFamilyIndex(int) queueFamilyIndex}. */
public static void nqueueFamilyIndex(long struct, int value) { UNSAFE.putInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.QUEUEFAMILYINDEX, value); }
/** Sets the specified value to the {@code counterIndexCount} field of the specified {@code struct}. */
public static void ncounterIndexCount(long struct, int value) { UNSAFE.putInt(null, struct + VkQueryPoolPerformanceCreateInfoKHR.COUNTERINDEXCOUNT, value); }
/** Unsafe version of {@link #pCounterIndices(IntBuffer) pCounterIndices}. */
public static void npCounterIndices(long struct, IntBuffer value) { memPutAddress(struct + VkQueryPoolPerformanceCreateInfoKHR.PCOUNTERINDICES, memAddress(value)); ncounterIndexCount(struct, value.remaining()); }
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param struct the struct to validate
*/
public static void validate(long struct) {
check(memGetAddress(struct + VkQueryPoolPerformanceCreateInfoKHR.PCOUNTERINDICES));
}
// -----------------------------------
/** An array of {@link VkQueryPoolPerformanceCreateInfoKHR} structs. */
public static class Buffer extends StructBuffer<VkQueryPoolPerformanceCreateInfoKHR, Buffer> implements NativeResource {
private static final VkQueryPoolPerformanceCreateInfoKHR ELEMENT_FACTORY = VkQueryPoolPerformanceCreateInfoKHR.create(-1L);
/**
* Creates a new {@code VkQueryPoolPerformanceCreateInfoKHR.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkQueryPoolPerformanceCreateInfoKHR#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkQueryPoolPerformanceCreateInfoKHR getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link VkQueryPoolPerformanceCreateInfoKHR#sType} field. */
@NativeType("VkStructureType")
public int sType() { return VkQueryPoolPerformanceCreateInfoKHR.nsType(address()); }
/** @return the value of the {@link VkQueryPoolPerformanceCreateInfoKHR#pNext} field. */
@NativeType("void const *")
public long pNext() { return VkQueryPoolPerformanceCreateInfoKHR.npNext(address()); }
/** @return the value of the {@link VkQueryPoolPerformanceCreateInfoKHR#queueFamilyIndex} field. */
@NativeType("uint32_t")
public int queueFamilyIndex() { return VkQueryPoolPerformanceCreateInfoKHR.nqueueFamilyIndex(address()); }
/** @return the value of the {@link VkQueryPoolPerformanceCreateInfoKHR#counterIndexCount} field. */
@NativeType("uint32_t")
public int counterIndexCount() { return VkQueryPoolPerformanceCreateInfoKHR.ncounterIndexCount(address()); }
/** @return a {@link IntBuffer} view of the data pointed to by the {@link VkQueryPoolPerformanceCreateInfoKHR#pCounterIndices} field. */
@NativeType("uint32_t const *")
public IntBuffer pCounterIndices() { return VkQueryPoolPerformanceCreateInfoKHR.npCounterIndices(address()); }
/** Sets the specified value to the {@link VkQueryPoolPerformanceCreateInfoKHR#sType} field. */
public VkQueryPoolPerformanceCreateInfoKHR.Buffer sType(@NativeType("VkStructureType") int value) { VkQueryPoolPerformanceCreateInfoKHR.nsType(address(), value); return this; }
/** Sets the {@link KHRPerformanceQuery#VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR} value to the {@link VkQueryPoolPerformanceCreateInfoKHR#sType} field. */
public VkQueryPoolPerformanceCreateInfoKHR.Buffer sType$Default() { return sType(KHRPerformanceQuery.VK_STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR); }
/** Sets the specified value to the {@link VkQueryPoolPerformanceCreateInfoKHR#pNext} field. */
public VkQueryPoolPerformanceCreateInfoKHR.Buffer pNext(@NativeType("void const *") long value) { VkQueryPoolPerformanceCreateInfoKHR.npNext(address(), value); return this; }
/** Sets the specified value to the {@link VkQueryPoolPerformanceCreateInfoKHR#queueFamilyIndex} field. */
public VkQueryPoolPerformanceCreateInfoKHR.Buffer queueFamilyIndex(@NativeType("uint32_t") int value) { VkQueryPoolPerformanceCreateInfoKHR.nqueueFamilyIndex(address(), value); return this; }
/** Sets the address of the specified {@link IntBuffer} to the {@link VkQueryPoolPerformanceCreateInfoKHR#pCounterIndices} field. */
public VkQueryPoolPerformanceCreateInfoKHR.Buffer pCounterIndices(@NativeType("uint32_t const *") IntBuffer value) { VkQueryPoolPerformanceCreateInfoKHR.npCounterIndices(address(), value); return this; }
}
} | bsd-3-clause |
Caleydo/caleydo | org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/internal/event/WeightsChangedEvent.java | 844 | /*******************************************************************************
* 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.vis.lineup.internal.event;
import org.caleydo.core.event.ADirectedEvent;
/**
* @author Samuel Gratzl
*
*/
public class WeightsChangedEvent extends ADirectedEvent {
private final float[] weights;
public WeightsChangedEvent(float[] weights) {
this.weights = weights;
}
/**
* @return the weights, see {@link #weights}
*/
public float[] getWeights() {
return weights;
}
@Override
public boolean checkIntegrity() {
return true;
}
}
| bsd-3-clause |
NCIP/cagrid-portal | cagrid-portal/aggr/src/java/gov/nih/nci/cagrid/portal/aggr/geocode/Geocoder.java | 830 | /**
*============================================================================
* 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-portal/LICENSE.txt for details.
*============================================================================
**/
/**
*
*/
package gov.nih.nci.cagrid.portal.aggr.geocode;
import gov.nih.nci.cagrid.portal.domain.Address;
import gov.nih.nci.cagrid.portal.domain.Geocode;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*
*/
public interface Geocoder {
Geocode getGeocode(Address address) throws GeocodingException;
}
| bsd-3-clause |
NemesisMate/UtilJME3-Base | src/main/java/com/nx/util/jme3/base/MergeUtil.java | 41984 | package com.nx.util.jme3.base;
/*
* 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.
*/
import com.jme3.animation.AnimControl;
import com.jme3.animation.Animation;
import com.jme3.animation.Bone;
import com.jme3.animation.BoneTrack;
import com.jme3.animation.Skeleton;
import com.jme3.animation.SkeletonControl;
import com.jme3.animation.Track;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetManager;
import com.jme3.asset.TextureKey;
import com.jme3.material.MatParam;
import com.jme3.material.MatParamTexture;
import com.jme3.material.Material;
import com.jme3.material.MaterialDef;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.texture.Texture;
import com.jme3.util.TempVars;
import jme3tools.optimize.GeometryBatchFactory;
import jme3tools.optimize.TextureAtlas;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* //TODO: improvement: remove vertexes dups.
* //TODO: Efficiency: change all put(index, value) by put(value). It's faster.
* @author NemesisMate
*/
public final class MergeUtil {
private static int mergedCount;
private MergeUtil() {
}
public static boolean createSkeletonBuffers(Mesh mesh, byte boneIndex) {
// If the skeleton buffer is null, we create a new one
if(mesh.getBuffer(VertexBuffer.Type.BoneIndex) == null) {
//TODO: Use the BufferUtils clone utilities instead of manually copying
VertexBuffer indexBuffer = mesh.getBuffer(VertexBuffer.Type.Index);
int bufferComponents = 4;
int bufferSize = indexBuffer.getNumElements() * bufferComponents;
byte[] zeroIndex = new byte[bufferSize];
float[] zeroWeight = new float[indexBuffer.getNumElements() * bufferComponents];
if(boneIndex != 0) {
for(int i = 0; i < bufferSize; i += bufferComponents) {
zeroIndex[i] = boneIndex;
zeroWeight[i] = 1;
}
}
mesh.setBuffer(VertexBuffer.Type.BoneIndex, bufferComponents, zeroIndex);
mesh.setBuffer(VertexBuffer.Type.BoneWeight, bufferComponents, zeroWeight);
// mesh.setBuffer(VertexBuffer.Type.HWBoneIndex, bufferComponents, zeroIndex);
// mesh.setBuffer(VertexBuffer.Type.HWBoneWeight, bufferComponents, zeroWeight);
//TODO: Use the BufferUtils clone utilities instead of manually copying.
VertexBuffer posBuffer = mesh.getBuffer(VertexBuffer.Type.Position);
bufferComponents = posBuffer.getNumComponents();
float[] array = new float[indexBuffer.getNumElements() * bufferComponents];
FloatBuffer floatBuffer = (FloatBuffer) posBuffer.getDataReadOnly();
int buffSize = bufferComponents * posBuffer.getNumElements();
for (int k = 0; k < buffSize; k++) {
array[k] = floatBuffer.get(k);
}
// BindPosePosition, according to it docs, has to have the same format and components as the Position buffer.
mesh.setBuffer(VertexBuffer.Type.BindPosePosition, bufferComponents, array);
// Why this doesn't work?
// mesh.setBuffer(VertexBuffer.Type.BindPosePosition, bufferComponents, BufferUtils.clone((FloatBuffer) mesh.getBuffer(VertexBuffer.Type.Position).getDataReadOnly()));
posBuffer = mesh.getBuffer(VertexBuffer.Type.Normal);
bufferComponents = posBuffer.getNumComponents();
array = new float[indexBuffer.getNumElements() * bufferComponents];
floatBuffer = (FloatBuffer) posBuffer.getDataReadOnly();
buffSize = bufferComponents * posBuffer.getNumElements();
for (int k = 0; k < buffSize; k++) {
array[k] = floatBuffer.get(k);
}
// BindPoseNormal, according to it docs, has to have the same format and components as the Normal buffer.
mesh.setBuffer(VertexBuffer.Type.BindPoseNormal, bufferComponents, array);
// Why this doesn't work?
// mesh.setBuffer(VertexBuffer.Type.BindPoseNormal, bufferComponents, BufferUtils.clone((FloatBuffer) mesh.getBuffer(VertexBuffer.Type.Normal).getData()));
mesh.setMaxNumWeights(4);
return true;
}
return false;
}
public static List<Geometry> gatherGeometries(List<Geometry> store, Spatial... spatials) {
if(store == null) {
store = new ArrayList<>();
}
// Not added to a node to not dettach from their parents and, so, do not mutate the original things.
for(Spatial spatial : spatials) {
GeometryBatchFactory.gatherGeoms(spatial, store);
}
return store;
}
public static boolean checkAtlasNeed(List<Geometry> geometries) {
Material material = geometries.get(0).getMaterial();
for(Geometry geometry : geometries) {
//TODO: If is needed real-time checking should change !equals for !=.
//TODO: Change !equals by != once the material loading system ensures there is no dup-materials.
if(!geometry.getMaterial().equals(material)) {
return true;
}
}
return false;
}
public static TextureAtlas createAtlasFor(List<Geometry> geometries, int atlasSize) {
TextureAtlas atlas = new TextureAtlas(atlasSize, atlasSize);
for (Geometry geometry : geometries) {
for(MatParam param : geometry.getMaterial().getParams()) {
if(param instanceof MatParamTexture) {
Texture texture = ((MatParamTexture)param).getTextureValue();
if(texture.getKey() == null) {
// Logger.getLogger(MergeUtil.class.getName()).log(Level.WARNING, "Texture ({0}) hasn't got an assetKey, creating a generic one (this may lead to unexpected behaviors).", param.getName());
LoggerFactory.getLogger(MergeUtil.class).warn("Texture ({}) hasn't got an assetKey, creating a generic one (this may lead to unexpected behaviors).", param.getName());
texture.setKey(new TextureKey(geometry.getName() + "_packed_" + param.getName()));
}
}
}
if (!atlas.addGeometry(geometry)) {
// Logger.getLogger(MergeUtil.class.getName()).log(Level.WARNING, "Texture atlas size too small, cannot add all textures.");
LoggerFactory.getLogger(MergeUtil.class).warn("Texture atlas size too small, cannot add all textures.");
return null;
}
}
return atlas;
}
public static void applyAtlasTo(TextureAtlas atlas, List<Geometry> geometries) {
for(Geometry geometry : geometries) {
atlas.applyCoords(geometry);
}
}
public static void applyAtlasTo(TextureAtlas atlas, List<Geometry> geometries, Mesh outMesh) {
int currentIndex = 0;
for(Geometry geometry : geometries) {
atlas.applyCoords(geometry, currentIndex, outMesh);
currentIndex += geometry.getMesh().getBuffer(VertexBuffer.Type.TexCoord).getNumElements();
}
}
public static Material createAtlasMaterialFor(TextureAtlas atlas, AssetManager assetManager, String matDef) {
return createAtlasMaterialFor(atlas, (MaterialDef) assetManager.loadAsset(new AssetKey(matDef)));
}
public static Material createAtlasMaterialFor(TextureAtlas atlas, AssetManager assetManager) {
return createAtlasMaterialFor(atlas, assetManager, "Common/MatDefs/Light/Lighting.j3md");
}
public static Material createAtlasMaterialFor(TextureAtlas atlas, MaterialDef materialDef) {
Material material = new Material(materialDef);
for(MatParam param : materialDef.getMaterialParams()) {
if(param instanceof MatParamTexture) {
Texture texture = atlas.getAtlasTexture(param.getName());
if(texture != null) {
material.setTexture(param.getName(), texture);
}
}
}
return material;
}
//If two animations have the same name, merge it tracks (if they aren't the same)
//Remove repeated bones (with same name) optionally. In this case, if A has bone b1 and b2, and B has b1 and b3, the resultant skeleton should have b1, b2, and b3
//TODO: optionally allow to attach a full skeleton to a desired bone.
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, Spatial spatial, Map<Geometry, String> boneLinks) {
List<Geometry> geometries = new ArrayList<Geometry>();
GeometryBatchFactory.gatherGeoms(spatial, geometries);
return mergeSpatialsWithAnimations(assetManager, replaceBoneDups, geometries, boneLinks);
}
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, Map<Geometry, String> boneLinks, Geometry... geometries) {
List<Geometry> geoms = Arrays.asList(geometries);
// // Not added to a node to not dettach from their parents and, so, do not mutate the original things.
// for(Spatial spatial : spatials) {
// GeometryBatchFactory.gatherGeoms(spatial, geometries);
// }
return mergeSpatialsWithAnimations(assetManager, replaceBoneDups, geoms, boneLinks);
}
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, Map<Geometry, String> boneLinks, Spatial... spatials) {
List<Geometry> geometries = new ArrayList<Geometry>();
// Not added to a node to not dettach from their parents and, so, do not mutate the original things.
for(Spatial spatial : spatials) {
GeometryBatchFactory.gatherGeoms(spatial, geometries);
}
return mergeSpatialsWithAnimations(assetManager, replaceBoneDups, geometries, boneLinks);
}
public static void findSkAnimControlsFor(List<Geometry> geometries,Set<SkeletonControl> skeletonControls, Set<AnimControl> animControls) {
for(Geometry geometry : geometries) {
Spatial parent = geometry;
while(parent != null) {
SkeletonControl skeletonControl = parent.getControl(SkeletonControl.class);
boolean well = true;
if(skeletonControl != null) {
well = false;
skeletonControls.add(skeletonControl);
// Patch to not updated targets
if(skeletonControl.getTargets().length == 0) {
parent.removeControl(skeletonControl);
parent.addControl(skeletonControl);
if(skeletonControl.getTargets().length == 0) {
throw new UnknownError();
}
}
}
AnimControl animControl = parent.getControl(AnimControl.class);
if(animControl != null) {
well = !well;
animControls.add(animControl);
}
if(!well) {
LoggerFactory.getLogger(MergeUtil.class).warn("Spatial: {}, has only a SekeletonControl or an AnimControl. This can lead to further problems.", parent);
}
parent = parent.getParent();
}
}
}
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, Map<Geometry, String> boneLinks, List<Geometry> geometries) {
return mergeSpatialsWithAnimations(assetManager, replaceBoneDups, geometries, boneLinks);
}
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, List<Geometry> geometries, Map<Geometry, String> boneLinks) {
Set<SkeletonControl> skeletonControls = new HashSet<SkeletonControl>(geometries.size());
Set<AnimControl> animControls = new HashSet<AnimControl>(geometries.size());
return mergeSpatialsWithAnimations(assetManager, replaceBoneDups, geometries, boneLinks, skeletonControls, animControls);
}
public static Spatial mergeSpatialsWithAnimations(AssetManager assetManager, boolean replaceBoneDups, List<Geometry> geometries, Map<Geometry, String> boneLinks, Set<SkeletonControl> skeletonControls, Set<AnimControl> animControls) {
findSkAnimControlsFor(geometries, skeletonControls, animControls);
Mesh newMesh = new Mesh();
//TODO: Allow this decision to the tool user.
if(!skeletonControls.isEmpty()) {
for(Geometry geom : geometries) {
createSkeletonBuffers(geom.getMesh(), (byte) 0);
}
}
// If this throws a NPE can be because geometries is empty. If problems with buffers, check that the HWBoneWeight and HWBoneIndex have the same components that BoneWeight and BoneIndex respectively.
GeometryBatchFactory.mergeGeometries(geometries, newMesh);
int boneCount = 0;
for(SkeletonControl skeletonControl : skeletonControls) {
boneCount += skeletonControl.getSkeleton().getBoneCount();
}
Map<Bone, Bone> bonesAssocs = new HashMap<>((int) (boneCount / 0.75f) + 1, 0.75f);
Map<Bone, Integer> newSkeletonBoneIndexes = new HashMap<>();
//TODO: Can be done more efficiently with an int[] array containing the bone index redefinition based on the boneOffset when looping over them. The conterpart is it is less robust.
SkeletonControl skeletonControl = copySkeletonControls(skeletonControls, geometries, newMesh, replaceBoneDups, bonesAssocs, newSkeletonBoneIndexes);
//TODO: FIXME: support hardware skinning.
skeletonControl.setHardwareSkinningPreferred(false);
if(boneLinks != null && !boneLinks.isEmpty()) {
Skeleton skeleton = skeletonControl.getSkeleton();
int count = skeleton.getBoneCount();
Map<String, Byte> boneIndexPerName = new HashMap<>((int) (count / 0.75f) + 1, 0.75f);
for(int k = 0; k < count; k++) {
Bone bone = skeleton.getBone(k);
boneIndexPerName.put(bone.getName(), (byte)k);
}
// int i = 0;
int offset = 0;
for(Geometry geom : geometries) {
// for (String boneLink : boneLinks) {
Mesh mesh = geom.getMesh();
int bufferSize = mesh.getTriangleCount() * 4;
// String boneLink = boneLinks[i];
String boneLink = boneLinks.get(geom);
if (boneLink != null) {
byte boneIndex = boneIndexPerName.get(boneLink);
ByteBuffer boneIndexBuffer = (ByteBuffer) newMesh.getBuffer(VertexBuffer.Type.BoneIndex).getData();
FloatBuffer boneWeightBuffer = mesh.getFloatBuffer(VertexBuffer.Type.BoneWeight);
int endOffset = bufferSize + offset;
for (int k = offset; k < endOffset; k++) {
boneIndexBuffer.put(k, boneIndex);
boneWeightBuffer.put(k, 1);
}
// The bindPosePosition should already be set.
}
offset += bufferSize;
// i++;
}
}
String spatialName = "Merged" + mergedCount;
Node node = new Node(spatialName + "_node");
Geometry geometry = new Geometry(spatialName + "_geom", newMesh);
node.addControl(skeletonControl);
// Atlas
if(checkAtlasNeed(geometries)) {
TextureAtlas atlas = createAtlasFor(geometries, 4096);
if (atlas == null) {
// LoggerFactory.getLogger(MergeUtil.class).error("Atlas too small");
throw new NullPointerException("Atlas too small");
}
// applyAtlasTo(atlas, geometries);
applyAtlasTo(atlas, geometries, newMesh);
//TODO: when using hardware skinning the material uses bones parameters (so something must be done with these)
geometry.setMaterial(createAtlasMaterialFor(atlas, assetManager));
} else {
geometry.setMaterial(geometries.get(0).getMaterial());
}
/////////////////////
node.addControl(copyAnimControls(animControls, skeletonControl.getSkeleton(), bonesAssocs, newSkeletonBoneIndexes));
node.attachChild(geometry);
return node;
}
// public static AnimControl copyAnimControls(Collection<AnimControl> animControls, Skeleton toSkeleton) {
// int currentBoneOffset = 0;
//
// AnimControl newAnimControl = new AnimControl(toSkeleton);
//
//
// for(AnimControl animControl : animControls) {
// for(String animName : animControl.getAnimationNames()) {
// Animation anim = animControl.getAnim(animName);
//
//// if(currentBoneOffset > 0) {
// Animation newAnim = new Animation(anim.getName(), anim.getLength());
//
// for(Track track : anim.getTracks()) {
// if(track instanceof BoneTrack) {
// //TODO: TOASK: Would be much easier if bonetrack could be cloned (it can) and the targetBoneIndex changed with a set (it CAN'T)
// // If so, it would be just as easy as clone the animation and then use the set of the desired boneTracks.
// int tablesLength = ((BoneTrack)track).getTimes().length;
//
// float[] times = ((BoneTrack)track).getTimes().clone();
// Vector3f[] sourceTranslations = ((BoneTrack)track).getTranslations();
// Quaternion[] sourceRotations = ((BoneTrack)track).getRotations();
// Vector3f[] sourceScales = ((BoneTrack)track).getScales();
//
// Vector3f[] translations = new Vector3f[tablesLength];
// Quaternion[] rotations = new Quaternion[tablesLength];
// Vector3f[] scales = new Vector3f[tablesLength];
// for (int i = 0; i < tablesLength; ++i) {
// translations[i] = sourceTranslations[i].clone();
// rotations[i] = sourceRotations[i].clone();
// scales[i] = sourceScales != null ? sourceScales[i].clone() : new Vector3f(1.0f, 1.0f, 1.0f);
// }
//
// // Need to use the constructor here because of the final fields used in this class
// newAnim.addTrack(new BoneTrack(((BoneTrack)track).getTargetBoneIndex() + currentBoneOffset, times, translations, rotations, scales));
//
// } else {
// newAnim.addTrack(track.clone());
// }
// }
//
// newAnimControl.addAnim(newAnim);
//// } else {
//// newAnimControl.addAnim(anim.clone());
//// }
//
// }
// currentBoneOffset += animControl.getSkeleton().getBoneCount();
//// skeletonNumber++;
//// mergedNode.addControl(animControl);
// }
// return newAnimControl;
// }
public static AnimControl copyAnimControls(Collection<AnimControl> animControls, Skeleton toSkeleton, Map<Bone, Bone> bonesAssocs, Map<Bone, Integer> newSkeletonBoneIndexes) {
int currentBoneOffset = 0;
AnimControl newAnimControl = new AnimControl(toSkeleton);
Map<String, Animation> nameAnimAssocs = new HashMap<String, Animation>();
for(AnimControl animControl : animControls) {
for(String animName : animControl.getAnimationNames()) {
Animation alreadyAnim = nameAnimAssocs.get(animName);
Animation anim = animControl.getAnim(animName);
// if(currentBoneOffset > 0) {
if(alreadyAnim != null) {
for(Track track : anim.getTracks()) {
boolean duplicated = false;
int newBoneIndex = -1;
if(track instanceof BoneTrack) {
newBoneIndex = newSkeletonBoneIndexes.get(bonesAssocs.get(animControl.getSkeleton().getBone(((BoneTrack) track).getTargetBoneIndex())));
for(Track track2 : alreadyAnim.getTracks()) {
if(track2 instanceof BoneTrack) {
if(newBoneIndex == ((BoneTrack) track2).getTargetBoneIndex()) {
duplicated = true;
break;
}
}
}
} else {
for(Track track2 : alreadyAnim.getTracks()) {
if(track.equals(track2)) {
duplicated = true;
break;
}
}
}
if(!duplicated) {
alreadyAnim.addTrack(copyTrack(track, newBoneIndex));
// alreadyAnim.addTrack(copyTrack(track, currentBoneOffset));
}
}
} else {
Animation newAnim = new Animation(anim.getName(), anim.getLength());
int newBoneIndex;
for(Track track : anim.getTracks()) {
newBoneIndex = newSkeletonBoneIndexes.get(bonesAssocs.get(animControl.getSkeleton().getBone(((BoneTrack) track).getTargetBoneIndex())));
newAnim.addTrack(copyTrack(track, newBoneIndex));
// newAnim.addTrack(copyTrack(track, currentBoneOffset));
// if(track instanceof BoneTrack) {
// //TODO: TOASK: Would be much easier if bonetrack could be cloned (it can) and the targetBoneIndex changed with a set (it CAN'T)
// // If so, it would be just as easy as clone the animation and then use the set of the desired boneTracks.
// int tablesLength = ((BoneTrack)track).getTimes().length;
//
// float[] times = ((BoneTrack)track).getTimes().clone();
// Vector3f[] sourceTranslations = ((BoneTrack)track).getTranslations();
// Quaternion[] sourceRotations = ((BoneTrack)track).getRotations();
// Vector3f[] sourceScales = ((BoneTrack)track).getScales();
//
// Vector3f[] translations = new Vector3f[tablesLength];
// Quaternion[] rotations = new Quaternion[tablesLength];
// Vector3f[] scales = new Vector3f[tablesLength];
// for (int i = 0; i < tablesLength; ++i) {
// translations[i] = sourceTranslations[i].clone();
// rotations[i] = sourceRotations[i].clone();
// scales[i] = sourceScales != null ? sourceScales[i].clone() : new Vector3f(1.0f, 1.0f, 1.0f);
// }
//
// // Need to use the constructor here because of the final fields used in this class
// newAnim.addTrack(new BoneTrack(((BoneTrack)track).getTargetBoneIndex() + currentBoneOffset, times, translations, rotations, scales));
//
// } else {
// newAnim.addTrack(track.clone());
// }
}
newAnimControl.addAnim(newAnim);
nameAnimAssocs.put(animName, newAnim);
}
// } else {
// newAnimControl.addAnim(anim.clone());
// }
}
currentBoneOffset += animControl.getSkeleton().getBoneCount();
// skeletonNumber++;
// mergedNode.addControl(animControl);
}
return newAnimControl;
}
private static Track copyTrack(Track track, int currentIndex) {//int currentBoneOffset) {
if(track instanceof BoneTrack) {
//TODO: TOASK: Would be much easier if bonetrack could be cloned (it can) and the targetBoneIndex changed with a set (it CAN'T)
// If so, it would be just as easy as clone the animation and then use the set of the desired boneTracks.
int tablesLength = ((BoneTrack)track).getTimes().length;
float[] times = ((BoneTrack)track).getTimes().clone();
Vector3f[] sourceTranslations = ((BoneTrack)track).getTranslations();
Quaternion[] sourceRotations = ((BoneTrack)track).getRotations();
Vector3f[] sourceScales = ((BoneTrack)track).getScales();
Vector3f[] translations = new Vector3f[tablesLength];
Quaternion[] rotations = new Quaternion[tablesLength];
Vector3f[] scales = new Vector3f[tablesLength];
for (int i = 0; i < tablesLength; ++i) {
translations[i] = sourceTranslations[i].clone();
rotations[i] = sourceRotations[i].clone();
scales[i] = sourceScales != null ? sourceScales[i].clone() : new Vector3f(1.0f, 1.0f, 1.0f);
}
// Need to use the constructor here because of the final fields used in this class
// return new BoneTrack(((BoneTrack)track).getTargetBoneIndex() + currentBoneOffset, times, translations, rotations, scales);
return new BoneTrack(currentIndex, times, translations, rotations, scales);
} else {
return track.clone();
}
}
public static SkeletonControl copySkeletonControls(Collection<SkeletonControl> skeletonControls, List<Geometry> geometries, Mesh toMesh, boolean replaceDups, Map<Bone, Bone> bonesAssocs, Map<Bone, Integer> newSkeletonBoneIndexes) {
int size = skeletonControls.size();
Skeleton[] skeletons = new Skeleton[size];
Vector3f[] skeletonOffsets = new Vector3f[size];
Map<Mesh, Geometry> geometryMeshAssoc = new HashMap<Mesh, Geometry>((int) (geometries.size() / 0.75f) + 1, 0.75f);
for(Geometry geometry : geometries) {
geometryMeshAssoc.put(geometry.getMesh(), geometry);
}
int i = 0;
for(SkeletonControl skeletonControl : skeletonControls) {
Skeleton skeleton = skeletonControl.getSkeleton();
skeletons[i] = skeleton;
// LoggerFactory.getLogger(MergeUtil.class).debug("Null??? is: {}, {}", skeletonControl);
Spatial skeletonSpatial = skeletonControl.getSpatial();
if(skeletonSpatial != null) {
skeletonOffsets[i] = skeletonSpatial.getWorldTranslation();
} else {
LoggerFactory.getLogger(MergeUtil.class).trace("Merged skeleton control without spatial: {}", skeletonControl);
skeletonOffsets[i] = Vector3f.ZERO;
}
i++;
}
SkeletonControl newSkeletonControl = new SkeletonControl(copySkeleton(skeletons, skeletonOffsets, replaceDups, bonesAssocs, newSkeletonBoneIndexes));
int currentBoneIndex = 0;
int currentBindPoseIndex = 0;
int currentBoneOffset = 0;
Vector3f currentBindPoseOffset = Vector3f.ZERO.clone();
for(SkeletonControl skeletonControl : skeletonControls) {
// for(int i = 0; i < size; i++) {
// SkeletonControl skeletonControl = skeletonControls.get(i);
Skeleton skeleton = skeletonControl.getSkeleton();
// skeletons[i] = skeleton;
// skeletonOffsets[i] = skeletonControl.getSpatial().getWorldTranslation();
//TODO: create a set with meshes so they doesn't dup and avoid outofbounds with exceptions. maybe? - is it already with geometryMeshAssoc? xD
//TODO: treat the first case apart.
for(Mesh mesh : skeletonControl.getTargets()) {
// for (Geometry geom : geometries) {
// Mesh mesh = geom.getMesh();
// Bone buffer
VertexBuffer vertexBuffer = mesh.getBuffer(VertexBuffer.Type.BoneIndex);
// int bufferSize = vertexBuffer.getData().capacity();
int bufferSize;
// if(vertexBuffer == null) {
// vertexBuffer = mesh.getBuffer(VertexBuffer.Type.Index);
////// bufferSize = vertexBuffer.getNumComponents() * vertexBuffer.getNumElements();
//// float[] zeroBuffer = new float[vertexBuffer.getNumElements()];
//// mesh.setBuffer(VertexBuffer.Type.BoneIndex, 1, zeroBuffer);
////// vertexBuffer = VertexBuffer.createBuffer(VertexBuffer.Format.Float, 1, vertexBuffer.getNumElements());
//
// bufferSize = vertexBuffer.getNumElements();
// vertexBuffer = toMesh.getBuffer(VertexBuffer.Type.BoneIndex);
// bufferSize *= vertexBuffer.getNumComponents(); // To be sure the numComponents is the right amount, we get it from the known existant buffer.
//
//
// ByteBuffer byteData = (ByteBuffer) vertexBuffer.getData();
// for (int k = currentBoneIndex; k < bufferSize + currentBoneIndex; k++) {
// byteData.put(k, (byte) (byteData.get(k) + currentBoneOffset));
// }
//
//
// //TODO: link to the bone associated to a node instead of the rootBone
//
// continue;
// }
//
int numComponents = vertexBuffer.getNumComponents();
bufferSize = numComponents * vertexBuffer.getNumElements();
// LoggerFactory.getLogger(MergeUtil.class).debug("BufferSize: {} ({}), CurrentBoneIndex: {}, total: {}.", bufferSize, mesh.hashCode(), currentBoneIndex, bufferSize + currentBoneIndex);
// LoggerFactory.getLogger(MergeUtil.class).debug("toMesh buffer size: {}.", toMesh.getBuffer(VertexBuffer.Type.BoneIndex).getData().capacity());
ByteBuffer byteData = (ByteBuffer) toMesh.getBuffer(VertexBuffer.Type.BoneIndex).getData();
// OLD WAY --------------
// for (int k = currentBoneIndex; k < bufferSize + currentBoneIndex; k++) {
// byteData.put(k, (byte) (byteData.get(k) + currentBoneOffset));
// }
//
// currentBoneIndex += bufferSize;
/// NEW WAY
int newBoneIndex;
for (int k = currentBoneIndex; k < currentBoneIndex + bufferSize; k++) {
newBoneIndex = newSkeletonBoneIndexes.get(bonesAssocs.get(skeleton.getBone((byteData.get(k)))));
byteData.put(k, (byte) newBoneIndex);
}
// --------------------
// BindPose buffer
vertexBuffer = mesh.getBuffer(VertexBuffer.Type.BindPosePosition);
// bufferSize = vertexBuffer.getData().capacity();
numComponents = vertexBuffer.getNumComponents();
bufferSize = numComponents * vertexBuffer.getNumElements();
LoggerFactory.getLogger(MergeUtil.class).debug("Offset: {}, GeometryMeshAssoc: {}, mesh: {}, obtained: {}, SkeletonControl's Spatial: {}", currentBindPoseOffset, geometryMeshAssoc, mesh, geometryMeshAssoc.get(mesh), skeletonControl.getSpatial());
// If this throws a NPE is more likely because of the skeleton is having a wrong mesh (a mesh that isn't in the spatial being merged)
currentBindPoseOffset.set(geometryMeshAssoc.get(mesh).getWorldTranslation());
// currentBindPoseOffset.set(geom.getWorldTranslation());
FloatBuffer floatData = toMesh.getFloatBuffer(VertexBuffer.Type.BindPosePosition);
for (int k = currentBindPoseIndex; k < bufferSize + currentBindPoseIndex; k += 3) {
floatData.put(k, floatData.get(k) + currentBindPoseOffset.x);
}
for (int k = currentBindPoseIndex + 1; k < bufferSize + currentBindPoseIndex - 1; k += 3) {
floatData.put(k, floatData.get(k) + currentBindPoseOffset.y);
}
for (int k = currentBindPoseIndex + 2; k < bufferSize + currentBindPoseIndex - 2; k += 3) {
floatData.put(k, floatData.get(k) + currentBindPoseOffset.z);
}
currentBindPoseIndex += bufferSize;
}
currentBoneOffset += skeleton.getBoneCount();
// }
}
return newSkeletonControl;
// offsetBoneBuffers(mergedNode, 240, (byte)mergedSkeleton.getBoneCount());
// offsetBindPoseBuffers(mergedNode, 180, escoba.getWorldTranslation());
}
public static Skeleton copySkeleton(Skeleton skeleton, Vector3f offset) {
int boneCount = skeleton.getBoneCount();
Bone[] bones = new Bone[boneCount];
Map<Bone, Bone> bonesAssocs = new HashMap<Bone, Bone>((int) (boneCount / 0.75f) + 1, 0.75f);
for(Bone bone : skeleton.getRoots()) {
copyBone(bone, bonesAssocs, offset, null);
}
int b = 0;
for(int i = 0; i < boneCount; i++) {
bones[b++] = bonesAssocs.get(skeleton.getBone(i));
}
return new Skeleton(bones);
}
public static Skeleton copySkeleton(Skeleton[] skeletons, Vector3f[] offsets, boolean replaceDups, Map<Bone, Bone> bonesAssocs, Map<Bone, Integer> newSkeletonBoneIndexes) {
return copySkeleton(Arrays.asList(skeletons), Arrays.asList(offsets), replaceDups, bonesAssocs, newSkeletonBoneIndexes);
}
public static Skeleton copySkeleton(List<Skeleton> skeletons, List<Vector3f> offsets, boolean replaceDups, Map<Bone, Bone> bonesAssocs, Map<Bone, Integer> newSkeletonBoneIndexes) {
int boneCount = 0;
for(Skeleton skeleton : skeletons) {
boneCount += skeleton.getBoneCount();
}
Bone[] bones = new Bone[boneCount];
// bonesAssocs = new HashMap<Bone, Bone>((int) (boneCount / 0.75f) + 1, 0.75f);
Map<String, Map<String, Bone>> rootNameAssocs = new HashMap<>();
// List<Map<Bone, Integer>> skeletonBoneIndexes; // Index on the final skeleton for a bone in the original skeleton.
// newSkeletonBoneIndexes = new HashMap<>(); // Not needed to make a list if using Bones as keys (as they are different for every skeleton, not as the bone names)
int b = 0;
int offsetIndex = 0;
for(Skeleton skeleton : skeletons) {
for(Bone bone : skeleton.getRoots()) {
LoggerFactory.getLogger(MergeUtil.class).debug("Merging skeleton under root bone: {}.", bone.getName());
Map<String, Bone> nameBoneAssocs = rootNameAssocs.get(bone.getName());
if(nameBoneAssocs == null) {
nameBoneAssocs = new HashMap<>();
rootNameAssocs.put(bone.getName(), nameBoneAssocs);
}
// Hm... why is this returned bone ignored? - Once the answer is known, write it here as a comment xD.
copyBone(bone, bonesAssocs, offsets.get(offsetIndex), replaceDups ? nameBoneAssocs: null);
}
int count = skeleton.getBoneCount();
for(int i = 0; i < count; i++) {
Bone newBone = bonesAssocs.get(skeleton.getBone(i));
if(!newSkeletonBoneIndexes.containsKey(newBone)) {
if (newSkeletonBoneIndexes.put(newBone, b) == null) {
bones[b++] = newBone;
} else {
LoggerFactory.getLogger(MergeUtil.class).error("WTF!");
}
}
// bones[b++] = bonesAssocs.get(skeleton.getBone(i));
}
offsetIndex++;
}
return new Skeleton(Arrays.copyOf(bones, b));
}
private static Bone copyBone(Bone bone, Map<Bone, Bone> assoc, Vector3f offset, Map<String, Bone> nameBoneAssocs) {
TempVars vars = TempVars.get();
Bone newBone = null;
boolean newBoneCreated = false;
if(nameBoneAssocs != null) {
newBone = nameBoneAssocs.get(bone.getName());
}
if(newBone == null) {
newBone = new Bone(bone.getName());
newBone.setUserControl(bone.hasUserControl());
if(bone.hasUserControl()) {
newBone.setUserTransforms(vars.vect1.set(bone.getLocalPosition()).addLocal(offset), bone.getLocalRotation(), bone.getLocalScale());
}
newBone.setBindTransforms(vars.vect1.set(bone.getBindPosition()).addLocal(offset), bone.getBindRotation(), bone.getBindScale());
nameBoneAssocs.put(newBone.getName(), newBone);
newBoneCreated = true;
} else {
LoggerFactory.getLogger(MergeUtil.class).debug("Duplicated bone: {}. Replaced.", bone.getName());
}
vars.release();
// newBone.getModelBindInversePosition().set(bone.getModelBindInversePosition());
// newBone.getModelBindInverseRotation().set(bone.getModelBindInverseRotation());
// newBone.getModelBindInverseScale().set(bone.getModelBindInverseScale());
for(Bone b : bone.getChildren()) {
Bone childBone = copyBone(b, assoc, Vector3f.ZERO, nameBoneAssocs);
if(childBone != null) {
// This if check is needed because of when newBone was dup, the childBone can also be a dup. Not needed if in dup case null is returned?
// if(!newBone.getChildren().contains(childBone)) {
newBone.addChild(childBone);
// }
}
}
assoc.put(bone, newBone);
return newBoneCreated ? newBone : null;
}
// public static Skeleton copySkeleton(Skeleton skeleton, Vector3f offset) {
// int boneCount = skeleton.getBoneCount();
//
// Bone[] bones = new Bone[boneCount];
//
// Map<Bone, Bone> bonesAssocs = new HashMap<Bone, Bone>((int) (boneCount / 0.75f) + 1, 0.75f);
//
// for(Bone bone : skeleton.getRoots()) {
// copyBone(bone, bonesAssocs, offset);
// }
//
// int b = 0;
// for(int i = 0; i < boneCount; i++) {
// bones[b++] = bonesAssocs.get(skeleton.getBone(i));
// }
//
// return new Skeleton(bones);
// }
//
// public static Skeleton copySkeleton(Skeleton[] skeletons, Vector3f[] offsets) {
// return copySkeleton(Arrays.asList(skeletons), Arrays.asList(offsets));
// }
//
// public static Skeleton copySkeleton(List<Skeleton> skeletons, List<Vector3f> offsets) {
// int boneCount = 0;
// for(Skeleton skeleton : skeletons) {
// boneCount += skeleton.getBoneCount();
// }
//
// Bone[] bones = new Bone[boneCount];
//
// Map<Bone, Bone> bonesAssocs = new HashMap<Bone, Bone>((int) (boneCount / 0.75f) + 1, 0.75f);
//
// int b = 0;
// int offsetIndex = 0;
// for(Skeleton skeleton : skeletons) {
// for(Bone bone : skeleton.getRoots()) {
// copyBone(bone, bonesAssocs, offsets.get(offsetIndex));
// }
//
// int count = skeleton.getBoneCount();
// for(int i = 0; i < count; i++) {
// bones[b++] = bonesAssocs.get(skeleton.getBone(i));
// }
//
// offsetIndex++;
// }
//
//
// return new Skeleton(bones);
// }
//
// private static Bone copyBone(Bone bone, Map<Bone, Bone> assoc, Vector3f offset) {
//
// TempVars vars = TempVars.get();
//
// Bone newBone = new Bone(bone.getName());
// newBone.setUserControl(bone.hasUserControl());
// if(bone.hasUserControl()) {
// newBone.setUserTransforms(vars.vect1.set(bone.getLocalPosition()).addLocal(offset), bone.getLocalRotation(), bone.getLocalScale());
// }
//
//
//
// newBone.setBindTransforms(vars.vect1.set(bone.getBindPosition()).addLocal(offset), bone.getBindRotation(), bone.getBindScale());
//
// vars.release();
//
//// newBone.getModelBindInversePosition().set(bone.getModelBindInversePosition());
//// newBone.getModelBindInverseRotation().set(bone.getModelBindInverseRotation());
//// newBone.getModelBindInverseScale().set(bone.getModelBindInverseScale());
//
// for(Bone b : bone.getChildren()) {
// newBone.addChild(copyBone(b, assoc, Vector3f.ZERO));
// }
//
// assoc.put(bone, newBone);
//
// return newBone;
// }
}
| bsd-3-clause |
crepi22/finecrop | src/main/java/org/crepi22/finecrop/Rotate.java | 1915 | package org.crepi22.finecrop;
import java.io.File;
import java.util.Arrays;
class Rotate extends Thread {
final double angle;
final Continuation continuation;
final Photo photo;
Rotate(Continuation continuation, Photo photo, int startX, int startY, int endX, int endY) {
this.photo = photo;
int dx = endX - startX;
int dy = endY - startY;
if (dx == 0) angle = 0;
else angle = Math.atan((float) dy / dx) / Math.PI * 180;
this.continuation = continuation;
}
Rotate(Continuation continuation, Photo photo, double angle) {
this.photo = photo;
this.continuation = continuation;
this.angle = angle;
}
@Override
public void run() {
synchronized (continuation) {
try {
continuation.showEffect(true);
File rotatedImageFile = File.createTempFile("rotated", ".jpg");; //$NON-NLS-1$ //$NON-NLS-2$
String[] command = new String[] {
Config.getConvertPath(),
"-rotate", //$NON-NLS-1$
String.format("%.2f", -angle), //$NON-NLS-1$
photo.getPath(),
rotatedImageFile.getAbsolutePath()
};
Process p = Runtime.getRuntime().exec(command);
int exit = p.waitFor();
if (exit == 0) {
continuation.runFile(rotatedImageFile);
} else {
continuation.error(String.format(Messages.getString("Rotate.command_error"),exit, Arrays.toString(command))); //$NON-NLS-1$
}
} catch (Exception e) {
continuation.error(e.getMessage());
} finally {
continuation.showEffect(false);
}
}
}
} | bsd-3-clause |
BayesianLogic/blog | src/main/java/blog/absyn/BooleanExpr.java | 468 | package blog.absyn;
/**
* @author leili
* @date Apr 22, 2012
*
*/
public class BooleanExpr extends Expr {
public boolean value;
public BooleanExpr(int p, boolean v) {
this(0, p, v);
}
public BooleanExpr(int line, int col, boolean v) {
super(line, col);
value = v;
}
public BooleanExpr(boolean v) { this(0, v); }
@Override
public void printTree(Printer pr, int d) {
pr.indent(d);
pr.say("BooleanExpr(");
pr.say(value);
pr.say(")");
}
}
| bsd-3-clause |
DoubleDoorDevelopment/InsiderTrading | src/main/java/net/doubledoordev/insidertrading/util/Constants.java | 375 | package net.doubledoordev.insidertrading.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* @author Dries007
*/
public class Constants
{
public static final String MODID = "InsiderTrading";
public static final String MODID_ASM = "InsiderTrading-ASM";
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
}
| bsd-3-clause |
ksclarke/basex | basex-core/src/main/java/org/basex/query/func/db/DbBackups.java | 1316 | package org.basex.query.func.db;
import static org.basex.util.Token.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.util.list.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-15, BSD License
* @author Christian Gruen
*/
public final class DbBackups extends StandardFunc {
/** Backup element name. */
private static final String BACKUP = "backup";
/** Size element name. */
private static final String SIZE = "size";
@Override
public Iter iter(final QueryContext qc) throws QueryException {
checkCreate(qc);
final String name = exprs.length == 0 ? null : string(toToken(exprs[0], qc));
final StringList backups = name == null ? qc.context.databases.backups() :
qc.context.databases.backups(name);
final IOFile dbpath = qc.context.soptions.dbpath();
return new Iter() {
int up = -1;
@Override
public Item next() {
if(++up >= backups.size()) return null;
final String backup = backups.get(up);
final long length = new IOFile(dbpath, backup + IO.ZIPSUFFIX).length();
return new FElem(BACKUP).add(backup).add(SIZE, token(length));
}
};
}
}
| bsd-3-clause |
NCIP/cacore-sdk | hydra/src/java/gov/nih/nci/sdk/ide/modelexplorer/meaning/DomainView.java | 611 | /*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 gov.nih.nci.sdk.ide.modelexplorer.meaning;
import java.util.List;
public interface DomainView
{
public String getDomainName();
public String getDomainDesc();
public List<String> getConceptList();
public void setDomainName(String _domainName);
public void setDomainDesc(String _domainDesc);
public void setConceptList(List<String> _conceptList);
}
| bsd-3-clause |
dalifreire/rultor | src/main/java/com/rultor/web/TkToggles.java | 2468 | /**
* Copyright (c) 2009-2016, rultor.com
* 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 rultor.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
* 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.rultor.web;
import com.rultor.Toggles;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.flash.RsFlash;
import org.takes.facets.forward.RsForward;
/**
* Toggles.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 1.0
*/
final class TkToggles implements Take {
/**
* Toggles.
*/
private final transient Toggles toggles;
/**
* Ctor.
* @param tgls Toggles
*/
TkToggles(final Toggles tgls) {
this.toggles = tgls;
}
@Override
public Response act(final Request req) throws IOException {
this.toggles.toggle();
return new RsForward(
new RsFlash(
String.format(
"read-only mode set to %B", this.toggles.readOnly()
)
)
);
}
}
| bsd-3-clause |
MLCL/Byblo | src/main/java/uk/ac/susx/mlcl/byblo/io/WeightStatsObjectSource.java | 2845 | /*
* Copyright (c) 2010-2013, University of Sussex
* 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 University of Sussex 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.
*/
package uk.ac.susx.mlcl.byblo.io;
import uk.ac.susx.mlcl.lib.io.CountingObjectSource;
import uk.ac.susx.mlcl.lib.io.ObjectSource;
import java.io.IOException;
/**
* @param <T>
* @author Hamish I A Morgan <hamish.morgan@sussex.ac.uk>
*/
class WeightStatsObjectSource<T> extends CountingObjectSource<ObjectSource<Weighted<T>>, Weighted<T>> {
private double weightMin = Double.POSITIVE_INFINITY;
private double weightMax = Double.NEGATIVE_INFINITY;
private double weightSum = 0;
public WeightStatsObjectSource(ObjectSource<Weighted<T>> inner) {
super(inner);
}
public double getWeightSum() {
return weightSum;
}
double getWeightMax() {
return weightMax;
}
double getWeightMin() {
return weightMin;
}
public double getWeightRange() {
return getWeightMax() - getWeightMin();
}
public double getWeightMean() {
return getWeightSum() / getCount();
}
@Override
public Weighted<T> read() throws IOException {
Weighted<T> wt = super.read();
weightSum += wt.weight();
weightMax = Math.max(weightMax, wt.weight());
weightMin = Math.min(weightMin, wt.weight());
return wt;
}
}
| bsd-3-clause |
vtkio/vtk | src/main/java/vtk/web/servlet/SessionRepositoryFilter.java | 2587 | /* Copyright (c) 2016 University of Oslo, Norway
* 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 University of Oslo 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 vtk.web.servlet;
import org.springframework.session.ExpiringSession;
import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.HttpSessionStrategy;
/**
* This class exists only to be able to instantiate
* {@link org.springframework.session.web.http.SessionRepositoryFilter}
* with overloaded setter method
* {@link org.springframework.session.web.http.SessionRepositoryFilter#setHttpSessionStrategy(HttpSessionStrategy)}
*
* from XML config. (This is not supported by Spring, as overloaded
* setters break the JavaBean specification.)
*/
public class SessionRepositoryFilter<S extends ExpiringSession> extends
org.springframework.session.web.http.SessionRepositoryFilter<S> {
public SessionRepositoryFilter(SessionRepository<S> sessionRepository) {
super(sessionRepository);
}
public void setSessionStrategy(HttpSessionStrategy strategy) {
super.setHttpSessionStrategy(strategy);
}
}
| bsd-3-clause |
arnaudsj/carrot2 | core/carrot2-source-xml/src-test/org/carrot2/source/xml/XmlDocumentSourceTest.java | 12363 |
/*
* Carrot2 project.
*
* Copyright (C) 2002-2010, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.source.xml;
import static org.carrot2.core.test.ExternalApiTestAssumptions.externalApiTestsEnabled;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.carrot2.core.*;
import org.carrot2.core.attribute.AttributeNames;
import org.carrot2.core.test.DocumentSourceTestBase;
import org.carrot2.util.attribute.AttributeUtils;
import org.carrot2.util.resource.*;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Test cases for {@link XmlDocumentSource}.
*/
public class XmlDocumentSourceTest extends DocumentSourceTestBase<XmlDocumentSource>
{
private ResourceUtils resourceUtils = ResourceUtilsFactory.getDefaultResourceUtils();
@Override
public Class<XmlDocumentSource> getComponentClass()
{
return XmlDocumentSource.class;
}
@Test
public void testLegacyXml()
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-apple-computer.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "results"),
300);
final int documentCount = runQuery();
assertEquals(200, documentCount);
assertEquals("apple computer", resultAttributes.get(AttributeNames.QUERY));
}
@Test
public void testResultsTruncation()
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-apple-computer.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
processingAttributes.put(AttributeNames.RESULTS, 50);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "readAll"),
false);
final int documentCount = runQuery();
assertEquals(50, documentCount);
assertEquals("apple computer", resultAttributes.get(AttributeNames.QUERY));
}
@Test
public void testXsltNoParameters()
{
IResource xml = resourceUtils.getFirst("/xml/custom-parameters-not-required.xml",
XmlDocumentSourceTest.class);
IResource xslt = resourceUtils.getFirst("/xsl/custom-xslt.xsl",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xslt"),
xslt);
final int documentCount = runQuery();
assertTransformedDocumentsEqual(documentCount);
}
@Test
public void testXsltWithParameters()
{
IResource xml = resourceUtils.getFirst("/xml/custom-parameters-required.xml",
XmlDocumentSourceTest.class);
IResource xslt = resourceUtils.getFirst("/xsl/custom-xslt.xsl",
XmlDocumentSourceTest.class);
Map<String, String> xsltParameters = Maps.newHashMap();
xsltParameters.put("id-field", "number");
xsltParameters.put("title-field", "heading");
xsltParameters.put("snippet-field", "snippet");
xsltParameters.put("url-field", "url");
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xslt"),
xslt);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class,
"xsltParameters"), xsltParameters);
final int documentCount = runQuery();
assertTransformedDocumentsEqual(documentCount);
}
@Test
public void testNoIdsInSourceXml()
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-no-ids.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
final int documentCount = runQuery();
assertEquals(2, documentCount);
assertEquals(Lists.newArrayList(0, 1), Lists.transform(getDocuments(),
DOCUMENT_TO_ID));
}
@Test
public void testGappedIdsInSourceXml()
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-gapped-ids.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
final int documentCount = runQuery();
assertEquals(4, documentCount);
assertEquals(Lists.newArrayList(6, 2, 5, 7), Lists.transform(getDocuments(),
DOCUMENT_TO_ID));
}
@Test
public void testDuplicatedIdsInSourceXml()
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-duplicated-ids.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
runQuery();
final List<Document> documents = getDocuments();
assertThat(documents.get(0).getId()).isEqualTo(1);
assertThat(documents.get(1).getId()).isEqualTo(2);
}
@Test
public void testInitializationTimeXslt()
{
IResource xslt = resourceUtils.getFirst("/xsl/custom-xslt.xsl",
XmlDocumentSourceTest.class);
initAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xslt"), xslt);
IResource xml = resourceUtils.getFirst("/xml/custom-parameters-not-required.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
final int documentCount = runQueryInCachingController();
assertTransformedDocumentsEqual(documentCount);
}
@Test
public void testOverridingInitializationTimeXslt()
{
IResource initXslt = resourceUtils.getFirst("/xsl/carrot2-identity.xsl",
XmlDocumentSourceTest.class);
initAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xslt"),
initXslt);
Controller controller = getCachingController(initAttributes);
// Run with identity XSLT
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-test.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils
.getKey(XmlDocumentSource.class, "xml"), xml);
final int documentCount = runQuery(controller);
assertEquals(2, documentCount);
assertEquals(Lists.newArrayList("Title 0", "Title 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_TITLE));
assertEquals(Lists.newArrayList("Snippet 0", "Snippet 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_SUMMARY));
}
// Run with swapping XSLT
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-test.xml",
XmlDocumentSourceTest.class);
IResource xslt = resourceUtils.getFirst(
"/xsl/carrot2-title-snippet-switch.xsl", XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils
.getKey(XmlDocumentSource.class, "xml"), xml);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class,
"xslt"), xslt);
final int documentCount = runQuery(controller);
assertEquals(2, documentCount);
assertEquals(Lists.newArrayList("Snippet 0", "Snippet 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_TITLE));
assertEquals(Lists.newArrayList("Title 0", "Title 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_SUMMARY));
}
}
@Test
public void testDisablingInitializationTimeXslt()
{
IResource initXslt = resourceUtils.getFirst(
"/xsl/carrot2-title-snippet-switch.xsl", XmlDocumentSourceTest.class);
initAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xslt"),
initXslt);
Controller controller = getCachingController(initAttributes);
// Run with swapping XSLT
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-test.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils
.getKey(XmlDocumentSource.class, "xml"), xml);
final int documentCount = runQuery(controller);
assertEquals(2, documentCount);
assertEquals(Lists.newArrayList("Snippet 0", "Snippet 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_TITLE));
assertEquals(Lists.newArrayList("Title 0", "Title 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_SUMMARY));
}
// Run without XSLT
{
IResource xml = resourceUtils.getFirst("/xml/carrot2-test.xml",
XmlDocumentSourceTest.class);
processingAttributes.put(AttributeUtils
.getKey(XmlDocumentSource.class, "xml"), xml);
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class,
"xslt"), null);
final int documentCount = runQuery(controller);
assertEquals(2, documentCount);
assertEquals(Lists.newArrayList("Title 0", "Title 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_TITLE));
assertEquals(Lists.newArrayList("Snippet 0", "Snippet 1"), Lists.transform(
getDocuments(), DOCUMENT_TO_SUMMARY));
}
}
@Test
public void testRemoteUrl() throws MalformedURLException
{
assumeTrue(carrot2XmlFeedTestsEnabled());
IResource xml = new URLResourceWithParams(new URL(getCarrot2XmlFeedUrlBase()
+ "&q=${query}&results=${results}"));
final String query = "apple computer";
processingAttributes.put(AttributeUtils.getKey(XmlDocumentSource.class, "xml"),
xml);
processingAttributes.put(AttributeNames.QUERY, query);
processingAttributes.put(AttributeNames.RESULTS, 50);
final int documentCount = runQuery();
assertEquals(50, documentCount);
assertEquals(query, resultAttributes.get(AttributeNames.QUERY));
}
private void assertTransformedDocumentsEqual(final int documentCount)
{
assertEquals(2, documentCount);
assertEquals("xslt test", resultAttributes.get(AttributeNames.QUERY));
assertEquals(Lists.newArrayList(498967, 831478), Lists.transform(getDocuments(),
DOCUMENT_TO_ID));
assertEquals(Lists.newArrayList("IBM's MARS Block Cipher.",
"IBM WebSphere Studio Device Developer"), Lists.transform(getDocuments(),
DOCUMENT_TO_TITLE));
assertEquals(Lists.newArrayList(
"The company's AES proposal using 128 bit blocks.",
"An integrated development environment."), Lists.transform(getDocuments(),
DOCUMENT_TO_SUMMARY));
assertEquals(Lists.newArrayList("http://www.research.ibm.com/security/mars.html",
"http://www-3.ibm.com/software/wireless/wsdd/"), Lists.transform(
getDocuments(), DOCUMENT_TO_CONTENT_URL));
}
/**
* Allows to skip running tests when details of the Carrot2 search feed are not
* provided.
*/
private static boolean carrot2XmlFeedTestsEnabled()
{
return externalApiTestsEnabled() && StringUtils.isNotBlank(getCarrot2XmlFeedUrlBase());
}
/**
* Returns the Carrot2 XML feed URL base or <code>null</code> if not provided.
*/
private static String getCarrot2XmlFeedUrlBase()
{
return System.getProperty("carrot2.xml.feed.url.base");
}
}
| bsd-3-clause |
wendal/beetl2.0 | beetl-core/src/main/java/org/beetl/core/statement/GeneralForStatement.java | 4477 | /*
[The "BSD license"]
Copyright (c) 2011-2014 Joel Li (李家智)
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. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.beetl.core.statement;
import org.beetl.core.Context;
import org.beetl.core.InferContext;
import org.beetl.core.exception.BeetlException;
/**
*
* for(var a=0;a <10;i++){}elsefor{}
* @author joelli
*
*/
public class GeneralForStatement extends Statement implements IGoto
{
public Expression[] expInit;
public Expression condtion;
public Expression[] expUpdate;
public Statement forPart;
public Statement elseforPart;
public VarAssignStatementSeq varAssignSeq;
public boolean hasGoto = false;
public short itType = 0;
//for(expInit;condtion;expUpdate){}
public GeneralForStatement(VarAssignStatementSeq varAssignSeq, Expression[] expInit, Expression condtion,
Expression[] expUpdate, Statement forPart, Statement elseforPart, GrammarToken token)
{
super(token);
this.varAssignSeq = varAssignSeq;
this.expInit = expInit;
this.condtion = condtion;
this.expUpdate = expUpdate;
this.elseforPart = elseforPart;
this.forPart = forPart;
}
public void execute(Context ctx)
{
if (expInit != null)
{
for (Expression exp : expInit)
{
exp.evaluate(ctx);
}
}
if (varAssignSeq != null)
{
varAssignSeq.execute(ctx);
}
//todo 需要提高效率,减少hasLooped赋值,以及每次gotoFlag检测,然而,这个不太常用,目前不优化
boolean hasLooped = false;
for (;;)
{
Object val = condtion.evaluate(ctx);
boolean bool = false;
if (val instanceof Boolean)
{
bool = ((Boolean) val).booleanValue();
}
else
{
BeetlException be = new BeetlException(BeetlException.BOOLEAN_EXPECTED_ERROR);
be.pushToken(condtion.token);
throw be;
}
if (bool)
{
hasLooped = true;
forPart.execute(ctx);
switch (ctx.gotoFlag)
{
case IGoto.NORMAL:
break;
case IGoto.CONTINUE:
ctx.gotoFlag = IGoto.NORMAL;
continue;
case IGoto.RETURN:
return;
case IGoto.BREAK:
ctx.gotoFlag = IGoto.NORMAL;
return;
}
}
else
{
break;
}
if (this.expUpdate != null)
{
for (Expression exp : expUpdate)
{
exp.evaluate(ctx);
}
}
}
}
@Override
public final boolean hasGoto()
{
// TODO Auto-generated method stub
return hasGoto;
}
@Override
public final void setGoto(boolean occour)
{
this.hasGoto = occour;
}
@Override
public void infer(InferContext inferCtx)
{
if (expInit != null)
{
for (Expression exp : expInit)
{
exp.infer(inferCtx);
}
}
if (varAssignSeq != null)
{
varAssignSeq.infer(inferCtx);
}
if (condtion != null)
{
condtion.infer(inferCtx);
}
if (expUpdate != null)
{
for (Expression exp : expUpdate)
{
exp.infer(inferCtx);
}
}
forPart.infer(inferCtx);
if (elseforPart != null)
{
elseforPart.infer(inferCtx);
}
}
}
| bsd-3-clause |
kakada/dhis2 | dhis-services/dhis-service-importexport/src/main/java/org/hisp/dhis/importexport/dhis14/file/configuration/DefaultIbatisConfigurationManager.java | 4133 | package org.hisp.dhis.importexport.dhis14.file.configuration;
/*
* Copyright (c) 2004-2015, 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 java.io.File;
import java.util.Properties;
import org.hisp.dhis.importexport.IbatisConfigurationManager;
import org.hisp.dhis.setting.SystemSettingManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author Lars Helge Overland
* @version $Id: DefaultIbatisConfigurationManager.java 6270 2008-11-13 11:49:21Z larshelg $
*/
public class DefaultIbatisConfigurationManager
implements IbatisConfigurationManager
{
private static final String KEY_CONNECTION_URL_DATABASE = "ibatis.connection.url.database";
private static final String KEY_PASSWORD = "ibatis.connection.password";
private static final String KEY_USERNAME = "ibatis.connection.username";
private static final String KEY_LEVELS = "ibatis.levels";
private static final String ACCESS_EXTENSION = ".mdb";
@Autowired
private SystemSettingManager systemSettingManager;
// -------------------------------------------------------------------------
// IbatisConfigurationManager implementation
// -------------------------------------------------------------------------
@Override
public Properties getPropertiesConfiguration()
{
Properties properties = new Properties();
properties.put( KEY_CONNECTION_URL_DATABASE, systemSettingManager.getSystemSetting( KEY_CONNECTION_URL_DATABASE ) );
properties.put( KEY_USERNAME, systemSettingManager.getSystemSetting( KEY_USERNAME ) );
properties.put( KEY_PASSWORD, systemSettingManager.getSystemSetting( KEY_PASSWORD ) );
properties.put( KEY_LEVELS, systemSettingManager.getSystemSetting( KEY_LEVELS ) );
return properties;
}
@Override
public void setConfiguration( String connectionUrl, String username, String password, String levels )
{
systemSettingManager.saveSystemSetting( KEY_CONNECTION_URL_DATABASE, connectionUrl );
systemSettingManager.saveSystemSetting( KEY_USERNAME, username );
systemSettingManager.saveSystemSetting( KEY_PASSWORD, password );
systemSettingManager.saveSystemSetting( KEY_LEVELS, levels );
}
@Override
public boolean fileIsValid( String path )
{
if ( path == null || !path.endsWith( ACCESS_EXTENSION ) )
{
return false;
}
File file = new File( path );
return file.exists();
}
}
| bsd-3-clause |
uwescience/myria | src/edu/washington/escience/myria/io/ByteSink.java | 537 | /**
*
*/
package edu.washington.escience.myria.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class ByteSink implements DataSink {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
private transient ByteArrayOutputStream writerOutput;
@Override
public OutputStream getOutputStream() throws IOException {
if (writerOutput == null) {
writerOutput = new ByteArrayOutputStream();
}
return writerOutput;
}
}
| bsd-3-clause |
ipapapa/IoT-MicroLocation | microlocationServer/src/microlocation/models/BeaconAuthenticator.java | 3097 | /*
* Five different data members of type string.
* A Boolean data type success initialized to be false
* Connection data type declared to be null
* There is a function used to connect to the SQL database (check function for comments)
* The authenticateBeacon connects to SQL database to verify the UUID, major and minor value
* along with the name and usecase of the beacons. Then the values after verification
* are stored in the response array and returned back
*/
package microlocation.models;
import java.io.IOException;
import java.sql.*;
public class BeaconAuthenticator
{
String p_uuid = "";
String p_major = "";
String p_minor = "";
String name = "";
String usecase = "";
Boolean success = false;
Connection connection = null;
/*
* Connect with SQL Database
*/
public void connectToSQLDatabase()
{
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://127.0.0.1:3306/microlocation_aws";
try
{
Class.forName(JDBC_DRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
System.out.println("JDBC Driver Registered!");
try
{
connection = DriverManager.getConnection(DB_URL, "root", "");
}
catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection == null)
{
System.out.println("Failed to make connection!");
}
}
/*
* Authenticate Beacons with the DBss
*/
public String[] authenticateBeaconCloudant(String uuid, String major, String minor)
{
String[] response = new String[5];
connectToSQLDatabase(); //connect to SQL database
try
{
String sql = "SELECT * FROM beacons WHERE (uuid = '"+uuid+
"' AND major = '"+major+"' AND minor = '"+minor+"')";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery(sql);
while (result.next()) // loop runs as long as the result set has some data (rows)
{
p_uuid = result.getString(1);
p_major = result.getString(2);
p_minor = result.getString(3);
name = result.getString(4);
usecase = result.getString(5);
/* check matching uuid, major and minor */
if((p_uuid.equalsIgnoreCase(uuid)) && (p_major.equalsIgnoreCase(major))
&& (p_minor.equalsIgnoreCase(minor)))
{
success = true; //if it matches it then set the success=true
response[0] = p_uuid; // response array stores the values
response[1] = p_major; // the UUID and other values are stored in
//the response array and returned back.
response[2] = p_minor;
response[3] = name;
response[4] = usecase;
}
}
result.close();
statement.close();
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
return response;
}
} | bsd-3-clause |
CedricGatay/Checkstyle-IDEA-no-logger-dependency | src/test/java/org/infernus/idea/checkstyle/model/FileConfigurationLocationTest.java | 1729 | package org.infernus.idea.checkstyle.model;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class FileConfigurationLocationTest {
private static final String PROJECT_PATH = "/the/base-project/path";
@Mock
private Project project;
@Mock
private VirtualFile projectBase;
private FileConfigurationLocation unit;
@Before
public void setUp() {
unit = new FileConfigurationLocation(project);
unit.setLocation("aLocation");
unit.setDescription("aDescription");
when(project.getBaseDir()).thenReturn(projectBase);
when(projectBase.getPath()).thenReturn(PROJECT_PATH);
}
@Test
public void descriptorShouldContainsTypeLocationAndDescription() {
assertThat(unit.getDescriptor(), is(equalTo("FILE:aLocation:aDescription")));
}
@Test
public void baseDirectoryShouldBeTokenisedInDescriptor() {
unit.setLocation(PROJECT_PATH + "/a-path/to/checkstyle.xml");
assertThat(unit.getDescriptor(), is(equalTo("FILE:$PROJECT_DIR$/a-path/to/checkstyle.xml:aDescription")));
}
@Test
public void locationShouldBeDetokenisedCorrectly() {
unit.setLocation(PROJECT_PATH + "/a-path/to/checkstyle.xml");
assertThat(unit.getLocation(), is(equalTo(PROJECT_PATH + "/a-path/to/checkstyle.xml")));
}
}
| bsd-3-clause |
lxp/sulong | projects/com.oracle.truffle.llvm.parser.base/src/com/oracle/truffle/llvm/parser/base/model/visitors/ValueSymbolVisitor.java | 1904 | /*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder 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.
*/
package com.oracle.truffle.llvm.parser.base.model.visitors;
import com.oracle.truffle.llvm.parser.base.model.symbols.instructions.VoidInstruction;
public abstract class ValueSymbolVisitor extends ReducedInstructionVisitor {
@Override
public void visitVoidInstruction(VoidInstruction voidInstruction) {
}
}
| bsd-3-clause |
ConnorGoldstick/2014SHOREWOODROBOTFINAL | src/edu/wpi/first/wpilibj/templates/loadAndShoot.java | 9879 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class loadAndShoot extends Thread {
boolean running = false;
Solenoid sol4, sol5, sol7, sol8;
Victor victor;
AnalogChannel encoder;
DigitalInput digi14, digi13, digi3;
Joystick xBox;
Shoot shooter;
DigitalOutput readyShoot;
boolean shooting = false; //starts the catapult
int ShootCount = 0;
Load Load;
boolean loadingWithBall = false; //loads with more force, to compensate for the ball
boolean loadingWithoutBall = false; //loads with less force
int endLoadCount = 0;
Unload Unload;
boolean unloading = false; //extends the suction cup
SuckUpBall SuckUpBall;
boolean okToSuck = false; //toggles on/off the auto suction
boolean sucking = false; //begins the autosuction
int suckingCount = 0;
boolean doNotSuck = false; //stops the autosuction from screwing up
SmartDashboard smart;
public final double LOADARM_REST_ANGLE = 3.6;
public final double LOADARM_REST_ADJUSTMENT_SPEED = 0.4;
public final double LOADARM_UNLOADED_MIN_THESHOLD = 2.5;
public final double LOADARM_UNLOADED_THESHOLD = 3.6;
public final int SHOOT_COUNT_MAX = 155;
public final int SUCTION_COUNT_MAX = 100;
public loadAndShoot(AnalogChannel e, Victor v, Solenoid s4, Solenoid s5, Solenoid s7, Solenoid s8, Joystick x, DigitalInput d14, DigitalInput d13, DigitalInput d3, SmartDashboard sd, DigitalOutput rs) {
victor = v;
encoder = e;
sol4 = s4;
sol5 = s5;
sol7 = s7;
sol8 = s8;
xBox = x;
digi14 = d14;
digi13 = d13;
digi3 = d3;
smart = sd;
readyShoot = rs;
shooter = new Shoot(sol4, sol5, sol7, sol8);
Load = new Load(victor, encoder);
Unload = new Unload(victor, sol4, sol5);
SuckUpBall = new SuckUpBall(victor, sol4, sol5);
}
public void setRun(boolean run) {
running = run;
}
public void teleoperatedInit() {
suctionOff();
victor.set(0);
shooting = false;
loadingWithBall = false;
loadingWithoutBall = false;
endLoadCount = 0;
unloading = false;
ShootCount = 0;
okToSuck = true;
sucking = false;
suckingCount = 0;
doNotSuck = false;
}
public void resetBooleans() {
shooting = false;
loadingWithBall = false;
loadingWithoutBall = false;
unloading = false;
okToSuck = true;
sucking = false;
doNotSuck = false;
suctionOff();
noShooty();
}
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (Exception ex) {
}
while (running) {
try {
Thread.sleep(10);
} catch (Exception ex) {
}
boolean xButton = xBox.getRawButton(3);
boolean yButton = xBox.getRawButton(4);
boolean leftBumper = xBox.getRawButton(5);
boolean rightBumper = xBox.getRawButton(6);
double leftRightTrigger = xBox.getRawAxis(3);
double dPad = xBox.getRawAxis(6);
smart.putBoolean("auto suction enabled", !doNotSuck && okToSuck);
if (dPad == -1) {
System.out.println("reset everything");
reset();
}
System.out.println(encoder.getAverageVoltage());
//begin autosuction and manual suction
if (xButton) { //toggle off
System.out.println("toggle suction off");
suctionOff();
okToSuck = false;
}
if (yButton) { //toggle on
System.out.println("toggle suction on");
okToSuck = true;
doNotSuck = false; //resets the autosuction stop
}
if ((digi14.get() || digi13.get() || leftRightTrigger > .95) && !loadingWithBall && !loadingWithoutBall && !unloading && !shooting && !sucking && okToSuck && !doNotSuck && !digi3.get()) {
System.out.println("start suction");
sucking = true; //checks to see if ball is touching limit switch
}
if (sucking) { //autosuction occurs as long as this is true
System.out.println("suctioning");
suckingCount++;
SuckUpBall.suckItUp(); //suction command
}
if (suckingCount > SUCTION_COUNT_MAX) { //ends autosuction
System.out.println("end suction");
suckingCount = 0;
endAutosuction();
}
//end autosuction and manual suction
//start end load
if (digi3.get() && !unloading) {//stops the loading
endLoading();
setReadyShootLED();
}
// end end load
//begin loading
if (rightBumper && !loadingWithBall && !loadingWithoutBall && !unloading && !shooting) {
System.out.println("start loading");
//checks to see if suction is on or not
if (returnSuctionValue() == true) { //suctioning
System.out.println("start load w/ ball");
loadingWithBall = true;
}
if (returnSuctionValue() == false) { //not suctioning
System.out.println("start load w/out ball");
loadingWithoutBall = true;
}
}
if (loadingWithBall) { //runs load with ball
System.out.println("load w/ ball");
Load.loadWithBall(); //loadWithBall command
}
if (loadingWithoutBall) { //runs load without ball
System.out.println("load w/out ball");
Load.loadWithoutBall(); //loadWithoutBall command
}
//end loading
//begin shooter
if (leftRightTrigger < -.95 && !loadingWithBall && !loadingWithoutBall && !unloading && !shooting) {
System.out.println("start shooting");
setReadyShootLED();
shooting = true;
shooter.setCountToZero(); //resets the count in the class to zero
}
if (shooting) { //currently shooting
System.out.println("shooting");
ShootCount++;
shooter.Shoot(); //shoot command
}
if (ShootCount > SHOOT_COUNT_MAX) { //turns off the shoot
System.out.println("end shoot");
shooting = false;
ShootCount = 0;
}
//end shooter
//begin unloading
if (leftBumper && !loadingWithBall && !loadingWithoutBall && !unloading && !shooting) {
unloading = true;
System.out.println("start unload");
}
if (unloading) { //suction arm extends
System.out.println("unloading");
Unload.unload(); //unload command
}
if (encoder.getVoltage() >= LOADARM_UNLOADED_MIN_THESHOLD && encoder.getVoltage() <= LOADARM_UNLOADED_THESHOLD && (unloading)) { //ends unloading
System.out.println("end unload");
endUnload();
}
//end Unload
if (!loadingWithBall && !loadingWithoutBall && !sucking && !unloading && !digi3.get()) {
if (encoder.getAverageVoltage() < LOADARM_REST_ANGLE) {
victor.set(LOADARM_REST_ADJUSTMENT_SPEED);
System.out.println("adjusting");
} else {
victor.set(0);
System.out.println("adjusted");
}
}
}
}
}
public void endUnload() {
unloading = false;
victor.set(0); //stops the victor
doNotSuck = false; //resets the autosuction stop
}
public void reset() {
loadingWithBall = false;
loadingWithoutBall = false;
unloading = false;
shooting = false;
sucking = false;
okToSuck = false;
doNotSuck = false;
sol7.set(true);
sol8.set(false);
}
public void suctionOff() {
sol4.set(false);
sol5.set(true);
}
public void noShooty() {
sol7.set(true);
sol8.set(false);
}
public void endLoading() {
victor.set(0);
suctionOff();
loadingWithBall = false;
loadingWithoutBall = false;
}
public boolean returnSuctionValue() {
if (sol4.get() == true && sol5.get() == false) {
return true;
} else {
return false;
}
}
public void endAutosuction() {
victor.set(0); //stops the victor movement
sucking = false;
doNotSuck = true; //prevents the autosuction from activating again
}
public void setReadyShootLED(){
if(loadingWithBall){
readyShoot.set(true);
}
if(shooting){
readyShoot.set(false);
}
}
}
| bsd-3-clause |
Ozuru/NormalityZero2014 | src/edu/wpi/first/wpilibj/templates/RobotMap.java | 1572 | package edu.wpi.first.wpilibj.templates;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static final int leftMotor = 1;
// public static final int rightMotor = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static final int rangefinderPort = 1;
// public static final int rangefinderModule = 1;
public static final int JOYSTICK_AXIS_DRIVE_LEFT = 2,
JOYSTICK_AXIS_DRIVE_RIGHT = 6;
public static final int PORT_DRIVETRAIN_LEFT_FR = 1,
PORT_DRIVETRAIN_LEFT_BACK = 2,
PORT_DRIVETRAIN_RIGHT_FR = 3,
PORT_DRIVETRAIN_RIGHT_BACK = 4;
public static final int PORT_WINCH = 6;
public static final int PORT_COMPRESSOR_1 = 8,
PORT_COMPRESSOR_2 = 7;
public static final int PORT_SHIFTER = 1;
public static final int PORT_ARMS_FORW = 2,
PORT_ARMS_REV = 3;
public static final int PORT_FINGERS_FORW = 4,
PORT_FINGERS_REV = 5;
public static final int PORT_WINCH_LIMIT = 10;
}
| bsd-3-clause |
synergynet/synergynet2.5 | synergynet2.5/src/main/java/apps/tablepositionsetup/Stepper.java | 8865 | package apps.tablepositionsetup;
import java.awt.Color;
import java.awt.Font;
import java.text.DecimalFormat;
import synergynetframework.appsystem.contentsystem.ContentSystem;
import synergynetframework.appsystem.contentsystem.items.ContentItem;
import synergynetframework.appsystem.contentsystem.items.TextLabel;
import synergynetframework.appsystem.contentsystem.items.listener.ItemListener;
import synergynetframework.jme.Updateable;
/**
* The Class Stepper.
*/
public class Stepper implements Updateable {
/** The suffix text. */
private TextLabel distanceText, upper, downer, prefixText,
suffixText = null;
/** The loc y. */
private int locX, locY = 0;
/** The measurement. */
private String measurement;
/** The scale. */
private float result, scale = 0;
/** The down. */
private boolean up, down = false;
/** The lower limit. */
private float upperLimit, lowerLimit = 0;
/** The lower limit set. */
private boolean upperLimitSet, lowerLimitSet = false;
/**
* Instantiates a new stepper.
*
* @param contentSystem
* the content system
* @param x
* the x
* @param y
* the y
* @param startValue
* the start value
* @param stepSize
* the step size
* @param prefix
* the prefix
* @param suffix
* the suffix
* @param measure
* the measure
*/
public Stepper(ContentSystem contentSystem, int x, int y, float startValue,
float stepSize, String prefix, String suffix, String measure) {
this.locX = x;
this.locY = y;
this.measurement = measure;
this.scale = stepSize;
result = startValue;
prefixText = (TextLabel) contentSystem
.createContentItem(TextLabel.class);
prefixText.setBackgroundColour(Color.black);
prefixText.setBorderSize(0);
prefixText.setTextColour(Color.white);
prefixText.setFont(new Font("Arial", Font.PLAIN, 20));
prefixText.setRotateTranslateScalable(false);
prefixText.setBringToTopable(false);
prefixText.setText(prefix);
prefixText.setLocalLocation(locX, locY);
distanceText = (TextLabel) contentSystem
.createContentItem(TextLabel.class);
distanceText.setBackgroundColour(Color.black);
distanceText.setBorderSize(0);
distanceText.setTextColour(Color.white);
distanceText.setFont(new Font("Arial", Font.PLAIN, 20));
distanceText.setRotateTranslateScalable(false);
distanceText.setBringToTopable(false);
distanceText.setText(" " + new DecimalFormat("0.##").format(result)
+ measurement + " ");
distanceText.setLocalLocation(locX + (prefixText.getWidth() / 2)
+ (distanceText.getWidth() / 2), locY);
suffixText = (TextLabel) contentSystem
.createContentItem(TextLabel.class);
suffixText.setBackgroundColour(Color.black);
suffixText.setBorderSize(0);
suffixText.setTextColour(Color.white);
suffixText.setFont(new Font("Arial", Font.PLAIN, 20));
suffixText.setRotateTranslateScalable(false);
suffixText.setBringToTopable(false);
suffixText.setText(suffix);
suffixText.setLocalLocation(locX + (prefixText.getWidth() / 2)
+ distanceText.getWidth(), locY);
upper = (TextLabel) contentSystem.createContentItem(TextLabel.class);
upper.setBackgroundColour(Color.black);
upper.setBorderSize(2);
upper.setBorderColour(Color.green);
upper.setTextColour(Color.green);
upper.setFont(new Font("Arial", Font.BOLD, 20));
upper.setRotateTranslateScalable(false);
upper.setBringToTopable(false);
upper.setText("+");
int buttonWidth = upper.getWidth();
upper.setAutoFitSize(false);
upper.setWidth(buttonWidth);
upper.setHeight(buttonWidth);
upper.setLocalLocation(locX + upper.getWidth(),
locY - (distanceText.getHeight() / 2) - (upper.getHeight() / 2));
upper.addItemListener(new ItemListener() {
@Override
public void cursorChanged(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorDoubleClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorLongHeld(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorPressed(ContentItem item, long id, float x,
float y, float pressure) {
up = true;
}
@Override
public void cursorReleased(ContentItem item, long id, float x,
float y, float pressure) {
up = false;
}
@Override
public void cursorRightClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
});
downer = (TextLabel) contentSystem.createContentItem(TextLabel.class);
downer.setBackgroundColour(Color.black);
downer.setBorderSize(2);
downer.setBorderColour(Color.red);
downer.setTextColour(Color.red);
downer.setFont(new Font("Arial", Font.BOLD, 20));
downer.setRotateTranslateScalable(false);
downer.setBringToTopable(false);
downer.setText("-");
downer.setAutoFitSize(false);
downer.setWidth(buttonWidth);
downer.setHeight(buttonWidth);
downer.setLocalLocation(locX - downer.getWidth(),
locY - (distanceText.getHeight() / 2)
- (downer.getHeight() / 2));
downer.addItemListener(new ItemListener() {
@Override
public void cursorChanged(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorDoubleClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorLongHeld(ContentItem item, long id, float x,
float y, float pressure) {
}
@Override
public void cursorPressed(ContentItem item, long id, float x,
float y, float pressure) {
down = true;
}
@Override
public void cursorReleased(ContentItem item, long id, float x,
float y, float pressure) {
down = false;
}
@Override
public void cursorRightClicked(ContentItem item, long id, float x,
float y, float pressure) {
}
});
}
/**
* Destroy dial.
*/
public void destroyDial() {
distanceText.setVisible(false, true);
upper.setVisible(false, true);
downer.setVisible(false, true);
prefixText.setVisible(false, true);
suffixText.setVisible(false, true);
}
/**
* Gets the value.
*
* @return the value
*/
public float getValue() {
return result;
}
/**
* Sets the lower limit.
*
* @param limit
* the new lower limit
*/
public void setLowerLimit(float limit) {
lowerLimitSet = true;
lowerLimit = limit;
}
/**
* Sets the upper limit.
*
* @param limit
* the new upper limit
*/
public void setUpperLimit(float limit) {
upperLimitSet = true;
upperLimit = limit;
}
/**
* Sets the value.
*
* @param value
* the new value
*/
public void setValue(float value) {
result = value;
updateStepper();
;
}
/**
* Un set lower limit.
*/
public void unSetLowerLimit() {
lowerLimitSet = false;
}
/**
* Un set upper limit.
*/
public void unSetUpperLimit() {
upperLimitSet = false;
}
/*
* (non-Javadoc)
* @see synergynetframework.jme.Updateable#update(float)
*/
@Override
public void update(float timePerFrame) {
if (up) {
if (upperLimitSet
&& ((result + (scale * timePerFrame)) > upperLimit)) {
result = upperLimit;
updateStepper();
} else if (lowerLimitSet
&& ((result + (scale * timePerFrame)) < lowerLimit)) {
result = lowerLimit;
updateStepper();
} else {
result += (scale * timePerFrame);
updateStepper();
}
}
if (down) {
if (upperLimitSet
&& ((result - (scale * timePerFrame)) > upperLimit)) {
result = upperLimit;
updateStepper();
} else if (lowerLimitSet
&& ((result - (scale * timePerFrame)) < lowerLimit)) {
result = lowerLimit;
updateStepper();
} else {
result -= (scale * timePerFrame);
updateStepper();
}
}
}
/**
* Update stepper.
*/
private void updateStepper() {
distanceText.setText(" " + new DecimalFormat("0.##").format(result)
+ measurement + " ");
distanceText.setLocalLocation(locX + (prefixText.getWidth() / 2)
+ (distanceText.getWidth() / 2), locY);
suffixText.setLocalLocation(locX + (prefixText.getWidth() / 2)
+ distanceText.getWidth(), locY);
}
}
| bsd-3-clause |
wangxin39/xstat | SupervisorSystem/src/cn/iaicc/smgk/web/action/manage/list/ListAppealResultAction.java | 6793 | package cn.iaicc.smgk.web.action.manage.list;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.iaicc.smgk.business.IClientAccountInfoService;
import cn.iaicc.smgk.business.IEmployeeInfoService;
import cn.iaicc.smgk.business.IReqInfoService;
import cn.iaicc.smgk.business.IReqResultInfoService;
import cn.iaicc.smgk.po.ClientAccountInfo;
import cn.iaicc.smgk.po.EmployeeInfo;
import cn.iaicc.smgk.po.ReqInfo;
import cn.iaicc.smgk.po.ReqResultInfo;
import cn.iaicc.smgk.web.conf.SmgkConstants;
import cn.iaicc.smgk.web.conf.StatusConstants;
import cn.iaicc.smgk.web.util.PaginationUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ListAppealResultAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 7739475960664629870L;
private static Log logger = LogFactory.getLog(ListAppealResultAction.class);
private IClientAccountInfoService clientAccountInfoService = null;
private IReqResultInfoService reqResultInfoService= null;
private IEmployeeInfoService employeeInfoService = null;
private IReqInfoService reqInfoService= null;
private List<String> clientAccountList = new LinkedList<String>();
private List<String> employeeList = new LinkedList<String>();
private List<String> reqList = new LinkedList<String>();
private Long reqID = null;
private Long resultID = null;
/**
* 当前第几页
*/
private Integer num = null;
/**
* 分页数据列表
*/
private List<ReqResultInfo> pageList = null;
private PaginationUtil pu = null;
@Override
public String execute() 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;
}
EmployeeInfo employeeInfo = employeeInfoService.isLogin(username, password);
if(employeeInfo == null) {
this.addActionError("employeeInfo为空!");
return LOGIN;
}
int page = 1;
if(num != null){
page = num.intValue();
}
int total = reqResultInfoService.getReqResultInfoTotal();
pu = new PaginationUtil(total,page,SmgkConstants.PAGE_MAX_RESULT);
pageList = reqResultInfoService.findReqResultInfoByPage(pu.getStartRecord(),SmgkConstants.PAGE_MAX_RESULT);
for(ReqResultInfo info:pageList){
ClientAccountInfo ci = clientAccountInfoService.getClientAccountInfo(info.getAccountID());
if(ci != null){
clientAccountList.add(""+ci.getClientName());
}
else{
clientAccountList.add("");
}
if( info.getEmployeeID() != null) {
EmployeeInfo ei = employeeInfoService.getEmployeeInfo(info.getEmployeeID());
if(ei != null) {
employeeList.add(""+ei.getName());
}
}else{
employeeList.add("");
}
ReqInfo ri = reqInfoService.getReqInfo(info.getReqID());
if(ri!=null && ri.getName()!=null){
reqList.add(""+ri.getName());
}else{
reqList.add("");
}
}
}catch(Exception e) {
logger.error(""+e.getMessage(),e.getCause());
}
return SUCCESS;
}
@SuppressWarnings("unchecked")
public String input() throws Exception {
String username = (String)ActionContext.getContext().getSession().get("LOGINUSERNAME");
String password = (String)ActionContext.getContext().getSession().get("LOGINPASSWORD");
if(username == null || password == null) {
return LOGIN;
}
try{
ActionContext.getContext().getSession().put("CLIENTINPUTADDISOK","OK");//防止刷新提交多次相同信息
}catch(Exception e) {
logger.error(""+e.getMessage(),e.getCause());
}
return SUCCESS;
}
public String detail() 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;
}
if(resultID == null){
this.addActionError("resultID为空!");
return ERROR;
}
ReqResultInfo info = reqResultInfoService.getReqResultInfo(resultID);
if(info!=null && info.getStatus()!=null){
ActionContext.getContext().put("RESULTDETAIL",info);
ActionContext.getContext().put("STATUS", StatusConstants.StatusDict.get(info.getStatus()));
}
ReqInfo ri = reqInfoService.getReqInfo(info.getReqID());
ClientAccountInfo ci = clientAccountInfoService.getClientAccountInfo(info.getAccountID());
EmployeeInfo ei = employeeInfoService.getEmployeeInfo(info.getEmployeeID());
if(ri!=null && ri.getName()!=null){
ActionContext.getContext().put("REQINOF",ri.getName());
}
if(ci!=null && ci.getClientName()!=null){
ActionContext.getContext().put("ACCOUNT",ci.getClientName());
}
if(ei!=null && ei.getName()!=null){
ActionContext.getContext().put("EMPLOYEE",ei.getName());
}
}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 setEmployeeInfoService(IEmployeeInfoService employeeInfoService) {
this.employeeInfoService = employeeInfoService;
}
public PaginationUtil getPu() {
return pu;
}
public void setReqResultInfoService(IReqResultInfoService reqResultInfoService) {
this.reqResultInfoService = reqResultInfoService;
}
public List<ReqResultInfo> getPageList() {
return pageList;
}
public void setPageList(List<ReqResultInfo> pageList) {
this.pageList = pageList;
}
public void setPu(PaginationUtil pu) {
this.pu = pu;
}
public void setClientAccountInfoService(
IClientAccountInfoService clientAccountInfoService) {
this.clientAccountInfoService = clientAccountInfoService;
}
public void setClientAccountList(List<String> clientAccountList) {
this.clientAccountList = clientAccountList;
}
public List<String> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<String> employeeList) {
this.employeeList = employeeList;
}
public List<String> getClientAccountList() {
return clientAccountList;
}
public List<String> getReqList() {
return reqList;
}
public void setReqList(List<String> reqList) {
this.reqList = reqList;
}
public void setReqInfoService(IReqInfoService reqInfoService) {
this.reqInfoService = reqInfoService;
}
public Long getResultID() {
return resultID;
}
public void setResultID(Long resultID) {
this.resultID = resultID;
}
public Long getReqID() {
return reqID;
}
public void setReqID(Long reqID) {
this.reqID = reqID;
}
}
| bsd-3-clause |
dritanlatifi/AndroidPrefuse | src/swing/javax/swing/event/ListSelectionEvent.java | 2015 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Anton Avtamonov
*/
package swing.javax.swing.event;
import java.util.EventObject;
public class ListSelectionEvent extends EventObject {
private final int firstIndex;
private final int lastIndex;
private final boolean isAdjusting;
public ListSelectionEvent(final Object source, final int firstIndex, final int lastIndex, final boolean isAdjusting) {
super(source);
this.firstIndex = firstIndex;
this.lastIndex = lastIndex;
this.isAdjusting = isAdjusting;
}
public int getFirstIndex() {
return firstIndex;
}
public int getLastIndex() {
return lastIndex;
}
public boolean getValueIsAdjusting() {
return isAdjusting;
}
/*
* The format of the string is based on 1.5 release behavior
* which can be revealed using the following code:
*
* Object obj = new ListSelectionEvent(new JList(), 0, 1, false);
* System.out.println(obj.toString());
*/
public String toString() {
return this.getClass().getName() + "[source="+source+" firstIndex= " + firstIndex + " lastIndex= " + lastIndex + " isAdjusting= " + isAdjusting + " ]";
}
}
| bsd-3-clause |
googleapis/api-client-staging | generated/java/proto-google-common-protos/src/main/java/com/google/api/SystemParameter.java | 26124 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/system_parameter.proto
package com.google.api;
/**
* <pre>
* Define a parameter's name and location. The parameter may be passed as either
* an HTTP header or a URL query parameter, and if both are passed the behavior
* is implementation-dependent.
* </pre>
*
* Protobuf type {@code google.api.SystemParameter}
*/
public final class SystemParameter extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.api.SystemParameter)
SystemParameterOrBuilder {
private static final long serialVersionUID = 0L;
// Use SystemParameter.newBuilder() to construct.
private SystemParameter(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SystemParameter() {
name_ = "";
httpHeader_ = "";
urlQueryParameter_ = "";
}
@Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private SystemParameter(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18: {
String s = input.readStringRequireUtf8();
httpHeader_ = s;
break;
}
case 26: {
String s = input.readStringRequireUtf8();
urlQueryParameter_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.api.SystemParameterProto.internal_static_google_api_SystemParameter_descriptor;
}
@Override
protected FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.SystemParameterProto.internal_static_google_api_SystemParameter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SystemParameter.class, Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile Object name_;
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public String getName() {
Object ref = name_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int HTTP_HEADER_FIELD_NUMBER = 2;
private volatile Object httpHeader_;
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public String getHttpHeader() {
Object ref = httpHeader_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
httpHeader_ = s;
return s;
}
}
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public com.google.protobuf.ByteString
getHttpHeaderBytes() {
Object ref = httpHeader_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
httpHeader_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int URL_QUERY_PARAMETER_FIELD_NUMBER = 3;
private volatile Object urlQueryParameter_;
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public String getUrlQueryParameter() {
Object ref = urlQueryParameter_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
urlQueryParameter_ = s;
return s;
}
}
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public com.google.protobuf.ByteString
getUrlQueryParameterBytes() {
Object ref = urlQueryParameter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
urlQueryParameter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!getHttpHeaderBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, httpHeader_);
}
if (!getUrlQueryParameterBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, urlQueryParameter_);
}
unknownFields.writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!getHttpHeaderBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, httpHeader_);
}
if (!getUrlQueryParameterBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, urlQueryParameter_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SystemParameter)) {
return super.equals(obj);
}
SystemParameter other = (SystemParameter) obj;
if (!getName()
.equals(other.getName())) return false;
if (!getHttpHeader()
.equals(other.getHttpHeader())) return false;
if (!getUrlQueryParameter()
.equals(other.getUrlQueryParameter())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + HTTP_HEADER_FIELD_NUMBER;
hash = (53 * hash) + getHttpHeader().hashCode();
hash = (37 * hash) + URL_QUERY_PARAMETER_FIELD_NUMBER;
hash = (53 * hash) + getUrlQueryParameter().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SystemParameter parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SystemParameter parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SystemParameter parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SystemParameter parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SystemParameter parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SystemParameter parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SystemParameter parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SystemParameter parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static SystemParameter parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SystemParameter parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static SystemParameter parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SystemParameter parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SystemParameter prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(
BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Define a parameter's name and location. The parameter may be passed as either
* an HTTP header or a URL query parameter, and if both are passed the behavior
* is implementation-dependent.
* </pre>
*
* Protobuf type {@code google.api.SystemParameter}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.api.SystemParameter)
com.google.api.SystemParameterOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.api.SystemParameterProto.internal_static_google_api_SystemParameter_descriptor;
}
@Override
protected FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.SystemParameterProto.internal_static_google_api_SystemParameter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SystemParameter.class, Builder.class);
}
// Construct using com.google.api.SystemParameter.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@Override
public Builder clear() {
super.clear();
name_ = "";
httpHeader_ = "";
urlQueryParameter_ = "";
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.api.SystemParameterProto.internal_static_google_api_SystemParameter_descriptor;
}
@Override
public SystemParameter getDefaultInstanceForType() {
return SystemParameter.getDefaultInstance();
}
@Override
public SystemParameter build() {
SystemParameter result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public SystemParameter buildPartial() {
SystemParameter result = new SystemParameter(this);
result.name_ = name_;
result.httpHeader_ = httpHeader_;
result.urlQueryParameter_ = urlQueryParameter_;
onBuilt();
return result;
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SystemParameter) {
return mergeFrom((SystemParameter)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SystemParameter other) {
if (other == SystemParameter.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getHttpHeader().isEmpty()) {
httpHeader_ = other.httpHeader_;
onChanged();
}
if (!other.getUrlQueryParameter().isEmpty()) {
urlQueryParameter_ = other.urlQueryParameter_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SystemParameter parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SystemParameter) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private Object name_ = "";
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public String getName() {
Object ref = name_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setName(
String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* Define the name of the parameter, such as "api_key" . It is case sensitive.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private Object httpHeader_ = "";
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public String getHttpHeader() {
Object ref = httpHeader_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
httpHeader_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public com.google.protobuf.ByteString
getHttpHeaderBytes() {
Object ref = httpHeader_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
httpHeader_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public Builder setHttpHeader(
String value) {
if (value == null) {
throw new NullPointerException();
}
httpHeader_ = value;
onChanged();
return this;
}
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public Builder clearHttpHeader() {
httpHeader_ = getDefaultInstance().getHttpHeader();
onChanged();
return this;
}
/**
* <pre>
* Define the HTTP header name to use for the parameter. It is case
* insensitive.
* </pre>
*
* <code>string http_header = 2;</code>
*/
public Builder setHttpHeaderBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
httpHeader_ = value;
onChanged();
return this;
}
private Object urlQueryParameter_ = "";
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public String getUrlQueryParameter() {
Object ref = urlQueryParameter_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
urlQueryParameter_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public com.google.protobuf.ByteString
getUrlQueryParameterBytes() {
Object ref = urlQueryParameter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
urlQueryParameter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public Builder setUrlQueryParameter(
String value) {
if (value == null) {
throw new NullPointerException();
}
urlQueryParameter_ = value;
onChanged();
return this;
}
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public Builder clearUrlQueryParameter() {
urlQueryParameter_ = getDefaultInstance().getUrlQueryParameter();
onChanged();
return this;
}
/**
* <pre>
* Define the URL query parameter name to use for the parameter. It is case
* sensitive.
* </pre>
*
* <code>string url_query_parameter = 3;</code>
*/
public Builder setUrlQueryParameterBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
urlQueryParameter_ = value;
onChanged();
return this;
}
@Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.api.SystemParameter)
}
// @@protoc_insertion_point(class_scope:google.api.SystemParameter)
private static final SystemParameter DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SystemParameter();
}
public static SystemParameter getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SystemParameter>
PARSER = new com.google.protobuf.AbstractParser<SystemParameter>() {
@Override
public SystemParameter parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new SystemParameter(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<SystemParameter> parser() {
return PARSER;
}
@Override
public com.google.protobuf.Parser<SystemParameter> getParserForType() {
return PARSER;
}
@Override
public SystemParameter getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseEmptyListsTest.java | 2906 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.payments;
import android.support.test.filters.MediumTest;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.AutofillTestHelper;
import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.payments.PaymentRequestTestRule.AppPresence;
import org.chromium.chrome.browser.payments.PaymentRequestTestRule.FactorySpeed;
import org.chromium.chrome.browser.payments.PaymentRequestTestRule.MainActivityStartCallback;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.ui.test.util.DisableAnimationsTestRule;
import java.util.concurrent.TimeoutException;
/**
* A payment integration test for the show promise that resolves with empty lists of display
* items, modifiers, and shipping options, which clears out the Payment Request data.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class PaymentRequestShowPromiseEmptyListsTest implements MainActivityStartCallback {
// Disable animations to reduce flakiness.
@ClassRule
public static DisableAnimationsTestRule sNoAnimationsRule = new DisableAnimationsTestRule();
@Rule
public PaymentRequestTestRule mRule =
new PaymentRequestTestRule("show_promise/resolve_with_empty_lists.html", this);
@Override
public void onMainActivityStarted() throws TimeoutException {
new AutofillTestHelper().setProfile(new AutofillProfile("", "https://example.com", true,
"Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US",
"650-253-0000", "", "en-US"));
}
@Test
@MediumTest
@Feature({"Payments"})
public void testResolveWithEmptyLists() throws TimeoutException {
mRule.addPaymentAppFactory("basic-card", AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY);
mRule.triggerUIAndWait(mRule.getReadyForInput());
Assert.assertEquals("USD $1.00", mRule.getOrderSummaryTotal());
mRule.clickInOrderSummaryAndWait(mRule.getReadyForInput());
Assert.assertEquals(0, mRule.getNumberOfLineItems());
mRule.clickInShippingAddressAndWait(R.id.payments_section, mRule.getReadyForInput());
Assert.assertEquals("To see shipping methods and requirements, select an address",
mRule.getShippingAddressDescriptionLabel());
}
}
| bsd-3-clause |
was4444/chromium.src | chrome/android/java/src/org/chromium/chrome/browser/datausage/DataUseTabUIManager.java | 14471 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.datausage;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.EmbedContentViewActivity;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.sessions.SessionTabHelper;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.components.variations.VariationsAssociatedData;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.common.Referrer;
/**
* Entry point to manage all UI details for measuring data use within a Tab.
*/
public class DataUseTabUIManager {
private static final String SHARED_PREF_DATA_USE_DIALOG_OPT_OUT = "data_use_dialog_opt_out";
private static final String FIELD_TRIAL_NAME = "ExternalDataUseObserver";
/**
* Data use started UI snackbar will not be shown if {@link DISABLE_DATA_USE_STARTED_UI_PARAM}
* fieldtrial parameter is set to {@value DISABLE_DATA_USE_UI_PARAM_VALUE}.
*/
private static final String DISABLE_DATA_USE_STARTED_UI_PARAM = "disable_data_use_started_ui";
/**
* Data use ended UI snackbar/dialog will not be shown if {@link
* DISABLE_DATA_USE_ENDED_UI_PARAM} fieldtrial parameter is set to
* {@value DISABLE_DATA_USE_UI_PARAM_VALUE}.
*/
private static final String DISABLE_DATA_USE_ENDED_UI_PARAM = "disable_data_use_ended_ui";
/**
* Data use ended dialog will not be shown if {@link DISABLE_DATA_USE_ENDED_DIALOG_PARAM}
* fieldtrial parameter is set to {@value DISABLE_DATA_USE_UI_PARAM_VALUE}.
*/
private static final String DISABLE_DATA_USE_ENDED_DIALOG_PARAM =
"disable_data_use_ended_dialog";
private static final String DISABLE_DATA_USE_UI_PARAM_VALUE = "true";
/**
* Represents the possible user actions with the data use snackbars and dialog. This must
* remain in sync with DataUsage.UIAction in tools/metrics/histograms/histograms.xml.
*/
public static class DataUsageUIAction {
public static final int STARTED_SNACKBAR_SHOWN = 0;
public static final int STARTED_SNACKBAR_MORE_CLICKED = 1;
public static final int ENDED_SNACKBAR_SHOWN = 2;
public static final int ENDED_SNACKBAR_MORE_CLICKED = 3;
public static final int DIALOG_SHOWN = 4;
public static final int DIALOG_CONTINUE_CLICKED = 5;
public static final int DIALOG_CANCEL_CLICKED = 6;
public static final int DIALOG_LEARN_MORE_CLICKED = 7;
public static final int DIALOG_OPTED_OUT = 8;
public static final int INDEX_BOUNDARY = 9;
}
/**
* Returns true if data use tracking has started within a Tab. When data use tracking has
* started, returns true only once to signify the started event.
*
* @param tab The tab that may have started tracking data use.
* @return true If data use tracking has indeed started.
*/
public static boolean checkAndResetDataUseTrackingStarted(Tab tab) {
return nativeCheckAndResetDataUseTrackingStarted(
SessionTabHelper.sessionIdForTab(tab.getWebContents()), tab.getProfile());
}
/**
* Notifies that the user clicked "Continue" when the dialog box warning about exiting data use
* was shown.
*
* @param tab The tab on which the dialog box was shown.
*/
public static void userClickedContinueOnDialogBox(Tab tab) {
nativeUserClickedContinueOnDialogBox(
SessionTabHelper.sessionIdForTab(tab.getWebContents()), tab.getProfile());
}
/**
* Returns true if data use tracking is currently active on {@link tab} but will stop if the
* navigation continues. Should only be called before the navigation starts.
*
* @param tab The tab that is being queried for data use tracking.
* @param pageTransitionType transition type of the navigation
* @param packageName package name of the app package that started this navigation.
* @return true If {@link tab} is currently tracked but would stop if the navigation were to
* continue.
*/
public static boolean wouldDataUseTrackingEnd(Tab tab, String url, int pageTransitionType) {
return nativeWouldDataUseTrackingEnd(SessionTabHelper.sessionIdForTab(tab.getWebContents()),
url, pageTransitionType, tab.getProfile());
}
/**
* Returns true if data use tracking has ended within a Tab. When data use tracking has
* ended, returns true only once to signify the ended event.
*
* @param tab The tab that may have ended tracking data use.
* @return true If data use tracking has indeed ended.
*/
public static boolean checkAndResetDataUseTrackingEnded(Tab tab) {
return nativeCheckAndResetDataUseTrackingEnded(
SessionTabHelper.sessionIdForTab(tab.getWebContents()), tab.getProfile());
}
/**
* Tells native code that a custom tab is navigating to a url from the given client app package.
*
* @param tab The custom tab that is navigating.
* @param packageName The client app package for the custom tab loading a url.
* @param url URL that is being loaded in the custom tab.
*/
public static void onCustomTabInitialNavigation(Tab tab, String packageName, String url) {
nativeOnCustomTabInitialNavigation(SessionTabHelper.sessionIdForTab(tab.getWebContents()),
packageName, url, tab.getProfile());
}
/**
* Returns whether a navigation should be paused to show a dialog telling the user that data use
* tracking has ended within a Tab. If the navigation should be paused, shows a dialog with the
* option to cancel the navigation or continue.
*
* @param activity Current activity.
* @param tab The tab to see if tracking has ended in.
* @param url URL that is pending.
* @param pageTransitionType The type of transition. see
* {@link org.chromium.content.browser.PageTransition} for valid values.
* @param referrerUrl URL for the referrer.
* @return true If the URL loading should be overriden.
*/
public static boolean shouldOverrideUrlLoading(Activity activity,
final Tab tab, final String url, final int pageTransitionType,
final String referrerUrl) {
if (shouldShowDataUseEndedUI() && !shouldShowDataUseEndedSnackbar(activity)
&& wouldDataUseTrackingEnd(tab, url, pageTransitionType)) {
startDataUseDialog(activity, tab, url, pageTransitionType, referrerUrl);
return true;
}
return false;
}
/**
* Shows a dialog with the option to cancel the navigation or continue. Also allows the user to
* opt out of seeing this dialog again.
*
* @param activity Current activity.
* @param tab The tab loading the url.
* @param url URL that is pending.
* @param pageTransitionType The type of transition. see
* {@link org.chromium.content.browser.PageTransition} for valid values.
* @param referrerUrl URL for the referrer.
*/
private static void startDataUseDialog(final Activity activity, final Tab tab,
final String url, final int pageTransitionType, final String referrerUrl) {
View dataUseDialogView = View.inflate(activity, R.layout.data_use_dialog, null);
final TextView textView = (TextView) dataUseDialogView.findViewById(R.id.data_use_message);
textView.setText(getDataUseUIString(DataUseUIMessage.DATA_USE_TRACKING_ENDED_MESSAGE));
final CheckBox checkBox = (CheckBox) dataUseDialogView.findViewById(R.id.data_use_checkbox);
checkBox.setText(
getDataUseUIString(DataUseUIMessage.DATA_USE_TRACKING_ENDED_CHECKBOX_MESSAGE));
View learnMore = dataUseDialogView.findViewById(R.id.learn_more);
learnMore.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
EmbedContentViewActivity.show(activity,
getDataUseUIString(DataUseUIMessage.DATA_USE_LEARN_MORE_TITLE),
getDataUseUIString(DataUseUIMessage.DATA_USE_LEARN_MORE_LINK_URL));
recordDataUseUIAction(DataUsageUIAction.DIALOG_LEARN_MORE_CLICKED);
}
});
new AlertDialog.Builder(activity, R.style.AlertDialogTheme)
.setTitle(getDataUseUIString(DataUseUIMessage.DATA_USE_TRACKING_ENDED_TITLE))
.setView(dataUseDialogView)
.setPositiveButton(
getDataUseUIString(DataUseUIMessage.DATA_USE_TRACKING_ENDED_CONTINUE),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setOptedOutOfDataUseDialog(activity, checkBox.isChecked());
LoadUrlParams loadUrlParams = new LoadUrlParams(url,
pageTransitionType);
if (!TextUtils.isEmpty(referrerUrl)) {
Referrer referrer = new Referrer(referrerUrl,
Referrer.REFERRER_POLICY_ALWAYS);
loadUrlParams.setReferrer(referrer);
}
tab.loadUrl(loadUrlParams);
recordDataUseUIAction(DataUsageUIAction.DIALOG_CONTINUE_CLICKED);
userClickedContinueOnDialogBox(tab);
}
})
.setNegativeButton(R.string.cancel,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setOptedOutOfDataUseDialog(activity, checkBox.isChecked());
recordDataUseUIAction(DataUsageUIAction.DIALOG_CANCEL_CLICKED);
}
})
.show();
recordDataUseUIAction(DataUsageUIAction.DIALOG_SHOWN);
}
/**
* @return true if the data use tracking started UI (snackbar) should be shown.
*/
public static boolean shouldShowDataUseStartedUI() {
return !DISABLE_DATA_USE_UI_PARAM_VALUE.equals(
VariationsAssociatedData.getVariationParamValue(
FIELD_TRIAL_NAME, DISABLE_DATA_USE_STARTED_UI_PARAM));
}
/**
* @return true if the data use tracking ended UI (snackbar or interstitial) should be shown.
*/
public static boolean shouldShowDataUseEndedUI() {
return !DISABLE_DATA_USE_UI_PARAM_VALUE.equals(
VariationsAssociatedData.getVariationParamValue(
FIELD_TRIAL_NAME, DISABLE_DATA_USE_ENDED_UI_PARAM));
}
/**
* Returns true if the data use ended snackbar should be shown instead of the dialog. The
* snackbar will be shown if the user has opted out of seeing the data use ended dialog or if
* the dialog is diabled by the fieldtrial.
*
* @param context An Android context.
* @return true If the data use ended snackbar should be shown.
*/
public static boolean shouldShowDataUseEndedSnackbar(Context context) {
assert shouldShowDataUseEndedUI();
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
SHARED_PREF_DATA_USE_DIALOG_OPT_OUT, false)
|| DISABLE_DATA_USE_UI_PARAM_VALUE.equals(
VariationsAssociatedData.getVariationParamValue(
FIELD_TRIAL_NAME, DISABLE_DATA_USE_ENDED_DIALOG_PARAM));
}
/**
* Sets whether the user has opted out of seeing the data use dialog.
*
* @param context An Android context.
* @param optedOut Whether the user has opted out of seeing the data use dialog.
*/
private static void setOptedOutOfDataUseDialog(Context context, boolean optedOut) {
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putBoolean(SHARED_PREF_DATA_USE_DIALOG_OPT_OUT, optedOut)
.apply();
if (optedOut) {
recordDataUseUIAction(DataUsageUIAction.DIALOG_OPTED_OUT);
}
}
/**
* Record the DataUsage.UIAction histogram.
* @param action Action with the data use tracking snackbar or dialog.
*/
public static void recordDataUseUIAction(int action) {
assert action >= 0 && action < DataUsageUIAction.INDEX_BOUNDARY;
RecordHistogram.recordEnumeratedHistogram(
"DataUsage.UIAction", action,
DataUsageUIAction.INDEX_BOUNDARY);
}
/**
* Gets native strings which may be overridden by Finch.
*/
public static String getDataUseUIString(int messageID) {
assert messageID >= 0 && messageID < DataUseUIMessage.DATA_USE_UI_MESSAGE_MAX;
return nativeGetDataUseUIString(messageID);
}
private static native boolean nativeCheckAndResetDataUseTrackingStarted(
int tabId, Profile profile);
private static native boolean nativeCheckAndResetDataUseTrackingEnded(
int tabId, Profile profile);
private static native void nativeUserClickedContinueOnDialogBox(int tabId, Profile profile);
private static native boolean nativeWouldDataUseTrackingEnd(
int tabId, String url, int pageTransitionType, Profile jprofile);
private static native void nativeOnCustomTabInitialNavigation(int tabID, String packageName,
String url, Profile profile);
private static native String nativeGetDataUseUIString(int messageID);
}
| bsd-3-clause |
NCIP/cagrid-portal | cagrid-portal/db/src/java/gov/nih/nci/cagrid/portal/dao/CQLQueryInstanceDao.java | 1301 | /**
*============================================================================
* 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-portal/LICENSE.txt for details.
*============================================================================
**/
/**
*
*/
package gov.nih.nci.cagrid.portal.dao;
import java.util.List;
import gov.nih.nci.cagrid.portal.domain.GridDataService;
import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQueryInstance;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*
*/
public class CQLQueryInstanceDao extends AbstractDao<CQLQueryInstance> {
/**
*
*/
public CQLQueryInstanceDao() {
}
/* (non-Javadoc)
* @see gov.nih.nci.cagrid.portal.dao.AbstractDao#domainClass()
*/
@Override
public Class domainClass() {
return CQLQueryInstance.class;
}
public List<CQLQueryInstance> getByDataService(GridDataService dataService) {
return getHibernateTemplate().find(
"from CQLQueryInstance inst where inst.dataService.id = ?",
new Object[] { dataService.getId() });
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-core/src/main/java/jodd/util/collection/ClassMap.java | 3740 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.util.collection;
import java.util.Arrays;
/**
* Storage for holding classes keys and values.
* It is <b>NOT</b> a <code>Map</code> instance. It is very fast
* on un-synchronized lookups, faster then <code>HashMap</code>.
* Uses identity for checking if <code>Class</code> keys are equal.
* <p>
* The initial version of this class was provided by @zqq90, from
* <a href="https://github.com/zqq90/webit-script/">WebIt-script</a>
* project. Thank you!
*/
public final class ClassMap<V> {
private static final int MAXIMUM_CAPACITY = 1 << 29;
private Entry<V>[] table;
private int threshold;
private int size;
/**
* Creates new map with given initial capacity.
*/
@SuppressWarnings("unchecked")
public ClassMap(int initialCapacity) {
int initlen;
if (initialCapacity > MAXIMUM_CAPACITY) {
initlen = MAXIMUM_CAPACITY;
}
else {
initlen = 16;
while (initlen < initialCapacity) {
initlen <<= 1;
}
}
this.table = new Entry[initlen];
this.threshold = (int) (initlen * 0.75f);
}
public ClassMap() {
this(64);
}
/**
* Returns total number of stored classes.
*/
public int size() {
return size;
}
/**
* Returns a value associated to a key in unsafe, but very fast way.
*/
public V unsafeGet(final Class key) {
final Entry<V>[] tab;
Entry<V> e = (tab = table)[key.hashCode() & (tab.length - 1)];
while (e != null) {
if (key == e.key) {
return e.value;
}
e = e.next;
}
return null;
}
/**
* Returns a value associated to a key in thread-safe way.
*/
public synchronized V get(Class key) {
return unsafeGet(key);
}
@SuppressWarnings("unchecked")
private void resize() {
if (size < threshold) {
return;
}
final Entry<V>[] oldTable = table;
final int oldCapacity = oldTable.length;
final int newCapacity = oldCapacity << 1;
if (newCapacity > MAXIMUM_CAPACITY) {
if (threshold == MAXIMUM_CAPACITY - 1) {
throw new IllegalStateException("Capacity exhausted");
}
threshold = MAXIMUM_CAPACITY - 1;
return;
}
final int newMark = newCapacity - 1;
final Entry<V>[] newTable = new Entry[newCapacity];
for (int i = oldCapacity; i-- > 0; ) {
int index;
for (Entry<V> old = oldTable[i], e; old != null; ) {
e = old;
old = old.next;
index = e.id & newMark;
e.next = newTable[index];
newTable[index] = e;
}
}
this.threshold = (int) (newCapacity * 0.75f);
// must be last
this.table = newTable;
}
/**
* Associates the specified value with the specified Class in this map.
* Returns the previous value associated with key, or <code>null</code>
* if there was no mapping for key.
*/
@SuppressWarnings("unchecked")
public synchronized V put(Class key, V value) {
final int id;
int index;
Entry<V>[] tab;
Entry<V> e = (tab = table)[index = (id = key.hashCode()) & (tab.length - 1)];
while (e != null) {
if (key == e.key) { // identity check
// key found, replace
V existing = e.value;
e.value = value;
return existing;
}
e = e.next;
}
if (size >= threshold) {
resize();
tab = table;
index = id & (tab.length - 1);
}
// creates the new entry
tab[index] = new Entry(id, key, value, tab[index]);
size++;
return null;
}
/**
* Clears the class map.
*/
public synchronized void clear() {
size = 0;
Arrays.fill(table, null);
}
/**
* Maps entry.
*/
private static final class Entry<V> {
final int id;
final Class key;
V value;
Entry<V> next;
private Entry(int id, Class key, V value, Entry<V> next) {
this.value = value;
this.id = id;
this.key = key;
this.next = next;
}
}
} | bsd-3-clause |
lang010/acit | leetcode/252.meeting-rooms.337136559.ac.java | 989 | /*
* @lc app=leetcode id=252 lang=java
*
* [252] Meeting Rooms
*
* https://leetcode.com/problems/meeting-rooms/description/
*
* algorithms
* Easy (55.14%)
* Total Accepted: 164.6K
* Total Submissions: 298.4K
* Testcase Example: '[[0,30],[5,10],[15,20]]'
*
* Given an array of meeting time intervals where intervals[i] = [starti,
* endi], determine if a person could attend all meetings.
*
*
* Example 1:
* Input: intervals = [[0,30],[5,10],[15,20]]
* Output: false
* Example 2:
* Input: intervals = [[7,10],[2,4]]
* Output: true
*
*
* Constraints:
*
*
* 0 <= intervals.length <= 10^4
* intervals[i].length == 2
* 0 <= starti < endi <= 10^6
*
*
*/
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
for (int i = 0; i < intervals.length-1; i++)
if (intervals[i][1] > intervals[i+1][0])
return false;
return true;
}
}
| bsd-3-clause |
pongad/api-client-staging | generated/java/proto-google-cloud-dlp-v2beta2/src/main/java/com/google/privacy/dlp/v2beta2/RangeOrBuilder.java | 624 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2beta2/dlp.proto
package com.google.privacy.dlp.v2beta2;
public interface RangeOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2beta2.Range)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Index of the first character of the range (inclusive).
* </pre>
*
* <code>int64 start = 1;</code>
*/
long getStart();
/**
* <pre>
* Index of the last character of the range (exclusive).
* </pre>
*
* <code>int64 end = 2;</code>
*/
long getEnd();
}
| bsd-3-clause |
muloem/xins | src/tests/org/xins/tests/server/SOAPMapCallingConventionTests.java | 8125 | /*
* $Id$
*
* Copyright 2003-2008 Online Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.tests.server;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.common.text.HexConverter;
import org.xins.common.xml.Element;
import org.xins.tests.AllTests;
/**
* Tests for calling conventions.
*
* @version $Revision$ $Date$
* @author <a href="mailto:anthony.goubard@japplis.com">Anthony Goubard</a>
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*/
public class SOAPMapCallingConventionTests extends TestCase {
/**
* Constructs a new <code>SOAPMapCallingConventionTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public SOAPMapCallingConventionTests(String name) {
super(name);
}
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(SOAPMapCallingConventionTests.class);
}
/**
* Tests the SOAP calling convention.
*/
public void testSOAPMapCallingConvention() throws Throwable {
String randomLong = HexConverter.toHexString(CallingConventionTests.RANDOM.nextLong());
String randomFive = randomLong.substring(0, 5);
// Successful call
postSOAPRequest(randomFive, true);
// Unsuccessful call
//postSOAPRequest(randomFive, false);
}
/**
* Posts SOAP request.
*
* @param randomFive
* A randomly generated String.
* @param success
* <code>true</code> if the expected result should be successfal,
* <code>false</code> otherwise.
*
* @throws Exception
* If anything goes wrong.
*/
private void postSOAPRequest(String randomFive, boolean success) throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap-map";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">" +
" <soap:Body xmlns:m=\"http://www.example.org/stock\">" +
" <m:ResultCodeRequest>" +
" <m:useDefault>false</m:useDefault>" +
" <m:inputText>" + randomFive + "</m:inputText>" +
" </m:ResultCodeRequest>" +
" </soap:Body>" +
"</soap:Envelope>";
int expectedStatus = success ? 200 : 500;
Element result = CallingConventionTests.postXML(destination, data, expectedStatus);
assertEquals("Envelope", result.getLocalName());
assertEquals("soap", result.getNamespacePrefix());
assertEquals("http://schemas.xmlsoap.org/soap/envelope/", result.getNamespaceURI());
Element.QualifiedName encodingStyle = new Element.QualifiedName("soap", "http://schemas.xmlsoap.org/soap/envelope/", "encodingStyle");
assertEquals("http://www.w3.org/2001/12/soap-encoding", result.getAttribute(encodingStyle));
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = result.getUniqueChildElement("Body");
if (success) {
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("ResultCodeResponse").size());
assertEquals("Incorrect namespace prefix of the response:" + bodyElem.getNamespacePrefix(), "soap", bodyElem.getNamespacePrefix());
Element responseElem = (Element) bodyElem.getChildElements("ResultCodeResponse").get(0);
assertEquals("Incorrect number of \"outputText\" elements.", 1, responseElem.getChildElements("outputText").size());
Element outputTextElem = (Element) responseElem.getChildElements("outputText").get(0);
assertEquals("Incorrect returned text", randomFive + " added.", outputTextElem.getText());
assertNull("Incorrect namespace prefix of the outputText.", outputTextElem.getNamespacePrefix());
} else {
assertEquals("Incorrect number of \"Fault\" elements.", 1, bodyElem.getChildElements("Fault").size());
Element faultElem = (Element) bodyElem.getChildElements("Fault").get(0);
assertEquals("Incorrect number of \"faultcode\" elements.", 1, faultElem.getChildElements("faultcode").size());
Element faultCodeElem = (Element) faultElem.getChildElements("faultcode").get(0);
assertEquals("Incorrect faultcode text", "soap:Server", faultCodeElem.getText());
assertEquals("Incorrect number of \"faultstring\" elements.", 1, faultElem.getChildElements("faultstring").size());
Element faultStringElem = (Element) faultElem.getChildElements("faultstring").get(0);
assertEquals("Incorrect faultstring text", "AlreadySet", faultStringElem.getText());
}
}
/**
* Tests the SOAP calling convention for the type convertion.
*/
public void testSOAPMapCallingConvention2() throws Throwable {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap-map";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
" <SOAP-ENV:Body>" +
" <gs:SimpleTypes xmlns:gs=\"urn:WhatEver\">" +
" <inputBoolean>0</inputBoolean>" +
" <inputByte>0</inputByte>" +
" <inputInt>0</inputInt>" +
" <inputLong>0</inputLong>" +
" <inputFloat>1.0</inputFloat>" +
" <inputText>0</inputText>" +
" </gs:SimpleTypes>" +
" </SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
Element result = CallingConventionTests.postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("SOAP-ENV", result.getNamespacePrefix());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = result.getUniqueChildElement("Body");
Element responseElem = bodyElem.getUniqueChildElement("SimpleTypesResponse");
assertEquals("Incorrect response namespace prefix.", "gs", responseElem.getNamespacePrefix());
}
/**
* Tests the SOAP calling convention with a data section.
*/
public void testSOAPMapCallingConvention3() throws Throwable {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap-map";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:DataSection3Request>" +
" <address><company>McDo</company><postcode>1234</postcode></address>" +
" <address><company>Drill</company><postcode>4567</postcode></address>" +
" </ns0:DataSection3Request>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = CallingConventionTests.postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("DataSection3Response").size());
}
}
| bsd-3-clause |
Team319/RecyleRush | src/org/usfirst/frc319/RecyleRush/commands/Auto3Tote2Container.java | 3952 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc319.RecyleRush.commands;
import org.usfirst.frc319.RecyleRush.Robot;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class Auto3Tote2Container extends CommandGroup {
public Auto3Tote2Container() { //BAG DAY WORKING CODE //Time: 20 seconds
//REAR ARM SHOULD BE EXTENDED BUT JUST IN CASE
addSequential(new RearArmExtend());
//GRAB REAR CONTAINER
addSequential(new RearClawClose());
//LIFTS REAR ARM AND GRABS REAR CONTAINER,LIFTS ELEVATOR SO TOTE CAN SLIDE UNDER
addParallel(new RearShoulderGoToThreeTote()); //Parallels are tied to
addSequential(new CollectContainer());// the next sequential^^^ is finished=Elevator is Up
//DRIVES FORWARD UNTIL 1st TOTE IS DETECTED
//AutoDriveStraightStage1 is slowed down, so the tote isn't pushed to far
//(P,I,D,F)= (1.0, 0.0, 0.0, 0.02) Speed = -0.85
addSequential(new AutoDriveStraight(-0.57)); // is finished = toteready
//PLACES CONTAINER ONTO TOTE/DROPS ELEVATOR DOWN AND GRABS 1st TOTE
addSequential(new PrepareToAquire());//"opens claw,elevator to bottom,detect, close claw"
// is finished = claw is closed
//these motors are "Cold Warm"
// LIFTS 1st TOTE off the ground (So it doesn't drag as we spin)
addSequential(new ElevatorTwoInchPosition());
//Lifts TO ELEVATOR to Clearance AND TURNS 180 @ THE SAME TIME
//AutoTurn 180 : (P,I,D,F)= (1, 0.0, 0.0, 0.02) Setpoint = 150
addParallel(new GrabAndLiftToClearance());
addSequential(new AutoTurn180()); //is finished = isOnTarget tolerence = 1 (degree).
//Resets encoders so it doesn't start auto correcting to "finish"
addSequential(new DistancePIDResetEncoders());
// DRIVES FORWARD UNTIL RF's SEES 2nd TOTE
//AutoDriveStraight : (P,I,D,F)= (1.0, 0.0, 0.0, 0.02) Speed = -0.95
//Maybe add a timeout
addSequential(new AutoDriveStraight(-0.63)); // is finished = istoteready
// OPENS CLAW AND DROPS TO FLOOR PICKUP THEN GRABS 2ND TOTE
addSequential(new PrepareToAquire());
//LIFTS 2ND TOTE
addSequential(new GrabAndLiftToClearance());
// DRIVES FORWARD UNTIL RF's SEES 3rd TOTE
addSequential(new AutoDriveStraight(-0.63));//is finished = claw closed
// OPENS CLAW AND DROPS TO FLOOR PICKUP THEN GRABS 3rd TOTE
addSequential(new PrepareToAquire());
//Lifts 3rd TOTE OFF FLOOR TO REDUCE FRICTION
addSequential(new GrabAndLiftToTwoInches());
//CLOSES CLAW ROTATES 90
//AutoTurn(62) : (P,I,D,F)= (1, 0.0, 0.0, 0.02) Setpoint = 62
addSequential(new AutoRotate(62)); //need to check clockwise counterclockwise
//RESETS ENCODERS BEFORE DRIVING STRAIGHT
addSequential(new DistancePIDResetEncoders());
//DRIVES FORWARD INTO AUTO ZONE
//Sets .arcadeDrive(-1.0, 0); distance = ie- 6 Feet //(Robot.driveTrain.getDistanceFromEncoderValues()- initialDistance > 6*12)
addSequential(new AutoDriveForwardUntilDistanceIsReached(72.0)); // is finished = distance reached
// OPEN TOTE CLAW, OPEN CONTAINER CLAW - SLAM!
addSequential(new ContainerClawOpen());
addSequential(new ToteClawOpen());
//BACK UP TWO INCHES
}
}
| bsd-3-clause |
gEt-rIgHt-jR/voc | python/common/org/python/types/Object.java | 37570 | package org.python.types;
public class Object extends java.lang.RuntimeException implements org.python.Object {
public java.util.Map<java.lang.String, org.python.Object> __dict__;
public org.python.types.Type __class__;
public org.python.types.Type.Origin origin;
/**
* A utility method to update the internal value of this object.
*
* Used by __i*__ operations to do an in-place operation.
* On a base object, it will always fail. Subclasses should override
* to provide the relevant assignment info.
*/
void setValue(org.python.Object obj) {
throw new org.python.exceptions.RuntimeError("'" + this.typeName() + "' object cannot be updated.");
}
public java.lang.Object toJava() {
return this;
}
public java.lang.Object toObject() {
return this;
}
public org.python.Object byValue() {
return this;
}
/**
* Return the Python type for this object.
*/
public org.python.types.Type type() {
return this.__class__;
}
public java.lang.String typeName() {
return org.Python.typeName(this.getClass());
}
/**
* Construct a new object instance.
*
* The argument `origin` is used to describe where the object is defined -
* Python or Java. It can also be "PLACEHOLDER" - these are transient objects
* that exist during instantiation of other objects. As a result, they don't
* have attributes or any of the other usual infrastructure of a Python object.
*
* klass is the underlying java class being represented by this object.
* In the case of a Python object, the klass is the Java manifestation of
* the object; when wrapping Java objects, the native class of the object
* is used.
*/
protected Object(org.python.types.Type.Origin origin, java.lang.Class klass, java.lang.String msg) {
super(msg);
this.origin = origin;
this.__dict__ = new java.util.HashMap<java.lang.String, org.python.Object>();
if (origin != org.python.types.Type.Origin.PLACEHOLDER) {
if (klass == null) {
klass = this.getClass();
}
this.__new__(org.python.types.Type.pythonType(klass));
}
}
protected Object(org.python.types.Type.Origin origin, java.lang.Class klass) {
this(origin, klass, "");
}
public Object() {
this(org.python.types.Type.Origin.PYTHON, null);
}
public Object(java.lang.String msg) {
this(org.python.types.Type.Origin.PYTHON, null, msg);
}
@org.python.Method(
__doc__ = "The most base type"
)
public Object(org.python.Object[] args, java.util.Map<java.lang.String, org.python.Object> kwargs) {
this(org.python.types.Type.Origin.PYTHON, null);
if (args != null && args.length > 0) {
throw new org.python.exceptions.TypeError("object() takes no parameters");
} else if (kwargs != null && kwargs.size() > 0) {
throw new org.python.exceptions.TypeError("object() takes no parameters");
}
}
/**
* Proxy Java object methods onto their Python counterparts.
*/
public boolean equals(java.lang.Object other) {
if (other instanceof org.python.Object) {
org.python.Object result = org.python.types.Object.__cmp_bool__(this, (org.python.Object) other, org.python.types.Object.CMP_OP.EQ);
return ((org.python.types.Bool) result).value;
} else {
throw new org.python.exceptions.RuntimeError("Can't compare a Python object with non-Python object.");
}
}
public int compareTo(java.lang.Object other) {
try {
if (((org.python.types.Bool) this.__lt__((org.python.Object) other)).value) {
return -1;
} else if (((org.python.types.Bool) this.__gt__((org.python.Object) other)).value) {
return 1;
}
return 0;
} catch (ClassCastException e) {
throw new org.python.exceptions.RuntimeError("Can't compare a Python object with non-Python object.");
}
}
public java.lang.String toString() {
return ((org.python.types.Str) this.__str__()).value;
}
protected void finalize() throws Throwable {
try {
this.__del__();
} finally {
super.finalize();
}
}
/**
* Python interface compatibility
* Section 3.3.1 - Basic customization
*/
@org.python.Method(
__doc__ = "Create and return a new object. See help(type) for accurate signature."
)
public org.python.Object __new__(org.python.Object klass) {
this.__class__ = (org.python.types.Type) klass;
if (this.__class__.origin == org.python.types.Type.Origin.PLACEHOLDER) {
this.__class__.add_reference(this);
}
return this.__class__;
}
// public void __init__(java.util.List<org.python.Object> args, java.util.Map<java.lang.String, org.python.Object> kwargs, java.util.List<org.python.Object> default_args, java.util.Map<java.lang.String, org.python.Object> default_kwargs) {
// throw new org.python.exceptions.AttributeError(this, "__init__");
// }
@org.python.Method(
__doc__ = "Destroy an existing object. See help(type) for accurate signature."
)
public void __del__() {
}
@org.python.Method(
__doc__ = "Return repr(self)."
)
public org.python.Object __repr__() {
return new org.python.types.Str(String.format("<%s object at 0x%x>", this.typeName(), this.hashCode()));
}
@org.python.Method(
__doc__ = "Return str(self)."
)
public org.python.Object __str__() {
return this.__repr__();
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __bytes__() {
throw new org.python.exceptions.AttributeError(this, "__bytes__");
}
@org.python.Method(
__doc__ = "",
args = {"format_string"}
)
public org.python.Object __format__(org.python.Object format_string) {
throw new org.python.exceptions.NotImplementedError("'" + this.typeName() + ".__format__' has not been implemented");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __lt__(org.python.Object other) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __le__(org.python.Object other) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __eq__(org.python.Object other) {
if (this == other) {
return new org.python.types.Bool(true);
} else {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ne__(org.python.Object other) {
// By default, __ne__() delegates to __eq__() and inverts the result unless it is NotImplemented.
// see: http://bugs.python.org/issue4395
org.python.Object result = this.__eq__(other);
if (result instanceof org.python.types.NotImplementedType) {
return result;
}
return new org.python.types.Bool(!((org.python.types.Bool) result).value);
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __gt__(org.python.Object other) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ge__(org.python.Object other) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __hash__() {
return new org.python.types.Int(this.hashCode());
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __bool__() {
throw new org.python.exceptions.AttributeError(this, "__bool__");
}
/**
* Section 3.3.2 - Emulating container types
*/
@org.python.Method(
__doc__ = "",
args = {"attr"}
)
public org.python.Object __getattr__(org.python.Object name) {
try {
return this.__getattr__(((org.python.types.Str) name).value);
} catch (java.lang.ClassCastException e) {
throw new org.python.exceptions.TypeError("__getattr__(): attribute name must be string");
}
}
public org.python.Object __getattr__(java.lang.String name) {
org.python.Object value = this.__getattr_null(name);
if (value == null) {
throw new org.python.exceptions.AttributeError(this, name);
}
return value;
}
public org.python.Object __getattr_null(java.lang.String name) {
return null;
}
@org.python.Method(
__doc__ = "",
args = {"name"}
)
public org.python.Object __getattribute__(org.python.Object name) {
try {
return this.__getattribute__(((org.python.types.Str) name).value);
} catch (java.lang.ClassCastException e) {
throw new org.python.exceptions.TypeError("__getattribute__(): attribute name must be string");
}
}
public org.python.Object __getattribute__(java.lang.String name) {
org.python.Object value = this.__getattribute_null(name);
if (value == null) {
throw new org.python.exceptions.AttributeError(this, name);
}
return value;
}
public org.python.Object __getattribute_null(java.lang.String name) {
// Look for local instance attributes first
// org.Python.debug("GETATTRIBUTE ", name);
// org.Python.debug("SELF ", this.__repr__());
// org.Python.debug("ATTRS ", this.__dict__);
org.python.Object value = this.__dict__.get(name);
if (value == null) {
// Look to the class for an attribute
// org.Python.debug("no instance attribute");
value = this.__class__.__getattribute_null(name);
if (value == null) {
// org.Python.debug("no class attribute");
// Use the descriptor protocol
value = this.__getattr_null(name);
if (value == null) {
// org.Python.debug("no descriptor protocol");
// Still nothing - give up, and return a value
// that can be interpreted as an exception.
return null;
}
}
}
// org.Python.debug(String.format("GETATTRIBUTE %s = ", name), value);
// Post-process the value retrieved.
return value.__get__(this, this.__class__);
}
@org.python.Method(
__doc__ = "",
args = {"instance", "klass"}
)
public org.python.Object __get__(org.python.Object instance, org.python.Object klass) {
// System.out.println("__GET__ on " + this + " " + this.getClass());
return this;
}
@org.python.Method(
__doc__ = "",
args = {"name", "value"}
)
public void __setattr__(org.python.Object name, org.python.Object value) {
try {
this.__setattr__(((org.python.types.Str) name).value, value);
} catch (java.lang.ClassCastException e) {
throw new org.python.exceptions.TypeError("__setattr__(): attribute name must be string");
}
}
public void __setattr__(java.lang.String name, org.python.Object value) {
if (!this.__setattr_null(name, value)) {
throw new org.python.exceptions.AttributeError(this, name);
}
}
public boolean __setattr_null(java.lang.String name, org.python.Object value) {
// org.Python.debug(String.format("SETATTR %s", name), value);
// org.Python.debug("SELF ", this.__repr__());
// org.Python.debug("ATTRS ", this.__dict__);
// If the attribute already exists, then it's OK to set it.
org.python.Object attr = this.__class__.__getattribute_null(name);
// org.Python.debug("ATTR ", attr);
// The base object can't have attribute set on it unless the attribute already exists.
if (this.getClass() == org.python.types.Object.class) {
if (attr == null) {
return false;
}
}
if (attr == null) {
this.__dict__.put(name, value);
} else {
// if attribute is not a descriptor add it to local instance
if (!(attr instanceof org.python.types.Property)) {
this.__dict__.put(name, value);
}
attr.__set__(this, value);
}
return true;
}
@org.python.Method(
__doc__ = "",
args = {"instance", "value"}
)
public void __set__(org.python.Object instance, org.python.Object value) {
}
@org.python.Method(
__doc__ = "",
args = {"attr"}
)
public void __delattr__(org.python.Object name) {
try {
this.__delattr__(((org.python.types.Str) name).value);
} catch (java.lang.ClassCastException e) {
throw new org.python.exceptions.TypeError("attribute name must be string, not '" + name.typeName() + "'");
}
}
public void __delattr__(java.lang.String name) {
if (!this.__delattr_null(name)) {
throw new org.python.exceptions.AttributeError(this, name);
}
}
public boolean __delattr_null(java.lang.String name) {
// org.Python.debug(String.format("DELATTR %s", name));
// org.Python.debug("SELF ", this.__repr__());
// org.Python.debug("ATTRS ", this.__dict__);
// If the attribute already exists, then it's OK to set it.
org.python.Object attr = this.__class__.__getattribute_null(name);
if (attr == null) {
org.python.Object result = this.__dict__.remove(name);
return result != null && !(result instanceof org.python.exceptions.AttributeError);
} else {
attr.__delete__(this);
return true;
}
}
@org.python.Method(
__doc__ = "",
args = {"instance", "value"}
)
public void __delete__(org.python.Object instance) {
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __dir__() {
org.python.types.List names = new org.python.types.List(new java.util.ArrayList(this.__dict__.keySet()));
names.extend(this.__dict__.get("__class__").__dir__());
names.sort(null, null);
return names;
}
/**
* Section 3.3.4 - Customizing instance and subclass checks
*/
// public org.python.Object __instancecheck__(org.python.Object instance) {
// throw new org.python.exceptions.AttributeError(this, "__instancecheck__");
// }
// public org.python.Object __subclasscheck__(org.python.Object subclass) {
// throw new org.python.exceptions.AttributeError(this, "__subclasscheck__");
// }
/**
* Section 3.3.5 - Emulating callable objects
*/
// public org.python.Object __call__(org.python.Object... args) {
// throw new org.python.exceptions.AttributeError(this, "__call__");
// }
/**
* Section 3.3.6 - Emulating container types
*/
@org.python.Method(
__doc__ = ""
)
public org.python.Object __len__() {
throw new org.python.exceptions.AttributeError(this, "__len__");
}
// public org.python.Object __length_hint__(java.util.List<org.python.Object> args, java.util.Map<java.lang.String, org.python.Object> kwargs, java.util.List<org.python.Object> default_args, java.util.Map<java.lang.String, org.python.Object> default_kwargs) {
// throw new org.python.exceptions.AttributeError(this, "__length_hint__");
// }
@org.python.Method(
__doc__ = "",
args = {"index"}
)
public org.python.Object __getitem__(org.python.Object index) {
throw new org.python.exceptions.AttributeError(this, "__getitem__");
}
@org.python.Method(
__doc__ = "",
args = {"key"}
)
public org.python.Object __missing__(org.python.Object key) {
throw new org.python.exceptions.AttributeError(this, "__missing__");
}
@org.python.Method(
__doc__ = "",
args = {"index", "value"}
)
public void __setitem__(org.python.Object index, org.python.Object value) {
throw new org.python.exceptions.AttributeError(this, "__setitem__");
}
@org.python.Method(
__doc__ = "",
args = {"index"}
)
public void __delitem__(org.python.Object index) {
throw new org.python.exceptions.AttributeError(this, "__delitem__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Iterable __iter__() {
throw new org.python.exceptions.AttributeError(this, "__iter__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Iterable __reversed__() {
throw new org.python.exceptions.AttributeError(this, "__reversed__");
}
@org.python.Method(
__doc__ = "",
args = {"item"}
)
public org.python.Object __contains__(org.python.Object item) {
throw new org.python.exceptions.AttributeError(this, "__contains__");
}
@org.python.Method(
__doc__ = "",
args = {"item"}
)
public org.python.Object __not_contains__(org.python.Object item) {
throw new org.python.exceptions.AttributeError(this, "__not_contains__");
}
/**
* Section 3.3.7 - Emulating numeric types
*/
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __add__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for +: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __sub__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for -: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __mul__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for *: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __truediv__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for /: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __floordiv__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for //: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __mod__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for %: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __divmod__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for divmod(): '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other", "modulus"}
)
public org.python.Object __pow__(org.python.Object other, org.python.Object modulus) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for ** or pow(): '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __lshift__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for <<: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rshift__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for >>: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __and__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for &: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __xor__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for ^: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __or__(org.python.Object other) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for |: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __radd__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__radd__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rsub__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rsub__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rmul__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rmul__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rtruediv__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rtruediv__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rfloordiv__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rfloordiv__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rmod__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rmod__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rdivmod__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rdivmod__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rpow__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rpow__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rlshift__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rlshift__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rrshift__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rrshift__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rand__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rand__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __rxor__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__rxor__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ror__(org.python.Object other) {
throw new org.python.exceptions.AttributeError(this, "__ror__");
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __iadd__(org.python.Object other) {
try {
this.setValue(this.__add__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for +=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __isub__(org.python.Object other) {
try {
this.setValue(this.__sub__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for -=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __imul__(org.python.Object other) {
try {
this.setValue(this.__mul__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for *=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __itruediv__(org.python.Object other) {
try {
this.setValue(this.__truediv__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for /=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ifloordiv__(org.python.Object other) {
try {
this.setValue(this.__floordiv__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for //=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __imod__(org.python.Object other) {
try {
this.setValue(this.__mod__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for %=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __idivmod__(org.python.Object other) {
try {
this.setValue(this.__divmod__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for //=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ipow__(org.python.Object other) {
this.setValue(this.__pow__(other, null));
return this;
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ilshift__(org.python.Object other) {
try {
this.setValue(this.__lshift__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for <<=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __irshift__(org.python.Object other) {
try {
this.setValue(this.__rshift__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for >>=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __iand__(org.python.Object other) {
try {
this.setValue(this.__and__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for &=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ixor__(org.python.Object other) {
try {
this.setValue(this.__xor__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for ^=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = "",
args = {"other"}
)
public org.python.Object __ior__(org.python.Object other) {
try {
this.setValue(this.__or__(other));
return this;
} catch (org.python.exceptions.TypeError e) {
throw new org.python.exceptions.TypeError("unsupported operand type(s) for |=: '" + this.typeName() + "' and '" + other.typeName() + "'");
}
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __neg__() {
throw new org.python.exceptions.AttributeError(this, "__neg__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __pos__() {
throw new org.python.exceptions.AttributeError(this, "__pos__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __abs__() {
throw new org.python.exceptions.AttributeError(this, "__abs__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __invert__() {
throw new org.python.exceptions.AttributeError(this, "__invert__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __not__() {
return new org.python.types.Bool(!((org.python.types.Bool) this.__bool__()).value);
}
@org.python.Method(
__doc__ = "",
args = {"real", "imag"}
)
public org.python.Object __complex__(org.python.Object real, org.python.Object imag) {
throw new org.python.exceptions.AttributeError(this, "__complex__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __int__() {
throw new org.python.exceptions.AttributeError(this, "__int__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __float__() {
throw new org.python.exceptions.AttributeError(this, "__float__");
}
@org.python.Method(
__doc__ = ""
)
public org.python.Object __index__() {
throw new org.python.exceptions.AttributeError(this, "__index__");
}
@org.python.Method(
__doc__ = "",
args = {"ndigits"}
)
public org.python.Object __round__(org.python.Object ndigits) {
throw new org.python.exceptions.AttributeError(this, "__round__");
}
// Need to implement Is __eq__ Is Not __ne__
// In __contains__ (reversed operands) Not In __not_contains__ (reversed operands)
//
// for Is and Is Not, falls through to here only when either side is a constant in python
// which ends up as org.python.types.[Int|Float|Complex], otherwise it's dealt with
// by object reference comparison IF_ACMEQ. so we fall through to __eq__!
public enum CMP_OP {
GE(">=", "__ge__", "__le__"),
GT(">", "__gt__", "__lt__"),
EQ("==", "__eq__", "__eq__"),
NE("!=", "__ne__", "__ne__"),
LE("<=", "__le__", "__ge__"),
LT("<", "__lt__", "__gt__");
public final String oper;
public final String operMethod;
public final String reflOperMethod;
CMP_OP(java.lang.String oper, java.lang.String operMethod, java.lang.String reflOperMethod) {
this.oper = oper;
this.operMethod = operMethod;
this.reflOperMethod = reflOperMethod;
}
}
/* This method is used from standard library datatypes, etc */
public static org.python.Object __cmp__(org.python.Object v, org.python.Object w,
org.python.types.Object.CMP_OP op) {
return __cmp__(v, w, op.oper, op.operMethod, op.reflOperMethod);
}
/* This method is used from standard library container datatypes */
public static org.python.Object __cmp_bool__(org.python.Object v, org.python.Object w,
org.python.types.Object.CMP_OP op) {
// identity implies equality
if (v == w) {
if (op == org.python.types.Object.CMP_OP.EQ) {
return new org.python.types.Bool(true);
} else if (op == org.python.types.Object.CMP_OP.NE) {
return new org.python.types.Bool(false);
}
}
org.python.Object result = __cmp__(v, w, op.oper, op.operMethod, op.reflOperMethod);
if (result instanceof org.python.types.Bool) {
return result;
} else {
return result.__bool__();
}
}
/* This method is invoked from the AST for Compare nodes */
public static org.python.Object __cmp__(org.python.Object v, org.python.Object w, java.lang.String oper,
java.lang.String operMethod, java.lang.String reflOperMethod) {
org.python.Object result = org.python.types.NotImplementedType.NOT_IMPLEMENTED;
boolean reflectedChecked = v.type() != w.type()
&& ((org.python.types.Bool) org.Python.isinstance(w, v.type())).value;
if (reflectedChecked) {
result = invokeComparison(w, v, reflOperMethod);
if (result != org.python.types.NotImplementedType.NOT_IMPLEMENTED) {
return result;
}
}
result = invokeComparison(v, w, operMethod);
if (result != org.python.types.NotImplementedType.NOT_IMPLEMENTED) {
return result;
}
if (!reflectedChecked) {
result = invokeComparison(w, v, reflOperMethod);
if (result != org.python.types.NotImplementedType.NOT_IMPLEMENTED) {
return result;
}
}
if (oper.equals("==")) {
return new org.python.types.Bool(v == w);
} else if (oper.equals("!=")) {
return new org.python.types.Bool(v != w);
}
if (org.Python.VERSION < 0x03060000) {
throw new org.python.exceptions.TypeError(String.format(
"unorderable types: %s() %s %s()", v.typeName(), oper, w.typeName()));
} else {
throw new org.python.exceptions.TypeError(String.format(
"'%s' not supported between instances of '%s' and '%s'", oper, v.typeName(), w.typeName()));
}
}
private static org.python.Object invokeComparison(org.python.Object x, org.python.Object y, String methodName) {
if (methodName == null) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
org.python.Object comparator = x.__getattribute_null(methodName);
if (comparator == null) {
return org.python.types.NotImplementedType.NOT_IMPLEMENTED;
}
org.python.Object[] args = new org.python.Object[1];
args[0] = y;
java.util.Map<java.lang.String, org.python.Object> kwargs = new java.util.HashMap<java.lang.String, org.python.Object>();
return (org.python.Object) ((org.python.types.Method) comparator).invoke(args, kwargs);
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.tourguide.stratomex/src/main/java/org/caleydo/view/tourguide/internal/mode/VariableDataMode.java | 2214 | /*******************************************************************************
* 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.internal.mode;
import java.util.Collections;
import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.view.tourguide.api.adapter.ATourGuideDataMode;
import org.caleydo.view.tourguide.api.model.ADataDomainQuery;
import org.caleydo.view.tourguide.api.model.InhomogenousDataDomainQuery;
import org.caleydo.vis.lineup.model.RankTableModel;
import org.caleydo.vis.lineup.model.StringRankColumnModel;
import com.google.common.collect.Sets;
/**
* @author Samuel Gratzl
*
*/
public class VariableDataMode extends ATourGuideDataMode {
public static VariableDataMode INSTANCE = new VariableDataMode();
private VariableDataMode() {
}
@Override
public boolean apply(IDataDomain dataDomain) {
return (dataDomain instanceof ATableBasedDataDomain && !((ATableBasedDataDomain) dataDomain).getTable()
.isDataHomogeneous())
&& InhomogenousDataDomainQuery.hasOne(dataDomain,
Sets.immutableEnumSet(EDataClass.NATURAL_NUMBER, EDataClass.REAL_NUMBER));
}
@Override
public void addDefaultColumns(RankTableModel table) {
addDataDomainRankColumn(table);
final StringRankColumnModel base = new StringRankColumnModel(GLRenderers.drawText("Name"),
StringRankColumnModel.DEFAULT);
table.add(base);
base.setWidth(150);
base.orderByMe();
}
@Override
public Iterable<? extends ADataDomainQuery> createDataDomainQuery(IDataDomain dd) {
return Collections.singleton(createFor(dd));
}
protected ADataDomainQuery createFor(IDataDomain dd) {
return new InhomogenousDataDomainQuery((ATableBasedDataDomain) dd, Sets.immutableEnumSet(
EDataClass.NATURAL_NUMBER, EDataClass.REAL_NUMBER));
}
}
| bsd-3-clause |
capmills2014/2014-Robot-Code | src/Robot2014/RobotMain.java | 2422 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package Robot2014;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Relay;
import Subsystems.ClawMotor;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotMain extends IterativeRobot implements RobotPorts
{
/**
* This function is called once each time the robot enters autonomous mode.
*/
private static RobotDrive driveTrain;
private static Joystick gamePad;
private static ClawMotor claw;
public void robotInit()
{
gamePad = new Joystick(GAMEPAD);
driveTrain = new RobotDrive(MOTOR_LEFT_ONE, MOTOR_LEFT_TWO, MOTOR_RIGHT_ONE, MOTOR_RIGHT_TWO);
driveTrain.setSafetyEnabled(true);
claw = new ClawMotor();
}
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void teleopPeriodic()
{
driveTrain.tankDrive(gamePad, 4, gamePad, 2);
checkClaw();
}
public void checkClaw()
{
if(gamePad.getRawButton(2)){
getClaw().motorForward();
}
else if(gamePad.getRawButton(4)){
getClaw().motorBackward();
}
else{
getClaw().stopMotor();
}
}
public static ClawMotor getClaw()
{
return claw;
}
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
}
| bsd-3-clause |
jdrusso/ScraperBike2013 | src/edu/wpi/first/wpilibj/templates/commands/RotateRobot.java | 1707 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST Team 2035, 2013. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.templates.ScraperBike;
import edu.wpi.first.wpilibj.templates.subsystems.DriveTrain;
/** Turns the robot in place.
*
* @author Team 2035 Programmers
*/
public class RotateRobot extends CommandBase {
private DriveTrain turn;
/**
*
*/
public RotateRobot() {
super("RotateRobot");
turn = ScraperBike.getDriveTrain();
requires(turn);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run. Sets how fast the robot rotates
protected void execute() {
turn.rotate(0.4);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true. stops the robot rotating by setting the speed to 0.
protected void end() {
turn.rotate(0.0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
turn.rotate(0.0);
}
}
| bsd-3-clause |
gigaherz/Ender-Rift | src/main/java/dev/gigaherz/enderrift/common/AutomationEnergyWrapper.java | 5398 | package dev.gigaherz.enderrift.common;
import dev.gigaherz.enderrift.ConfigValues;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.items.IItemHandler;
import javax.annotation.Nonnull;
import java.util.Optional;
public class AutomationEnergyWrapper implements IItemHandler
{
private final IPoweredAutomation owner;
public AutomationEnergyWrapper(IPoweredAutomation owner)
{
this.owner = owner;
}
private double getEnergyInsert()
{
int sizeInventory = getSlots();
int sizeInventory2 = sizeInventory * sizeInventory;
return Math.min(ConfigValues.PowerPerInsertionCap,
ConfigValues.PowerPerInsertionConstant
+ (sizeInventory * ConfigValues.PowerPerInsertionLinear)
+ (sizeInventory2 * ConfigValues.PowerPerInsertionGeometric));
}
private double getEnergyExtract()
{
int sizeInventory = getSlots();
int sizeInventory2 = sizeInventory * sizeInventory;
return Math.min(ConfigValues.PowerPerExtractionCap,
ConfigValues.PowerPerExtractionConstant
+ (sizeInventory * ConfigValues.PowerPerExtractionLinear)
+ (sizeInventory2 * ConfigValues.PowerPerExtractionGeometric));
}
private int getEffectivePowerUsageToInsert(int stackSize)
{
return owner.isRemote() ? 0 : (int) Math.ceil(getEnergyInsert() * stackSize);
}
private int getEffectivePowerUsageToExtract(int limit)
{
return owner.isRemote() ? 0 : (int) Math.ceil(getEnergyExtract() * limit);
}
@Override
public int getSlots()
{
IItemHandler inventory = owner.getInventory();
return inventory != null ? inventory.getSlots() : 0;
}
@Override
public ItemStack getStackInSlot(int slot)
{
IItemHandler inventory = owner.getInventory();
return inventory != null ? inventory.getStackInSlot(slot) : ItemStack.EMPTY;
}
@Override
public ItemStack insertItem(int slot, ItemStack stack, boolean simulate)
{
int stackSize = stack.getCount();
int cost = getEffectivePowerUsageToInsert(stackSize);
Optional<IEnergyStorage> optBuffer = owner.getEnergyBuffer();
if (optBuffer.isPresent())
{
IEnergyStorage energyBuffer = optBuffer.get();
IItemHandler inventory = owner.getInventory();
if (inventory == null)
return ItemStack.EMPTY;
boolean powerFailure = false;
while (cost > energyBuffer.getEnergyStored() && stackSize > 0)
{
powerFailure = true;
stackSize--;
}
if (powerFailure)
owner.setLowOnPowerTemporary();
if (stackSize <= 0)
return stack;
ItemStack temp = stack.copy();
temp.setCount(stackSize);
ItemStack remaining = inventory.insertItem(slot, temp, simulate);
if (!simulate)
{
stackSize -= remaining.getCount();
int actualCost = getEffectivePowerUsageToInsert(stackSize);
energyBuffer.extractEnergy(actualCost, false);
owner.setDirty();
}
return remaining;
}
else
{
return stack;
}
}
@Override
public ItemStack extractItem(int slot, int wanted, boolean simulate)
{
int cost = getEffectivePowerUsageToExtract(wanted);
Optional<IEnergyStorage> optBuffer = owner.getEnergyBuffer();
if (optBuffer.isPresent())
{
IEnergyStorage energyBuffer = optBuffer.get();
IItemHandler inventory = owner.getInventory();
if (inventory == null)
return ItemStack.EMPTY;
ItemStack existing = inventory.extractItem(slot, wanted, true);
wanted = Math.min(wanted, existing.getCount());
boolean powerFailure = false;
while (cost > energyBuffer.getEnergyStored() && wanted > 0)
{
powerFailure = true;
wanted--;
cost = getEffectivePowerUsageToExtract(wanted);
}
if (powerFailure)
owner.setLowOnPowerTemporary();
if (wanted <= 0)
return ItemStack.EMPTY;
ItemStack extracted = inventory.extractItem(slot, wanted, simulate);
if (extracted.getCount() <= 0)
return ItemStack.EMPTY;
if (!simulate)
{
int actualCost = getEffectivePowerUsageToExtract(extracted.getCount());
energyBuffer.extractEnergy(actualCost, false);
owner.setDirty();
}
return extracted;
}
else
{
return ItemStack.EMPTY;
}
}
@Override
public int getSlotLimit(int slot)
{
return 64;
}
@Override
public boolean isItemValid(int slot, @Nonnull ItemStack stack)
{
return true;
}
public boolean isLowOnPower()
{
return owner.getEnergyBuffer().map(buffer -> getEffectivePowerUsageToExtract(1) > buffer.getEnergyStored()).orElse(false);
}
} | bsd-3-clause |
BukkitDevTeam/Cascade | src/main/java/com/md_5/cascade/CascadeServer.java | 12248 | package com.md_5.cascade;
import com.avaje.ebean.config.ServerConfig;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.GameMode;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.Warning.WarningState;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.help.HelpMap;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.map.MapView;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.scheduler.BukkitScheduler;
public class CascadeServer implements Server {
@Override
public String getName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getBukkitVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Player[] getOnlinePlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getMaxPlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getPort() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getViewDistance() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getIp() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServerName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServerId() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getWorldType() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getGenerateStructures() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getAllowEnd() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getAllowNether() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasWhitelist() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setWhitelist(boolean value) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<OfflinePlayer> getWhitelistedPlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void reloadWhitelist() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int broadcastMessage(String message) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getUpdateFolder() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public File getUpdateFolderFile() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getConnectionThrottle() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getTicksPerAnimalSpawns() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getTicksPerMonsterSpawns() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Player getPlayer(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Player getPlayerExact(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Player> matchPlayer(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public PluginManager getPluginManager() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public BukkitScheduler getScheduler() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ServicesManager getServicesManager() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<World> getWorlds() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public World createWorld(WorldCreator creator) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadWorld(String name, boolean save) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadWorld(World world, boolean save) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public World getWorld(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public World getWorld(UUID uid) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public MapView getMap(short id) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public MapView createMap(World world) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void reload() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Logger getLogger() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public PluginCommand getPluginCommand(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void savePlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void configureDbConfig(ServerConfig config) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean addRecipe(Recipe recipe) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Recipe> getRecipesFor(ItemStack result) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Iterator<Recipe> recipeIterator() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void clearRecipes() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void resetRecipes() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Map<String, String[]> getCommandAliases() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getSpawnRadius() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setSpawnRadius(int value) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getOnlineMode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getAllowFlight() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean useExactLoginLocation() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void shutdown() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int broadcast(String message, String permission) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public OfflinePlayer getOfflinePlayer(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<String> getIPBans() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void banIP(String address) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void unbanIP(String address) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<OfflinePlayer> getBannedPlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<OfflinePlayer> getOperators() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public GameMode getDefaultGameMode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setDefaultGameMode(GameMode mode) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ConsoleCommandSender getConsoleSender() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public File getWorldContainer() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public OfflinePlayer[] getOfflinePlayers() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Messenger getMessenger() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public HelpMap getHelpMap() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Inventory createInventory(InventoryHolder owner, InventoryType type) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Inventory createInventory(InventoryHolder owner, int size) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Inventory createInventory(InventoryHolder owner, int size, String title) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getMonsterSpawnLimit() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getAnimalSpawnLimit() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getWaterAnimalSpawnLimit() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isPrimaryThread() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getMotd() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public WarningState getWarningState() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void sendPluginMessage(Plugin source, String channel, byte[] message) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<String> getListeningPluginChannels() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| bsd-3-clause |
stanik137/xtreemfs | java/servers/test/org/xtreemfs/test/osd/StripingTest.java | 31429 | /*
* Copyright (c) 2009-2011 by Jan Stender,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.test.osd;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.xtreemfs.common.Capability;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.xloc.StripingPolicyImpl;
import org.xtreemfs.dir.DIRConfig;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication;
import org.xtreemfs.foundation.pbrpc.client.RPCResponse;
import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener;
import org.xtreemfs.foundation.util.FSUtils;
import org.xtreemfs.osd.OSD;
import org.xtreemfs.osd.OSDConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SnapConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.XCap;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.XLocSet;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectData;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestEnvironment;
public class StripingTest extends TestCase {
private static final boolean COW = false;
private TestEnvironment testEnv;
static class MRCDummy implements RPCResponseAvailableListener<OSDWriteResponse> {
private long issuedEpoch;
private long epoch;
private long fileSize;
private final String capSecret;
public MRCDummy(String capSecret) {
this.capSecret = capSecret;
}
Capability open(char mode) {
if (mode == 't')
issuedEpoch++;
return new Capability(FILE_ID, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber(), 60, System.currentTimeMillis(), "",
(int) issuedEpoch, false, COW ? SnapConfig.SNAP_CONFIG_ACCESS_CURRENT
: SnapConfig.SNAP_CONFIG_SNAPS_DISABLED, 0, capSecret);
}
synchronized long getFileSize() {
return fileSize;
}
@Override
public void responseAvailable(RPCResponse<OSDWriteResponse> r) {
try {
OSDWriteResponse resp = r.get();
// System.out.println("fs-update: " + resp);
if (resp.hasSizeInBytes()) {
final long newFileSize = resp.getSizeInBytes();
final long epochNo = resp.getTruncateEpoch();
if (epochNo < epoch)
return;
if (epochNo > epoch || newFileSize > fileSize) {
epoch = epochNo;
fileSize = newFileSize;
}
}
} catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}
private static final String FILE_ID = "1:1";
private static final int KB = 1;
private static final int SIZE = KB * 1024;
private static final byte[] ZEROS_HALF = new byte[SIZE / 2];
private static final byte[] ZEROS = new byte[SIZE];
private final DIRConfig dirConfig;
private final OSDConfig osdCfg1;
private final OSDConfig osdCfg2;
private final OSDConfig osdCfg3;
private final String capSecret;
private List<OSD> osdServer;
private List<ServiceUUID> osdIDs;
private OSDServiceClient client;
private final StripingPolicyImpl sp;
private XLocSet xloc;
/** Creates a new instance of StripingTest */
public StripingTest(String testName) throws IOException {
super(testName);
Logging.start(SetupUtils.DEBUG_LEVEL, SetupUtils.DEBUG_CATEGORIES);
osdCfg1 = SetupUtils.createOSD1Config();
osdCfg2 = SetupUtils.createOSD2Config();
osdCfg3 = SetupUtils.createOSD3Config();
capSecret = osdCfg1.getCapabilitySecret();
Replica r = Replica.newBuilder().setStripingPolicy(SetupUtils.getStripingPolicy(3, KB))
.setReplicationFlags(0).build();
sp = StripingPolicyImpl.getPolicy(r, 0);
dirConfig = SetupUtils.createDIRConfig();
}
@Override
protected void setUp() throws Exception {
System.out.println("TEST: " + getClass().getSimpleName() + "." + getName());
FSUtils.delTree(new File(SetupUtils.TEST_DIR));
// startup: DIR
testEnv = new TestEnvironment(new TestEnvironment.Services[] { TestEnvironment.Services.DIR_SERVICE,
TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.UUID_RESOLVER,
TestEnvironment.Services.MRC_CLIENT, TestEnvironment.Services.OSD_CLIENT });
testEnv.start();
osdIDs = new ArrayList<ServiceUUID>(3);
osdIDs.add(SetupUtils.getOSD1UUID());
osdIDs.add(SetupUtils.getOSD2UUID());
osdIDs.add(SetupUtils.getOSD3UUID());
osdServer = new ArrayList<OSD>(3);
osdServer.add(new OSD(osdCfg1));
osdServer.add(new OSD(osdCfg2));
osdServer.add(new OSD(osdCfg3));
client = testEnv.getOSDClient();
List<String> osdset = new ArrayList(3);
osdset.add(SetupUtils.getOSD1UUID().toString());
osdset.add(SetupUtils.getOSD2UUID().toString());
osdset.add(SetupUtils.getOSD3UUID().toString());
Replica r = Replica.newBuilder().setStripingPolicy(SetupUtils.getStripingPolicy(3, KB))
.setReplicationFlags(0).addAllOsdUuids(osdset).build();
xloc = XLocSet.newBuilder().setReadOnlyFileSize(0).setVersion(1).addReplicas(r)
.setReplicaUpdatePolicy("").build();
}
private Capability getCap(String fname) {
return new Capability(fname, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber(), 60, System.currentTimeMillis(), "", 0, false,
COW ? SnapConfig.SNAP_CONFIG_ACCESS_CURRENT : SnapConfig.SNAP_CONFIG_SNAPS_DISABLED, 0, capSecret);
}
@Override
protected void tearDown() throws Exception {
osdServer.get(0).shutdown();
osdServer.get(1).shutdown();
osdServer.get(2).shutdown();
testEnv.shutdown();
}
/* TODO: test delete/truncate epochs! */
public void testPUTandGET() throws Exception {
final int numObjs = 5;
final int[] testSizes = { 1, 2, SIZE - 1, SIZE };
for (int ts : testSizes) {
ReusableBuffer data = SetupUtils.generateData(ts);
String file = "1:1" + ts;
final FileCredentials fcred = FileCredentials.newBuilder().setXcap(getCap(file).getXCap())
.setXlocs(xloc).build();
for (int i = 0, osdIndex = 0; i < numObjs; i++, osdIndex = i % osdIDs.size()) {
// write an object with the given test size
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
RPCResponse<OSDWriteResponse> r = client.write(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, file, i, 0, 0, 0,
objdata, data.createViewBuffer());
OSDWriteResponse resp = r.get();
r.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(i * SIZE + ts, resp.getSizeInBytes());
// read and check the previously written object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, file, i, 0, 0, data
.capacity());
ObjectData result = r2.get();
checkResponse(data.array(), result, r2.getData());
r2.freeBuffers();
}
}
}
public void testIntermediateHoles() throws Exception {
final FileCredentials fcred = FileCredentials.newBuilder().setXcap(getCap(FILE_ID).getXCap())
.setXlocs(xloc).build();
final ReusableBuffer data = SetupUtils.generateData(3);
// write the nineth object, check the file size
int obj = 8;
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
RPCResponse<OSDWriteResponse> r = client.write(osdIDs.get(obj % osdIDs.size()).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, obj, 0, 0, 0, objdata,
data.createViewBuffer());
OSDWriteResponse resp = r.get();
r.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(obj * SIZE + data.limit(), resp.getSizeInBytes());
// write the fifth object, check the file size
obj = 5;
r = client.write(osdIDs.get(obj % osdIDs.size()).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, obj, 0, 0, 0, objdata, data.createViewBuffer());
resp = r.get();
r.freeBuffers();
assertTrue(!resp.hasSizeInBytes()
|| (resp.hasSizeInBytes() && (obj * SIZE + data.limit() == resp.getSizeInBytes())));
// check whether the first object consists of zeros
obj = 0;
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(obj % osdIDs.size()).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, obj, 0, 0, data
.capacity());
ObjectData result = r2.get();
// either padding data or all zeros
if (result.getZeroPadding() == 0)
checkResponse(ZEROS, result, r2.getData());
else
assertEquals(data.capacity(), result.getZeroPadding());
r2.freeBuffers();
// write the first object, check the file size header (must be null)
r = client.write(osdIDs.get(obj % osdIDs.size()).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, obj, 0, 0, 0, objdata, data.createViewBuffer());
resp = r.get();
r.freeBuffers();
assertFalse(resp.hasSizeInBytes());
}
public void testWriteExtend() throws Exception {
final FileCredentials fcred = FileCredentials.newBuilder().setXcap(getCap(FILE_ID).getXCap())
.setXlocs(xloc).build();
final ReusableBuffer data = SetupUtils.generateData(3);
final byte[] paddedData = new byte[SIZE];
System.arraycopy(data.array(), 0, paddedData, 0, data.limit());
// write first object
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
RPCResponse<OSDWriteResponse> r = client.write(osdIDs.get(0).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, 0, 0, 0, 0, objdata,
data.createViewBuffer());
OSDWriteResponse resp = r.get();
r.freeBuffers();
// write second object
r = client.write(osdIDs.get(1).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 1, 0, 0, 0, objdata, data.createViewBuffer());
resp = r.get();
r.freeBuffers();
// read first object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 0, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
// System.out.println(result);
// either padding data or all zeros
assertNotNull(dataOut);
assertEquals(3, dataOut.capacity());
assertEquals(SIZE - 3, result.getZeroPadding());
r2.freeBuffers();
}
/**
* tests the truncation of striped files
*/
public void testTruncate() throws Exception {
ReusableBuffer data = SetupUtils.generateData(SIZE);
FileCredentials fcred = FileCredentials.newBuilder().setXcap(getCap(FILE_ID).getXCap())
.setXlocs(xloc).build();
// -------------------------------
// create a file with five objects
// -------------------------------
for (int i = 0, osdIndex = 0; i < 5; i++, osdIndex = i % osdIDs.size()) {
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
RPCResponse<OSDWriteResponse> r = client.write(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, 0,
objdata, data.createViewBuffer());
OSDWriteResponse resp = r.get();
r.freeBuffers();
}
// ----------------------------------------------
// shrink the file to a length of one full object
// ----------------------------------------------
XCap newCap = fcred.getXcap().toBuilder().setTruncateEpoch(1).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
RPCResponse<OSDWriteResponse> rt = client.truncate(osdIDs.get(0).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, SIZE);
OSDWriteResponse resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(SIZE, resp.getSizeInBytes());
// check whether all objects have the expected content
for (int i = 0, osdIndex = 0; i < 5; i++, osdIndex = i % osdIDs.size()) {
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
// the first object must exist, all other ones must have been
// deleted
if (i == 0)
checkResponse(data.array(), result, dataOut);
else
checkResponse(null, result, dataOut);
r2.freeBuffers();
}
// -------------------------------------------------
// extend the file to a length of eight full objects
// -------------------------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(2).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, SIZE * 8);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(SIZE * 8, resp.getSizeInBytes());
// check whether all objects have the expected content
for (int i = 0, osdIndex = 0; i < 8; i++, osdIndex = i % osdIDs.size()) {
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
// the first object must contain data, all other ones must contain
// zeros
if (i == 0)
checkResponse(data.array(), result, dataOut);
else {
if (dataOut == null) {
assertEquals(SIZE, result.getZeroPadding());
} else {
checkResponse(ZEROS, result, dataOut);
}
}
r2.freeBuffers();
}
// ------------------------------------------
// shrink the file to a length of 3.5 objects
// ------------------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(3).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
final long size3p5 = (long) (SIZE * 3.5f);
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, size3p5);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(size3p5, resp.getSizeInBytes());
// check whether all objects have the expected content
for (int i = 0, osdIndex = 0; i < 5; i++, osdIndex = i % osdIDs.size()) {
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
// the first object must contain data, all other ones must contain
// zeros, where the last one must only be half an object size
if (i == 0)
checkResponse(data.array(), result, dataOut);
else if (i == 3)
checkResponse(ZEROS_HALF, result, dataOut);
else if (i >= 4) {
assertEquals(0, result.getZeroPadding());
assertNull(dataOut);
} else {
if (dataOut == null) {
assertEquals(SIZE, result.getZeroPadding());
} else {
checkResponse(ZEROS, result, dataOut);
}
}
r2.freeBuffers();
}
// --------------------------------------------------
// truncate the file to the same length it had before
// --------------------------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(4).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, size3p5);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(size3p5, resp.getSizeInBytes());
// check whether all objects have the expected content
for (int i = 0, osdIndex = 0; i < 5; i++, osdIndex = i % osdIDs.size()) {
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
// the first object must contain data, all other ones must contain
// zeros, where the last one must only be half an object size
if (i == 0)
checkResponse(data.array(), result, dataOut);
else if (i == 3)
checkResponse(ZEROS_HALF, result, dataOut);
else if (i >= 4) {
assertEquals(0, result.getZeroPadding());
assertNull(dataOut);
} else {
if (dataOut == null) {
assertEquals(SIZE, result.getZeroPadding());
} else {
checkResponse(ZEROS, result, dataOut);
}
}
r2.freeBuffers();
}
// --------------------------------
// truncate the file to zero length
// --------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(5).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 0);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(0, resp.getSizeInBytes());
// check whether all objects have the expected content
for (int i = 0, osdIndex = 0; i < 5; i++, osdIndex = i % osdIDs.size()) {
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
assertEquals(0, result.getZeroPadding());
assertNull(r2.getData());
r2.freeBuffers();
}
data = SetupUtils.generateData(5);
// ----------------------------------
// write new data to the first object
// ----------------------------------
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
rt = client.write(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 0, 0, 0, 0, objdata, data.createViewBuffer());
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(5, resp.getSizeInBytes());
// ----------------------------------------------
// extend the file to a length of one full object
// ----------------------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(6).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, SIZE);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(SIZE, resp.getSizeInBytes());
// try to read the object
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 0, 0, 0, SIZE);
ObjectData result = r2.get();
// the object must contain data plus padding zeros
final byte[] dataWithZeros = new byte[SIZE];
System.arraycopy(data.array(), 0, dataWithZeros, 0, data.limit());
checkResponse(dataWithZeros, result, r2.getData());
r2.freeBuffers();
// ---------------------------------------------
// shrink the file to a length of half an object
// ---------------------------------------------
newCap = fcred.getXcap().toBuilder().setTruncateEpoch(7).build();
fcred = fcred.toBuilder().setXcap(newCap).build();
rt = client.truncate(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, SIZE / 2);
resp = rt.get();
rt.freeBuffers();
assertTrue(resp.hasSizeInBytes());
assertEquals(SIZE / 2, resp.getSizeInBytes());
// try to read the object
r2 = client.read(osdIDs.get(0).getAddress(), RPCAuthentication.authNone,
RPCAuthentication.userService, fcred, FILE_ID, 0, 0, 0, SIZE);
result = r2.get();
// the object must contain data plus padding zeros
final byte[] dataWithHalfZeros = new byte[SIZE / 2];
System.arraycopy(data.array(), 0, dataWithHalfZeros, 0, data.limit());
checkResponse(dataWithHalfZeros, result, r2.getData());
r2.freeBuffers();
}
public void testInterleavedWriteAndTruncate() throws Exception {
final int numIterations = 20;
final int maxObject = 20;
final int maxSize = maxObject * SIZE;
final int numWrittenObjs = 5;
final MRCDummy mrcDummy = new MRCDummy(capSecret);
FileCredentials fcred = FileCredentials.newBuilder().setXcap(getCap(FILE_ID).getXCap())
.setXlocs(xloc).build();
final List<RPCResponse> responses = new LinkedList<RPCResponse>();
for (int l = 0; l < numIterations; l++) {
Capability cap = mrcDummy.open('w');
// randomly write 'numWrittenObjs' objects
for (int i = 0; i < numWrittenObjs; i++) {
final int objId = (int) (Math.random() * maxObject);
final int osdIndex = objId % osdIDs.size();
// write an object with a random amount of bytes
final int size = (int) ((SIZE - 1) * Math.random()) + 1;
ObjectData objdata = ObjectData.newBuilder().setChecksum(0).setZeroPadding(0)
.setInvalidChecksumOnOsd(false).build();
RPCResponse<OSDWriteResponse> r = client.write(osdIDs.get(osdIndex).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, objId, 0, 0,
0, objdata, SetupUtils.generateData(size));
responses.add(r);
// update the file size when the response is received
r.registerListener(mrcDummy);
}
// wait until all write requests have been completed, i.e. all file
// size updates have been performed
for (RPCResponse r : responses) {
r.waitForResult();
r.freeBuffers();
}
responses.clear();
fcred = fcred.toBuilder().setXcap(mrcDummy.open('t').getXCap()).build();
// truncate the file
long newSize = (long) (Math.random() * maxSize);
RPCResponse<OSDWriteResponse> rt = client.truncate(osdIDs.get(0).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, newSize);
rt.registerListener(mrcDummy);
rt.waitForResult();
rt.freeBuffers();
long fileSize = mrcDummy.getFileSize();
// read the previously truncated objects, check size
for (int i = 0; i < maxObject; i++) {
RPCResponse<ObjectData> r2 = client.read(osdIDs.get(i % osdIDs.size()).getAddress(),
RPCAuthentication.authNone, RPCAuthentication.userService, fcred, FILE_ID, i, 0, 0, SIZE);
ObjectData result = r2.get();
ReusableBuffer dataOut = r2.getData();
int dataOutLen = (dataOut == null) ? 0 : dataOut.capacity();
// check inner objects - should be full
if (i < fileSize / SIZE)
assertEquals(SIZE, result.getZeroPadding() + dataOutLen);
// check last object - should either be an EOF (null) or partial
// object
else if (i == fileSize / SIZE) {
if (fileSize % SIZE == 0)
assertEquals(0, result.getZeroPadding() + dataOutLen);
else
assertEquals(fileSize % SIZE, result.getZeroPadding() + dataOutLen);
}
// check outer objects - should be EOF (null)
else
assertEquals(0, result.getZeroPadding() + dataOutLen);
r2.freeBuffers();
}
}
}
/**
* tests the deletion of striped files
*/
// public void testDELETE() throws Exception {
//
// final int numObjs = 5;
//
// final FileCredentials fcred = new FileCredentials(xloc,
// getCap(FILE_ID).getXCap());
//
// ReusableBuffer data = SetupUtils.generateData(SIZE);
//
// // create all objects
// for (int i = 0, osdIndex = 0; i < numObjs; i++, osdIndex = i %
// osdIDs.size()) {
//
// ObjectData objdata = new ObjectData(data.createViewBuffer(), 0, 0,
// false);
// RPCResponse<OSDWriteResponse> r =
// client.write(osdIDs.get(osdIndex).getAddress(),
// FILE_ID, fcred, i, 0, 0, 0, objdata);
// r.get();
// }
//
// // delete the file
// RPCResponse dr = client.unlink(osdIDs.get(0).getAddress(), FILE_ID,
// fcred);
// dr.get();
// dr.freeBuffers();
// }
public static void main(String[] args) {
TestRunner.run(StripingTest.class);
}
/**
* Checks whether the data array received with the response is equal to the
* given one.
*
* @param data
* the data array
* @param response
* the response
* @throws Exception
*/
public void checkResponse(byte[] data, ObjectData response, ReusableBuffer objData) throws Exception {
if (data == null) {
if (objData != null)
/*
* System.out.println("body (" + response.getBody().capacity() +
* "): " + new String(response.getBody().array()));
*/
assertEquals(0, objData.remaining());
}
else {
byte[] responseData = objData.array();
assertEquals(data.length, responseData.length);
for (int i = 0; i < data.length; i++)
assertEquals(data[i], responseData[i]);
}
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.radial/src/org/caleydo/view/radial/event/DetailOutsideEvent.java | 1249 | /*******************************************************************************
* 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.radial.event;
import org.caleydo.core.event.AEvent;
/**
* This event signals that a detail view of the specified element shall be displayed in radial hierarchy.
*
* @author Christian Partl
*/
public class DetailOutsideEvent
extends AEvent {
private int elementID;
public DetailOutsideEvent() {
elementID = -1;
}
@Override
public boolean checkIntegrity() {
if (elementID == -1)
throw new IllegalStateException("iMaxDisplayedHierarchyDepth was not set");
return true;
}
/**
* @return Element the detail view shall be displayed for.
*/
public int getElementID() {
return elementID;
}
/**
* Sets the element the detail view shall be displayed for.
*
* @param elementID
* Element the detail view shall be displayed for.
*/
public void setElementID(int elementID) {
this.elementID = elementID;
}
}
| bsd-3-clause |
NCIP/cab2b | software/cab2b/src/java/client/edu/wustl/cab2b/client/ui/visualization/charts/LineChart.java | 3925 | /*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.
*/
/**
*
*/
package edu.wustl.cab2b.client.ui.visualization.charts;
import java.awt.Color;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.Dataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleInsets;
/**
* This class generates the Line Chart
* @author chetan_patil
*/
public class LineChart extends AbstractChart {
/**
* Parameterized constructor
* @param chartRawData
*/
public LineChart() {
}
/*
* (non-Javadoc)
* @see edu.wustl.cab2b.client.ui.charts.AbstractChart#createChart(org.jfree.data.general.Dataset)
*/
protected JFreeChart createChart(Dataset dataset) {
XYDataset xyDataset = (XYDataset) dataset;
JFreeChart jfreechart = ChartFactory.createXYLineChart("Line Chart", "X", "Y", xyDataset,
PlotOrientation.VERTICAL, true, true, false);
jfreechart.setBackgroundPaint(Color.white);
XYPlot xyplot = (XYPlot) jfreechart.getPlot();
xyplot.setBackgroundPaint(Color.white);
xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
xyplot.setDomainGridlinePaint(Color.white);
xyplot.setRangeGridlinePaint(Color.white);
XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
xylineandshaperenderer.setShapesVisible(true);
xylineandshaperenderer.setShapesFilled(true);
NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
return jfreechart;
}
@Override
protected Dataset createColumnWiseData() {
List<String> selectedColumnNames = chartModel.getSelectedColumnsNames();
List<String> selectedRowNames = chartModel.getSelectedRowNames();
XYSeries xySeries = null;
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
for (int i = 0; i < selectedColumnNames.size(); i++) {
String seriesName = selectedColumnNames.get(i);
xySeries = new XYSeries(seriesName);
for (int j = 0; j < selectedRowNames.size(); j++) {
Object value = chartModel.getValueAt(j, i);
xySeries.add(convertValue(selectedRowNames.get(j)), convertValue(value));
}
xySeriesCollection.addSeries(xySeries);
}
return xySeriesCollection;
}
@Override
protected Dataset createRowWiseData() {
List<String> selectedColumnNames = chartModel.getSelectedColumnsNames();
List<String> selectedRowNames = chartModel.getSelectedRowNames();
XYSeries xySeries = null;
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
for (int i = 0; i < selectedRowNames.size(); i++) {
String seriesName = selectedRowNames.get(i) + "";
xySeries = new XYSeries(seriesName);
for (int j = 0; j < selectedColumnNames.size(); j++) {
Object value = chartModel.getValueAt(i, j);
xySeries.add(convertValue(selectedColumnNames.get(j)), convertValue(value));
}
xySeriesCollection.addSeries(xySeries);
}
return xySeriesCollection;
}
}
| bsd-3-clause |
shubhambeehyv/motech | platform/web-security/src/main/java/org/motechproject/security/service/authentication/MotechOpenIdUserDetailsService.java | 3701 | package org.motechproject.security.service.authentication;
import org.motechproject.security.domain.MotechRole;
import org.motechproject.security.domain.MotechUser;
import org.motechproject.security.domain.UserStatus;
import org.motechproject.security.repository.AllMotechRoles;
import org.motechproject.security.repository.AllMotechUsers;
import org.motechproject.security.service.AuthoritiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.openid.OpenIDAttribute;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Implementation class for @AuthenticationUserDetailsService. Retrieves user details given OpenId
* authentication
*/
public class MotechOpenIdUserDetailsService implements AuthenticationUserDetailsService<OpenIDAuthenticationToken> {
private AllMotechRoles allMotechRoles;
private AllMotechUsers allMotechUsers;
private AuthoritiesService authoritiesService;
/**
* Adds user for given OpenId to {@link org.motechproject.security.repository.AllMotechUsers}
* and return his {@link org.springframework.security.core.userdetails.UserDetails}
*
* @param token for OpenId
* @return details of added user
*/
@Override
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) {
MotechUser user = allMotechUsers.findUserByOpenId(token.getName());
if (user == null) {
List<String> roles = new ArrayList<String>();
if (allMotechUsers.getOpenIdUsers().isEmpty()) {
for (MotechRole role : allMotechRoles.getRoles()) {
roles.add(role.getRoleName());
}
}
user = new MotechUser(getAttribute(token.getAttributes(), "Email"), "", getAttribute(token.getAttributes(), "Email"), "", roles, token.getName(), Locale.getDefault());
allMotechUsers.addOpenIdUser(user);
}
return new User(user.getUserName(), user.getPassword(), user.isActive(), true, !UserStatus.MUST_CHANGE_PASSWORD.equals(user.getUserStatus()),
!UserStatus.BLOCKED.equals(user.getUserStatus()), authoritiesService.authoritiesFor(user));
}
/**
* Looks for attribute with given name in given list
*
* @param attributes list of OpenId attributes
* @param attributeName of attribute we're looking for
* @return string with attribute value if attribute with given
* name exists, otherwise return empty string
*/
private String getAttribute(List<OpenIDAttribute> attributes, String attributeName) {
String attributeValue = "";
for (OpenIDAttribute attribute : attributes) {
if (attribute.getName() != null && (attribute.getName().equals("ax" + attributeName) || attribute.getName().equals("ae" + attributeName))) {
attributeValue = attribute.getValues().get(0);
}
}
return attributeValue;
}
@Autowired
public void setAllMotechRoles(AllMotechRoles allMotechRoles) {
this.allMotechRoles = allMotechRoles;
}
@Autowired
public void setAllMotechUsers(AllMotechUsers allMotechUsers) {
this.allMotechUsers = allMotechUsers;
}
@Autowired
public void setAuthoritiesService(AuthoritiesService authoritiesService) {
this.authoritiesService = authoritiesService;
}
}
| bsd-3-clause |
Nelspike/ShareManager | ShareManager/src/share/manager/adapters/SharesAdapter.java | 2751 |
package share.manager.adapters;
import share.manager.stock.R;
import share.manager.utils.FileHandler;
import share.manager.utils.SharesGraphicsBuilder;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class SharesAdapter extends ArrayAdapter<String> {
private String[] strings, regions, shares, ticks;
private Context context;
private SharesGraphicsBuilder graph;
public SharesAdapter(Context context, int textViewResourceId,
String[] objects, String[] regions, String[] shares, String[] ticks,
SharesGraphicsBuilder graph) {
super(context, textViewResourceId, objects);
this.context = context;
this.strings = objects;
this.regions = regions;
this.ticks = ticks;
this.shares = shares;
this.graph = graph;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
final int inner = position;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.shares_box, parent, false);
TextView label = (TextView) row.findViewById(R.id.shares_name_box);
label.setText(strings[position]);
TextView labelRegion = (TextView) row.findViewById(R.id.shares_region_box);
labelRegion.setText(regions[position]);
final TextView labelChange = (TextView) row
.findViewById(R.id.shares_num_box);
labelChange.setText(shares[position]);
Button minus = (Button) row.findViewById(R.id.minus_share);
minus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (labelChange.getText().toString().equals("0")) return;
FileHandler.changeShare(ticks[inner], false);
labelChange.setText(FileHandler.getSharesFromTick(ticks[inner]));
graph.repaintGraph(FileHandler.getSharePercentages(),
FileHandler.getNamesString());
}
});
Button plus = (Button) row.findViewById(R.id.plus_share);
plus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FileHandler.changeShare(ticks[inner], true);
labelChange.setText(FileHandler.getSharesFromTick(ticks[inner]));
graph.repaintGraph(FileHandler.getSharePercentages(),
FileHandler.getNamesString());
}
});
return row;
}
}
| bsd-3-clause |
914802951/sdl_android | sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/PerformAudioPassThru.java | 9890 | package com.smartdevicelink.proxy.rpc;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCRequest;
import com.smartdevicelink.proxy.rpc.enums.AudioType;
import com.smartdevicelink.proxy.rpc.enums.BitsPerSample;
import com.smartdevicelink.proxy.rpc.enums.SamplingRate;
import java.util.Hashtable;
import java.util.List;
/**
* This will open an audio pass thru session. By doing so the app can receive
* audio data through the vehicles microphone
*
* <p>Function Group: AudioPassThru</p>
*
* <b>HMILevel needs to be FULL, LIMITED or BACKGROUND</b>
*
* <p><b>Parameter List</b></p>
* <table border="1" rules="all">
* <tr>
* <th>Name</th>
* <th>Type</th>
* <th>Description</th>
* <th>Reg.</th>
* <th>Notes</th>
* <th> Version</th>
* </tr>
* <tr>
* <td>initialPrompt</td>
* <td>TTSChunk[]</td>
* <td>SDL will speak this prompt before opening the audio pass thru session. </td>
* <td>N</td>
* <td>This is an array of text chunks of type TTSChunk. The array must have at least one item If omitted, then no initial prompt is spoken: <p>Array Minsize: 1</p> Array Maxsize: 100</td>
* <td>SmartDeviceLink 2.0 </td>
* </tr>
* <tr>
* <td>audioPassThruDisplayText1</td>
* <td>String</td>
* <td>First line of text displayed during audio capture.</td>
* <td>N</td>
* <td>Maxlength = 500</td>
* <td>SmartDeviceLink 2.0 </td>
* </tr>
* <tr>
* <td>samplingRate</td>
* <td>SamplingRate</td>
* <td>This value shall is allowed to be 8 or 16 or 22 or 44 khz.</td>
* <td>Y</td>
* <td></td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>maxDuration</td>
* <td>Integer</td>
* <td>The maximum duration of audio recording in milliseconds.</td>
* <td>Y</td>
* <td>Minvalue: 1; Maxvalue: 1000000</td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>bitsPerSample</td>
* <td>BitsPerSample</td>
* <td>Specifies the quality the audio is recorded - 8 bit or 16 bit.</td>
* <td>Y</td>
* <td></td>
* <td>SmartDeviceLink 2.0 </td>
* </tr>
* <tr>
* <td>audioType</td>
* <td>AudioType</td>
* <td>Specifies the type of audio data being requested.</td>
* <td>Y</td>
* <td></td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>muteAudio</td>
* <td>Boolean</td>
* <td>N</td>
* <td>N</td>
* <td></td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
*
*
*
*
*
* </table>
* @since SmartDeviceLink 2.0
* @see EndAudioPassThru
*/
public class PerformAudioPassThru extends RPCRequest {
public static final String KEY_MAX_DURATION = "maxDuration";
public static final String KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_1 = "audioPassThruDisplayText1";
public static final String KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_2 = "audioPassThruDisplayText2";
public static final String KEY_MUTE_AUDIO = "muteAudio";
public static final String KEY_SAMPLING_RATE = "samplingRate";
public static final String KEY_AUDIO_TYPE = "audioType";
public static final String KEY_INITIAL_PROMPT = "initialPrompt";
public static final String KEY_BITS_PER_SAMPLE = "bitsPerSample";
/**
* Constructs a new PerformAudioPassThru object
*/
public PerformAudioPassThru() {
super(FunctionID.PERFORM_AUDIO_PASS_THRU.toString());
}
/**
* <p>Constructs a new PerformAudioPassThru object indicated by the Hashtable
* parameter</p>
*
*
* @param hash
* The Hashtable to use
*/
public PerformAudioPassThru(Hashtable<String, Object> hash) {
super(hash);
}
/**
* Sets initial prompt which will be spoken before opening the audio pass
* thru session by SDL
*
* @param initialPrompt
* a List<TTSChunk> value represents the initial prompt which
* will be spoken before opening the audio pass thru session by
* SDL
* <p></p>
* <b>Notes: </b>
* <ul>
* <li>This is an array of text chunks of type TTSChunk</li>
* <li>The array must have at least one item</li>
* <li>If omitted, then no initial prompt is spoken</li>
* <li>Array Minsize: 1</li>
* <li>Array Maxsize: 100</li>
* </ul>
*/
public void setInitialPrompt(List<TTSChunk> initialPrompt) {
setParameters(KEY_INITIAL_PROMPT, initialPrompt);
}
/**
* Gets a List value representing an initial prompt which will be spoken
* before opening the audio pass thru session by SDL
*
* @return List<TTSChunk> -a List value representing an initial prompt
* which will be spoken before opening the audio pass thru session
* by SDL
*/
@SuppressWarnings("unchecked")
public List<TTSChunk> getInitialPrompt() {
return (List<TTSChunk>) getObject(TTSChunk.class, KEY_INITIAL_PROMPT);
}
/**
* Sets a line of text displayed during audio capture
*
* @param audioPassThruDisplayText1
* <p>a String value representing the line of text displayed during
* audio capture</p>
* <p></p>
* <b>Notes: </b>Maxlength=500
*/
public void setAudioPassThruDisplayText1(String audioPassThruDisplayText1) {
setParameters(KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_1, audioPassThruDisplayText1);
}
/**
* Gets a first line of text displayed during audio capture
*
* @return String -a String value representing a first line of text
* displayed during audio capture
*/
public String getAudioPassThruDisplayText1() {
return getString(KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_1);
}
/**
* Sets a line of text displayed during audio capture
*
* @param audioPassThruDisplayText2
* <p>a String value representing the line of text displayed during
* audio capture</p>
* <p></p>
* <b>Notes: </b>Maxlength=500
*/
public void setAudioPassThruDisplayText2(String audioPassThruDisplayText2) {
setParameters(KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_2, audioPassThruDisplayText2);
}
/**
* Gets a second line of text displayed during audio capture
*
* @return String -a String value representing a first line of text
* displayed during audio capture
*/
public String getAudioPassThruDisplayText2() {
return getString(KEY_AUDIO_PASS_THRU_DISPLAY_TEXT_2);
}
/**
* Sets a samplingRate
*
* @param samplingRate
* a SamplingRate value representing a 8 or 16 or 22 or 24 khz
*/
public void setSamplingRate(SamplingRate samplingRate) {
setParameters(KEY_SAMPLING_RATE, samplingRate);
}
/**
* Gets a samplingRate
*
* @return SamplingRate -a SamplingRate value
*/
public SamplingRate getSamplingRate() {
return (SamplingRate) getObject(SamplingRate.class, KEY_SAMPLING_RATE);
}
/**
* Sets the maximum duration of audio recording in milliseconds
*
* @param maxDuration
* an Integer value representing the maximum duration of audio
* recording in millisecond
* <p></p>
* <b>Notes: </b>Minvalue:1; Maxvalue:1000000
*/
public void setMaxDuration(Integer maxDuration) {
setParameters(KEY_MAX_DURATION, maxDuration);
}
/**
* Gets a max duration of audio recording in milliseconds
*
* @return int -an int value representing the maximum duration of audio
* recording in milliseconds
*/
public Integer getMaxDuration() {
return getInteger(KEY_MAX_DURATION);
}
/**
* Sets the quality the audio is recorded - 8 bit or 16 bit
*
* @param audioQuality
* a BitsPerSample value representing 8 bit or 16 bit
*/
public void setBitsPerSample(BitsPerSample audioQuality) {
setParameters(KEY_BITS_PER_SAMPLE, audioQuality);
}
/**
* Gets a BitsPerSample value, 8 bit or 16 bit
*
* @return BitsPerSample -a BitsPerSample value
*/
public BitsPerSample getBitsPerSample() {
return (BitsPerSample) getObject(BitsPerSample.class, KEY_BITS_PER_SAMPLE);
}
/**
* Sets an audioType
*
* @param audioType
* an audioType
*/
public void setAudioType(AudioType audioType) {
setParameters(KEY_AUDIO_TYPE, audioType);
}
/**
* Gets a type of audio data
*
* @return AudioType -an AudioType
*/
public AudioType getAudioType() {
return (AudioType) getObject(AudioType.class, KEY_AUDIO_TYPE);
}
/**
*<p> Gets a Boolean value representing if the current audio source should be
* muted during the APT session</p>
*
*
* @return Boolean -a Boolean value representing if the current audio source
* should be muted during the APT session
*/
public Boolean getMuteAudio() {
return getBoolean(KEY_MUTE_AUDIO);
}
/**
* <p>Sets a muteAudio value representing if the current audio source should be
* muted during the APT session
* If not, the audio source will play without interruption. If omitted, the
* value is set to true</p>
*
*
* @param muteAudio
* a Boolean value representing if the current audio source
* should be muted during the APT session
*/
public void setMuteAudio(Boolean muteAudio) {
setParameters(KEY_MUTE_AUDIO, muteAudio);
}
}
| bsd-3-clause |
tectonicus/tectonicus | src/main/java/tectonicus/blockTypes/Lilly.java | 3913 | /*
* Copyright (c) 2020, John Campbell and other contributors. All rights reserved.
*
* This file is part of Tectonicus. It is subject to the license terms in the LICENSE file found in
* the top-level directory of this distribution. The full list of project contributors is contained
* in the AUTHORS file found in the same location.
*
*/
package tectonicus.blockTypes;
import org.joml.Vector3f;
import org.joml.Vector4f;
import tectonicus.BlockContext;
import tectonicus.BlockType;
import tectonicus.BlockTypeRegistry;
import tectonicus.cache.BiomeCache;
import tectonicus.cache.BiomeData;
import tectonicus.configuration.LightFace;
import tectonicus.rasteriser.Mesh;
import tectonicus.rasteriser.MeshUtil;
import tectonicus.raw.RawChunk;
import tectonicus.renderer.Geometry;
import tectonicus.texture.SubTexture;
import tectonicus.texture.TexturePack;
import tectonicus.util.Colour4f;
public class Lilly implements BlockType
{
private final String name;
private final SubTexture texture;
private final BiomeCache biomeCache;
private final TexturePack texturePack;
public Lilly(String name, SubTexture texture, BiomeCache biomeCache, TexturePack texturePack)
{
this.name = name;
this.texture = texture;
this.biomeCache = biomeCache;
this.texturePack = texturePack;
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isSolid()
{
return false;
}
@Override
public boolean isWater()
{
return false;
}
@Override
public void addInteriorGeometry(int x, int y, int z, BlockContext world, BlockTypeRegistry registry, RawChunk chunk, Geometry geometry)
{
addEdgeGeometry(x, y, z, world, registry, chunk, geometry);
}
@Override
public void addEdgeGeometry(int x, int y, int z, BlockContext world, BlockTypeRegistry registry, RawChunk rawChunk, Geometry geometry)
{
BiomeData biomeData = biomeCache.loadBiomeData(rawChunk.getChunkCoord());
BiomeData.ColourCoord colourCoord = biomeData.getColourCoord(x, z);
Colour4f colour = new Colour4f( texturePack.getGrassColour(colourCoord.getX(), colourCoord.getY()) );
Mesh mesh = geometry.getMesh(texture.texture, Geometry.MeshType.AlphaTest);
final float lightness = world.getLight(rawChunk.getChunkCoord(), x, y, z, LightFace.Top);
int wx = (int)rawChunk.getChunkCoord().x * 16 + x;
int wz = (int)rawChunk.getChunkCoord().z * 16 + z;
/* The three lines below, to figure out lilypad rotation, were taken straight from this blog here: http://llbit.se/?p=1537 */
long pr = (wx * 3129871L) ^ (wz * 116129781L) ^ ((long) y);
pr = pr * pr * 42317861L + pr * 11L;
int rotation = 3 & (int)(pr >> 16);
if(rotation == 0)
{
MeshUtil.addQuad(mesh, new Vector3f(x, y, z),
new Vector3f(x+1, y, z),
new Vector3f(x+1, y, z+1),
new Vector3f(x, y, z+1),
new Vector4f(colour.r * lightness, colour.g * lightness, colour.b * lightness, colour.a),
texture);
}
else if(rotation == 1)
{
MeshUtil.addQuad(mesh, new Vector3f(x, y, z+1),
new Vector3f(x, y, z),
new Vector3f(x+1, y, z),
new Vector3f(x+1, y, z+1),
new Vector4f(colour.r * lightness, colour.g * lightness, colour.b * lightness, colour.a),
texture);
}
else if(rotation == 2)
{
MeshUtil.addQuad(mesh, new Vector3f(x+1, y, z+1),
new Vector3f(x, y, z+1),
new Vector3f(x, y, z),
new Vector3f(x+1, y, z),
new Vector4f(colour.r * lightness, colour.g * lightness, colour.b * lightness, colour.a),
texture);
}
else if(rotation == 3)
{
MeshUtil.addQuad(mesh, new Vector3f(x+1, y, z),
new Vector3f(x+1, y, z+1),
new Vector3f(x, y, z+1),
new Vector3f(x, y, z),
new Vector4f(colour.r * lightness, colour.g * lightness, colour.b * lightness, colour.a),
texture);
}
}
}
| bsd-3-clause |
WhitmoreLakeTroBots/2016-Stronghold | src/org/usfirst/frc3668/Stronghold/commands/CMDjoyTurtleTail.java | 1450 | package org.usfirst.frc3668.Stronghold.commands;
import org.usfirst.frc3668.Stronghold.Robot;
import org.usfirst.frc3668.Stronghold.RobotMap;
import org.usfirst.frc3668.Stronghold.Settings;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class CMDjoyTurtleTail extends Command {
public CMDjoyTurtleTail() {
// Use requires() here to declare subsystem dependencies
requires(Robot.TurtleTail);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
double joyVector = Robot.oi.getJoyArticulator().getY();
if (Math.abs(joyVector) > Settings.Joystick_Deadband) {
Robot.TurtleTail.Move(joyVector);
}
// if(Robot.oi.joyArticulator.getY() > 0){
// Robot.TurtleTail.Raise(Robot.oi.joyArticulator);
// }
// if(Robot.oi.joyArticulator.getY() < 0){
// Robot.TurtleTail.Lower(Robot.oi.joyArticulator);
// }
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.TurtleTail.Move(0);
}
}
| bsd-3-clause |
smartdevicelink/sdl_android | android/sdl_android/src/androidTest/java/com/smartdevicelink/test/rpc/enums/WindowTypeTests.java | 2209 | package com.smartdevicelink.test.rpc.enums;
import com.smartdevicelink.proxy.rpc.enums.WindowType;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This is a unit test class for the SmartDeviceLink library project class :
* {@link com.smartdevicelink.proxy.rpc.enums.WindowType}
*/
public class WindowTypeTests extends TestCase {
/**
* Verifies that the enum values are not null upon valid assignment.
*/
public void testValidEnums() {
String example = "MAIN";
WindowType enumMain = WindowType.valueForString(example);
example = "WIDGET";
WindowType enumWidget = WindowType.valueForString(example);
assertNotNull("MAIN returned null", enumMain);
assertNotNull("WIDGET returned null", enumWidget);
}
/**
* Verifies that an invalid assignment is null.
*/
public void testInvalidEnum() {
String example = "mAIN";
try {
WindowType temp = WindowType.valueForString(example);
assertNull("Result of valueForString should be null.", temp);
} catch (IllegalArgumentException exception) {
fail("Invalid enum throws IllegalArgumentException.");
}
}
/**
* Verifies that a null assignment is invalid.
*/
public void testNullEnum() {
String example = null;
try {
WindowType temp = WindowType.valueForString(example);
assertNull("Result of valueForString should be null.", temp);
} catch (NullPointerException exception) {
fail("Null string throws NullPointerException.");
}
}
/**
* Verifies the possible enum values of WindowType.
*/
public void testListEnum() {
List<WindowType> enumValueList = Arrays.asList(WindowType.values());
List<WindowType> enumTestList = new ArrayList<WindowType>();
enumTestList.add(WindowType.MAIN);
enumTestList.add(WindowType.WIDGET);
assertTrue("Enum value list does not match enum class list",
enumValueList.containsAll(enumTestList) && enumTestList.containsAll(enumValueList));
}
} | bsd-3-clause |
Civcraft/BetterShards | BetterShardsBukkit/src/main/java/vg/civcraft/mc/bettershards/command/commands/JoinPortal.java | 1714 | package vg.civcraft.mc.bettershards.command.commands;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import vg.civcraft.mc.bettershards.BetterShardsPlugin;
import vg.civcraft.mc.bettershards.manager.PortalsManager;
import vg.civcraft.mc.bettershards.portal.Portal;
import vg.civcraft.mc.civmodcore.command.PlayerCommand;
public class JoinPortal extends PlayerCommand {
private PortalsManager pm;
public JoinPortal(String name) {
super(name);
setIdentifier("bsj");
setDescription("Joins the main Portal to the secondary Portal.");
setUsage("/bsj <main portal> <connection>");
setArguments(2,2);
pm = BetterShardsPlugin.getPortalManager();
}
@Override
public boolean execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Must be a player to execute this command.");
return true;
}
Player p = (Player) sender;
Portal one = pm.getPortal(args[0]);
Portal two = pm.getPortal(args[1]);
if (one == null)
return sendPlayerMessage(p, ChatColor.RED + "The first portal does not exist.", true);
if (two == null)
return sendPlayerMessage(p, ChatColor.RED + "The second portal does not exist.", true);
if (!one.getClass().equals(two.getClass())) {
return sendPlayerMessage(p, ChatColor.RED + "You can not join portals of a different type", true);
}
one.setPartnerPortal(two);
String m = "%s has been set as Portal %s partner.";
sender.sendMessage(ChatColor.GREEN + String.format(m, two.getName(), one.getName()));
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
return null;
}
}
| bsd-3-clause |
mikejurka/engine | shell/platform/android/io/flutter/embedding/engine/FlutterEnginePluginRegistry.java | 31420 | // Copyright 2013 The Flutter 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 io.flutter.embedding.engine;
import android.app.Activity;
import android.app.Service;
import android.arch.lifecycle.Lifecycle;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.flutter.Log;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.PluginRegistry;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.broadcastreceiver.BroadcastReceiverAware;
import io.flutter.embedding.engine.plugins.broadcastreceiver.BroadcastReceiverControlSurface;
import io.flutter.embedding.engine.plugins.broadcastreceiver.BroadcastReceiverPluginBinding;
import io.flutter.embedding.engine.plugins.contentprovider.ContentProviderAware;
import io.flutter.embedding.engine.plugins.contentprovider.ContentProviderControlSurface;
import io.flutter.embedding.engine.plugins.contentprovider.ContentProviderPluginBinding;
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference;
import io.flutter.embedding.engine.plugins.service.ServiceAware;
import io.flutter.embedding.engine.plugins.service.ServiceControlSurface;
import io.flutter.embedding.engine.plugins.service.ServicePluginBinding;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class FlutterEnginePluginRegistry
implements PluginRegistry,
ActivityControlSurface,
ServiceControlSurface,
BroadcastReceiverControlSurface,
ContentProviderControlSurface {
private static final String TAG = "FlutterEnginePluginRegistry";
// PluginRegistry
@NonNull
private final Map<Class<? extends FlutterPlugin>, FlutterPlugin> plugins = new HashMap<>();
// Standard FlutterPlugin
@NonNull private final FlutterEngine flutterEngine;
@NonNull private final FlutterPlugin.FlutterPluginBinding pluginBinding;
// ActivityAware
@NonNull
private final Map<Class<? extends FlutterPlugin>, ActivityAware> activityAwarePlugins =
new HashMap<>();
@Nullable private Activity activity;
@Nullable private FlutterEngineActivityPluginBinding activityPluginBinding;
private boolean isWaitingForActivityReattachment = false;
// ServiceAware
@NonNull
private final Map<Class<? extends FlutterPlugin>, ServiceAware> serviceAwarePlugins =
new HashMap<>();
@Nullable private Service service;
@Nullable private FlutterEngineServicePluginBinding servicePluginBinding;
// BroadcastReceiver
@NonNull
private final Map<Class<? extends FlutterPlugin>, BroadcastReceiverAware>
broadcastReceiverAwarePlugins = new HashMap<>();
@Nullable private BroadcastReceiver broadcastReceiver;
@Nullable private FlutterEngineBroadcastReceiverPluginBinding broadcastReceiverPluginBinding;
// ContentProvider
@NonNull
private final Map<Class<? extends FlutterPlugin>, ContentProviderAware>
contentProviderAwarePlugins = new HashMap<>();
@Nullable private ContentProvider contentProvider;
@Nullable private FlutterEngineContentProviderPluginBinding contentProviderPluginBinding;
FlutterEnginePluginRegistry(
@NonNull Context appContext,
@NonNull FlutterEngine flutterEngine,
@NonNull FlutterLoader flutterLoader) {
this.flutterEngine = flutterEngine;
pluginBinding =
new FlutterPlugin.FlutterPluginBinding(
appContext,
flutterEngine,
flutterEngine.getDartExecutor(),
flutterEngine.getRenderer(),
flutterEngine.getPlatformViewsController().getRegistry(),
new DefaultFlutterAssets(flutterLoader));
}
public void destroy() {
Log.v(TAG, "Destroying.");
// Detach from any Android component that we may currently be attached to, e.g., Activity,
// Service,
// BroadcastReceiver, ContentProvider. This must happen before removing all plugins so that the
// plugins have an opportunity to clean up references as a result of component detachment.
detachFromAndroidComponent();
// Remove all registered plugins.
removeAll();
}
@Override
public void add(@NonNull FlutterPlugin plugin) {
if (has(plugin.getClass())) {
Log.w(
TAG,
"Attempted to register plugin ("
+ plugin
+ ") but it was "
+ "already registered with this FlutterEngine ("
+ flutterEngine
+ ").");
return;
}
Log.v(TAG, "Adding plugin: " + plugin);
// Add the plugin to our generic set of plugins and notify the plugin
// that is has been attached to an engine.
plugins.put(plugin.getClass(), plugin);
plugin.onAttachedToEngine(pluginBinding);
// For ActivityAware plugins, add the plugin to our set of ActivityAware
// plugins, and if this engine is currently attached to an Activity,
// notify the ActivityAware plugin that it is now attached to an Activity.
if (plugin instanceof ActivityAware) {
ActivityAware activityAware = (ActivityAware) plugin;
activityAwarePlugins.put(plugin.getClass(), activityAware);
if (isAttachedToActivity()) {
activityAware.onAttachedToActivity(activityPluginBinding);
}
}
// For ServiceAware plugins, add the plugin to our set of ServiceAware
// plugins, and if this engine is currently attached to a Service,
// notify the ServiceAware plugin that it is now attached to a Service.
if (plugin instanceof ServiceAware) {
ServiceAware serviceAware = (ServiceAware) plugin;
serviceAwarePlugins.put(plugin.getClass(), serviceAware);
if (isAttachedToService()) {
serviceAware.onAttachedToService(servicePluginBinding);
}
}
// For BroadcastReceiverAware plugins, add the plugin to our set of BroadcastReceiverAware
// plugins, and if this engine is currently attached to a BroadcastReceiver,
// notify the BroadcastReceiverAware plugin that it is now attached to a BroadcastReceiver.
if (plugin instanceof BroadcastReceiverAware) {
BroadcastReceiverAware broadcastReceiverAware = (BroadcastReceiverAware) plugin;
broadcastReceiverAwarePlugins.put(plugin.getClass(), broadcastReceiverAware);
if (isAttachedToBroadcastReceiver()) {
broadcastReceiverAware.onAttachedToBroadcastReceiver(broadcastReceiverPluginBinding);
}
}
// For ContentProviderAware plugins, add the plugin to our set of ContentProviderAware
// plugins, and if this engine is currently attached to a ContentProvider,
// notify the ContentProviderAware plugin that it is now attached to a ContentProvider.
if (plugin instanceof ContentProviderAware) {
ContentProviderAware contentProviderAware = (ContentProviderAware) plugin;
contentProviderAwarePlugins.put(plugin.getClass(), contentProviderAware);
if (isAttachedToContentProvider()) {
contentProviderAware.onAttachedToContentProvider(contentProviderPluginBinding);
}
}
}
@Override
public void add(@NonNull Set<FlutterPlugin> plugins) {
for (FlutterPlugin plugin : plugins) {
add(plugin);
}
}
@Override
public boolean has(@NonNull Class<? extends FlutterPlugin> pluginClass) {
return plugins.containsKey(pluginClass);
}
@Override
public FlutterPlugin get(@NonNull Class<? extends FlutterPlugin> pluginClass) {
return plugins.get(pluginClass);
}
@Override
public void remove(@NonNull Class<? extends FlutterPlugin> pluginClass) {
FlutterPlugin plugin = plugins.get(pluginClass);
if (plugin != null) {
Log.v(TAG, "Removing plugin: " + plugin);
// For ActivityAware plugins, notify the plugin that it is detached from
// an Activity if an Activity is currently attached to this engine. Then
// remove the plugin from our set of ActivityAware plugins.
if (plugin instanceof ActivityAware) {
if (isAttachedToActivity()) {
ActivityAware activityAware = (ActivityAware) plugin;
activityAware.onDetachedFromActivity();
}
activityAwarePlugins.remove(pluginClass);
}
// For ServiceAware plugins, notify the plugin that it is detached from
// a Service if a Service is currently attached to this engine. Then
// remove the plugin from our set of ServiceAware plugins.
if (plugin instanceof ServiceAware) {
if (isAttachedToService()) {
ServiceAware serviceAware = (ServiceAware) plugin;
serviceAware.onDetachedFromService();
}
serviceAwarePlugins.remove(pluginClass);
}
// For BroadcastReceiverAware plugins, notify the plugin that it is detached from
// a BroadcastReceiver if a BroadcastReceiver is currently attached to this engine. Then
// remove the plugin from our set of BroadcastReceiverAware plugins.
if (plugin instanceof BroadcastReceiverAware) {
if (isAttachedToBroadcastReceiver()) {
BroadcastReceiverAware broadcastReceiverAware = (BroadcastReceiverAware) plugin;
broadcastReceiverAware.onDetachedFromBroadcastReceiver();
}
broadcastReceiverAwarePlugins.remove(pluginClass);
}
// For ContentProviderAware plugins, notify the plugin that it is detached from
// a ContentProvider if a ContentProvider is currently attached to this engine. Then
// remove the plugin from our set of ContentProviderAware plugins.
if (plugin instanceof ContentProviderAware) {
if (isAttachedToContentProvider()) {
ContentProviderAware contentProviderAware = (ContentProviderAware) plugin;
contentProviderAware.onDetachedFromContentProvider();
}
contentProviderAwarePlugins.remove(pluginClass);
}
// Notify the plugin that is now detached from this engine. Then remove
// it from our set of generic plugins.
plugin.onDetachedFromEngine(pluginBinding);
plugins.remove(pluginClass);
}
}
@Override
public void remove(@NonNull Set<Class<? extends FlutterPlugin>> pluginClasses) {
for (Class<? extends FlutterPlugin> pluginClass : pluginClasses) {
remove(pluginClass);
}
}
@Override
public void removeAll() {
// We copy the keys to a new set so that we can mutate the set while using
// the keys.
remove(new HashSet<>(plugins.keySet()));
plugins.clear();
}
private void detachFromAndroidComponent() {
if (isAttachedToActivity()) {
detachFromActivity();
} else if (isAttachedToService()) {
detachFromService();
} else if (isAttachedToBroadcastReceiver()) {
detachFromBroadcastReceiver();
} else if (isAttachedToContentProvider()) {
detachFromContentProvider();
}
}
// -------- Start ActivityControlSurface -------
private boolean isAttachedToActivity() {
return activity != null;
}
@Override
public void attachToActivity(@NonNull Activity activity, @NonNull Lifecycle lifecycle) {
Log.v(
TAG,
"Attaching to an Activity: "
+ activity
+ "."
+ (isWaitingForActivityReattachment ? " This is after a config change." : ""));
// If we were already attached to an Android component, detach from it.
detachFromAndroidComponent();
this.activity = activity;
this.activityPluginBinding = new FlutterEngineActivityPluginBinding(activity, lifecycle);
// Activate the PlatformViewsController. This must happen before any plugins attempt
// to use it, otherwise an error stack trace will appear that says there is no
// flutter/platform_views channel.
flutterEngine
.getPlatformViewsController()
.attach(activity, flutterEngine.getRenderer(), flutterEngine.getDartExecutor());
// Notify all ActivityAware plugins that they are now attached to a new Activity.
for (ActivityAware activityAware : activityAwarePlugins.values()) {
if (isWaitingForActivityReattachment) {
activityAware.onReattachedToActivityForConfigChanges(activityPluginBinding);
} else {
activityAware.onAttachedToActivity(activityPluginBinding);
}
}
isWaitingForActivityReattachment = false;
}
@Override
public void detachFromActivityForConfigChanges() {
if (isAttachedToActivity()) {
Log.v(TAG, "Detaching from an Activity for config changes: " + activity);
isWaitingForActivityReattachment = true;
for (ActivityAware activityAware : activityAwarePlugins.values()) {
activityAware.onDetachedFromActivityForConfigChanges();
}
// Deactivate PlatformViewsController.
flutterEngine.getPlatformViewsController().detach();
activity = null;
activityPluginBinding = null;
} else {
Log.e(TAG, "Attempted to detach plugins from an Activity when no Activity was attached.");
}
}
@Override
public void detachFromActivity() {
if (isAttachedToActivity()) {
Log.v(TAG, "Detaching from an Activity: " + activity);
for (ActivityAware activityAware : activityAwarePlugins.values()) {
activityAware.onDetachedFromActivity();
}
// Deactivate PlatformViewsController.
flutterEngine.getPlatformViewsController().detach();
activity = null;
activityPluginBinding = null;
} else {
Log.e(TAG, "Attempted to detach plugins from an Activity when no Activity was attached.");
}
}
@Override
public boolean onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
Log.v(TAG, "Forwarding onRequestPermissionsResult() to plugins.");
if (isAttachedToActivity()) {
return activityPluginBinding.onRequestPermissionsResult(
requestCode, permissions, grantResult);
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onRequestPermissionsResult, but no Activity was attached.");
return false;
}
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
Log.v(TAG, "Forwarding onActivityResult() to plugins.");
if (isAttachedToActivity()) {
return activityPluginBinding.onActivityResult(requestCode, resultCode, data);
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onActivityResult, but no Activity was attached.");
return false;
}
}
@Override
public void onNewIntent(@NonNull Intent intent) {
Log.v(TAG, "Forwarding onNewIntent() to plugins.");
if (isAttachedToActivity()) {
activityPluginBinding.onNewIntent(intent);
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onNewIntent, but no Activity was attached.");
}
}
@Override
public void onUserLeaveHint() {
Log.v(TAG, "Forwarding onUserLeaveHint() to plugins.");
if (isAttachedToActivity()) {
activityPluginBinding.onUserLeaveHint();
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onUserLeaveHint, but no Activity was attached.");
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle bundle) {
Log.v(TAG, "Forwarding onSaveInstanceState() to plugins.");
if (isAttachedToActivity()) {
activityPluginBinding.onSaveInstanceState(bundle);
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onSaveInstanceState, but no Activity was attached.");
}
}
@Override
public void onRestoreInstanceState(@Nullable Bundle bundle) {
Log.v(TAG, "Forwarding onRestoreInstanceState() to plugins.");
if (isAttachedToActivity()) {
activityPluginBinding.onRestoreInstanceState(bundle);
} else {
Log.e(
TAG,
"Attempted to notify ActivityAware plugins of onRestoreInstanceState, but no Activity was attached.");
}
}
// ------- End ActivityControlSurface -----
// ----- Start ServiceControlSurface ----
private boolean isAttachedToService() {
return service != null;
}
@Override
public void attachToService(
@NonNull Service service, @Nullable Lifecycle lifecycle, boolean isForeground) {
Log.v(TAG, "Attaching to a Service: " + service);
// If we were already attached to an Android component, detach from it.
detachFromAndroidComponent();
this.service = service;
this.servicePluginBinding = new FlutterEngineServicePluginBinding(service, lifecycle);
// Notify all ServiceAware plugins that they are now attached to a new Service.
for (ServiceAware serviceAware : serviceAwarePlugins.values()) {
serviceAware.onAttachedToService(servicePluginBinding);
}
}
@Override
public void detachFromService() {
if (isAttachedToService()) {
Log.v(TAG, "Detaching from a Service: " + service);
// Notify all ServiceAware plugins that they are no longer attached to a Service.
for (ServiceAware serviceAware : serviceAwarePlugins.values()) {
serviceAware.onDetachedFromService();
}
service = null;
servicePluginBinding = null;
} else {
Log.e(TAG, "Attempted to detach plugins from a Service when no Service was attached.");
}
}
@Override
public void onMoveToForeground() {
if (isAttachedToService()) {
Log.v(TAG, "Attached Service moved to foreground.");
servicePluginBinding.onMoveToForeground();
}
}
@Override
public void onMoveToBackground() {
if (isAttachedToService()) {
Log.v(TAG, "Attached Service moved to background.");
servicePluginBinding.onMoveToBackground();
}
}
// ----- End ServiceControlSurface ---
// ----- Start BroadcastReceiverControlSurface ---
private boolean isAttachedToBroadcastReceiver() {
return broadcastReceiver != null;
}
@Override
public void attachToBroadcastReceiver(
@NonNull BroadcastReceiver broadcastReceiver, @NonNull Lifecycle lifecycle) {
Log.v(TAG, "Attaching to BroadcastReceiver: " + broadcastReceiver);
// If we were already attached to an Android component, detach from it.
detachFromAndroidComponent();
this.broadcastReceiver = broadcastReceiver;
this.broadcastReceiverPluginBinding =
new FlutterEngineBroadcastReceiverPluginBinding(broadcastReceiver);
// TODO(mattcarroll): resolve possibility of different lifecycles between this and engine
// attachment
// Notify all BroadcastReceiverAware plugins that they are now attached to a new
// BroadcastReceiver.
for (BroadcastReceiverAware broadcastReceiverAware : broadcastReceiverAwarePlugins.values()) {
broadcastReceiverAware.onAttachedToBroadcastReceiver(broadcastReceiverPluginBinding);
}
}
@Override
public void detachFromBroadcastReceiver() {
if (isAttachedToBroadcastReceiver()) {
Log.v(TAG, "Detaching from BroadcastReceiver: " + broadcastReceiver);
// Notify all BroadcastReceiverAware plugins that they are no longer attached to a
// BroadcastReceiver.
for (BroadcastReceiverAware broadcastReceiverAware : broadcastReceiverAwarePlugins.values()) {
broadcastReceiverAware.onDetachedFromBroadcastReceiver();
}
} else {
Log.e(
TAG,
"Attempted to detach plugins from a BroadcastReceiver when no BroadcastReceiver was attached.");
}
}
// ----- End BroadcastReceiverControlSurface ----
// ----- Start ContentProviderControlSurface ----
private boolean isAttachedToContentProvider() {
return contentProvider != null;
}
@Override
public void attachToContentProvider(
@NonNull ContentProvider contentProvider, @NonNull Lifecycle lifecycle) {
Log.v(TAG, "Attaching to ContentProvider: " + contentProvider);
// If we were already attached to an Android component, detach from it.
detachFromAndroidComponent();
this.contentProvider = contentProvider;
this.contentProviderPluginBinding =
new FlutterEngineContentProviderPluginBinding(contentProvider);
// TODO(mattcarroll): resolve possibility of different lifecycles between this and engine
// attachment
// Notify all ContentProviderAware plugins that they are now attached to a new ContentProvider.
for (ContentProviderAware contentProviderAware : contentProviderAwarePlugins.values()) {
contentProviderAware.onAttachedToContentProvider(contentProviderPluginBinding);
}
}
@Override
public void detachFromContentProvider() {
if (isAttachedToContentProvider()) {
Log.v(TAG, "Detaching from ContentProvider: " + contentProvider);
// Notify all ContentProviderAware plugins that they are no longer attached to a
// ContentProvider.
for (ContentProviderAware contentProviderAware : contentProviderAwarePlugins.values()) {
contentProviderAware.onDetachedFromContentProvider();
}
} else {
Log.e(
TAG,
"Attempted to detach plugins from a ContentProvider when no ContentProvider was attached.");
}
}
// ----- End ContentProviderControlSurface -----
private static class DefaultFlutterAssets implements FlutterPlugin.FlutterAssets {
final FlutterLoader flutterLoader;
private DefaultFlutterAssets(@NonNull FlutterLoader flutterLoader) {
this.flutterLoader = flutterLoader;
}
public String getAssetFilePathByName(@NonNull String assetFileName) {
return flutterLoader.getLookupKeyForAsset(assetFileName);
}
public String getAssetFilePathByName(
@NonNull String assetFileName, @NonNull String packageName) {
return flutterLoader.getLookupKeyForAsset(assetFileName, packageName);
}
public String getAssetFilePathBySubpath(@NonNull String assetSubpath) {
return flutterLoader.getLookupKeyForAsset(assetSubpath);
}
public String getAssetFilePathBySubpath(
@NonNull String assetSubpath, @NonNull String packageName) {
return flutterLoader.getLookupKeyForAsset(assetSubpath, packageName);
}
}
private static class FlutterEngineActivityPluginBinding implements ActivityPluginBinding {
@NonNull private final Activity activity;
@NonNull private final HiddenLifecycleReference hiddenLifecycleReference;
@NonNull
private final Set<io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener>
onRequestPermissionsResultListeners = new HashSet<>();
@NonNull
private final Set<io.flutter.plugin.common.PluginRegistry.ActivityResultListener>
onActivityResultListeners = new HashSet<>();
@NonNull
private final Set<io.flutter.plugin.common.PluginRegistry.NewIntentListener>
onNewIntentListeners = new HashSet<>();
@NonNull
private final Set<io.flutter.plugin.common.PluginRegistry.UserLeaveHintListener>
onUserLeaveHintListeners = new HashSet<>();
@NonNull
private final Set<OnSaveInstanceStateListener> onSaveInstanceStateListeners = new HashSet<>();
public FlutterEngineActivityPluginBinding(
@NonNull Activity activity, @NonNull Lifecycle lifecycle) {
this.activity = activity;
this.hiddenLifecycleReference = new HiddenLifecycleReference(lifecycle);
}
@Override
@NonNull
public Activity getActivity() {
return activity;
}
@NonNull
@Override
public Object getLifecycle() {
return hiddenLifecycleReference;
}
@Override
public void addRequestPermissionsResultListener(
@NonNull
io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener listener) {
onRequestPermissionsResultListeners.add(listener);
}
@Override
public void removeRequestPermissionsResultListener(
@NonNull
io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener listener) {
onRequestPermissionsResultListeners.remove(listener);
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} has its {@code onRequestPermissionsResult(...)} method invoked.
*/
boolean onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
boolean didConsumeResult = false;
for (io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener listener :
onRequestPermissionsResultListeners) {
didConsumeResult =
listener.onRequestPermissionsResult(requestCode, permissions, grantResult)
|| didConsumeResult;
}
return didConsumeResult;
}
@Override
public void addActivityResultListener(
@NonNull io.flutter.plugin.common.PluginRegistry.ActivityResultListener listener) {
onActivityResultListeners.add(listener);
}
@Override
public void removeActivityResultListener(
@NonNull io.flutter.plugin.common.PluginRegistry.ActivityResultListener listener) {
onActivityResultListeners.remove(listener);
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} has its {@code onActivityResult(...)} method invoked.
*/
boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
boolean didConsumeResult = false;
for (io.flutter.plugin.common.PluginRegistry.ActivityResultListener listener :
onActivityResultListeners) {
didConsumeResult =
listener.onActivityResult(requestCode, resultCode, data) || didConsumeResult;
}
return didConsumeResult;
}
@Override
public void addOnNewIntentListener(
@NonNull io.flutter.plugin.common.PluginRegistry.NewIntentListener listener) {
onNewIntentListeners.add(listener);
}
@Override
public void removeOnNewIntentListener(
@NonNull io.flutter.plugin.common.PluginRegistry.NewIntentListener listener) {
onNewIntentListeners.remove(listener);
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} has its {@code onNewIntent(...)} method invoked.
*/
void onNewIntent(@Nullable Intent intent) {
for (io.flutter.plugin.common.PluginRegistry.NewIntentListener listener :
onNewIntentListeners) {
listener.onNewIntent(intent);
}
}
@Override
public void addOnUserLeaveHintListener(
@NonNull io.flutter.plugin.common.PluginRegistry.UserLeaveHintListener listener) {
onUserLeaveHintListeners.add(listener);
}
@Override
public void removeOnUserLeaveHintListener(
@NonNull io.flutter.plugin.common.PluginRegistry.UserLeaveHintListener listener) {
onUserLeaveHintListeners.remove(listener);
}
@Override
public void addOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener) {
onSaveInstanceStateListeners.add(listener);
}
@Override
public void removeOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener) {
onSaveInstanceStateListeners.remove(listener);
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} has its {@code onUserLeaveHint()} method invoked.
*/
void onUserLeaveHint() {
for (io.flutter.plugin.common.PluginRegistry.UserLeaveHintListener listener :
onUserLeaveHintListeners) {
listener.onUserLeaveHint();
}
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} or {@code Fragment} has its {@code onSaveInstanceState(Bundle)}
* method invoked.
*/
void onSaveInstanceState(@NonNull Bundle bundle) {
for (OnSaveInstanceStateListener listener : onSaveInstanceStateListeners) {
listener.onSaveInstanceState(bundle);
}
}
/**
* Invoked by the {@link FlutterEngine} that owns this {@code ActivityPluginBinding} when its
* associated {@link Activity} has its {@code onCreate(Bundle)} method invoked, or its
* associated {@code Fragment} has its {@code onActivityCreated(Bundle)} method invoked.
*/
void onRestoreInstanceState(@Nullable Bundle bundle) {
for (OnSaveInstanceStateListener listener : onSaveInstanceStateListeners) {
listener.onRestoreInstanceState(bundle);
}
}
}
private static class FlutterEngineServicePluginBinding implements ServicePluginBinding {
@NonNull private final Service service;
@Nullable private final HiddenLifecycleReference hiddenLifecycleReference;
@NonNull
private final Set<ServiceAware.OnModeChangeListener> onModeChangeListeners = new HashSet<>();
FlutterEngineServicePluginBinding(@NonNull Service service, @Nullable Lifecycle lifecycle) {
this.service = service;
hiddenLifecycleReference = lifecycle != null ? new HiddenLifecycleReference(lifecycle) : null;
}
@Override
@NonNull
public Service getService() {
return service;
}
@Nullable
@Override
public Object getLifecycle() {
return hiddenLifecycleReference;
}
@Override
public void addOnModeChangeListener(@NonNull ServiceAware.OnModeChangeListener listener) {
onModeChangeListeners.add(listener);
}
@Override
public void removeOnModeChangeListener(@NonNull ServiceAware.OnModeChangeListener listener) {
onModeChangeListeners.remove(listener);
}
void onMoveToForeground() {
for (ServiceAware.OnModeChangeListener listener : onModeChangeListeners) {
listener.onMoveToForeground();
}
}
void onMoveToBackground() {
for (ServiceAware.OnModeChangeListener listener : onModeChangeListeners) {
listener.onMoveToBackground();
}
}
}
private static class FlutterEngineBroadcastReceiverPluginBinding
implements BroadcastReceiverPluginBinding {
@NonNull private final BroadcastReceiver broadcastReceiver;
FlutterEngineBroadcastReceiverPluginBinding(@NonNull BroadcastReceiver broadcastReceiver) {
this.broadcastReceiver = broadcastReceiver;
}
@NonNull
@Override
public BroadcastReceiver getBroadcastReceiver() {
return broadcastReceiver;
}
}
private static class FlutterEngineContentProviderPluginBinding
implements ContentProviderPluginBinding {
@NonNull private final ContentProvider contentProvider;
FlutterEngineContentProviderPluginBinding(@NonNull ContentProvider contentProvider) {
this.contentProvider = contentProvider;
}
@NonNull
@Override
public ContentProvider getContentProvider() {
return contentProvider;
}
}
}
| bsd-3-clause |
treejames/StarAppSquare | src/com/nd/android/u/square/interf/IMultimediaInfo.java | 1938 | package com.nd.android.u.square.interf;
/**
* 语音,图片,gif信息
*
* <br>
* Created 2014-10-29 下午4:17:31
*
* @version
* @author chenpeng
*
* @see
*/
public interface IMultimediaInfo {
// public MultiTypy ext;// 类型 audio, image, gif
// public long _id;// 一般不需要,当MultiType=audio的时候,最好传入音频所属对象的id
// public long fid;// 文件id,储存在文件系统的fid
// public String path;// 文件路径
// public String extra;// 额外信息:如音频长度
// 类型
public enum MultiTypy {
audio, image, circleimage, gif, video
};
/**
* 获得类型信息
*
* <br>Created 2014-10-29 下午5:26:54
* @return
* @author chenpeng
*/
public MultiTypy getExt();
// 设置类型
public void setExt(MultiTypy ext);
/**
* 获得Multimedia拥有对象id
*
* <br>Created 2014-10-29 下午5:27:16
* @return
* @author chenpeng
*/
public long getId();
// 设置Multimedia拥有对象id
public void setId(long id);
/**
* 获得Multimedia内容id
*
* <br>Created 2014-10-29 下午5:28:22
* @return
* @author chenpeng
*/
public long getFid();
// 设置Multimedia内容id
public void setFid(long fid);
/**
* 获得Multimedia内容下载地址
*
* <br>Created 2014-10-29 下午5:28:50
* @return
* @author chenpeng
*/
public String getPath();
// 设置Multimedia内容下载地址
public void setPath(String path);
/**
* 获得附加信息(如:音频文件的时长信息)
*
* <br>Created 2014-10-29 下午5:30:35
* @return
* @author chenpeng
*/
public String getExtra();
// 设置附加信息(如:音频文件的时长信息)
public void setExtra(String extra);
}
| bsd-3-clause |
ValentinMinder/pocketcampus | platform/android/src/main/java/org/pocketcampus/platform/android/ui/list/LabeledListViewElement.java | 1448 | package org.pocketcampus.platform.android.ui.list;
import java.util.List;
import org.pocketcampus.platform.android.ui.adapter.LabeledArrayAdapter;
import org.pocketcampus.platform.android.ui.element.Element;
import org.pocketcampus.platform.android.ui.element.ElementDimension;
import org.pocketcampus.platform.android.ui.labeler.ILabeler;
import android.content.Context;
import android.widget.ListView;
/**
* Labeled list that displays a list of Item using the default style.
* Labeled means that it gets the text of its element from a <code>Labeler</code>.
* @author Florian
*
*/
public class LabeledListViewElement extends ListView implements Element {
private ElementDimension mDimension = ElementDimension.NORMAL;
public LabeledListViewElement(Context context) {
super(context);
}
/**
* Shortcut constructor that creates the <code>LabeledArrayAdapter</code> itself.
* @param context
* @param items
* @param labeler
*/
public LabeledListViewElement(Context context, List<? extends Object> items, ILabeler<? extends Object> labeler) {
super(context);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
setLayoutParams(params);
LabeledArrayAdapter adapter = new LabeledArrayAdapter(context, items, labeler);
adapter.setDimension(mDimension);
setAdapter(adapter);
}
public void setDimension(ElementDimension dimension) {
mDimension = dimension;
}
}
| bsd-3-clause |
deadc0de-dev/genesis | src/main/java/dev/deadc0de/genesis/module/Default.java | 372 | package dev.deadc0de.genesis.module;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Default {
String[] value();
}
| bsd-3-clause |
smartdevicelink/sdl_android | android/sdl_android/src/androidTest/java/com/smartdevicelink/test/rpc/requests/ReleaseInteriorVehicleDataModuleTests.java | 4252 | package com.smartdevicelink.test.rpc.requests;
import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCMessage;
import com.smartdevicelink.proxy.rpc.ReleaseInteriorVehicleDataModule;
import com.smartdevicelink.proxy.rpc.enums.ModuleType;
import com.smartdevicelink.test.BaseRpcTests;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;
import com.smartdevicelink.test.json.rpc.JsonFileReader;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import java.util.Hashtable;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.fail;
public class ReleaseInteriorVehicleDataModuleTests extends BaseRpcTests {
@Override
protected RPCMessage createMessage() {
ReleaseInteriorVehicleDataModule msg = new ReleaseInteriorVehicleDataModule();
msg.setModuleType(TestValues.GENERAL_MODULETYPE);
msg.setModuleId(TestValues.GENERAL_STRING);
return msg;
}
@Override
protected JSONObject getExpectedParameters(int sdlVersion) {
JSONObject result = new JSONObject();
try {
result.put(ReleaseInteriorVehicleDataModule.KEY_MODULE_TYPE, TestValues.GENERAL_MODULETYPE);
result.put(ReleaseInteriorVehicleDataModule.KEY_MODULE_ID, TestValues.GENERAL_STRING);
} catch (JSONException e) {
fail(TestValues.JSON_FAIL);
}
return result;
}
@Override
protected String getCommandType() {
return FunctionID.RELEASE_INTERIOR_VEHICLE_MODULE.toString();
}
@Override
protected String getMessageType() {
return RPCMessage.KEY_REQUEST;
}
@Test
public void testRpcValues() {
ModuleType type = ((ReleaseInteriorVehicleDataModule) msg).getModuleType();
String id = ((ReleaseInteriorVehicleDataModule) msg).getModuleId();
//valid tests
assertEquals(TestValues.MATCH, TestValues.GENERAL_MODULETYPE, type);
assertEquals(TestValues.MATCH, TestValues.GENERAL_STRING, id);
//null tests
ReleaseInteriorVehicleDataModule msg = new ReleaseInteriorVehicleDataModule();
assertNull(TestValues.NULL, msg.getModuleType());
assertNull(TestValues.NULL, msg.getModuleId());
// required param tests
ReleaseInteriorVehicleDataModule msg2 = new ReleaseInteriorVehicleDataModule(TestValues.GENERAL_MODULETYPE);
assertEquals(TestValues.MATCH, TestValues.GENERAL_MODULETYPE, msg2.getModuleType());
}
@Test
public void testJsonConstructor() {
JSONObject commandJson = JsonFileReader.readId(getInstrumentation().getTargetContext(), getCommandType(), getMessageType());
assertNotNull(TestValues.NOT_NULL, commandJson);
try {
Hashtable<String, Object> hash = JsonRPCMarshaller.deserializeJSONObject(commandJson);
ReleaseInteriorVehicleDataModule cmd = new ReleaseInteriorVehicleDataModule(hash);
JSONObject body = JsonUtils.readJsonObjectFromJsonObject(commandJson, getMessageType());
assertNotNull(TestValues.NOT_NULL, body);
assertEquals(TestValues.MATCH, JsonUtils.readStringFromJsonObject(body, RPCMessage.KEY_FUNCTION_NAME), cmd.getFunctionName());
assertEquals(TestValues.MATCH, JsonUtils.readIntegerFromJsonObject(body, RPCMessage.KEY_CORRELATION_ID), cmd.getCorrelationID());
JSONObject parameters = JsonUtils.readJsonObjectFromJsonObject(body, RPCMessage.KEY_PARAMETERS);
assertEquals(TestValues.MATCH, JsonUtils.readObjectFromJsonObject(parameters, ReleaseInteriorVehicleDataModule.KEY_MODULE_TYPE).toString(), cmd.getModuleType().toString());
assertEquals(TestValues.MATCH, JsonUtils.readStringListFromJsonObject(parameters, ReleaseInteriorVehicleDataModule.KEY_MODULE_ID), cmd.getModuleId());
} catch (JSONException e) {
fail(TestValues.JSON_FAIL);
}
}
}
| bsd-3-clause |
alameluchidambaram/CONNECT | Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/properties/PropertyFileManager.java | 4686 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.properties;
import java.io.File;
import java.util.Properties;
import java.io.FileWriter;
/**
* This class is used to manage a property file programmtically.
*
* @author Les Westberg
*/
public class PropertyFileManager {
/**
* This saves out the properties to the specified property file. If the file already exists, it is replaced by the
* specified one. If it does not exist, it is created.
*
* @param sPropertyFile The name of the property file without the ".properties" extension.
* @param oProps The contents to write out as the property file.
* @throws PropertyAccessException This exception is thrown if there are any errors.
*/
public static void writePropertyFile(String sPropertyFile, Properties oProps) throws PropertyAccessException {
if ((sPropertyFile == null) || (sPropertyFile.length() <= 0)) {
throw new PropertyAccessException("writePropertyFile called with no property file name.");
}
if (oProps == null) {
throw new PropertyAccessException("writePropertyFile called with no property file.");
}
String sPropFile = PropertyAccessor.getInstance().getPropertyFileLocation(sPropertyFile);
FileWriter fwPropFile = null;
Exception eError = null;
String sErrorMessage = "";
try {
fwPropFile = new FileWriter(sPropFile);
oProps.store(fwPropFile, "");
} catch (Exception e) {
sErrorMessage = "Failed to store property file: " + sPropFile + ". Error: " + e.getMessage();
eError = e;
} finally {
if (fwPropFile != null) {
try {
fwPropFile.close();
} catch (Exception e) {
sErrorMessage = "Failed to close property file: " + sPropFile + ". Error: " + e.getMessage();
eError = e;
}
}
}
if (eError != null) {
throw new PropertyAccessException(sErrorMessage, eError);
}
}
/**
* Delete the specified property file.
*
* @param sPropertyFile The file to be deleted. This is the name of the property file without the ".properties"
* extension. It must be located in the configured properties directory.
* @throws gov.hhs.fha.nhinc.properties.PropertyAccessException This exception is thrown if there is an error.
*/
public static void deletePropertyFile(String sPropertyFile) throws PropertyAccessException {
String sPropFile = PropertyAccessor.getInstance().getPropertyFileLocation(sPropertyFile);
File fPropFile = new File(sPropFile);
try {
if (fPropFile.exists()) {
fPropFile.delete();
}
} catch (Exception e) {
throw new PropertyAccessException("Failed to delete file: " + sPropFile + ". Error: " + e.getMessage(), e);
}
}
}
| bsd-3-clause |
cvsuser-chromium/chromium | chrome/android/testshell/javatests/src/org/chromium/chrome/testshell/TabShellTabUtils.java | 2436 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.testshell;
import org.chromium.chrome.browser.EmptyTabObserver;
import org.chromium.chrome.browser.TabBase;
import org.chromium.content.browser.ContentViewClient;
import org.chromium.content.browser.test.util.CallbackHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer;
import org.chromium.content.browser.test.util.TestContentViewClient;
import org.chromium.content.browser.test.util.TestContentViewClientWrapper;
import org.chromium.content.browser.test.util.TestWebContentsObserver;
/**
* A utility class that contains methods generic to all Tabs tests.
*/
public class TabShellTabUtils {
private static TestContentViewClient createTestContentViewClientForTab(TestShellTab tab) {
ContentViewClient client = tab.getContentView().getContentViewClient();
if (client instanceof TestContentViewClient) return (TestContentViewClient) client;
TestContentViewClient testClient = new TestContentViewClientWrapper(client);
tab.getContentView().setContentViewClient(testClient);
return testClient;
}
public static class TestCallbackHelperContainerForTab extends TestCallbackHelperContainer {
private final OnCloseTabHelper mOnCloseTabHelper;
public TestCallbackHelperContainerForTab(TestShellTab tab) {
super(createTestContentViewClientForTab(tab),
new TestWebContentsObserver(tab.getContentView().getContentViewCore()));
mOnCloseTabHelper = new OnCloseTabHelper();
tab.addObserver(new EmptyTabObserver() {
@Override
public void onDestroyed(TabBase tab) {
mOnCloseTabHelper.notifyCalled();
}
});
}
public static class OnCloseTabHelper extends CallbackHelper {
}
public OnCloseTabHelper getOnCloseTabHelper() {
return mOnCloseTabHelper;
}
}
/**
* Creates, binds and returns a TestCallbackHelperContainer for a given Tab.
*/
public static TestCallbackHelperContainerForTab getTestCallbackHelperContainer(
final TestShellTab tab) {
return tab == null ? null : new TestCallbackHelperContainerForTab(tab);
}
}
| bsd-3-clause |
andronix3/UIO | com/imagero/uio/imageio/spi/UioInputStreamImageInputStreamSpi.java | 2828 | /*
* Copyright (c) Andrey Kuznetsov. All Rights Reserved.
*
* http://uio.imagero.com
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Andrey Kuznetsov 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 com.imagero.uio.imageio.spi;
import com.imagero.uio.imageio.UioImageInputStream;
import com.imagero.uio.RandomAccessInput;
import com.imagero.uio.UIOStreamBuilder;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Locale;
/**
* @author Andrey Kuznetsov
*/
public class UioInputStreamImageInputStreamSpi extends ImageInputStreamSpi {
public UioInputStreamImageInputStreamSpi() {
super("imagero.com (Andrey Kuznetsov)", "0.9", InputStream.class);
}
public String getDescription(Locale locale) {
return "Service provider that instantiates a UioImageInputStream from a InputStream";
}
public ImageInputStream createInputStreamInstance(Object input, boolean useCache, File cacheDir) {
if (input instanceof File) {
try {
InputStream in = (InputStream) input;
RandomAccessInput ro = new UIOStreamBuilder(in).create();
return new UioImageInputStream(ro);
}
catch (Exception ex) {
return null;
}
}
throw new IllegalArgumentException();
}
}
| bsd-3-clause |
knopflerfish/knopflerfish.org | osgi/bundles/desktop/src/org/knopflerfish/bundle/log/window/impl/ExtLogEntry.java | 3134 | /*
* Copyright (c) 2003-2004,2013, 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.log.window.impl;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogEntry;
/**
* LogEntry implementation with an extra ID field.
*/
public class ExtLogEntry implements LogEntry {
LogEntry entry;
long id;
public ExtLogEntry(LogEntry entry, long id) {
this.entry = entry;
this.id = id;
}
public long getId() {
return id;
}
public Bundle getBundle() {
return entry.getBundle();
}
public ServiceReference<?> getServiceReference() {
return entry.getServiceReference();
}
public int getLevel() {
return entry.getLevel();
}
public String getMessage() {
return entry.getMessage();
}
public Throwable getException() {
return entry.getException();
}
public long getTime() {
return entry.getTime();
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getId());
sb.append(": " + new Date(getTime()));
sb.append(" " + Util.levelString(getLevel()));
sb.append(" #" + getBundle().getBundleId());
sb.append(" " + Util.getBundleName(getBundle()));
sb.append(" - " + getMessage());
if(getException() != null) {
StringWriter w = new StringWriter();
getException().printStackTrace(new PrintWriter(w));
sb.append(", ");
sb.append(w.toString());
}
return sb.toString();
}
}
| bsd-3-clause |
exponent/exponent | android/versioned-abis/expoview-abi38_0_0/src/main/java/abi38_0_0/expo/modules/webbrowser/CustomTabsActivitiesHelper.java | 4224 | package abi38_0_0.expo.modules.webbrowser;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.browser.customtabs.CustomTabsClient;
import androidx.browser.customtabs.CustomTabsIntent;
import abi38_0_0.org.unimodules.core.ModuleRegistry;
import abi38_0_0.org.unimodules.core.errors.CurrentActivityNotFoundException;
import abi38_0_0.org.unimodules.core.interfaces.ActivityProvider;
import abi38_0_0.org.unimodules.core.interfaces.Function;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import abi38_0_0.expo.modules.webbrowser.error.PackageManagerNotFoundException;
import static androidx.browser.customtabs.CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION;
class CustomTabsActivitiesHelper {
private final static String DUMMY_URL = "https://expo.io";
private ModuleRegistry mModuleRegistry;
CustomTabsActivitiesHelper(ModuleRegistry moduleRegistry) {
this.mModuleRegistry = moduleRegistry;
}
ArrayList<String> getCustomTabsResolvingActivities() throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
return mapCollectionToDistinctArrayList(getResolvingActivities(createDefaultCustomTabsIntent()), resolveInfo -> resolveInfo.activityInfo.packageName);
}
ArrayList<String> getCustomTabsResolvingServices() throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
return mapCollectionToDistinctArrayList(getPackageManager().queryIntentServices(createDefaultCustomTabsServiceIntent(), 0), resolveInfo -> resolveInfo.serviceInfo.packageName);
}
String getPreferredCustomTabsResolvingActivity(@Nullable List<String> packages) throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
if (packages == null) packages = getCustomTabsResolvingActivities();
return CustomTabsClient.getPackageName(getCurrentActivity(), packages);
}
String getDefaultCustomTabsResolvingActivity() throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
return getPackageManager().resolveActivity(createDefaultCustomTabsIntent(), 0).activityInfo.packageName;
}
List<ResolveInfo> getResolvingActivities(@NonNull Intent intent) throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
PackageManager pm = getPackageManager();
if (pm == null) {
throw new PackageManagerNotFoundException();
}
return pm.queryIntentActivities(intent, 0);
}
void startCustomTabs(Intent intent) throws CurrentActivityNotFoundException {
getCurrentActivity().startActivity(intent);
}
private PackageManager getPackageManager() throws PackageManagerNotFoundException, CurrentActivityNotFoundException {
PackageManager pm = getCurrentActivity().getPackageManager();
if (pm == null) throw new PackageManagerNotFoundException();
else return pm;
}
private Activity getCurrentActivity() throws CurrentActivityNotFoundException {
ActivityProvider activityProvider = mModuleRegistry.getModule(ActivityProvider.class);
if (activityProvider == null || activityProvider.getCurrentActivity() == null) {
throw new CurrentActivityNotFoundException();
}
return activityProvider.getCurrentActivity();
}
private Intent createDefaultCustomTabsIntent() {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
Intent intent = customTabsIntent.intent;
intent.setData(Uri.parse(DUMMY_URL));
return intent;
}
private Intent createDefaultCustomTabsServiceIntent() {
Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
return serviceIntent;
}
public static <T, R> ArrayList<R> mapCollectionToDistinctArrayList(Collection<? extends T> toMap, Function<T, R> mapper) {
LinkedHashSet<R> resultSet = new LinkedHashSet<>();
for (T element : toMap) {
resultSet.add(mapper.apply(element));
}
return new ArrayList<>(resultSet);
}
}
| bsd-3-clause |
NCIP/cagrid-portal | cagrid-portal/portlets/src/java/gov/nih/nci/cagrid/portal/portlet/discovery/details/SelectUmlClassForQueryController.java | 2321 | /**
*============================================================================
* 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-portal/LICENSE.txt for details.
*============================================================================
**/
/**
*
*/
package gov.nih.nci.cagrid.portal.portlet.discovery.details;
import gov.nih.nci.cagrid.portal.portlet.AbstractActionResponseHandlerCommandController;
import gov.nih.nci.cagrid.portal.portlet.InterPortletMessageSender;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import org.springframework.validation.BindException;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*
*/
public class SelectUmlClassForQueryController extends
AbstractActionResponseHandlerCommandController {
private InterPortletMessageSender interPortletMessageSender;
/**
*
*/
public SelectUmlClassForQueryController() {
}
/**
* @param commandClass
*/
public SelectUmlClassForQueryController(Class commandClass) {
super(commandClass);
}
/**
* @param commandClass
* @param commandName
*/
public SelectUmlClassForQueryController(Class commandClass,
String commandName) {
super(commandClass, commandName);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.cagrid.portal.portlet.AbstractActionResponseHandlerCommandController#doHandleAction(javax.portlet.ActionRequest,
* javax.portlet.ActionResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
@Override
protected void doHandleAction(ActionRequest request,
ActionResponse response, Object obj, BindException errors)
throws Exception {
SelectDetailsCommand command = (SelectDetailsCommand) obj;
getInterPortletMessageSender().send(request, command.getSelectedId());
}
public InterPortletMessageSender getInterPortletMessageSender() {
return interPortletMessageSender;
}
public void setInterPortletMessageSender(
InterPortletMessageSender interPortletMessageSender) {
this.interPortletMessageSender = interPortletMessageSender;
}
}
| bsd-3-clause |
knopflerfish/knopflerfish.org | osgi/bundles/event/src/org/knopflerfish/bundle/event/EventAdminService.java | 5604 | /*
* Copyright (c) 2005-2013, 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.event;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Implementation of the EventAdmin interface. This is a singleton
* class and should always be active.
*
* The implementation is responsible for track event handlers and check
* their permissions. It will also host two threads sending different
* types of data. If an event handler is subscribed to the published
* event the EventAdmin service will put the event on one of the two
* internal send-stacks depending on what type of deliverance the event
* requires.
*
* @author Magnus Klack (refactoring by Bj\u00f6rn Andersson)
*/
public class EventAdminService
implements EventAdmin
{
final private Map<Object, QueueHandler> queueHandlers
= new HashMap<Object, QueueHandler>();
final private MultiListener ml;
final private ConfigurationListenerImpl cli;
private ServiceRegistration<EventAdmin> reg;
public EventAdminService() {
ml = new MultiListener();
cli = new ConfigurationListenerImpl();
}
public void postEvent(Event event) {
try {
final InternalAdminEvent iae
= new InternalAdminEvent(event, getMatchingHandlers(event.getTopic()));
if (iae.getHandlers() == null) { // No-one to deliver to
return;
}
QueueHandler queueHandler = null;
boolean newQueueHandlerCreated = false;
synchronized(queueHandlers) {
final Thread currentThread = Thread.currentThread();
if (currentThread instanceof QueueHandler) {
// Event posted by event handler, queue it on the queue that
// called the event handler to keep the number of queue
// handlers down.
queueHandler = (QueueHandler) currentThread;
} else {
final Object key = Activator.useMultipleQueueHandlers
? (Object) currentThread : (Object) this;
queueHandler = queueHandlers.get(key);
if (null==queueHandler) {
queueHandler = new QueueHandler(queueHandlers, key);
queueHandler.start();
queueHandlers.put(queueHandler.getKey(), queueHandler);
newQueueHandlerCreated = true;
}
}
queueHandler.addEvent(iae);
}
// Must not do logging from within synchronized code since that
// may cause deadlock between the Log-service and the
// EventAdmin-service; each new log entry is sent out as an
// event via EventAdmin...
if (newQueueHandlerCreated && Activator.log.doDebug()) {
Activator.log.debug(queueHandler.getName() +" created.");
}
} catch(Exception e){
Activator.log.error("Unknown exception in postEvent():", e);
}
}
public void sendEvent(Event event) {
try {
final InternalAdminEvent iae
= new InternalAdminEvent(event, getMatchingHandlers(event.getTopic()));
if (iae.getHandlers() == null) { // No-one to deliver to
return;
}
iae.deliver();
} catch(Exception e){
Activator.log.error("Unknown exception in sendEvent():", e);
}
}
Set<TrackedEventHandler> getMatchingHandlers(String topic) {
return Activator.handlerTracker.getHandlersMatching(topic);
}
synchronized void start() {
ml.start();
cli.start();
reg = Activator.bc.registerService(EventAdmin.class, this, null);
}
synchronized void stop() {
reg.unregister();;
reg = null;
cli.stop();
ml.stop();
Set<QueueHandler> activeQueueHandlers = null;
synchronized(queueHandlers) {
activeQueueHandlers = new HashSet<QueueHandler>(queueHandlers.values());
}
for (Iterator<QueueHandler> it = activeQueueHandlers.iterator(); it.hasNext(); ) {
final QueueHandler queueHandler = it.next();
queueHandler.stopIt();
}
}
}
| bsd-3-clause |
TheFakeMontyOnTheRun/level-editor-3d | level-editor-core-java/src/main/java/br/odb/moonshot/SnapTreeCommand.java | 1744 | package br.odb.moonshot;
import br.odb.gameapp.ConsoleApplication;
import br.odb.gameapp.command.CommandParameterDefinition;
import br.odb.gameapp.command.UserCommandLineAction;
import br.odb.libscene.GroupSector;
import br.odb.libscene.SceneNode;
import br.odb.libscene.SpaceRegion;
public class SnapTreeCommand extends UserCommandLineAction {
LevelEditor editor;
@Override
public String getDescription() {
return "";
}
@Override
public void run(ConsoleApplication app, String arg1) throws Exception {
editor = (LevelEditor) app;
SceneNode target;
if ( arg1 == null || arg1.length() == 0 ) {
target = editor.world.masterSector;
} else {
target = editor.world.masterSector.getChild( arg1 );
}
snap( target );
}
private void snap( SceneNode target ) {
target.localPosition.x = (float) Math.round( target.localPosition.x );
target.localPosition.y = (float) Math.round( target.localPosition.y );
target.localPosition.z = (float) Math.round( target.localPosition.z );
editor.getClient().printVerbose( "snapping " + target.id );
if ( target instanceof SpaceRegion ) {
snapRegion( (SpaceRegion) target );
}
}
private void snapRegion( SpaceRegion region ) {
region.size.x = (float) Math.round( region.size.x );
region.size.x = (float) Math.round( region.size.y );
region.size.x = (float) Math.round( region.size.z );
if ( region instanceof GroupSector ) {
GroupSector gs = (GroupSector) region;
for ( SceneNode sn : gs.getSons() ) {
snap( sn );
}
}
}
@Override
public String toString() {
return "snap-tree";
}
@Override
public CommandParameterDefinition[] requiredOperands() {
return new CommandParameterDefinition[0];
}
}
| bsd-3-clause |
wdv4758h/ZipPy | edu.uci.python.test/src/edu/uci/python/test/runtime/PythonModuleTests.java | 3359 | /*
* Copyright (c) 2013, Regents of the University of California
* 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 edu.uci.python.test.runtime;
import static org.junit.Assert.*;
import org.junit.*;
import edu.uci.python.runtime.*;
import edu.uci.python.runtime.builtin.*;
import edu.uci.python.runtime.function.*;
import edu.uci.python.runtime.standardtype.*;
import edu.uci.python.test.*;
public class PythonModuleTests {
@Test
public void pythonModuleTest() {
final PythonContext context = PythonTests.getContext();
PythonModule module = new PythonModule(context, "testModule", null);
assertEquals("testModule", module.getAttribute("__name__").toString());
assertEquals("", module.getAttribute("__doc__").toString());
assertEquals("", module.getAttribute("__package__").toString());
}
@Test
public void builtinsMinTest() {
final PythonContext context = PythonTests.getContext();
final PythonModule builtins = context.getBuiltins();
PBuiltinFunction min = (PBuiltinFunction) builtins.getAttribute("min");
Object returnValue = min.call(PArguments.createWithUserArguments(4, 2, 1));
assertEquals(1, returnValue);
}
@Test
public void builtinsIntTest() {
final PythonContext context = PythonTests.getContext();
final PythonModule builtins = context.getBuiltins();
PythonBuiltinClass intClass = (PythonBuiltinClass) builtins.getAttribute("int");
Object returnValue = intClass.call(PArguments.createWithUserArguments("42"));
assertEquals(42, returnValue);
}
@Test
public void mainModuleTest() {
final PythonContext context = PythonTests.getContext();
PythonModule main = context.createMainModule(null);
PythonModule builtins = (PythonModule) main.getAttribute("__builtins__");
PBuiltinFunction abs = (PBuiltinFunction) builtins.getAttribute("abs");
Object returned = abs.call(PArguments.createWithUserArguments(-42));
assertEquals(42, returned);
}
}
| bsd-3-clause |
jminusminus/core | Arrays.java | 2540 | //
// Copyright 2016, Yahoo Inc.
// Copyrights licensed under the New BSD License.
// See the accompanying LICENSE file for terms.
//
// ## Stability: 0 - Unstable
package github.com.jminusminus.core;
public class Arrays {
// Appends to the given array the given string.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b"};
//
// String[] a = Arrays.append(a, "c");
// // returns a,b,c
// ```
public static String[] append(String[] a, String b) {
int len = a.length;
String[] c = new String[len + 1];
System.arraycopy(a, 0, c, 0, a.length);
c[len] = b;
return c;
}
// Appends to the given array the given array.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b"};
// String[] a = new String[]{"c", "d"};
//
// String[] a = Arrays.append(a, b);
// // returns a,b,c,d
// ```
public static String[] append(String[] a, String[] b) {
int len = a.length + b.length;
String[] c = new String[len];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
// Slice the given array upto and including `end`.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b", "c", "d"};
//
// String[] s = Arrays.slice(a, 3);
// // returns a,b,c
//
// String[] s = Arrays.slice(a, -2);
// // returns a,b
// ```
public static String[] slice(String[] a, int end) {
if (end < 0) {
end = a.length + end;
}
return Arrays.slice(a, 0, end);
}
// Slice the given array after `start` upto and including `end`.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b", "c", "d"};
//
// String[] s = Arrays.slice(a, 0, 4);
// // a,b,c,d
//
// String[] s = Arrays.slice(a, 1, 3);
// // b,c
//
// String[] s = Arrays.slice(a, 1, -1);
// // b,c
// ```
public static String[] slice(String[] a, int start, int end) {
int len = a.length;
if (start > len) {
return new String[0];
}
if (start < 0) {
start = 0;
}
if (end > len) {
end = len - 1;
}
if (end < 0) {
end = a.length + end;
}
String[] b = new String[end - start];
System.arraycopy(a, start, b, 0, b.length);
return b;
}
}
| bsd-3-clause |
Demannu/hackwars-classic | src/classes/Hacktendo/Functions/FillRectangle.java | 1187 | package Hacktendo.Functions;
import java.util.ArrayList;
import Hackscript.Model.*;
import Hacktendo.*;
public class FillRectangle extends LinkerFunctions{
private RenderEngine RE;
private HacktendoLinker HL;
public FillRectangle(RenderEngine RE,HacktendoLinker HL){
this.RE=RE;
this.HL=HL;
}
public Object execute(ArrayList parameters){
int x = (int)(Integer)((TypeInteger)parameters.get(0)).getRawValue();
int y = (int)(Integer)((TypeInteger)parameters.get(1)).getRawValue();
int width = (int)(Integer)((TypeInteger)parameters.get(2)).getRawValue();
int height = (int)(Integer)((TypeInteger)parameters.get(3)).getRawValue();
int r = (int)(Integer)((TypeInteger)parameters.get(4)).getRawValue();
int g = (int)(Integer)((TypeInteger)parameters.get(5)).getRawValue();
int b = (int)(Integer)((TypeInteger)parameters.get(6)).getRawValue();
int a = (int)(Integer)((TypeInteger)parameters.get(7)).getRawValue();
if(a<0)
a=0;
Object O[] = new Object[]{RenderEngine.FILL_RECTANGLE,new Integer(x),new Integer(y),new Integer(width),new Integer(height),new Integer(r),new Integer(g),new Integer(b),new Integer(a)};
RE.addGraphics(O);
return null;
}
}
| isc |
davidi2/mopar | src/net/scapeemulator/game/model/player/skills/prayer/Prayer.java | 4074 | package net.scapeemulator.game.model.player.skills.prayer;
import static net.scapeemulator.game.model.player.skills.prayer.PrayerType.*;
import net.scapeemulator.game.model.player.requirement.PrayerPointRequirement;
import net.scapeemulator.game.model.player.requirement.Requirements;
import net.scapeemulator.game.model.player.requirement.SkillRequirement;
import net.scapeemulator.game.model.player.skills.Skill;
/**
* @author David Insley
*/
public enum Prayer {
// Tier one prayer bonuses
THICK_SKIN(1, 50, 83, 5, DEFENCE),
BURST_OF_STRENGTH(4, 50, 84, 7, STRENGTH),
CLARITY_OF_THOUGHT(7, 50, 85, 9, ATTACK),
SHARP_EYE(8, 50, 862, 11, RANGE, MAGIC),
MYSTIC_WILL(9, 50, 863, 13, MAGIC, RANGE),
// Tier two prayer bonuses
ROCK_SKIN(10, 100, 86, 15, DEFENCE),
SUPERHUMAN_STRENGTH(13, 100, 87, 17, STRENGTH),
IMPROVED_REFLEXES(16, 100, 88, 19, ATTACK),
HAWK_EYE(26, 100, 864, 27, RANGE, MAGIC),
MYSTIC_LORE(27, 100, 865, 29, MAGIC, RANGE),
// Tier three prayer bonuses
STEEL_SKIN(28, 200, 92, 31, DEFENCE),
ULTIMATE_STRENGTH(31, 200, 93, 33, STRENGTH),
INCREDIBLE_REFLEXES(34, 200, 94, 35, ATTACK),
EAGLE_EYE(44, 200, 866, 43, RANGE, MAGIC),
MYSTIC_MIGHT(45, 200, 867, 45, MAGIC, RANGE),
// Tier four prayer bonuses
CHIVALRY(60, 400, 1052, 55, DEFENCE, STRENGTH, ATTACK),
PIETY(70, 400, 1053, 57, DEFENCE, STRENGTH, ATTACK),
// Stat restore
RESTORE(19, 23, 89, 21, RAPID_RESTORE),
// Health restore
HEAL(22, 33, 90, 23, RAPID_HEAL),
// Protect item
PROTECT(25, 33, 91, 25, PROTECT_ITEM),
// Overhead prayers TODO differentiate to allow summoning to pair with one other protect
PROTECT_FROM_SUMMONING(35, 200, 1168, 53, OVERHEAD),
PROTECT_FROM_MAGIC(37, 200, 95, 37, OVERHEAD),
PROTECT_FROM_RANGED(40, 200, 96, 39, OVERHEAD),
PROTECT_FROM_MELEE(43, 200, 97, 41, OVERHEAD),
RETRIBUTION(46, 50, 98, 47, OVERHEAD),
REDEMPTION(49, 100, 99, 49, OVERHEAD),
SMITE(52, 300, 100, 51, OVERHEAD);
static {
// TODO chivalry/piety knights training ground requirements
CHIVALRY.requirements.addRequirements();
PIETY.requirements.addRequirements();
}
private final Requirements requirements;
/**
* How many points are drained per tick. One thousand is one point.
*/
private final int drainRate;
/**
* The config id to activate and deactivate this prayer in the prayer tab.
*/
private final int configId;
private final int buttonId;
private final PrayerType[] types;
private HeadIcon headIcon = HeadIcon.NONE;
private Prayer(int levelRequirement, int drainRate, int configId, int buttonId, PrayerType... types) {
requirements = new Requirements();
requirements.addRequirement(new SkillRequirement(Skill.PRAYER, levelRequirement, false, "activate that prayer"));
requirements.addRequirement(PrayerPointRequirement.NON_ZERO_POINTS);
this.drainRate = drainRate;
this.configId = configId;
this.buttonId = buttonId;
this.types = types;
}
public static Prayer forId(int buttonId) {
for (Prayer prayer : values()) {
if (prayer.buttonId == buttonId) {
return prayer;
}
}
return null;
}
public boolean conflicts(Prayer other) {
for (PrayerType type : types) {
for (PrayerType otherType : other.types) {
if (type == otherType) {
return true;
}
}
}
return false;
}
public Requirements getRequirements() {
return requirements;
}
public double getDrainRate() {
return drainRate;
}
public int getConfigId() {
return configId;
}
public PrayerType[] getTypes() {
return types;
}
public HeadIcon getHeadIcon() {
if (headIcon == HeadIcon.NONE) {
headIcon = HeadIcon.forPrayer(this);
}
return headIcon;
}
}
| isc |
jeasinlee/AndroidBasicLibs | basekit/src/main/java/cn/wwah/basekit/base/adapter/helper/DataHelper.java | 2184 | package cn.wwah.basekit.base.adapter.helper;
import java.util.List;
public interface DataHelper<T> {
boolean isEnabled(int position);
/**
* 添加单个数据到列表头部
*
* @param data
*/
void addItemToHead(T data);
/**
* 添加单个数据到列表尾部
*
* @param data 数据
*/
void addItemToLast(T data);
/**
* 添加数据集到列表头部
*
* @param dataList
*/
void addItemsToHead(List<T> dataList);
/**
* 添加数据集到列表尾部
*
* @param dataList
*/
void addItemsToLast(List<T> dataList);
/**
* 添加数据集合到指定位置
*
* @param startPosition 数据添加的位置
* @param dataList 数据集合
*/
void addAll(int startPosition, List<T> dataList);
/**
* 添加单个数据到指定位置
*
* @param startPosition 数据添加的位置
* @param data 数据
*/
void add(int startPosition, T data);
/**
* 获取index对于的数据
*
* @param index 数据座标
* @return 数据对象
*/
T getData(int index);
/**
* 将某一个数据修改
*
* @param oldData 旧的数据
* @param newData 新的数据
*/
void alterObj(T oldData, T newData);
/**
* 修改对应的位置的数据
*
* @param index 修改的位置
* @param data 要代替的的数据
*/
void alterObj(int index, T data);
/**
* 删除对应的数据
*
* @param data
*/
void remove(T data);
/**
* 删除对应位置的数据
*
* @param index
*/
void removeToIndex(int index);
/**
* 替换所有数据
*
* @param dataList
*/
void replaceAll(List<T> dataList);
/**
* 清除所有
*/
void clear();
/**
* 判断数据集合中是否包含这个对象
*
* @param data 判断对象
* @return true|false
*/
boolean contains(T data);
/**
* 覆盖所有数据
*
* @param dataList
*/
void setListAll(List<T> dataList);
}
| mit |
whelanp/sentenial-ws-client | src/main/java/com/sentenial/ws/client/dd/CommunicationLanguage.java | 1851 |
package com.sentenial.ws.client.dd;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CommunicationLanguage.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CommunicationLanguage">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="pt"/>
* <enumeration value="nl"/>
* <enumeration value="fr"/>
* <enumeration value="en"/>
* <enumeration value="it"/>
* <enumeration value="es"/>
* <enumeration value="de"/>
* <enumeration value="sk"/>
* <enumeration value="fr_BE"/>
* <enumeration value="nl_BE"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CommunicationLanguage", namespace = "urn:com:sentenial:origix:ws:common:types")
@XmlEnum
public enum CommunicationLanguage {
@XmlEnumValue("pt")
PT("pt"),
@XmlEnumValue("nl")
NL("nl"),
@XmlEnumValue("fr")
FR("fr"),
@XmlEnumValue("en")
EN("en"),
@XmlEnumValue("it")
IT("it"),
@XmlEnumValue("es")
ES("es"),
@XmlEnumValue("de")
DE("de"),
@XmlEnumValue("sk")
SK("sk"),
@XmlEnumValue("fr_BE")
FR_BE("fr_BE"),
@XmlEnumValue("nl_BE")
NL_BE("nl_BE");
private final String value;
CommunicationLanguage(String v) {
value = v;
}
public String value() {
return value;
}
public static CommunicationLanguage fromValue(String v) {
for (CommunicationLanguage c: CommunicationLanguage.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/servicefabric/mgmt-v2018_02_01/src/main/java/com/microsoft/azure/management/servicefabric/v2018_02_01/ErrorModelError.java | 1429 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.servicefabric.v2018_02_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The error details.
*/
public class ErrorModelError {
/**
* The error code.
*/
@JsonProperty(value = "code")
private String code;
/**
* The error message.
*/
@JsonProperty(value = "message")
private String message;
/**
* Get the error code.
*
* @return the code value
*/
public String code() {
return this.code;
}
/**
* Set the error code.
*
* @param code the code value to set
* @return the ErrorModelError object itself.
*/
public ErrorModelError withCode(String code) {
this.code = code;
return this;
}
/**
* Get the error message.
*
* @return the message value
*/
public String message() {
return this.message;
}
/**
* Set the error message.
*
* @param message the message value to set
* @return the ErrorModelError object itself.
*/
public ErrorModelError withMessage(String message) {
this.message = message;
return this;
}
}
| mit |
geth1b/h1b-coding-interview | src/test/java/com/geth1b/coding/skills/lc/_124_BinaryTreeMaximumPathSum_Test.java | 877 | package com.geth1b.coding.skills.lc;
import com.geth1b.coding.ds.TreeNode;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* @author geth1b
*/
public class _124_BinaryTreeMaximumPathSum_Test {
private _124_BinaryTreeMaximumPathSum solution;
@Before public void setUp() {
solution = new _124_BinaryTreeMaximumPathSum();
}
@Test public void maxPathSum() {
TreeNode root = TreeNode.create("1234567".toCharArray());
assertEquals(18, solution.maxPathSum(root));
}
@Test public void maxPathSum_failedCase1() {
TreeNode root = new TreeNode(-3);
assertEquals(-3, solution.maxPathSum(root));
}
@Test public void maxPathSum_failedCase2() {
TreeNode t1 = new TreeNode(2);
TreeNode t2 = new TreeNode(-1);
t1.left = t2;
assertEquals(2, solution.maxPathSum(t1));
}
}
| mit |
Biokinetica/toornament-client | src/main/java/ch/wisv/toornament/model/MatchDetails.java | 910 | package ch.wisv.toornament.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class MatchDetails extends Match {
private List<Stream> streams;
private List<Vod> vods;
@JsonProperty("private_note")
private String privateNote;
private String note;
public List<Stream> getStreams() {
return streams;
}
public void setStreams(List<Stream> streams) {
this.streams = streams;
}
public List<Vod> getVods() {
return vods;
}
public void setVods(List<Vod> vods) {
this.vods = vods;
}
public String getPrivateNote() {
return privateNote;
}
public void setPrivateNote(String privateNote) {
this.privateNote = privateNote;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/edgegateway/mgmt-v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/PeriodicTimerSourceInfo.java | 3249 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.edgegateway.v2019_03_01;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Periodic timer event source.
*/
public class PeriodicTimerSourceInfo {
/**
* The time of the day that results in a valid trigger. Schedule is
* computed with reference to the time specified up to seconds. If timezone
* is not specified the time will considered to be in device timezone. The
* value will always be returned as UTC time.
*/
@JsonProperty(value = "startTime", required = true)
private DateTime startTime;
/**
* Periodic frequency at which timer event needs to be raised. Supports
* daily, hourly, minutes, and seconds.
*/
@JsonProperty(value = "schedule", required = true)
private String schedule;
/**
* Topic where periodic events are published to IoT device.
*/
@JsonProperty(value = "topic")
private String topic;
/**
* Get the time of the day that results in a valid trigger. Schedule is computed with reference to the time specified up to seconds. If timezone is not specified the time will considered to be in device timezone. The value will always be returned as UTC time.
*
* @return the startTime value
*/
public DateTime startTime() {
return this.startTime;
}
/**
* Set the time of the day that results in a valid trigger. Schedule is computed with reference to the time specified up to seconds. If timezone is not specified the time will considered to be in device timezone. The value will always be returned as UTC time.
*
* @param startTime the startTime value to set
* @return the PeriodicTimerSourceInfo object itself.
*/
public PeriodicTimerSourceInfo withStartTime(DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Get periodic frequency at which timer event needs to be raised. Supports daily, hourly, minutes, and seconds.
*
* @return the schedule value
*/
public String schedule() {
return this.schedule;
}
/**
* Set periodic frequency at which timer event needs to be raised. Supports daily, hourly, minutes, and seconds.
*
* @param schedule the schedule value to set
* @return the PeriodicTimerSourceInfo object itself.
*/
public PeriodicTimerSourceInfo withSchedule(String schedule) {
this.schedule = schedule;
return this;
}
/**
* Get topic where periodic events are published to IoT device.
*
* @return the topic value
*/
public String topic() {
return this.topic;
}
/**
* Set topic where periodic events are published to IoT device.
*
* @param topic the topic value to set
* @return the PeriodicTimerSourceInfo object itself.
*/
public PeriodicTimerSourceInfo withTopic(String topic) {
this.topic = topic;
return this;
}
}
| mit |
aspose-cells/Aspose.Cells-for-Java | Examples/src/AsposeCellsExamples/TechnicalArticles/SettingSharedFormula.java | 843 | package AsposeCellsExamples.TechnicalArticles;
import com.aspose.cells.Cells;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import AsposeCellsExamples.Utils;
public class SettingSharedFormula {
public static void main(String[] args) throws Exception {
String dataDir = Utils.getSharedDataDir(SettingSharedFormula.class) + "TechnicalArticles/";
String filePath = dataDir + "input.xlsx";
// Instantiate a Workbook from existing file
Workbook workbook = new Workbook(filePath);
// Get the cells collection in the first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
// Apply the shared formula in the range i.e.., B2:B14
cells.get("B2").setSharedFormula("=A2*0.09", 13, 1);
// Save the excel file
workbook.save(dataDir + "SSharedFormula_out.xlsx", SaveFormat.XLSX);
}
}
| mit |
diedertimmers/oxAuth | Server/src/main/java/org/xdi/oxauth/model/fido/u2f/RegisterRequestMessageLdap.java | 1620 | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.model.fido.u2f;
import java.io.Serializable;
import org.gluu.site.ldap.persistence.annotation.LdapAttribute;
import org.gluu.site.ldap.persistence.annotation.LdapJsonObject;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterRequestMessage;
/**
* U2F registration requests
*
* @author Yuriy Movchan Date: 06/02/2015
*/
public class RegisterRequestMessageLdap extends RequestMessageLdap implements Serializable {
private static final long serialVersionUID = -2242931562244920584L;
@LdapJsonObject
@LdapAttribute(name = "oxRequest")
private RegisterRequestMessage registerRequestMessage;
public RegisterRequestMessageLdap() {}
public RegisterRequestMessageLdap(RegisterRequestMessage registerRequestMessage) {
this.registerRequestMessage = registerRequestMessage;
this.requestId = registerRequestMessage.getRequestId();
}
public RegisterRequestMessage getRegisterRequestMessage() {
return registerRequestMessage;
}
public void setRegisterRequestMessage(RegisterRequestMessage registerRequestMessage) {
this.registerRequestMessage = registerRequestMessage;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RegisterRequestMessageLdap [id=").append(id).append(", registerRequestMessage=").append(registerRequestMessage).append(", requestId=")
.append(requestId).append(", creationDate=").append(creationDate).append("]");
return builder.toString();
}
}
| mit |
hpe-idol/find | webapp/core/src/test/java/com/hp/autonomy/frontend/find/core/configuration/SavedSearchConfigTest.java | 2068 | /*
* Copyright 2015-2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.core.configuration;
import com.hp.autonomy.frontend.configuration.ConfigException;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class SavedSearchConfigTest {
private SavedSearchConfig savedSearchConfig;
@Before
public void setUp() {
savedSearchConfig = new SavedSearchConfig.Builder()
.setPollForUpdates(true)
.setPollingInterval(5)
.build();
}
@Test
public void merge() {
assertEquals(savedSearchConfig, new SavedSearchConfig.Builder().build().merge(savedSearchConfig));
}
@Test
public void mergeNoDefaults() {
assertEquals(savedSearchConfig, savedSearchConfig.merge(null));
}
@Test
public void basicValidate() throws ConfigException {
savedSearchConfig.basicValidate(null);
}
@Test
public void basicValidateWhenDisabled() throws ConfigException {
new SavedSearchConfig.Builder()
.setPollForUpdates(false)
.setPollingInterval(-1)
.build()
.basicValidate(null);
}
@Test
public void basicValidateWhenInvalid() throws ConfigException {
try {
new SavedSearchConfig.Builder()
.setPollForUpdates(true)
.setPollingInterval(-1)
.build()
.basicValidate(null);
fail("Exception should have been thrown");
} catch(final ConfigException e) {
assertThat("Exception has the correct message",
e.getMessage(),
containsString("Polling interval must be positive"));
}
}
}
| mit |
sdgdsffdsfff/csustRepo | trunk/src/com/yunstudio/struts/action/BaseAction.java | 1876 | package com.yunstudio.struts.action;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.CompoundRoot;
/**
* 通用Action类:存放通用的Action方法
* @author tocean
*
*/
public class BaseAction extends ActionSupport{
private static final long serialVersionUID = 3457764558820779292L;
public int page=1;//当前页码
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public HttpServletRequest getRequest(){
return ServletActionContext.getRequest();
}
public HttpServletResponse getResponse(){
return ServletActionContext.getResponse();
}
public HttpSession getSession(){
return getRequest().getSession();
}
public ServletContext getServletContext(){
return ServletActionContext.getServletContext();
}
public ActionContext getActionContext() {
return ActionContext.getContext();
}
public Map<String, Object> getParameters() {
return ActionContext.getContext().getParameters();
}
public Map<String, Object> getSessionMap() {
return ActionContext.getContext().getSession();
}
public Map<String, Object> getContextMap() {
return ActionContext.getContext().getContextMap();
}
public CompoundRoot getRoot() {
return ActionContext.getContext().getValueStack().getRoot();
}
public String getRealyPath(String path){
return getServletContext().getRealPath(path);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/SyncFullSchemaTableColumn.java | 3235 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sql.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Properties of the column in the table of database full schema. */
@Immutable
public final class SyncFullSchemaTableColumn {
@JsonIgnore private final ClientLogger logger = new ClientLogger(SyncFullSchemaTableColumn.class);
/*
* Data size of the column.
*/
@JsonProperty(value = "dataSize", access = JsonProperty.Access.WRITE_ONLY)
private String dataSize;
/*
* Data type of the column.
*/
@JsonProperty(value = "dataType", access = JsonProperty.Access.WRITE_ONLY)
private String dataType;
/*
* Error id of the column.
*/
@JsonProperty(value = "errorId", access = JsonProperty.Access.WRITE_ONLY)
private String errorId;
/*
* If there is error in the table.
*/
@JsonProperty(value = "hasError", access = JsonProperty.Access.WRITE_ONLY)
private Boolean hasError;
/*
* If it is the primary key of the table.
*/
@JsonProperty(value = "isPrimaryKey", access = JsonProperty.Access.WRITE_ONLY)
private Boolean isPrimaryKey;
/*
* Name of the column.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/*
* Quoted name of the column.
*/
@JsonProperty(value = "quotedName", access = JsonProperty.Access.WRITE_ONLY)
private String quotedName;
/**
* Get the dataSize property: Data size of the column.
*
* @return the dataSize value.
*/
public String dataSize() {
return this.dataSize;
}
/**
* Get the dataType property: Data type of the column.
*
* @return the dataType value.
*/
public String dataType() {
return this.dataType;
}
/**
* Get the errorId property: Error id of the column.
*
* @return the errorId value.
*/
public String errorId() {
return this.errorId;
}
/**
* Get the hasError property: If there is error in the table.
*
* @return the hasError value.
*/
public Boolean hasError() {
return this.hasError;
}
/**
* Get the isPrimaryKey property: If it is the primary key of the table.
*
* @return the isPrimaryKey value.
*/
public Boolean isPrimaryKey() {
return this.isPrimaryKey;
}
/**
* Get the name property: Name of the column.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Get the quotedName property: Quoted name of the column.
*
* @return the quotedName value.
*/
public String quotedName() {
return this.quotedName;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
marmotka/Java-Exercises-Basics | Lesson8StringMethods/src/Task01LowerUpper.java | 1044 |
import java.util.Scanner;
public class Task01LowerUpper {
public static void main(String[] args) {
String text1 = readInput();
String text2 = readInput();
System.out.print(text1.toUpperCase() + " ");
System.out.println(text1.toLowerCase());
System.out.print(text2.toUpperCase() + " ");
System.out.print(text2.toLowerCase());
}
static boolean validateInput(String text) {
if (text.length() > 40) {
System.out.println("The text is too long! ");
return false;
} else {
for (int i = 0; i < text.length(); i++) {
if (!((text.charAt(i) >= 'a' && text.charAt(i) <= 'z')
|| (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z'))) {
System.out.println("Text must contain latin letters only! ");
return false;
}
}
}
return true;
}
static String readInput() {
Scanner sc = new Scanner(System.in);
String text;
do {
System.out.println("Enter string with maximum 40 letters containing [a-z] and [A-Z]: ");
text = sc.nextLine();
} while (!(validateInput(text)));
return text;
}
}
| mit |
RabadanLab/Pegasus | resources/hsqldb-2.2.7/hsqldb/src/org/hsqldb/types/NullType.java | 3611 | /* Copyright (c) 2001-2011, The HSQL Development Group
* 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 HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.hsqldb.types;
import org.hsqldb.Session;
import org.hsqldb.SessionInterface;
import org.hsqldb.Tokens;
import org.hsqldb.error.Error;
import org.hsqldb.error.ErrorCode;
/**
* Type subclass for untyped NULL values.<p>
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 2.0.1
* @since 1.9.0
*/
public final class NullType extends Type {
static final NullType nullType = new NullType();
private NullType() {
super(Types.SQL_ALL_TYPES, Types.SQL_ALL_TYPES, 0, 0);
}
public int displaySize() {
return 4;
}
public int getJDBCTypeCode() {
return typeCode;
}
public Class getJDBCClass() {
return java.lang.Void.class;
}
public String getJDBCClassName() {
return "java.lang.Void";
}
public String getNameString() {
return Tokens.T_NULL;
}
public String getDefinition() {
return Tokens.T_NULL;
}
public Type getAggregateType(Type other) {
return other;
}
public Type getCombinedType(Session session, Type other, int operation) {
return other;
}
public int compare(Session session, Object a, Object b) {
throw Error.runtimeError(ErrorCode.U_S0500, "NullType");
}
public Object convertToTypeLimits(SessionInterface session, Object a) {
return null;
}
public Object convertToType(SessionInterface session, Object a,
Type otherType) {
return null;
}
public Object convertToDefaultType(SessionInterface session, Object a) {
return null;
}
public String convertToString(Object a) {
throw Error.runtimeError(ErrorCode.U_S0500, "NullType");
}
public String convertToSQLString(Object a) {
throw Error.runtimeError(ErrorCode.U_S0500, "NullType");
}
public boolean canConvertFrom(Type otherType) {
return true;
}
public static Type getNullType() {
return nullType;
}
}
| mit |
IrtazaSafi/CloudGaming | CentralServer/Client.java | 1447 | import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
public class Client implements Serializable {
String inetAddress;
int port;
int id;
int performance;
boolean occupied;
public Client(String inetAddress, int port) {
this.inetAddress = inetAddress;
this.port = port;
this.id = 0;
this.performance = 0;
this.occupied = false;
}
}
class ClientManager {
ArrayList<Client> curClients = new ArrayList<>();
int clientIDcounter = 0;
boolean isClient(Client input) {
for (Client curClient : curClients) {
if (input.inetAddress.equals(curClient.inetAddress) && input.port == curClient.port) {
return true;
}
}
return false;
}
void addClient(Client toAdd) {
curClients.add(toAdd);
}
int size() {
return curClients.size();
}
Client getClient(InetAddress inetAddress, int port) {
for (Client curClient : curClients) {
if (curClient.inetAddress.equals(inetAddress) && curClient.port == port) {
return curClient;
}
}
return null;
}
void setAllAvailable() {
for (Client curClient : curClients) {
curClient.occupied = false;
}
}
int clientIDgen() {
return clientIDcounter++;
}
} | mit |
psyco4j/shardy | src/main/java/maniac/lee/shardy/shard/TableMapping.java | 1188 | package maniac.lee.shardy.shard;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import maniac.lee.shardy.sqlparser.DruidSqlParser;
import maniac.lee.shardy.sqlparser.ISqlParser;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by lipeng on 16/2/18.
*/
public class TableMapping {
public static Map<MappedStatement, String> map = new ConcurrentHashMap<>();
public static String getTableName(MappedStatement mappedStatement, Object param) {
String re = map.get(mappedStatement);
if (re == null) {
ISqlParser iSqlParser = new DruidSqlParser();
try {
SqlSource sqlSource = mappedStatement.getSqlSource();
if (sqlSource instanceof ExtendedSqlSource) {
iSqlParser.init(((ExtendedSqlSource) sqlSource).getBoundSqlRaw(param).getSql());
re = iSqlParser.getTableName();
map.put(mappedStatement, re);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return re;
}
}
| mit |
spauny/xmlsoccer | src/main/java/com/github/pabloo99/xmlsoccer/webservice/package-info.java | 192 | @javax.xml.bind.annotation.XmlSchema(namespace = "http://xmlsoccer.com/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.github.pabloo99.xmlsoccer.webservice;
| mit |
David-Carlson/BlackBody | src/org/sunflow/core/shader/TexturedShinyDiffuseShader.java | 853 | package org.sunflow.core.shader;
import org.sunflow.SunflowAPI;
import org.sunflow.core.ParameterList;
import org.sunflow.core.ShadingState;
import org.sunflow.core.Texture;
import org.sunflow.core.TextureCache;
import org.sunflow.image.Color;
public class TexturedShinyDiffuseShader extends ShinyDiffuseShader {
private Texture tex;
public TexturedShinyDiffuseShader() {
tex = null;
}
public boolean update(ParameterList pl, SunflowAPI api) {
String filename = pl.getString("texture", null);
if (filename != null)
tex = TextureCache.getTexture(api.resolveTextureFilename(filename), false);
return tex != null && super.update(pl, api);
}
public Color getDiffuse(ShadingState state) {
return tex.getPixel(state.getUV().x, state.getUV().y);
}
} | mit |
Delthas/JavaUI | src/main/java/fr/delthas/javaui/AtlasTexture.java | 464 | package fr.delthas.javaui;
final class AtlasTexture implements Texture {
final Atlas atlas;
final int i;
boolean destroyed = false;
AtlasTexture(Atlas atlas, int i) {
this.atlas = atlas;
this.i = i;
}
public void destroy() {
if (destroyed) {
return;
}
destroyed = true;
atlas.destroyImage(i);
}
public int getWidth() {
return atlas.width;
}
public int getHeight() {
return atlas.height;
}
}
| mit |