repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
itman85/PiArchiver | PiArchiverLocal/src/main/java/com/piarchiverlocal/util/PiConfig.java | 2387 | package com.piarchiverlocal.util;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by phannguyen-pc on 3/23/2014.
*/
public class PiConfig {
static Logger log4j = Logger.getLogger(PiConfig.class.getName());
public static final String DOWNLOAD_PAGE_LOCAL_NAME = "\\LocalPage.html";
public static final String DOWNLOAD_PAGE_ORIGINAL_NAME = "\\OriginalPage.html";
public static final String EXTRACT_TEXT_FILE_NAME = "\\WebPageText.txt";
private static PiConfig instance = null;
private String archiverFolderPath;
private String embeddeddbPath;
protected PiConfig() {
// Exists only to defeat instantiation.
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "piconfig.properties";
input = PiConfig.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
log4j.error("Unable to find config file:" + filename);
archiverFolderPath="";
return;
}
log4j.info("Read OK config file:" + filename);
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
archiverFolderPath = prop.getProperty("piarchiverfolder");
embeddeddbPath = prop.getProperty("embedded_databasepath");
} catch (IOException ex) {
log4j.error(ex.getStackTrace());
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
log4j.error(e.getStackTrace());
}
}
}
}
public static PiConfig getInstance() {
if(instance == null) {
instance = new PiConfig();
}
return instance;
}
public String getArchiverFolderPath() {
return archiverFolderPath;
}
public void setArchiverFolderPath(String archiverFolderPath) {
this.archiverFolderPath = archiverFolderPath;
}
public String getEmbeddeddbPath() {
return embeddeddbPath;
}
public void setEmbeddeddbPath(String embeddeddbPath) {
this.embeddeddbPath = embeddeddbPath;
}
}
| apache-2.0 |
EvilMcJerkface/atlasdb | atlasdb-impl-shared/src/main/java/com/palantir/atlasdb/cleaner/CachingPuncherStore.java | 3055 | /*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.cleaner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* Wrap another PuncherStore, optimizing the #get() operation to operate on a local cache, only
* invoking the underlying #get() on cache misses. To improve the cache hit rate, we round the wall
* time to look up in the cache to a multiple of granularityMillis; this is safe because we always
* round down.
*
* @author jweel
*/
public final class CachingPuncherStore implements PuncherStore {
private static final int CACHE_SIZE = 64000;
public static CachingPuncherStore create(final PuncherStore puncherStore, long granularityMillis) {
LoadingCache<Long, Long> timeMillisToTimestamp = CacheBuilder.newBuilder()
.maximumSize(CACHE_SIZE)
.build(new CacheLoader<Long, Long>() {
@Override
public Long load(Long timeMillis) throws Exception {
return puncherStore.get(timeMillis);
}
});
return new CachingPuncherStore(puncherStore, timeMillisToTimestamp, granularityMillis);
}
private final PuncherStore puncherStore;
private final LoadingCache<Long, Long> timeMillisToTimeStamp;
private final long granularityMillis;
private CachingPuncherStore(
PuncherStore puncherStore, LoadingCache<Long, Long> timeMillisToTimestamp, long granularityMillis) {
this.puncherStore = puncherStore;
this.timeMillisToTimeStamp = timeMillisToTimestamp;
this.granularityMillis = granularityMillis;
}
@Override
public boolean isInitialized() {
return puncherStore.isInitialized();
}
@Override
public void put(long timestamp, long timeMillis) {
puncherStore.put(timestamp, timeMillis);
}
@Override
public Long get(Long timeMillis) {
long approximateTimeMillis = timeMillis - (timeMillis % granularityMillis);
return timeMillisToTimeStamp.getUnchecked(approximateTimeMillis);
}
@Override
public long getMillisForTimestamp(long timestamp) {
// Note: at the time of writing this (3-21-16), this operation is only
// used optionally by the backup CLI and doesn't need to be cached
return puncherStore.getMillisForTimestamp(timestamp);
}
}
| apache-2.0 |
embraceplus/android | embraceplus_android_v1.8b9_2015_feb_07/src/com/embraceplus/ble/BluetoothLeService.java | 16353 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.embraceplus.ble;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.UUID;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import com.embraceplus.app.R;
import com.embraceplus.app.SearchActivity;
import com.embraceplus.ble.utils.Constants;
import com.embraceplus.ble.utils.GlobalHandlerUtil;
import com.embraceplus.ble.utils.ServiceManager;
import com.embraceplus.model.EmbraceMsg;
import com.embraceplus.store.ExCommandManager;
import com.embraceplus.utils.EmbraceBatteryUtil;
import com.embraceplus.utils.Optional;
import com.embraceplus.utils.PhoneBatteryListenerUtil;
/**
* Service for managing connection and data communication with a GATT server
* hosted on a given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
// private String mBluetoothDeviceAddress;
private Handler myHandler = new Handler();
private Handler embraceHandler;
private boolean embraceConnected = false;
public static int currentRssi = 0;
// public final static String ACTION_GATT_SERVICES_RSSIR =
// "com.example.bluetooth.le.RSSI_R";
// Implements callback methods for GATT events that the app cares about. For
// example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
currentRssi = rssi;
// BluetoothLeService.this.sendBroadcast(new
// Intent(ACTION_GATT_SERVICES_RSSIR));
if (rssi < Constants.BLEMinValue) {
// final Optional<EmbraceMsg> msg = DbBuilder.getInstant()
// .getExCommandByNotification(
// Constants.notification_type_OUTOFSERVICE);
final Optional<EmbraceMsg> msg = ExCommandManager.getInstance()
.getExCommandByNotification(Constants.notification_type_OUTOFSERVICE);
if (msg.notEmpty()) {
if (!ServiceManager.getInstant().isRingOutofRangeMsgSended()) {
if (ServiceManager.getInstant().getBluetoothService() != null) {
ServiceManager
.getInstant()
.getBluetoothService()
.writeEffectCommand(
msg.get().getFXCommand());
}
ServiceManager.getInstant().setRingOutofRangeMsgSended(
true);
}
}
} else if (rssi >= Constants.BLEMinValue) {
ServiceManager.getInstant().setRingOutofRangeMsgSended(false);
}
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == 2 && 0 == status) {
// We can't rely on this event, so we'll move most of our status
// switching code to the setIsConnected function
if (gatt != null)
gatt.discoverServices();
ServiceManager.getInstant().setConnectStateChangeByUser(false);
ServiceManager.getInstant().setThisWakeupEmbraceLowPowerMsgSended(
false);
BluetoothLeService.this.setIsConnected(true);
ServiceManager.getInstant().stopAutoConnectThread();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED || (newState == 2 && status == 133)) {
//disconnect();
if(newState == BluetoothProfile.STATE_DISCONNECTED){
BluetoothLeService.this.setIsConnected(false);
}
if (!ServiceManager.getInstant().isConnectStateChangeByUser()) {
// AutoConnectUtil.getInstant().startAutoConnectThread();
ServiceManager.getInstant().startAutoConnectThread();
}
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
System.out.println("::onServicesDiscovered()");
PhoneBatteryListenerUtil.getInstant().registPhoneBatteryListener();
PhoneBatteryListenerUtil.getInstant().startListenRssi();
PhoneBatteryListenerUtil.getInstant().startListenEmbraceBattery();
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
byte[] notifValue = characteristic.getValue();
BluetoothLeService.this.setIsConnected(true);
// int embraceBattery = (int)notifValue[0];
int embraceBattery = 0;
try {
embraceBattery = readUnsignedShort(notifValue);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("onCharacteristicRead() embraceBattery:"
// + embraceBattery);
if (embraceHandler != null) {
Message msg = Message.obtain(embraceHandler,
Constants.getEmbraceBattery);
msg.obj = embraceBattery;
msg.sendToTarget();
}
String embraceBatteryValue = EmbraceBatteryUtil
.getEmbraceBatteryValue(embraceBattery);
if (embraceBatteryValue == null || embraceBatteryValue.equals("")) {
return;
}
String embraceBatteryStringValue = embraceBatteryValue.substring(0,
embraceBatteryValue.indexOf("%"));
int embraceBatteryIntValue = Integer
.parseInt(embraceBatteryStringValue);
if (embraceBatteryIntValue <= Constants.minBattery
&& !ServiceManager.getInstant()
.isThisWakeupEmbraceLowPowerMsgSended()) {
// final Optional<EmbraceMsg> EmbraceBatteryMsg = DbBuilder
// .getInstant().getExCommandByNotification(
// Constants.notification_type_BATTERYEMBRACCE);
final Optional<EmbraceMsg> EmbraceBatteryMsg = ExCommandManager.getInstance().
getExCommandByNotification(Constants.notification_type_BATTERYEMBRACCE);
if (EmbraceBatteryMsg.notEmpty()) {
ServiceManager
.getInstant()
.getBluetoothService()
.writeEffectCommand(
EmbraceBatteryMsg.get().getFXCommand());
PhoneBatteryListenerUtil.getInstant()
.setEmbraceBatteryThreadActived(true);
ServiceManager.getInstant()
.setThisWakeupEmbraceLowPowerMsgSended(true);
}
}
}
private int readUnsignedShort(byte[] readBuffer) throws IOException {
if (readBuffer == null || readBuffer.length < 2)
return 0;
byte[] uint64 = new byte[3];
uint64[2] = 0;
System.arraycopy(readBuffer, 0, uint64, 0, 2);
BigInteger intg = new BigInteger(reverse(uint64));
return intg.intValue();
}
private byte[] reverse(byte[] b) {
byte[] temp = new byte[b.length];
for (int i = 0; i < b.length; i++) {
temp[i] = b[b.length - 1 - i];
}
return temp;
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
// System.out.println("::onCharacteristicWrite()");
// System.out.println(status);
// Do nothing ???
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
// Do nothing ???
}
};
public class LocalBinder extends Binder {
public BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that
// BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular
// example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter
// through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
private void setIsConnected(boolean connected) {
if (connected) {
embraceConnected = true;
notifyStateChange(true);
} else {
embraceConnected = false;
notifyStateChange(false);
}
}
/**
* Tells if the device is reliabily connected. True mean connected and ready
* to use False means connecting, disconnecting or disconnected.
*
* @return
*/
public boolean isEmbraceAvailable() {
return embraceConnected;
}
public void notifyStateChange(boolean connected) {
int connectedMessage = Constants.handler_msg_disconnect_server;
if (connected)
connectedMessage = Constants.handler_msg_connected_server;
if (GlobalHandlerUtil.getInstant().getDemoHandler().notEmpty()) {
Message msg = Message.obtain(GlobalHandlerUtil.getInstant()
.getDemoHandler().get(), connectedMessage);
msg.sendToTarget();
}
}
public boolean connect(final String address) {
if (!initialize()) {
return false;
}
if (mBluetoothAdapter == null || address == null) {
return false;
}
final BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Previously connected device. Try to reconnect.
/*if (mBluetoothDeviceAddress != null
&& address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
Log.d(TAG,
"Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
return true;
} else {
return false;
}
}*/
if(mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
}
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
// mBluetoothGatt = device.connectGatt(this, true, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
// mBluetoothDeviceAddress = address;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The
* disconnection result is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
BluetoothLeService.this.setIsConnected(false);
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
}
/**
* After using a given BLE device, the app must call this method to ensure
* resources are released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read
* result is reported asynchronously through the
* {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic
* The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
if (characteristic == null) {
Log.w(TAG, "Characteristic is null");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
public void readEmbraceBattery() {
// use below code to read battery...
// ServiceManager.getInstant().getBluetoothService().readEmbraceBattery();
UUID batteryserviceUUID = UUID
.fromString(Constants.Battery_service_uuid);
UUID batteryNotifyUUID = UUID
.fromString(Constants.Battery_service_characteristics_uuid);
if (mBluetoothGatt != null
&& mBluetoothGatt.getService(batteryserviceUUID) != null) {
BluetoothGattCharacteristic notifyCharacteristic3 = mBluetoothGatt
.getService(batteryserviceUUID).getCharacteristic(
batteryNotifyUUID);
readCharacteristic(notifyCharacteristic3);
}
}
public void writeEffectCommand(byte[] msg) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
if (msg == null) {
Log.w(TAG, "Message is null");
return;
}
List<BluetoothGattService> services = mBluetoothGatt.getServices();
UUID serviceUUID = UUID.fromString(Constants.service_uuid);
UUID writeUUID = UUID.fromString(Constants.write_uuid_effect);
/*
* UUID serviceUUID =
* UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); UUID
* writeUUID = UUID.fromString("00002A06-0000-1000-8000-00805f9b34fb");
*/
if (mBluetoothGatt == null
|| mBluetoothGatt.getService(serviceUUID) == null) {
/*
* System.out.println(mBluetoothGatt);
* System.out.println(mBluetoothGatt.getService(serviceUUID));
* System.out.println("aaaaaa");
*/
return;
}
BluetoothGattCharacteristic writeCharacteristic = mBluetoothGatt
.getService(serviceUUID).getCharacteristic(writeUUID);
writeCharacteristic.setValue(msg);
mBluetoothGatt.writeCharacteristic(writeCharacteristic);
}
public void readRssi() {
if (mBluetoothGatt != null) {
mBluetoothGatt.readRemoteRssi();
}
}
public Handler getMyHandler() {
return myHandler;
}
public void setMyHandler(Handler myHandler) {
this.myHandler = myHandler;
}
public Handler getEmbraceHandler() {
return embraceHandler;
}
public void setEmbraceHandler(Handler embraceHandler) {
this.embraceHandler = embraceHandler;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
ServiceManager.getInstant().setBluetoothService(this);
SearchActivity.i = 200;
}
Handler handler = new Handler();
@Override
public void onDestroy() {
super.onDestroy();
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
gattServiceIntent.putExtra("needConnect", embraceConnected);
this.startService(gattServiceIntent);
if(embraceConnected){
handler.postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences deviceadd = BluetoothLeService.this.getSharedPreferences("deviceAddress", 0);
String previousAddress = deviceadd.getString("address", "");
if (ServiceManager.getInstant().getBluetoothService() != null && previousAddress != null){
ServiceManager.getInstant().getBluetoothService().connect(previousAddress);
}
}
}, 3000);
}
}
/* @Override
public int onStartCommand(Intent intent, int flags, int startId)
{
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
// return START_REDELIVER_INTENT;
}*/
//@Override
//public int onStartCommand(Intent intent, int flags, int startId) {
// return START_STICKY;
//}
}
| apache-2.0 |
sajavadi/pinot | thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/datalayer/dto/AnomalyFeedbackDTO.java | 915 | package com.linkedin.thirdeye.datalayer.dto;
import com.linkedin.thirdeye.anomalydetection.context.AnomalyFeedback;
import com.linkedin.thirdeye.constant.AnomalyFeedbackType;
import java.io.Serializable;
import com.linkedin.thirdeye.datalayer.pojo.AnomalyFeedbackBean;
public class AnomalyFeedbackDTO extends AnomalyFeedbackBean implements AnomalyFeedback, Serializable {
private static final long serialVersionUID = 1L;
public AnomalyFeedbackDTO() {
this.setFeedbackType(AnomalyFeedbackType.NO_FEEDBACK);
this.setComment("");
}
public AnomalyFeedbackDTO(AnomalyFeedback anomalyFeedback) {
this();
if (anomalyFeedback != null) {
if (anomalyFeedback.getFeedbackType() != null) {
this.setFeedbackType(anomalyFeedback.getFeedbackType());
}
if (anomalyFeedback.getFeedbackType() != null) {
this.setComment(anomalyFeedback.getComment());
}
}
}
}
| apache-2.0 |
JohnCny/PCCREDIT_QZ | src/java/com/cardpay/pccredit/intopieces/service/BackupDBService.java | 2809 | package com.cardpay.pccredit.intopieces.service;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.cardpay.pccredit.common.UploadFileTool;
import com.cardpay.pccredit.intopieces.constant.Constant;
import com.cardpay.pccredit.intopieces.model.QzApplnAttachmentBatch;
import com.cardpay.pccredit.intopieces.model.QzApplnAttachmentDetail;
import com.cardpay.pccredit.intopieces.model.QzApplnAttachmentList;
import com.cardpay.pccredit.intopieces.service.UploadDeamonService.UploadThread;
import com.sunyard.TransEngine.exception.SunTransEngineException;
/**
* java 程序 导入导出数据库 做到程序定时 ( 结合 quartz,log) 自动备份,防止数据丢失
*
* @author leiwei 2011 - 12 - 1
*
*/
@Service
public class BackupDBService {
public static final Logger logger = Logger.getLogger(UploadDeamonService.class);
@Autowired
private ThreadPoolTaskExecutor dmpDB;
Runtime runtime = Runtime.getRuntime();
Process process = null;
boolean isSuccess = false;
/**
* 备份、还原 oracle 数据库的方法
*
* @param cmdStr
* 备份命令 ( 即导出 )
*/
public boolean backupORreductionOracleDB(String cmdStr) {
try {
logger.info("开始备份");
process = runtime.exec(cmdStr);
isSuccess = true;
logger.info("备份完成");
} catch (IOException e) {
logger.info(e.getMessage(), e);
}
return isSuccess;
}
// 上传
public void doDmp(String cmdStr) {
// 前一次任务未完跳过本次
logger.info("getActiveCount():" + dmpDB.getActiveCount());
if (dmpDB.getActiveCount() > 0) {
return;
}
try {
dmpDB.execute(new dmpDBThread(cmdStr));
} catch (Exception e) {
// TODO Auto-generated catch block
logger.info("备份任务执行出错:", e);
}
}
// 上传线程
public class dmpDBThread implements Runnable {
String cmdStr;
public dmpDBThread(String cmdStr) {
this.cmdStr = cmdStr;
}
@Override
public void run() {
backupORreductionOracleDB(cmdStr);
}
}
/**
*
* 测试
*/
public static void main(String[] args) {
// oracle 备份、还原命令
String backupCmd = "exp scott/tiger@172.18.27.146/lworcl file=d:/javaDB.dmp full=y";
boolean reSuccess = new BackupDBService().backupORreductionOracleDB(backupCmd);
System.out.println(reSuccess);
}
}
| apache-2.0 |
ryanlfoster/SiteRenderer | site-renderer-api/src/main/java/com/terrabeata/wcm/siteRenderer/api/SiteRenderManager.java | 561 | package com.terrabeata.wcm.siteRenderer.api;
import java.util.Enumeration;
import org.apache.sling.event.jobs.Queue;
import com.terrabeata.wcm.siteRenderer.api.exception.RenderingException;
public interface SiteRenderManager {
Enumeration<Publisher> getPublishers();
void registerPublisher(Publisher publisher);
void unregisterPublisher(Publisher publisher);
Queue getQueue();
void publishTree(ResourceConfiguration resource)
throws RenderingException;
void publishResource(ResourceConfiguration resource)
throws RenderingException;
}
| apache-2.0 |
McLeodMoores/starling | projects/engine/src/main/java/com/opengamma/engine/marketdata/availability/MarketDataAvailabilityFilter.java | 3558 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.marketdata.availability;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.marketdata.MarketDataProvider;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.id.ExternalBundleIdentifiable;
import com.opengamma.id.ExternalIdentifiable;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.util.PublicSPI;
/**
* Used to obtain the availability status of market data.
* <p>
* This availability check may be external to a {@link MarketDataProvider} implementation to allow arbitrary filtering rules to be configured
* independently to the data connection. It may then be used as the basis to create a more closely coupled {@link MarketDataAvailabilityProvider}
* using the {@link #withProvider} method. This is intended for additional configuration of a {@code MarketDataProvider} instance. Most consumers
* of market data will use a {@code MarketDataAvailabilityProvider} as they will also require value resolution rather than just availability
* indication.
*/
@PublicSPI
public interface MarketDataAvailabilityFilter {
/**
* Tests whether a data requirement can be satisfied.
* <p>
* The target described by the requirement is resolved and described formally as the {@code targetSpec} parameter. This may be null if the target
* reference could not be resolved. The resolved form, if the object exists within the system, may be passed as the {@code target} parameter.
* If the object cannot be resolved to an item of the type indicated by the target specification, a minimum of
* {@link ExternalBundleIdentifiable}, {@link ExternalIdentifiable} or {@link UniqueIdentifiable} will be passed.
* <p>
* If this returns true the related {@link MarketDataAvailabilityProvider} instance would return a suitable {@link ValueSpecification} for the data provider.
*
* @param targetSpec the resolved target specification from the data requirement, not null
* @param target the resolved target the requirement corresponds to, not null (unless the target specification is {@link ComputationTargetSpecification#NULL})
* @param desiredValue the market data requirement to test, not null
* @return true if the value can be satisfied, false otherwise
* @throws MarketDataNotSatisfiableException if the requirement must not be satisfied
*/
boolean isAvailable(ComputationTargetSpecification targetSpec, Object target, ValueRequirement desiredValue) throws MarketDataNotSatisfiableException;
/**
* Combines this filter with a {@link MarketDataAvailabilityProvider} to produce resolved value specifications for items that would pass the filter.
* <p>
* Typically this will be used by a {@link MarketDataProvider} that has been initialized with an externally provided availability filter. This should be
* used in place of a provider just calling {@link #isAvailable} on the filter as the filter may need to perform conversion of the resolution parameters
* before they are passed to the underlying provider instance.
*
* @param provider the base provider that can construct value specifications corresponding to the {@code MarketDataProvider}
* @return a {@link MarketDataAvailabilityProvider} instance
*/
MarketDataAvailabilityProvider withProvider(MarketDataAvailabilityProvider provider);
}
| apache-2.0 |
SAG-KeLP/kelp-core | src/main/java/it/uniroma2/sag/kelp/predictionfunction/regressionfunction/UnivariateRegressionFunction.java | 2078 | /*
* Copyright 2014 Simone Filice and Giuseppe Castellucci and Danilo Croce and Roberto Basili
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.uniroma2.sag.kelp.predictionfunction.regressionfunction;
import java.util.Arrays;
import java.util.List;
import it.uniroma2.sag.kelp.data.example.Example;
import it.uniroma2.sag.kelp.data.label.Label;
import it.uniroma2.sag.kelp.predictionfunction.model.BinaryModel;
/**
* It is a univariate regression prediction function. Univariate
* means that the output is a single real value associated to a specific property.
*
* @author Simone Filice
*
*/
public abstract class UnivariateRegressionFunction implements RegressionFunction{
/**
*
*/
private static final long serialVersionUID = 3574945060218624003L;
protected Label property;
/**
* @param positiveClass the label associated to the positive class
*/
@Override
public void setLabels(List<Label> labels) {
if(labels.size()!=1){
throw new IllegalArgumentException("A UnivariateRegressor can predict a single property");
}
else{
this.property=labels.get(0);
}
}
/**
* @return the label associated to the property
*/
@Override
public List<Label> getLabels() {
return Arrays.asList(property);
}
@Override
public abstract UnivariateRegressionOutput predict(Example example);
/**
* @return the model
*/
public abstract BinaryModel getModel();
@Override
public void reset() {
this.getModel().reset();
}
}
| apache-2.0 |
jhrcek/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/canvas/command/SetChildNodeCommand.java | 2322 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.client.canvas.command;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
public class SetChildNodeCommand extends AbstractCanvasGraphCommand {
protected final Node parent;
protected final Node candidate;
public SetChildNodeCommand(final Node parent,
final Node candidate) {
this.parent = parent;
this.candidate = candidate;
}
@Override
@SuppressWarnings("unchecked")
protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) {
return new org.kie.workbench.common.stunner.core.graph.command.impl.SetChildNodeCommand(parent,
candidate);
}
@Override
protected AbstractCanvasCommand newCanvasCommand(final AbstractCanvasHandler context) {
return new SetCanvasChildNodeCommand(parent,
candidate);
}
public Node getParent() {
return parent;
}
public Node getCandidate() {
return candidate;
}
@Override
public String toString() {
return getClass().getSimpleName() +
" [candidate=" + getUUID(getCandidate()) + "," +
"parent=" + getUUID(getParent()) + "]";
}
}
| apache-2.0 |
sbobhate/5-to-the-2 | Source Code/5x5TicTacToe/src/ec327/project/x5tictactoe/SoundPalette.java | 2552 | package ec327.project.x5tictactoe;
/*
* @author Micheal Reavey
* EC327, Spring 2014
* Boston University, Boston, MA
*/
public class SoundPalette {
private double semitone = Math.pow(2.0f, 1/12.f);
private double base_freq = 440.f;
//These are all pitches, referred to by their pitch names for convenience
//Accessed from Sample class
protected double g5 = base_freq*(double)Math.pow(semitone, 23);
protected double e5 = base_freq*(double)Math.pow(semitone, 19);
protected double d5 = base_freq*(double)Math.pow(semitone, 17);
protected double c5 = base_freq*(double)Math.pow(semitone, 15);
protected double b5 = base_freq*(double)Math.pow(semitone, 14);
protected double bb5 = base_freq*(double)Math.pow(semitone, 13);
protected double a5 = base_freq*(double)Math.pow(semitone, 12);
protected double gs4 = base_freq*(double)Math.pow(semitone, 11);
protected double g4 = base_freq*(double)Math.pow(semitone, 10);
protected double fs4 = base_freq*(double)Math.pow(semitone, 9);
protected double f4 = base_freq*(double)Math.pow(semitone, 8);
protected double e4 = base_freq*(double)Math.pow(semitone, 7);
protected double eb4 = base_freq*(double)Math.pow(semitone, 6);
protected double d4 = base_freq*(double)Math.pow(semitone, 5);
protected double cs4 = base_freq*(double)Math.pow(semitone, 4);
protected double c4 = base_freq*(double)Math.pow(semitone, 3);
protected double b4 = base_freq*(double)Math.pow(semitone, 2);
protected double a4 = base_freq*(double)Math.pow(semitone, 0);
protected double g3 = base_freq*(double)Math.pow(semitone, -2);
protected double fs3 = base_freq*(double)Math.pow(semitone, -3);
protected double f3 = base_freq*(double)Math.pow(semitone, -4);
protected double e3 = base_freq*(double)Math.pow(semitone, -5);
protected double eb3 = base_freq*(double)Math.pow(semitone, -6);
protected double d3 = base_freq*(double)Math.pow(semitone, -7);
protected double db3 = base_freq*(double)Math.pow(semitone, -8);
protected double c3 = base_freq*(double)Math.pow(semitone, -9);
protected double b3 = base_freq*(double)Math.pow(semitone, -10);
protected double bb3 = base_freq*(double)Math.pow(semitone, -11);
protected double a3 = base_freq*(double)Math.pow(semitone, -12);
protected double e2 = base_freq*(double)Math.pow(semitone, -17);
protected double e1 = base_freq*(double)Math.pow(semitone, -29);
protected double e0 = base_freq*(double)Math.pow(semitone, -41);
protected double e4andb4 = base_freq*(double)Math.pow(semitone, 7) * base_freq*(double)Math.pow(semitone, 14);
}
| apache-2.0 |
inexistence/VideoMeeting | Client/VMeeting/app/src/main/java/com/jb/vmeeting/app/App.java | 1907 | package com.jb.vmeeting.app;
import android.app.Application;
import android.graphics.Bitmap;
import com.jb.vmeeting.app.constant.AppConstant;
import com.jb.vmeeting.tools.L;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
/**
*
* Created by Jianbin on 2015/12/24.
*/
public class App extends Application {
private static App sApplication;
@Override
public void onCreate() {
super.onCreate();
sApplication = this;
initLib();
}
private void initLib() {
// 初始化日志功能, 开启/关闭 日志输出
L.setLogOpen(AppConstant.LOG_OPEN);
// 初始化自定义异常捕获
CrashHandler.getInstance().init(this);
// 初始化ImageLoader
// 设置图片显示选项
DisplayImageOptions displayOp = new DisplayImageOptions.Builder()
.showImageOnLoading(0)// 图片正在加载时显示的背景
.cacheInMemory(true)// 缓存在内存中
.cacheOnDisk(true)// 缓存在磁盘中
.displayer(new FadeInBitmapDisplayer(300))// 显示渐变动画
.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
.considerExifParams(true)// 考虑旋转角
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(displayOp)
.denyCacheImageMultipleSizesInMemory()// 不解析多种尺寸
.build();
ImageLoader.getInstance().init(config);
}
public static App getInstance() {
return sApplication;
}
}
| apache-2.0 |
prime-framework/prime-mvc | src/main/java/org/primeframework/mvc/guice/GuiceBootstrap.java | 4191 | /*
* Copyright (c) 2012-2017, Inversoft Inc., All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.primeframework.mvc.guice;
import java.io.Closeable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.inject.Binding;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.spi.Message;
import org.primeframework.mvc.PrimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class bootstraps Guice.
*
* @author Brian Pontarelli
*/
public class GuiceBootstrap {
private static final Logger logger = LoggerFactory.getLogger(GuiceBootstrap.class);
private GuiceBootstrap() {
}
/**
* Please do not invoke this method unless you know what you are doing. This initializes Guice and does it once only
* so that synchronization is not used. This is called by the PrimeServletContextListener when the context is created
* and should cover all cases.
*
* @param modules The modules;
* @return The Guice injector.
*/
public static Injector initialize(Module... modules) {
logger.debug("Initializing Guice");
try {
return Guice.createInjector(modules);
} catch (CreationException e) {
logger.debug("Unable to create Guice injector", e);
Collection<Message> messages = e.getErrorMessages();
Set<String> errorMessages = new HashSet<>();
messages.forEach((message) -> {
if (message.getCause() != null) {
errorMessages.add("[" + message.getMessage() + "] \n\t-> [" + message.getCause().getClass() + "] " + message.getCause().getMessage());
} else {
errorMessages.add("[" + message.getMessage() + "]");
}
});
logger.error(
"\n\n===================================================================================================\n\n" +
" Unable to start the server. Here's why: \n\n\n{}" +
"\n\n===================================================================================================\n\n",
String.join("\n", errorMessages)
);
logger.error("Unable to start the server. Exception: \n", e);
throw new PrimeException();
}
}
/**
* Shuts down the Guice injector by locating all of the {@link Closeable} singletons classes and calling Close on each
* of them.
*
* @param injector The Injector to shutdown.
*/
public static void shutdown(Injector injector) {
Map<Key<?>, Binding<?>> bindings = injector.getBindings();
Set<Class<?>> closed = new HashSet<>();
for (Key<?> key : bindings.keySet()) {
Type type = key.getTypeLiteral().getType();
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
if (type instanceof Class) {
Class<?> bindingType = (Class<?>) type;
if (Closeable.class.isAssignableFrom(bindingType) && Scopes.isSingleton(bindings.get(key))) {
Closeable closable = (Closeable) injector.getInstance(key);
if (closable == null || closed.contains(closable.getClass())) {
continue;
}
try {
closable.close();
} catch (Throwable t) {
logger.error("Unable to shutdown Closeable [{}]", key);
} finally {
closed.add(closable.getClass());
}
}
}
}
}
} | apache-2.0 |
benjchristensen/RxJava | src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatest.java | 4059 | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.internal.operators.flowable;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Publisher;
import io.reactivex.*;
import io.reactivex.internal.util.ExceptionHelper;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.subscribers.DisposableSubscriber;
/**
* Wait for and iterate over the latest values of the source observable. If the source works faster than the
* iterator, values may be skipped, but not the {@code onError} or {@code onComplete} events.
* @param <T> the value type emitted
*/
public final class BlockingFlowableLatest<T> implements Iterable<T> {
final Publisher<? extends T> source;
public BlockingFlowableLatest(Publisher<? extends T> source) {
this.source = source;
}
@Override
public Iterator<T> iterator() {
LatestSubscriberIterator<T> lio = new LatestSubscriberIterator<T>();
Flowable.<T>fromPublisher(source).materialize().subscribe(lio);
return lio;
}
/** Subscriber of source, iterator for output. */
static final class LatestSubscriberIterator<T> extends DisposableSubscriber<Notification<T>> implements Iterator<T> {
final Semaphore notify = new Semaphore(0);
// observer's notification
final AtomicReference<Notification<T>> value = new AtomicReference<Notification<T>>();
// iterator's notification
Notification<T> iteratorNotification;
@Override
public void onNext(Notification<T> args) {
boolean wasNotAvailable = value.getAndSet(args) == null;
if (wasNotAvailable) {
notify.release();
}
}
@Override
public void onError(Throwable e) {
RxJavaPlugins.onError(e);
}
@Override
public void onComplete() {
// not expected
}
@Override
public boolean hasNext() {
if (iteratorNotification != null && iteratorNotification.isOnError()) {
throw ExceptionHelper.wrapOrThrow(iteratorNotification.getError());
}
if (iteratorNotification == null || iteratorNotification.isOnNext()) {
if (iteratorNotification == null) {
try {
notify.acquire();
} catch (InterruptedException ex) {
dispose();
iteratorNotification = Notification.createOnError(ex);
throw ExceptionHelper.wrapOrThrow(ex);
}
Notification<T> n = value.getAndSet(null);
iteratorNotification = n;
if (n.isOnError()) {
throw ExceptionHelper.wrapOrThrow(n.getError());
}
}
}
return iteratorNotification.isOnNext();
}
@Override
public T next() {
if (hasNext()) {
if (iteratorNotification.isOnNext()) {
T v = iteratorNotification.getValue();
iteratorNotification = null;
return v;
}
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Read-only iterator.");
}
}
} | apache-2.0 |
agarman/pulsar | pulsar-broker/src/test/java/com/yahoo/pulsar/stats/client/PulsarBrokerStatsClientTest.java | 3196 | /**
* Copyright 2016 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.pulsar.stats.client;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import java.net.URL;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.ServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import com.yahoo.pulsar.client.admin.PulsarAdmin;
import com.yahoo.pulsar.client.admin.PulsarAdminException;
import com.yahoo.pulsar.client.admin.PulsarAdminException.ConflictException;
import com.yahoo.pulsar.client.admin.PulsarAdminException.NotAuthorizedException;
import com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException;
import com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException;
import com.yahoo.pulsar.client.admin.PulsarAdminException.ServerSideErrorException;
import com.yahoo.pulsar.client.admin.internal.BrokerStatsImpl;
import com.yahoo.pulsar.client.api.Authentication;
public class PulsarBrokerStatsClientTest {
@Test
public void testServiceException() throws Exception {
URL url = new URL("http://localhost:15000");
PulsarAdmin admin = new PulsarAdmin(url, (Authentication) null);
BrokerStatsImpl client = (BrokerStatsImpl) spy(admin.brokerStats());
try {
client.getLoadReport();
} catch (PulsarAdminException e) {
// Ok
}
try {
client.getPendingBookieOpsStats();
} catch (PulsarAdminException e) {
// Ok
}
try {
client.getBrokerResourceAvailability("prop", "cluster", "ns");
} catch (PulsarAdminException e) {
// Ok
}
assertTrue(client.getApiException(new ClientErrorException(403)) instanceof NotAuthorizedException);
assertTrue(client.getApiException(new ClientErrorException(404)) instanceof NotFoundException);
assertTrue(client.getApiException(new ClientErrorException(409)) instanceof ConflictException);
assertTrue(client.getApiException(new ClientErrorException(412)) instanceof PreconditionFailedException);
assertTrue(client.getApiException(new ClientErrorException(400)) instanceof PulsarAdminException);
assertTrue(client.getApiException(new ServerErrorException(500)) instanceof ServerSideErrorException);
assertTrue(client.getApiException(new ServerErrorException(503)) instanceof PulsarAdminException);
log.info("Client: ", client);
admin.close();
}
private static final Logger log = LoggerFactory.getLogger(PulsarBrokerStatsClientTest.class);
}
| apache-2.0 |
webanno/webanno | webanno-model/src/main/java/de/tudarmstadt/ukp/clarin/webanno/model/SourceDocumentState.java | 2705 | /*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tudarmstadt.ukp.clarin.webanno.model;
import de.tudarmstadt.ukp.clarin.webanno.support.PersistentEnum;
/**
* Variables for the different states of a {@link SourceDocument} workflow.
*/
public enum SourceDocumentState
implements PersistentEnum
{
/**
* No annotation document has been created for this document
*/
NEW("NEW", "black"),
/**
* At least one annotation document has been created for the document
*/
ANNOTATION_IN_PROGRESS("ANNOTATION_INPROGRESS", "black"),
/**
* All annotations have marked their annotation document as finished
*
* @deprecated This is not used and should not be used. Will be removed in future versions. If
* you want to tell whether all annotators have marked a document as finished, you
* have to manually check if all annotators assigned to annotate this document have
* marked their annotation documents as done. This is nothing we can record
* statically in the source document.
*/
ANNOTATION_FINISHED("ANNOTATION_FINISHED", "green"),
/**
* curator has started working with the annotation document, annotators can no longer make
* modifications in annotation documents
*/
CURATION_IN_PROGRESS("CURATION_INPROGRESS", "blue"),
/**
* curator claims to have curated all annotations
*/
CURATION_FINISHED("CURATION_FINISHED", "red");
private final String id;
private final String color;
SourceDocumentState(String aId, String aColor)
{
id = aId;
color = aColor;
}
public String getName()
{
return getId();
}
@Override
public String getId()
{
return id;
}
public String getColor()
{
return color;
}
@Override
public String toString()
{
return getId();
}
}
| apache-2.0 |
bedatadriven/renjin-statet | org.renjin.core/src-gen/org/renjin/primitives/R$primitive$acosh$deferred_d.java | 1322 |
package org.renjin.primitives;
import org.renjin.primitives.vector.DeferredComputation;
import org.renjin.sexp.AttributeMap;
import org.renjin.sexp.DoubleVector;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.Vector;
public class R$primitive$acosh$deferred_d
extends DoubleVector
implements DeferredComputation
{
private final Vector arg0;
private final int argLength0;
private int length;
public R$primitive$acosh$deferred_d(Vector arg0, AttributeMap attributes) {
super(attributes);
length = 0;
this.arg0 = arg0;
argLength0 = arg0 .length();
length = argLength0;
}
public double getElementAsDouble(int index) {
double arg0_i = arg0 .getElementAsDouble(index);
if (DoubleVector.isNA(arg0_i)) {
return DoubleVector.NA;
}
return MathExt.acosh(arg0_i);
}
public int length() {
return length;
}
public SEXP cloneWithNewAttributes(AttributeMap attributes) {
return new R$primitive$acosh$deferred_d(arg0, attributes);
}
public Vector[] getOperands() {
return new Vector[] {arg0 };
}
public String getComputationName() {
return "acosh";
}
public static double compute(double p0) {
return MathExt.acosh(p0);
}
}
| apache-2.0 |
sguilhen/wildfly-elytron | src/test/java/org/wildfly/security/auth/KeyStoreBackedSecurityRealmTest.java | 5481 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.wildfly.security.WildFlyElytronProvider;
import org.wildfly.security.auth.realm.KeyStoreBackedSecurityRealm;
import org.wildfly.security.auth.server.IdentityLocator;
import org.wildfly.security.auth.server.RealmIdentity;
import org.wildfly.security.auth.server.SecurityRealm;
import org.wildfly.security.auth.server.SupportLevel;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.interfaces.BCryptPassword;
import org.wildfly.security.password.interfaces.UnixMD5CryptPassword;
/**
* Testsuite for the {@link org.wildfly.security.auth.realm.KeyStoreBackedSecurityRealm}.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
public class KeyStoreBackedSecurityRealmTest {
private static final Provider provider = new WildFlyElytronProvider();
@BeforeClass
public static void register() {
Security.addProvider(provider);
}
@AfterClass
public static void remove() {
Security.removeProvider(provider.getName());
}
@Test
public void testPasswordFileKeyStore() throws Exception {
// initialize the keystore, this time loading the users from a password file.
final InputStream stream = this.getClass().getResourceAsStream("passwd");
final KeyStore keyStore = KeyStore.getInstance("PasswordFile");
keyStore.load(stream, null);
assertEquals("Invalid number of keystore entries", 2, keyStore.size());
// create a realm identity that represents the user "elytron" (password is of type MD5Crypt)
SecurityRealm realm = new KeyStoreBackedSecurityRealm(keyStore);
RealmIdentity realmIdentity = realm.getRealmIdentity(IdentityLocator.fromName("elytron"));
// only the Password type credential type is supported in the password file keystore.
assertEquals("Invalid credential support", SupportLevel.SUPPORTED, realmIdentity.getCredentialAcquireSupport(PasswordCredential.class, UnixMD5CryptPassword.ALGORITHM_CRYPT_MD5));
assertEquals("Invalid credential support", SupportLevel.UNSUPPORTED, realmIdentity.getCredentialAcquireSupport(PasswordCredential.class, BCryptPassword.ALGORITHM_BCRYPT));
// as a result, the only type that will yield a non null credential is Password.
Password password = realmIdentity.getCredential(PasswordCredential.class, null).getPassword();
assertNotNull("Invalid null password", password);
assertTrue("Invalid password type", password instanceof UnixMD5CryptPassword);
// the realm identity must be able to verify the password for the user "elytron".
assertTrue("Error validating credential", realmIdentity.verifyEvidence(new PasswordGuessEvidence("passwd12#$".toCharArray())));
assertFalse("Error validating credential", realmIdentity.verifyEvidence(new PasswordGuessEvidence("wrongpass".toCharArray())));
// now create a realm identity that represents the user "javajoe" (password is of type BCrypt).
realmIdentity = realm.getRealmIdentity(IdentityLocator.fromName("javajoe"));
// only the Password type credential type is supported in the password file keystore.
assertEquals("Invalid credential support", SupportLevel.SUPPORTED, realmIdentity.getCredentialAcquireSupport(PasswordCredential.class, BCryptPassword.ALGORITHM_BCRYPT));
assertEquals("Invalid credential support", SupportLevel.UNSUPPORTED, realmIdentity.getCredentialAcquireSupport(PasswordCredential.class, UnixMD5CryptPassword.ALGORITHM_CRYPT_MD5));
// as a result, the only type that will yield a non null credential is Password.
password = realmIdentity.getCredential(PasswordCredential.class, null).getPassword();
assertNotNull("Invalid null password", password);
assertTrue("Invalid password type", password instanceof BCryptPassword);
// the realm identity must be able to verify the password for the user "javajoe".
assertTrue("Error validating credential", realmIdentity.verifyEvidence(new PasswordGuessEvidence("$#21pass".toCharArray())));
assertFalse("Error validating credential", realmIdentity.verifyEvidence(new PasswordGuessEvidence("wrongpass".toCharArray())));
}
}
| apache-2.0 |
lgoldstein/communitychest | chest/net/common/src/main/java/net/community/chest/net/TextNetConnection.java | 11957 | package net.community.chest.net;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/**
* Copyright 2007 as per GPLv2
*
* provides an abstract view of a textual (US-ASCII) network connection -
* e.g., FTP, SMTP, IMAP, POP3, etc.
*
* @author Lyor G.
* @since Jun 28, 2007 1:51:46 PM
*/
public interface TextNetConnection extends BinaryNetConnection, Readable, Appendable {
/**
* Reads data into supplied buffer
* @param buf buffer to read into
* @param offset offset in buffer to read into
* @param len maximum number of characters to read
* @return number of actual read characters
* @throws IOException if I/O error
*/
int read (final char[] buf, final int offset, final int len) throws IOException;
/**
* Reads data into supplied buffer
* @param buf buffer to read into
* @return number of actual read characters
* @throws IOException if I/O error
*/
int read (final char[] buf) throws IOException;
/**
* Fills data into supplied buffer
* @param buf buffer to read into
* @param offset offset in buffer to read into
* @param len EXACT number of characters to read
* @return number of actual read characters (same as <I>"len"</I>)
* @throws IOException if I/O error
*/
int fill (final char[] buf, final int offset, final int len) throws IOException;
/**
* Fills data into supplied buffer
* @param buf buffer to read into - EXACTLY entire buffer is to be read
* @return number of actual read characters (same as <I>buf.length</I>)
* @throws IOException if I/O error
*/
int fill (final char[] buf) throws IOException;
/**
* Reads a "line" of data - defined as sequence of characters up to LF.
* @param buf buffer into which to place the read data - not including CRLF(!)
* @param startOffset start offset in buffer where to start placing the read data (inclusive)
* @param maxLen maximum number of characters to read - if LF found BEFORE this length
* is reached, then function returns immediately. Otherwise, it returns an "incomplete"
* line information
* @param li read line information to be filled
* @return number of read characters (including any CR/LF) - (<0) if error
* @throws IOException if I/O errors
*/
int readLine (final char[] buf, final int startOffset, final int maxLen, final LineInfo li) throws IOException;
/**
* Reads a "line" of data - defined as sequence of characters up to LF.
* @param buf buffer into which to place the read data - not including CRLF(!)
* @param startOffset start offset in buffer where to start placing the read data (inclusive)
* @param maxLen maximum number of characters to read - if LF found BEFORE this length
* is reached, then function returns immediately. Otherwise, it returns an "incomplete"
* line information
* @return read line information
* @throws IOException if I/O or arguments errors
*/
LineInfo readLine (final char[] buf, final int startOffset, final int maxLen) throws IOException;
/**
* Reads a "line" of data - defined as sequence of characters up to LF.
* @param buf buffer into which to place the read data (not including
* CRLF (!))- if LF found BEFORE entire buffer is used, then function
* returns immediately. Otherwise, it returns an "incomplete" line information
* @param li read line information to be filled
* @return number of read characters (including any CR/LF) - (<0) if error
* @throws IOException if I/O or arguments errors
*/
int readLine (final char[] buf, final LineInfo li) throws IOException;
/**
* Reads a "line" of data - defined as sequence of characters up to LF.
* @param buf buffer into which to place the read data (not including
* CRLF (!))- if LF found BEFORE entire buffer is used, then function
* returns immediately. Otherwise, it returns an "incomplete" line information
* @return read line information
* @throws IOException if I/O or arguments errors
* @see #readLine(char[] buf, int startOffset, int maxLen)
*/
LineInfo readLine (final char[] buf) throws IOException;
/**
* Reads a line of data from input - as much as required
* @return read line as string - not including CRLF (!)
* @throws IOException if errors encountered
*/
String readLine () throws IOException;
/**
* Masks this object as a Reader - Note: if you want to use "readLine()" then
* better to use the interface call rather than masking it as a (Buffered)Reader
* @param autoClose if TRUE then call to Reader#close() also closes the underlying connection
* @return Reader object
* @throws IOException if problems creating the object
*/
Reader asReader (boolean autoClose) throws IOException;
/**
* Writes specified data to connection
* @param buf buffer from which to write
* @param startOffset offset in data buffer to start writing from (inclusive)
* @param maxLen number of characters to write
* @param flushIt if TRUE then channel is flushed AFTER writing the data
* @return number of actually written characters (should be same as <I>"maxLen"</I>) - or (<0) if error
* @throws IOException if I/O error
*/
int write (final char[] buf, final int startOffset, final int maxLen, final boolean flushIt) throws IOException;
/**
* Writes specified data to connection
* @param buf buffer from which to write - Note: ENTIRE buffer is written
* @param flushIt if TRUE then channel is flushed AFTER writing the data
* @return number of actually written characters (should be same as <I>buf.length</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int write (final char[] buf, final boolean flushIt) throws IOException;
/**
* Writes specified data to connection
* @param s string to write - Note: ENTIRE string is written
* @param flushIt if TRUE then channel is flushed AFTER writing the data
* @return number of actually written characters (should be same as <I>s.length()</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int write (String s, final boolean flushIt) throws IOException;
/**
* Writes specified data to connection
* @param buf buffer from which to write
* @param startOffset offset in data buffer to start writing from (inclusive)
* @param maxLen number of characters to write
* @return number of actually written characters (should be same as <I>"maxLen"</I>) - or (<0) if error
* @throws IOException if I/O error
*/
int write (final char[] buf, final int startOffset, final int maxLen) throws IOException;
/**
* Writes specified data to connection
* @param buf buffer from which to write - Note: ENTIRE buffer is written
* @return number of actually written characters (should be same as <I>buf.length</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int write (char ... buf) throws IOException;
/**
* Writes specified data to connection
* @param s string to write - Note: ENTIRE string is written
* @return number of actually written characters (should be same as <I>s.length()</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int write (String s) throws IOException;
/**
* Masks this object as a Writer
* @param autoClose if true then closes the underlying connection when Writer#close() is called
* @return writer object
* @throws IOException if problems creating the object
*/
Writer asWriter (boolean autoClose) throws IOException;
/**
* Writes CRLF to the output channel
* @param flushIt if TRUE then channel is flushed AFTER writing the CRLF
* @return number of written characters (or <0 if error) - should be same as <I>CRLF.length</I>
* @throws IOException
*/
int writeln (final boolean flushIt) throws IOException;
/**
* Writes specified data to connection and then adds a CRLF to its end
* @param buf buffer from which to write
* @param startOffset offset in data buffer to start writing from (inclusive)
* @param maxLen number of characters to write
* @param flushIt if TRUE then channel is flushed AFTER writing the CRLF
* @return number of actually written characters including CRLF (should be same as <I>"maxLen+2"</I>) - or (<0) if error
* @throws IOException if I/O error
*/
int writeln (final char[] buf, final int startOffset, final int maxLen, final boolean flushIt) throws IOException;
/**
* Writes specified data to connection and then adds a CRLF
* @param buf buffer from which to write - Note: ENTIRE buffer is written
* @param flushIt if TRUE then channel is flushed AFTER writing the CRLF
* @return number of actually written characters including CRLF (should be same as <I>buf.length+2</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int writeln (final char[] buf, final boolean flushIt) throws IOException;
/**
* Writes specified data to connection and then adds a CRLF
* @param s string to write - Note: ENTIRE string is written
* @param flushIt if TRUE then channel is flushed AFTER writing the CRLF
* @return number of actually written characters including CRLF (should be same as <I>s.length()+2</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int writeln (final String s, final boolean flushIt) throws IOException;
/**
* Writes CRLF to the output channel (but does not flush it)
* @return number of written characters (or <0 if error) - should be
* exactly 2 (CR+LF)
* @throws IOException if I/O error
* @see #writeln(boolean flushIt)
*/
int writeln () throws IOException;
/**
* Writes specified data to connection and then adds a CRLF to its end
* @param buf buffer from which to write
* @param startOffset offset in data buffer to start writing from (inclusive)
* @param maxLen number of characters to write
* @return number of actually written characters including CRLF (should be same as <I>"maxLen+2"</I>) - or (<0) if error
* @throws IOException if I/O error
*/
int writeln (final char[] buf, final int startOffset, final int maxLen) throws IOException;
/**
* Writes specified data to connection and then adds a CRLF
* @param buf buffer from which to write - Note: ENTIRE buffer is written
* @return number of actually written characters including CRLF (should be same as <I>buf.length+2</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int writeln (char ... buf) throws IOException;
/**
* Writes specified data to connection and then adds a CRLF
* @param s string to write - Note: ENTIRE string is written
* @return number of actually written characters including CRLF (should be same as <I>s.length()+2</I>) - or (<0) if error
* @throws IOException if I/O error
* @see #write(char[] buf, int startOffset, int maxLen)
*/
int writeln (final String s) throws IOException;
}
| apache-2.0 |
bshp/midPoint | gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/component/data/column/AbstractItemWrapperColumn.java | 3170 | /*
* Copyright (c) 2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.gui.impl.component.data.column;
import org.apache.commons.lang.Validate;
import org.apache.wicket.Component;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.export.IExportableColumn;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.prism.ItemWrapper;
import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper;
import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper;
import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.PrismContainerDefinition;
import com.evolveum.midpoint.prism.path.ItemPath;
/**
* @author skublik
*/
public abstract class AbstractItemWrapperColumn<C extends Containerable, VW extends PrismValueWrapper> extends AbstractColumn<PrismContainerValueWrapper<C>, String> implements IExportableColumn<PrismContainerValueWrapper<C>, String>{
public enum ColumnType {
LINK,
STRING,
VALUE;
}
private static final long serialVersionUID = 1L;
protected ItemPath itemName;
private ColumnType columnType;
private static final String ID_VALUE = "value";
private IModel<? extends PrismContainerDefinition<C>> mainModel = null;
AbstractItemWrapperColumn(IModel<? extends PrismContainerDefinition<C>> mainModel, ItemPath itemName, ColumnType columnType) {
super(null);
Validate.notNull(mainModel, "no model");
Validate.notNull(mainModel.getObject(), "no ContainerWrappe from model");
Validate.notNull(itemName, "no qName");
this.mainModel = mainModel;
this.itemName = itemName;
this.columnType = columnType;
}
@Override
public Component getHeader(String componentId) {
return createHeader(componentId, mainModel);
}
@Override
public void populateItem(Item<ICellPopulator<PrismContainerValueWrapper<C>>> cellItem, String componentId,
IModel<PrismContainerValueWrapper<C>> rowModel) {
cellItem.add(createColumnPanel(componentId, (IModel) getDataModel(rowModel)));
}
protected abstract Component createHeader(String componentId, IModel<? extends PrismContainerDefinition<C>> mainModel);
protected abstract <IW extends ItemWrapper> Component createColumnPanel(String componentId, IModel<IW> rowModel);
public ColumnType getColumnType() {
return columnType;
}
}
| apache-2.0 |
ganzux/SIRME | SIRME-core/src/main/java/com/alcedomoreno/sirme/core/dao/common/GenericHibernateDao.java | 895 | package com.alcedomoreno.sirme.core.dao.common;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* Clase genérica para operaciones sobre bd
* @param <T> entidad con la que se extiende la clase
*/
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T>
implements GenericDao<T> {
@SuppressWarnings("unchecked")
@Override
public List<T> loadAll(Class<T> clazz) {
return getCurrentSession().createQuery("FROM " + clazz.getName()).list();
}
@SuppressWarnings("unchecked")
@Override
public T findById(Class<T> clazz, Serializable id) {
return (T) getCurrentSession().get(clazz, id);
}
}
| apache-2.0 |
miniway/presto | presto-geospatial/src/test/java/io/prestosql/plugin/geospatial/TestExtractSpatialInnerJoin.java | 24808 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.geospatial;
import com.google.common.collect.ImmutableMap;
import io.prestosql.sql.planner.iterative.rule.ExtractSpatialJoins.ExtractSpatialInnerJoin;
import io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest;
import io.prestosql.sql.planner.iterative.rule.test.PlanBuilder;
import io.prestosql.sql.planner.iterative.rule.test.RuleAssert;
import io.prestosql.sql.planner.iterative.rule.test.RuleTester;
import org.testng.annotations.Test;
import static io.prestosql.plugin.geospatial.GeometryType.GEOMETRY;
import static io.prestosql.plugin.geospatial.SphericalGeographyType.SPHERICAL_GEOGRAPHY;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.expression;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.project;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.spatialJoin;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.values;
import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER;
public class TestExtractSpatialInnerJoin
extends BaseRuleTest
{
public TestExtractSpatialInnerJoin()
{
super(new GeoPlugin());
}
@Test
public void testDoesNotFire()
{
// scalar expression
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText('POLYGON ...'), b)"),
p.join(INNER,
p.values(),
p.values(p.symbol("b")))))
.doesNotFire();
// OR operand
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt), point) OR name_1 != name_2"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR), p.symbol("name_1")),
p.values(p.symbol("point", GEOMETRY), p.symbol("name_2")))))
.doesNotFire();
// NOT operator
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("NOT ST_Contains(ST_GeometryFromText(wkt), point)"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR), p.symbol("name_1")),
p.values(p.symbol("point", GEOMETRY), p.symbol("name_2")))))
.doesNotFire();
// ST_Distance(...) > r
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Distance(a, b) > 5"),
p.join(INNER,
p.values(p.symbol("a", GEOMETRY)),
p.values(p.symbol("b", GEOMETRY)))))
.doesNotFire();
// SphericalGeography operand
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Distance(a, b) < 5"),
p.join(INNER,
p.values(p.symbol("a", SPHERICAL_GEOGRAPHY)),
p.values(p.symbol("b", SPHERICAL_GEOGRAPHY)))))
.doesNotFire();
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(polygon, point)"),
p.join(INNER,
p.values(p.symbol("polygon", SPHERICAL_GEOGRAPHY)),
p.values(p.symbol("point", SPHERICAL_GEOGRAPHY)))))
.doesNotFire();
// to_spherical_geography() operand
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Distance(to_spherical_geography(ST_GeometryFromText(wkt)), point) < 5"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR)),
p.values(p.symbol("point", SPHERICAL_GEOGRAPHY)))))
.doesNotFire();
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(to_spherical_geography(ST_GeometryFromText(wkt)), point)"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR)),
p.values(p.symbol("point", SPHERICAL_GEOGRAPHY)))))
.doesNotFire();
}
@Test
public void testDistanceQueries()
{
testSimpleDistanceQuery("ST_Distance(a, b) <= r", "ST_Distance(a, b) <= r");
testSimpleDistanceQuery("ST_Distance(b, a) <= r", "ST_Distance(b, a) <= r");
testSimpleDistanceQuery("r >= ST_Distance(a, b)", "ST_Distance(a, b) <= r");
testSimpleDistanceQuery("r >= ST_Distance(b, a)", "ST_Distance(b, a) <= r");
testSimpleDistanceQuery("ST_Distance(a, b) < r", "ST_Distance(a, b) < r");
testSimpleDistanceQuery("ST_Distance(b, a) < r", "ST_Distance(b, a) < r");
testSimpleDistanceQuery("r > ST_Distance(a, b)", "ST_Distance(a, b) < r");
testSimpleDistanceQuery("r > ST_Distance(b, a)", "ST_Distance(b, a) < r");
testSimpleDistanceQuery("ST_Distance(a, b) <= r AND name_a != name_b", "ST_Distance(a, b) <= r AND name_a != name_b");
testSimpleDistanceQuery("r > ST_Distance(a, b) AND name_a != name_b", "ST_Distance(a, b) < r AND name_a != name_b");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) <= decimal '1.2'", "ST_Distance(a, b) <= radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("ST_Distance(b, a) <= decimal '1.2'", "ST_Distance(b, a) <= radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("decimal '1.2' >= ST_Distance(a, b)", "ST_Distance(a, b) <= radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("decimal '1.2' >= ST_Distance(b, a)", "ST_Distance(b, a) <= radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) < decimal '1.2'", "ST_Distance(a, b) < radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("ST_Distance(b, a) < decimal '1.2'", "ST_Distance(b, a) < radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("decimal '1.2' > ST_Distance(a, b)", "ST_Distance(a, b) < radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("decimal '1.2' > ST_Distance(b, a)", "ST_Distance(b, a) < radius", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) <= decimal '1.2' AND name_a != name_b", "ST_Distance(a, b) <= radius AND name_a != name_b", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("decimal '1.2' > ST_Distance(a, b) AND name_a != name_b", "ST_Distance(a, b) < radius AND name_a != name_b", "decimal '1.2'");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) <= 2 * r", "ST_Distance(a, b) <= radius", "2 * r");
testRadiusExpressionInDistanceQuery("ST_Distance(b, a) <= 2 * r", "ST_Distance(b, a) <= radius", "2 * r");
testRadiusExpressionInDistanceQuery("2 * r >= ST_Distance(a, b)", "ST_Distance(a, b) <= radius", "2 * r");
testRadiusExpressionInDistanceQuery("2 * r >= ST_Distance(b, a)", "ST_Distance(b, a) <= radius", "2 * r");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) < 2 * r", "ST_Distance(a, b) < radius", "2 * r");
testRadiusExpressionInDistanceQuery("ST_Distance(b, a) < 2 * r", "ST_Distance(b, a) < radius", "2 * r");
testRadiusExpressionInDistanceQuery("2 * r > ST_Distance(a, b)", "ST_Distance(a, b) < radius", "2 * r");
testRadiusExpressionInDistanceQuery("2 * r > ST_Distance(b, a)", "ST_Distance(b, a) < radius", "2 * r");
testRadiusExpressionInDistanceQuery("ST_Distance(a, b) <= 2 * r AND name_a != name_b", "ST_Distance(a, b) <= radius AND name_a != name_b", "2 * r");
testRadiusExpressionInDistanceQuery("2 * r > ST_Distance(a, b) AND name_a != name_b", "ST_Distance(a, b) < radius AND name_a != name_b", "2 * r");
testPointExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) <= 5", "ST_Distance(point_a, point_b) <= radius", "5");
testPointExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a)) <= 5", "ST_Distance(point_b, point_a) <= radius", "5");
testPointExpressionsInDistanceQuery("5 >= ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b))", "ST_Distance(point_a, point_b) <= radius", "5");
testPointExpressionsInDistanceQuery("5 >= ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a))", "ST_Distance(point_b, point_a) <= radius", "5");
testPointExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) < 5", "ST_Distance(point_a, point_b) < radius", "5");
testPointExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a)) < 5", "ST_Distance(point_b, point_a) < radius", "5");
testPointExpressionsInDistanceQuery("5 > ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b))", "ST_Distance(point_a, point_b) < radius", "5");
testPointExpressionsInDistanceQuery("5 > ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a))", "ST_Distance(point_b, point_a) < radius", "5");
testPointExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) <= 5 AND name_a != name_b", "ST_Distance(point_a, point_b) <= radius AND name_a != name_b", "5");
testPointExpressionsInDistanceQuery("5 > ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) AND name_a != name_b", "ST_Distance(point_a, point_b) < radius AND name_a != name_b", "5");
testPointAndRadiusExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) <= 500 / (111000 * cos(lat_b))", "ST_Distance(point_a, point_b) <= radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a)) <= 500 / (111000 * cos(lat_b))", "ST_Distance(point_b, point_a) <= radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("500 / (111000 * cos(lat_b)) >= ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b))", "ST_Distance(point_a, point_b) <= radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("500 / (111000 * cos(lat_b)) >= ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a))", "ST_Distance(point_b, point_a) <= radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) < 500 / (111000 * cos(lat_b))", "ST_Distance(point_a, point_b) < radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a)) < 500 / (111000 * cos(lat_b))", "ST_Distance(point_b, point_a) < radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("500 / (111000 * cos(lat_b)) > ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b))", "ST_Distance(point_a, point_b) < radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("500 / (111000 * cos(lat_b)) > ST_Distance(ST_Point(lng_b, lat_b), ST_Point(lng_a, lat_a))", "ST_Distance(point_b, point_a) < radius", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) <= 500 / (111000 * cos(lat_b)) AND name_a != name_b", "ST_Distance(point_a, point_b) <= radius AND name_a != name_b", "500 / (111000 * cos(lat_b))");
testPointAndRadiusExpressionsInDistanceQuery("500 / (111000 * cos(lat_b)) > ST_Distance(ST_Point(lng_a, lat_a), ST_Point(lng_b, lat_b)) AND name_a != name_b", "ST_Distance(point_a, point_b) < radius AND name_a != name_b", "500 / (111000 * cos(lat_b))");
}
private void testSimpleDistanceQuery(String filter, String newFilter)
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression(filter),
p.join(INNER,
p.values(p.symbol("a", GEOMETRY), p.symbol("name_a")),
p.values(p.symbol("b", GEOMETRY), p.symbol("name_b"), p.symbol("r")))))
.matches(
spatialJoin(newFilter,
values(ImmutableMap.of("a", 0, "name_a", 1)),
values(ImmutableMap.of("b", 0, "name_b", 1, "r", 2))));
}
private void testRadiusExpressionInDistanceQuery(String filter, String newFilter, String radiusExpression)
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression(filter),
p.join(INNER,
p.values(p.symbol("a", GEOMETRY), p.symbol("name_a")),
p.values(p.symbol("b", GEOMETRY), p.symbol("name_b"), p.symbol("r")))))
.matches(
spatialJoin(newFilter,
values(ImmutableMap.of("a", 0, "name_a", 1)),
project(ImmutableMap.of("radius", expression(radiusExpression)),
values(ImmutableMap.of("b", 0, "name_b", 1, "r", 2)))));
}
private void testPointExpressionsInDistanceQuery(String filter, String newFilter, String radiusExpression)
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression(filter),
p.join(INNER,
p.values(p.symbol("lat_a"), p.symbol("lng_a"), p.symbol("name_a")),
p.values(p.symbol("lat_b"), p.symbol("lng_b"), p.symbol("name_b")))))
.matches(
spatialJoin(newFilter,
project(ImmutableMap.of("point_a", expression("ST_Point(lng_a, lat_a)")),
values(ImmutableMap.of("lat_a", 0, "lng_a", 1, "name_a", 2))),
project(ImmutableMap.of("point_b", expression("ST_Point(lng_b, lat_b)")),
project(ImmutableMap.of("radius", expression(radiusExpression)), values(ImmutableMap.of("lat_b", 0, "lng_b", 1, "name_b", 2))))));
}
private void testPointAndRadiusExpressionsInDistanceQuery(String filter, String newFilter, String radiusExpression)
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression(filter),
p.join(INNER,
p.values(p.symbol("lat_a"), p.symbol("lng_a"), p.symbol("name_a")),
p.values(p.symbol("lat_b"), p.symbol("lng_b"), p.symbol("name_b")))))
.matches(
spatialJoin(newFilter,
project(ImmutableMap.of("point_a", expression("ST_Point(lng_a, lat_a)")),
values(ImmutableMap.of("lat_a", 0, "lng_a", 1, "name_a", 2))),
project(ImmutableMap.of("point_b", expression("ST_Point(lng_b, lat_b)")),
project(ImmutableMap.of("radius", expression(radiusExpression)),
values(ImmutableMap.of("lat_b", 0, "lng_b", 1, "name_b", 2))))));
}
@Test
public void testConvertToSpatialJoin()
{
// symbols
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(a, b)"),
p.join(INNER,
p.values(p.symbol("a")),
p.values(p.symbol("b")))))
.matches(
spatialJoin("ST_Contains(a, b)",
values(ImmutableMap.of("a", 0)),
values(ImmutableMap.of("b", 0))));
// AND
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("name_1 != name_2 AND ST_Contains(a, b)"),
p.join(INNER,
p.values(p.symbol("a"), p.symbol("name_1")),
p.values(p.symbol("b"), p.symbol("name_2")))))
.matches(
spatialJoin("name_1 != name_2 AND ST_Contains(a, b)",
values(ImmutableMap.of("a", 0, "name_1", 1)),
values(ImmutableMap.of("b", 0, "name_2", 1))));
// AND
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(a1, b1) AND ST_Contains(a2, b2)"),
p.join(INNER,
p.values(p.symbol("a1"), p.symbol("a2")),
p.values(p.symbol("b1"), p.symbol("b2")))))
.matches(
spatialJoin("ST_Contains(a1, b1) AND ST_Contains(a2, b2)",
values(ImmutableMap.of("a1", 0, "a2", 1)),
values(ImmutableMap.of("b1", 0, "b2", 1))));
}
@Test
public void testPushDownFirstArgument()
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt), point)"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR)),
p.values(p.symbol("point", GEOMETRY)))))
.matches(
spatialJoin("ST_Contains(st_geometryfromtext, point)",
project(ImmutableMap.of("st_geometryfromtext", expression("ST_GeometryFromText(wkt)")), values(ImmutableMap.of("wkt", 0))),
values(ImmutableMap.of("point", 0))));
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt), ST_Point(0, 0))"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR)),
p.values())))
.doesNotFire();
}
@Test
public void testPushDownSecondArgument()
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(polygon, ST_Point(lng, lat))"),
p.join(INNER,
p.values(p.symbol("polygon", GEOMETRY)),
p.values(p.symbol("lat"), p.symbol("lng")))))
.matches(
spatialJoin("ST_Contains(polygon, st_point)",
values(ImmutableMap.of("polygon", 0)),
project(ImmutableMap.of("st_point", expression("ST_Point(lng, lat)")), values(ImmutableMap.of("lat", 0, "lng", 1)))));
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText('POLYGON ...'), ST_Point(lng, lat))"),
p.join(INNER,
p.values(),
p.values(p.symbol("lat"), p.symbol("lng")))))
.doesNotFire();
}
@Test
public void testPushDownBothArguments()
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt), ST_Point(lng, lat))"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR)),
p.values(p.symbol("lat"), p.symbol("lng")))))
.matches(
spatialJoin("ST_Contains(st_geometryfromtext, st_point)",
project(ImmutableMap.of("st_geometryfromtext", expression("ST_GeometryFromText(wkt)")), values(ImmutableMap.of("wkt", 0))),
project(ImmutableMap.of("st_point", expression("ST_Point(lng, lat)")), values(ImmutableMap.of("lat", 0, "lng", 1)))));
}
@Test
public void testPushDownOppositeOrder()
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt), ST_Point(lng, lat))"),
p.join(INNER,
p.values(p.symbol("lat"), p.symbol("lng")),
p.values(p.symbol("wkt", VARCHAR)))))
.matches(
spatialJoin("ST_Contains(st_geometryfromtext, st_point)",
project(ImmutableMap.of("st_point", expression("ST_Point(lng, lat)")), values(ImmutableMap.of("lat", 0, "lng", 1))),
project(ImmutableMap.of("st_geometryfromtext", expression("ST_GeometryFromText(wkt)")), values(ImmutableMap.of("wkt", 0)))));
}
@Test
public void testPushDownAnd()
{
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("name_1 != name_2 AND ST_Contains(ST_GeometryFromText(wkt), ST_Point(lng, lat))"),
p.join(INNER,
p.values(p.symbol("wkt", VARCHAR), p.symbol("name_1")),
p.values(p.symbol("lat"), p.symbol("lng"), p.symbol("name_2")))))
.matches(
spatialJoin("name_1 != name_2 AND ST_Contains(st_geometryfromtext, st_point)",
project(ImmutableMap.of("st_geometryfromtext", expression("ST_GeometryFromText(wkt)")), values(ImmutableMap.of("wkt", 0, "name_1", 1))),
project(ImmutableMap.of("st_point", expression("ST_Point(lng, lat)")), values(ImmutableMap.of("lat", 0, "lng", 1, "name_2", 2)))));
// Multiple spatial functions - only the first one is being processed
assertRuleApplication()
.on(p ->
p.filter(PlanBuilder.expression("ST_Contains(ST_GeometryFromText(wkt1), geometry1) AND ST_Contains(ST_GeometryFromText(wkt2), geometry2)"),
p.join(INNER,
p.values(p.symbol("wkt1", VARCHAR), p.symbol("wkt2", VARCHAR)),
p.values(p.symbol("geometry1"), p.symbol("geometry2")))))
.matches(
spatialJoin("ST_Contains(st_geometryfromtext, geometry1) AND ST_Contains(ST_GeometryFromText(wkt2), geometry2)",
project(ImmutableMap.of("st_geometryfromtext", expression("ST_GeometryFromText(wkt1)")), values(ImmutableMap.of("wkt1", 0, "wkt2", 1))),
values(ImmutableMap.of("geometry1", 0, "geometry2", 1))));
}
private RuleAssert assertRuleApplication()
{
RuleTester tester = tester();
return tester.assertThat(new ExtractSpatialInnerJoin(tester.getMetadata(), tester.getSplitManager(), tester.getPageSourceManager(), tester.getSqlParser()));
}
}
| apache-2.0 |
patcadelina/rundeck | core/src/main/java/com/dtolabs/rundeck/plugins/scm/ScmUserInfoMissing.java | 1472 | package com.dtolabs.rundeck.plugins.scm;
/**
* Exception representing missing user info during an export action
*/
public class ScmUserInfoMissing extends ScmPluginException {
private String fieldName;
public ScmUserInfoMissing(final String fieldName, final String message) {
super(message);
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
/**
* Throw a ScmUserInfoMissing
*
* @param fieldName name of the missing field
*
* @throws ScmUserInfoMissing always
*/
public static void fieldMissing(String fieldName) throws ScmUserInfoMissing {
throw new ScmUserInfoMissing(fieldName, "Required user info field was not set: " + fieldName);
}
/**
* Check if an exception represents a missing user info field
*
* @param e plugin exception
*
* @return true if the exception is a {@link ScmUserInfoMissing}
*/
public static boolean isFieldMissing(ScmPluginException e) {
return e instanceof ScmUserInfoMissing;
}
/**
* Returns the missing field name if the exception is a {@link ScmUserInfoMissing}
*
* @param e exception
*
* @return missing field name, or null
*/
public static String missingFieldName(ScmPluginException e) {
if (isFieldMissing(e)) {
return ((ScmUserInfoMissing) e).getFieldName();
}
return null;
}
}
| apache-2.0 |
dkubiak/doctobook | app/src/main/java/com/github/dkubiak/doctobook/model/Visit.java | 4440 | package com.github.dkubiak.doctobook.model;
import java.math.BigDecimal;
import java.util.Date;
public final class Visit {
private long id;
private String patientName;
private Date date;
private ProcedureType procedureType;
private BigDecimal amount;
private BigDecimal extraCosts;
private int point;
private Office office;
public Visit(long id, String patientName, Date date, ProcedureType procedureType, BigDecimal amount, BigDecimal extraCosts, int point, Office office) {
this.id = id;
this.patientName = patientName;
this.date = date;
this.procedureType = procedureType;
this.amount = amount;
this.extraCosts = extraCosts;
this.point = point;
this.office = office;
}
public String getPatientName() {
return patientName;
}
public Date getDate() {
return date;
}
public ProcedureType getProcedureType() {
return procedureType;
}
public BigDecimal getAmount() {
return amount;
}
public int getPoint() {
return point;
}
public long getId() {
return id;
}
public Office getOffice() {
return office;
}
public BigDecimal getExtraCosts() {
return extraCosts;
}
public final static class Builder {
private long id;
private String patientName;
private Date date;
private ProcedureType procedureType;
private BigDecimal amount;
private int point;
private BigDecimal extraCosts;
private Office office = new Office.Builder().createOffice();
public Builder setPatientName(String patientName) {
this.patientName = patientName;
return this;
}
public Builder setDate(Date date) {
this.date = date;
return this;
}
public Builder setProcedureType(ProcedureType procedureType) {
this.procedureType = procedureType;
return this;
}
public Builder setAmount(BigDecimal amount) {
this.amount = amount;
return this;
}
public Builder setAmount(String amount) {
this.amount = amount.length() == 0 ? BigDecimal.ZERO : new BigDecimal(amount);
return this;
}
public Builder setExtraCosts(String extraCosts) {
this.extraCosts = extraCosts.length() == 0 ? BigDecimal.ZERO : new BigDecimal(extraCosts);
return this;
}
public Builder setPoint(int point) {
this.point = point;
return this;
}
public Builder setId(long id) {
this.id = id;
return this;
}
public Builder setOffice(Office office) {
this.office = office;
return this;
}
public Visit createVisit() {
return new Visit(id, patientName, date, procedureType, amount, extraCosts, point, office);
}
}
public final static class ProcedureType {
boolean prosthetics = false;
boolean endodontics = false;
boolean conservative = false;
public ProcedureType(boolean prosthetics, boolean endodontics, boolean conservative) {
this.prosthetics = prosthetics;
this.endodontics = endodontics;
this.conservative = conservative;
}
public boolean isProsthetics() {
return prosthetics;
}
public boolean isEndodontics() {
return endodontics;
}
public boolean isConservative() {
return conservative;
}
public final static class Builder {
private boolean prosthetics;
private boolean endodontics;
private boolean conservative;
public Builder isProsthetics() {
this.prosthetics = true;
return this;
}
public Builder isEndodontics() {
this.endodontics = true;
return this;
}
public Builder isConservative() {
this.conservative = true;
return this;
}
public Visit.ProcedureType createProcedureType() {
return new Visit.ProcedureType(prosthetics, endodontics, conservative);
}
}
}
}
| apache-2.0 |
aitusoftware/transport | src/test/java/com/aitusoftware/transport/integration/OrderGateway.java | 1674 | /*
* Copyright 2017 - 2018 Aitu Software Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aitusoftware.transport.integration;
public final class OrderGateway implements OrderNotifications
{
private final TradeNotifications tradeNotifications;
public OrderGateway(final TradeNotifications tradeNotifications)
{
this.tradeNotifications = tradeNotifications;
}
@Override
public void limitOrder(
final CharSequence symbol, final CharSequence orderId,
final boolean isBid, final long quantity, final double price, final int ecnId)
{
tradeNotifications.onOrderAccepted(symbol, orderId, isBid, quantity,
0, price, ecnId);
}
@Override
public void marketOrder(
final CharSequence symbol, final CharSequence orderId,
final boolean isBid, final long quantity, final int ecnId)
{
tradeNotifications.onOrderAccepted(symbol, orderId, isBid, quantity,
0, Double.MIN_VALUE, ecnId);
}
@Override
public void cancelOrder(final CharSequence orderId, final int ecnId)
{
// no-op
}
}
| apache-2.0 |
jexp/idea2 | plugins/InspectionGadgets/src/com/siyeh/ig/telemetry/TelemetryToolWindow.java | 924 | /*
* Copyright 2003-2005 Dave Griffith
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.telemetry;
import org.jetbrains.annotations.NonNls;
import com.intellij.openapi.project.Project;
public interface TelemetryToolWindow{
@NonNls String TOOL_WINDOW_ID = "IG Telemetry";
void register(Project project);
void show();
void close();
void unregister(Project project);
}
| apache-2.0 |
SH4DY/tripitude | backend/src/main/java/ac/tuwien/ase08/tripitude/controller/api/HistoryItemRestController.java | 2246 | package ac.tuwien.ase08.tripitude.controller.api;
import java.util.List;
import java.util.Locale;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import ac.tuwien.ase08.tripitude.entity.HistoryItem;
import ac.tuwien.ase08.tripitude.entity.User;
import ac.tuwien.ase08.tripitude.service.interfaces.IHistoryItemService;
import ac.tuwien.ase08.tripitude.service.interfaces.IUserService;
@Controller
@RequestMapping("api")
public class HistoryItemRestController {
@Autowired
private IHistoryItemService historyItemService;
@Autowired
private IUserService userService;
private static final Logger logger = LoggerFactory
.getLogger(HistoryItemRestController.class);
@RequestMapping(value = "user/{id}/historyitems", method = RequestMethod.GET)
@ResponseBody
public List<HistoryItem> getHistoryByUser(
@PathVariable Long id,
Locale locale, Model model) {
User user = userService.find(id);
List<HistoryItem> userHistory = historyItemService.getHistoryByUser(user);
return userHistory;
}
@PreAuthorize("hasRole('AUTHENTICATED')")
@RequestMapping(value = "user/historyitems", method = RequestMethod.GET)
@ResponseBody
public List<HistoryItem> getHistoryByCurrentUser(
Locale locale, Model model) {
List<HistoryItem> userHistory = historyItemService.getHistoryByUser(userService.getCurrentUser());
return userHistory;
}
@RequestMapping(value = "historyitem/{id}", method = RequestMethod.GET)
@ResponseBody
public HistoryItem getHistoryItem(@PathVariable Long id,Locale locale, Model model) throws NotFoundException {
HistoryItem h = historyItemService.find(id);
if (h == null) {
throw (new NotFoundException("historyitem not found"));
}
return h;
}
}
| apache-2.0 |
dbarentine/totalconnect | totalconnect/src/main/java/com/barentine/totalconnect/ws/DeviceStatusInfo.java | 2143 |
package com.barentine.totalconnect.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for DeviceStatusInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="DeviceStatusInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="lockInfo" type="{https://services.alarmnet.com/TC2/}LockStausInfo" minOccurs="0"/>
* <element name="securityInfo" type="{https://services.alarmnet.com/TC2/}SecurityStatusInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DeviceStatusInfo", propOrder = {
"lockInfo",
"securityInfo"
})
public class DeviceStatusInfo {
protected LockStausInfo lockInfo;
protected SecurityStatusInfo securityInfo;
/**
* Gets the value of the lockInfo property.
*
* @return
* possible object is
* {@link LockStausInfo }
*
*/
public LockStausInfo getLockInfo() {
return lockInfo;
}
/**
* Sets the value of the lockInfo property.
*
* @param value
* allowed object is
* {@link LockStausInfo }
*
*/
public void setLockInfo(LockStausInfo value) {
this.lockInfo = value;
}
/**
* Gets the value of the securityInfo property.
*
* @return
* possible object is
* {@link SecurityStatusInfo }
*
*/
public SecurityStatusInfo getSecurityInfo() {
return securityInfo;
}
/**
* Sets the value of the securityInfo property.
*
* @param value
* allowed object is
* {@link SecurityStatusInfo }
*
*/
public void setSecurityInfo(SecurityStatusInfo value) {
this.securityInfo = value;
}
}
| apache-2.0 |
AOEpeople/keycloak | model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/PolicyAdapter.java | 4803 | package org.keycloak.authorization.mongo.adapter;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.mongo.entities.PolicyEntity;
import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.models.mongo.keycloak.adapters.AbstractMongoAdapter;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class PolicyAdapter extends AbstractMongoAdapter<PolicyEntity> implements Policy {
private final PolicyEntity entity;
private final AuthorizationProvider authorizationProvider;
public PolicyAdapter(PolicyEntity entity, MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) {
super(invocationContext);
this.entity = entity;
this.authorizationProvider = authorizationProvider;
}
@Override
protected PolicyEntity getMongoEntity() {
return entity;
}
@Override
public String getId() {
return getMongoEntity().getId();
}
@Override
public String getType() {
return getMongoEntity().getType();
}
@Override
public DecisionStrategy getDecisionStrategy() {
return getMongoEntity().getDecisionStrategy();
}
@Override
public void setDecisionStrategy(DecisionStrategy decisionStrategy) {
getMongoEntity().setDecisionStrategy(decisionStrategy);
updateMongoEntity();
}
@Override
public Logic getLogic() {
return getMongoEntity().getLogic();
}
@Override
public void setLogic(Logic logic) {
getMongoEntity().setLogic(logic);
updateMongoEntity();
}
@Override
public Map<String, String> getConfig() {
return getMongoEntity().getConfig();
}
@Override
public void setConfig(Map<String, String> config) {
getMongoEntity().setConfig(config);
updateMongoEntity();
}
@Override
public String getName() {
return getMongoEntity().getName();
}
@Override
public void setName(String name) {
getMongoEntity().setName(name);
updateMongoEntity();
}
@Override
public String getDescription() {
return getMongoEntity().getDescription();
}
@Override
public void setDescription(String description) {
getMongoEntity().setDescription(description);
updateMongoEntity();
}
@Override
public ResourceServer getResourceServer() {
return this.authorizationProvider.getStoreFactory().getResourceServerStore().findById(getMongoEntity().getResourceServerId());
}
@Override
public Set<Policy> getAssociatedPolicies() {
return getMongoEntity().getAssociatedPolicies().stream()
.map((Function<String, Policy>) id -> authorizationProvider.getStoreFactory().getPolicyStore().findById(id))
.collect(Collectors.toSet());
}
@Override
public Set<Resource> getResources() {
return getMongoEntity().getResources().stream()
.map((Function<String, Resource>) id -> authorizationProvider.getStoreFactory().getResourceStore().findById(id))
.collect(Collectors.toSet());
}
@Override
public Set<Scope> getScopes() {
return getMongoEntity().getScopes().stream()
.map((Function<String, Scope>) id -> authorizationProvider.getStoreFactory().getScopeStore().findById(id))
.collect(Collectors.toSet());
}
@Override
public void addScope(Scope scope) {
getMongoEntity().addScope(scope.getId());
updateMongoEntity();
}
@Override
public void removeScope(Scope scope) {
getMongoEntity().removeScope(scope.getId());
updateMongoEntity();
}
@Override
public void addAssociatedPolicy(Policy associatedPolicy) {
getMongoEntity().addAssociatedPolicy(associatedPolicy.getId());
updateMongoEntity();
}
@Override
public void removeAssociatedPolicy(Policy associatedPolicy) {
getMongoEntity().removeAssociatedPolicy(associatedPolicy.getId());
updateMongoEntity();
}
@Override
public void addResource(Resource resource) {
getMongoEntity().addResource(resource.getId());
updateMongoEntity();
}
@Override
public void removeResource(Resource resource) {
getMongoEntity().removeResource(resource.getId());
updateMongoEntity();
}
}
| apache-2.0 |
youngwookim/presto | presto-hive/src/main/java/io/prestosql/plugin/hive/s3/HiveS3Module.java | 3103 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.hive.s3;
import com.google.inject.Binder;
import com.google.inject.Scopes;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.prestosql.plugin.hive.HiveConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.JavaUtils;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static io.airlift.configuration.ConfigBinder.configBinder;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
public class HiveS3Module
extends AbstractConfigurationAwareModule
{
private static final String EMR_FS_CLASS_NAME = "com.amazon.ws.emr.hadoop.fs.EmrFileSystem";
@Override
protected void setup(Binder binder)
{
S3FileSystemType type = buildConfigObject(HiveConfig.class).getS3FileSystemType();
if (type == S3FileSystemType.PRESTO) {
newSetBinder(binder, ConfigurationInitializer.class).addBinding().to(PrestoS3ConfigurationInitializer.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(HiveS3Config.class);
binder.bind(PrestoS3FileSystemStats.class).toInstance(PrestoS3FileSystem.getFileSystemStats());
newExporter(binder).export(PrestoS3FileSystemStats.class)
.as(generator -> generator.generatedNameOf(PrestoS3FileSystem.class));
}
else if (type == S3FileSystemType.EMRFS) {
validateEmrFsClass();
newSetBinder(binder, ConfigurationInitializer.class).addBinding().to(EmrFsS3ConfigurationInitializer.class).in(Scopes.SINGLETON);
}
else {
throw new RuntimeException("Unknown file system type: " + type);
}
}
private static void validateEmrFsClass()
{
// verify that the class exists
try {
Class.forName(EMR_FS_CLASS_NAME, true, JavaUtils.getClassLoader());
}
catch (ClassNotFoundException e) {
throw new RuntimeException("EMR File System class not found: " + EMR_FS_CLASS_NAME, e);
}
}
public static class EmrFsS3ConfigurationInitializer
implements ConfigurationInitializer
{
@Override
public void initializeConfiguration(Configuration config)
{
// re-map filesystem schemes to use the Amazon EMR file system
config.set("fs.s3.impl", EMR_FS_CLASS_NAME);
config.set("fs.s3a.impl", EMR_FS_CLASS_NAME);
config.set("fs.s3n.impl", EMR_FS_CLASS_NAME);
}
}
}
| apache-2.0 |
mproch/apache-ode | bpel-compiler/src/main/java/org/apache/ode/bpel/elang/xquery10/compiler/XQuery10ExpressionCompilerImpl.java | 17869 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.bpel.elang.xquery10.compiler;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQConstants;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQItemType;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQSequence;
import javax.xml.xquery.XQStaticContext;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.Validation;
import net.sf.saxon.xqj.SaxonXQConnection;
import net.sf.saxon.xqj.SaxonXQDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.compiler.api.CompilationException;
import org.apache.ode.bpel.compiler.api.CompilerContext;
import org.apache.ode.bpel.compiler.api.ExpressionCompiler;
import org.apache.ode.bpel.compiler.bom.Expression;
import org.apache.ode.bpel.elang.xpath10.compiler.XPathMessages;
import org.apache.ode.bpel.elang.xpath10.compiler.XslCompilationErrorListener;
import org.apache.ode.bpel.elang.xpath20.compiler.Constants;
import org.apache.ode.bpel.elang.xpath20.compiler.JaxpFunctionResolver;
import org.apache.ode.bpel.elang.xpath20.compiler.JaxpVariableResolver;
import org.apache.ode.bpel.elang.xpath20.compiler.WrappedResolverException;
import org.apache.ode.bpel.elang.xquery10.o.OXQuery10ExpressionBPEL20;
import org.apache.ode.bpel.o.OConstantVarType;
import org.apache.ode.bpel.o.OElementVarType;
import org.apache.ode.bpel.o.OExpression;
import org.apache.ode.bpel.o.OLValueExpression;
import org.apache.ode.bpel.o.OMessageVarType;
import org.apache.ode.bpel.o.OScope;
import org.apache.ode.bpel.o.OVarType;
import org.apache.ode.bpel.o.OXsdTypeVarType;
import org.apache.ode.bpel.o.OMessageVarType.Part;
import org.apache.ode.utils.DOMUtils;
import org.apache.ode.utils.NSContext;
import org.apache.ode.utils.Namespaces;
import org.apache.ode.utils.msg.MessageBundle;
import org.apache.ode.utils.xsl.XslTransformHandler;
import org.apache.xml.utils.XMLChar;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* XQuery compiler based on the SAXON implementation.
*/
public class XQuery10ExpressionCompilerImpl implements ExpressionCompiler {
protected static final Log __log = LogFactory.getLog(XQuery10ExpressionCompilerImpl.class);
protected String _bpelNS;
protected QName _qnLinkStatus;
protected QName _qnVarProp;
protected QName _qnVarData;
protected QName _qnXslTransform;
protected final XPathMessages __msgs = MessageBundle.getMessages(XPathMessages.class);
protected Map<String, String> _properties = new HashMap<String, String>();
protected CompilerContext _compilerContext;
public XQuery10ExpressionCompilerImpl(String bpelNS) {
_bpelNS = bpelNS;
_qnLinkStatus = new QName(_bpelNS, Constants.EXT_FUNCTION_GETLINKSTATUS);
_qnVarProp = new QName(_bpelNS, Constants.EXT_FUNCTION_GETVARIABLEPROPERTY);
_qnVarData = new QName(_bpelNS, Constants.EXT_FUNCTION_GETVARIABLEDATA);
_qnXslTransform = new QName(_bpelNS, Constants.EXT_FUNCTION_DOXSLTRANSFORM);
_properties.put("runtime-class", "org.apache.ode.bpel.elang.xquery10.runtime.XQuery10ExpressionRuntime");
TransformerFactory trsf = new net.sf.saxon.TransformerFactoryImpl();
XslTransformHandler.getInstance().setTransformerFactory(trsf);
}
public void setCompilerContext(CompilerContext compilerContext) {
_compilerContext = compilerContext;
XslCompilationErrorListener xe = new XslCompilationErrorListener(compilerContext);
XslTransformHandler.getInstance().setErrorListener(xe);
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compileJoinCondition(java.lang.Object)
*/
public OExpression compileJoinCondition(Object source) throws CompilationException {
return _compile((Expression) source, true);
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compile(java.lang.Object)
*/
public OExpression compile(Object source) throws CompilationException {
return _compile((Expression) source, false);
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compileLValue(java.lang.Object)
*/
public OLValueExpression compileLValue(Object source) throws CompilationException {
return (OLValueExpression) _compile((Expression) source, false);
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compile(java.lang.Object)
*/
private OExpression _compile(org.apache.ode.bpel.compiler.bom.Expression xquery, boolean isJoinCondition)
throws CompilationException {
OXQuery10ExpressionBPEL20 oexp = new OXQuery10ExpressionBPEL20(_compilerContext.getOProcess(), _qnVarData,
_qnVarProp, _qnLinkStatus, _qnXslTransform, isJoinCondition);
oexp.namespaceCtx = xquery.getNamespaceContext();
doJaxpCompile(oexp, xquery);
return oexp;
}
private void doJaxpCompile(OXQuery10ExpressionBPEL20 out, Expression source) throws CompilationException {
String xqueryStr;
Node node = source.getExpression();
if (node == null) {
throw new CompilationException(__msgs.errEmptyExpression(source.getURI(), new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
}
if (node.getNodeType() != Node.TEXT_NODE &&
node.getNodeType() != Node.ELEMENT_NODE &&
node.getNodeType() != Node.CDATA_SECTION_NODE) {
throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
}
xqueryStr = DOMUtils.domToString(node);
xqueryStr = xqueryStr.trim();
if (xqueryStr.length() == 0) {
throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
}
try {
XQDataSource xqds = new SaxonXQDataSource(new Configuration());
XQConnection xqconn = xqds.getConnection();
__log.debug("Compiling expression " + xqueryStr);
Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
configuration.setAllNodesUntyped(true);
configuration.setHostLanguage(Configuration.XQUERY);
XQStaticContext staticContext = xqconn.getStaticContext();
JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(
_compilerContext, out, source.getNamespaceContext(), _bpelNS);
JaxpVariableResolver variableResolver = new JaxpVariableResolver(
_compilerContext, out);
XQueryDeclarations declarations = new XQueryDeclarations();
NSContext nsContext = source.getNamespaceContext();
Set<String> prefixes = nsContext.getPrefixes();
if (!nsContext.getUriSet().contains(Namespaces.ODE_EXTENSION_NS)) {
nsContext.register("ode", Namespaces.ODE_EXTENSION_NS);
}
for (String prefix : prefixes) {
String uri = nsContext.getNamespaceURI(prefix);
staticContext.declareNamespace(prefix, uri);
if ("".equals(prefix)) {
declarations.declareDefaultElementNamespace(uri);
} else if ("bpws".equals(prefix)) {
declarations.declareNamespace("bpws", "java:" + Constants.XQUERY_FUNCTION_HANDLER_COMPILER);
} else {
declarations.declareNamespace(prefix, uri);
}
}
declarations.declareVariable(
getQName(nsContext, Namespaces.ODE_EXTENSION_NS, "pid"),
getQName(nsContext, Namespaces.XML_SCHEMA, "integer"));
// Map<URI, Source> schemaDocuments = _compilerContext.getSchemaSources();
// for (URI schemaUri : schemaDocuments.keySet()) {
// Source schemaSource = schemaDocuments.get(schemaUri);
// // Don't add schema sources, since our Saxon library is not schema-aware.
// // configuration.addSchemaSource(schemaSource);
// }
configuration.setSchemaValidationMode(Validation.SKIP);
List<OScope.Variable> variables = _compilerContext.getAccessibleVariables();
Map<QName, QName> variableTypes = new HashMap<QName, QName>();
for (String variableName : getVariableNames(xqueryStr)) {
OScope.Variable variable = getVariable(variables, variableName);
if (variable == null) {
continue;
}
OVarType type = variable.type;
QName nameQName = getNameQName(variableName);
QName typeQName = getTypeQName(variableName, type);
variableTypes.put(nameQName, typeQName);
String prefix = typeQName.getPrefix();
if (prefix == null || "".equals(prefix.trim())) {
prefix = getPrefixForUri(nsContext, typeQName.getNamespaceURI());
}
// don't declare typed variables, as our engine is not schema-aware
// declarations.declareVariable(variable.name, typeQName);
declarations.declareVariable(variableName);
}
// Add implicit declarations as prolog to the user-defined XQuery
out.xquery = declarations.toString() + xqueryStr;
// Check the XQuery for compilation errors
xqconn.setStaticContext(staticContext);
XQPreparedExpression exp = xqconn.prepareExpression(out.xquery);
// Pre-evaluate variables and functions by executing query
node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER,
funcResolver, null);
exp.bindItem(XQConstants.CONTEXT_ITEM,
xqconn.createItemFromNode(node, xqconn.createNodeType()));
// Bind external variables to dummy runtime values
for (QName variable : exp.getAllUnboundExternalVariables()) {
QName typeQName = variableTypes.get(variable);
Object value = variableResolver.resolveVariable(variable);
if (typeQName != null) {
if (value.getClass().getName().startsWith("java.lang")) {
exp.bindAtomicValue(variable, value.toString(),
xqconn.createAtomicType(XQItemType.XQBASETYPE_ANYATOMICTYPE));
} else if (value instanceof Node) {
exp.bindNode(variable, (Node) value, xqconn.createNodeType());
} else if (value instanceof NodeList) {
NodeList nodeList = (NodeList) value;
ArrayList nodeArray = new ArrayList();
for (int i = 0; i < nodeList.getLength(); i++) {
nodeArray.add(nodeList.item(i));
}
XQSequence sequence = xqconn.createSequence(nodeArray.iterator());
exp.bindSequence(variable, sequence);
}
}
}
// evaluate the expression so as to initialize the variables
try {
exp.executeQuery();
} catch (XQException xpee) {
// swallow errors caused by uninitialized variables
} finally {
// reset the expression's user data, in order to avoid
// serializing the function resolver in the compiled bpel file.
if (node != null) {
node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, null, null);
}
}
} catch (XQException xqe) {
__log.debug(xqe);
__log.info("Couldn't validate properly expression " + xqueryStr);
throw new CompilationException(__msgs.errXQuery10Syntax(xqueryStr, "Couldn't validate XQuery expression"));
} catch (WrappedResolverException wre) {
if (wre._compilationMsg != null)
throw new CompilationException(wre._compilationMsg, wre);
if (wre.getCause() instanceof CompilationException)
throw (CompilationException) wre.getCause();
throw wre;
}
}
public Map<String, String> getProperties() {
return _properties;
}
private String getQName(NSContext nsContext, String uri, String localPart) {
String prefix = getPrefixForUri(nsContext, uri);
return (prefix == null ? localPart : (prefix + ":" + localPart));
}
private String getPrefixForUri(NSContext nsContext, String uri) {
Set<String> prefixes = nsContext.getPrefixes();
for (String prefix : prefixes) {
String anUri = (nsContext.getNamespaceURI(prefix));
if (anUri != null && anUri.equals(uri)) {
return prefix;
}
}
return null;
}
protected static Collection<String> getVariableNames(String xquery) {
Collection<String> variableNames = new LinkedHashSet<String>();
for (int index = xquery.indexOf("$"); index != -1; index = xquery.indexOf("$")) {
StringBuilder variableName = new StringBuilder();
index++;
while(index < xquery.length() && XMLChar.isNCName(xquery.charAt(index))) {
variableName.append(xquery.charAt(index++));
}
variableNames.add(variableName.toString());
xquery = xquery.substring(index);
}
return variableNames;
}
private OScope.Variable getVariable(List<OScope.Variable> variables, String variableName) {
String declaredVariable = getVariableDeclaredName(variableName);
for (OScope.Variable variable : variables) {
if (variable.name.equals(declaredVariable)) {
return variable;
}
}
return null;
}
private String getVariableDeclaredName(String variableReference) {
int dotIndex = variableReference.indexOf(".");
return dotIndex >= 0 ? variableReference.substring(0, dotIndex) : variableReference;
}
private String getVariablePartName(String variableReference) {
int dotIndex = variableReference.indexOf(".");
return dotIndex >= 0 ? variableReference.substring(dotIndex + 1) : "";
}
private QName getNameQName(String variableName) {
String prefix = null, localName = null;;
int colonIndex = variableName.indexOf(":");
if (colonIndex >= 0) {
prefix = variableName.substring(0, colonIndex);
localName = variableName.substring(colonIndex + 1);
} else {
prefix = "";
localName = variableName;
}
return new QName(prefix, localName);
}
private QName getTypeQName(String variableName, OVarType type) {
QName typeQName = null;
if (type instanceof OConstantVarType) {
typeQName = new QName(Namespaces.XML_SCHEMA, "string", "xs");
} else if (type instanceof OElementVarType) {
typeQName = ((OElementVarType) type).elementType;
} else if (type instanceof OMessageVarType) {
Part part = ((OMessageVarType) type).parts.get(getVariablePartName(variableName));
if (part != null) {
typeQName = getTypeQName(variableName, part.type);
}
} else if (type instanceof OXsdTypeVarType) {
typeQName = ((OXsdTypeVarType) type).xsdType;
}
return typeQName;
}
private class XQueryDeclarations {
StringBuffer declarations = new StringBuffer();
public XQueryDeclarations() {}
public void declareVariable(String name, QName type) {
declareVariable(name, type.getPrefix() + ":" + type.getLocalPart());
}
public void declareVariable(String name, String type) {
declarations.append("declare variable ")
.append("$")
.append(name)
.append(" as ")
.append(type)
.append(" external ")
.append(";\n");
}
public void declareVariable(String name) {
declarations.append("declare variable ")
.append("$")
.append(name)
.append(" external ")
.append(";\n");
}
public void declareNamespace(String prefix, String uri) {
declarations.append("declare namespace ")
.append(prefix)
.append("=")
.append("\"" + uri + "\"")
.append(";\n");
}
public void declareDefaultElementNamespace(String uri) {
declarations.append("declare default element namespace ")
.append("\"" + uri + "\"")
.append(";\n");
}
public String toString() {
return declarations.toString();
}
}
}
| apache-2.0 |
ajm456/redgreenblue | src/game/grid/Grid.java | 5520 | package game.grid;
import game.entities.Entity;
import game.frame.Window;
/**
* A partitioned grid representing the viewable area in game. Each cell
* contains entities and is used to improve efficiency of collision
* detection.
*/
public class Grid
{
public final static int NUM_CELLS_TOTAL = 100;
/**
* Number of cells width-ways.
*/
public final static int NUM_OF_X_CELLS = 10;
/**
* Number of cells length-ways.
*/
public final static int NUM_OF_Y_CELLS = 10;
public final static int CELL_WIDTH = 60;
public final static int CELL_HEIGHT = 70;
private Entity[][] cells;
private CollisionListener gm;
/**
* Fills the Grid object with null entries.
* @param gm
*/
public Grid(CollisionListener gm) {
this.gm = gm;
cells = new Entity[10][10];
}
/**
* Adds an Entity to the correct cell based on its current
* position. If it is successfully added, true is returned -
* if it cannot be added (i.e. outside of the viewable area)
* false is returned.
*
* @param e the Entity object to be added to the grid
* @return true if the Entity object is added to a cell,
* false if not
*/
public boolean add(Entity e) {
if(!Window.BOUNDS.contains(e.getRectangle())) {
return false;
}
int cellX = (int) (e.getX() / CELL_WIDTH);
int cellY = (int) (e.getY() / CELL_HEIGHT);
e.setCellX(cellX);
e.setCellY(cellY);
e.setPrev(null);
e.setNext(cells[cellX][cellY]);
cells[cellX][cellY] = e;
if(e.getNext() != null) {
e.getNext().setPrev(e);
}
return true;
}
/**
* Iterates through the entire grid, calling {@link #handleCell(int, int) handleCell}
* on each cell.
*/
public void checkCollisions() {
for(int x=0; x<10; x++) {
for(int y=0; y<10; y++) {
handleCell(x, y);
}
}
}
/**
* For every Entity in a cell at given coordinates, checks
* whether said Entity object is colliding with any others.
* Also checks collisions with said Entity object and any
* Entity objects in surrounding cells (left and above only
* to prevent useless repetition).
*
* @param x the x location of the cell being checked
* @param y the y location of the cell being checked
*/
private void handleCell(int x, int y) {
Entity e = cells[x][y];
while(e != null) {
// Handle other units in this cell.
handleEntity(e, e.getNext());
// Also try the neighbouring cells.
if(x > 0 && y > 0)
handleEntity(e, cells[x-1][y-1]);
if(x > 0)
handleEntity(e, cells[x-1][y]);
if(y > 0)
handleEntity(e, cells[x][y-1]);
if(x > 0 && y < NUM_OF_Y_CELLS-1)
handleEntity(e, cells[x-1][y+1]);
e = e.getNext();
}
}
/**
* Checks for a collision between a primary Entity object and a
* secondary Entity object, before also checking the primary
* Entity object against every other Entity object in the secondary
* Entity object's cell.
*
* @param e the primary Entity object
* @param other the secondary Entity object
*/
public void handleEntity(Entity e, Entity other) {
while(other != null) {
if(e.getRectangle().intersects(other.getRectangle())) {
fireCollisionEvent(e, other);
}
other = other.getNext();
}
}
/**
* Handles the movement of an Entity from one position to a new one.
* Handled from inside the Grid class in order to correctly update
* which cell an Entity object is in should it change.
*
* @param e the Entity object moving
* @param x the new x location of the Entity object
* @param y the new y location of the Entity object
* @return true if the new location of the Entity object is
* inside the viewable area, false if not
*/
public boolean move(Entity e, double x, double y) {
// See which cell it was in.
int oldCellX = (int)(e.getX() / CELL_WIDTH);
int oldCellY = (int)(e.getY() / CELL_HEIGHT);
// See which cell it's moving to.
int cellX = (int)(x / CELL_WIDTH);
int cellY = (int)(y / CELL_HEIGHT);
e.setX(x);
e.setY(y);
// If it didn't change cells, we're done.
if(oldCellX == cellX && oldCellY == cellY) {
return true;
}
e.setCellX(cellX);
e.setCellY(cellY);
// Unlink it from the list of its old cell.
if(e.getPrev() != null) {
e.getPrev().setNext(e.getNext());
}
if(e.getNext() != null) {
e.getNext().setPrev(e.getPrev());
}
// If it's the head of a list, remove it.
if(cells[oldCellX][oldCellY] == e) {
cells[oldCellX][oldCellY] = e.getNext();
}
// Add it back to the grid at its new cell.
return add(e);
}
public void removeFromGrid(Entity e) {
// Unlink it from the list of its old cell.
if(e.getPrev() != null) {
e.getPrev().setNext(e.getNext());
}
if(e.getNext() != null) {
e.getNext().setPrev(e.getPrev());
}
// If it's the head of a list, remove it.
if(cells[e.getCellX()][e.getCellY()] == e) {
cells[e.getCellX()][e.getCellY()] = e.getNext();
}
}
/**
* Creates a new {@link game.grid.CollisionEvent CollisionEvent} and sends
* it to the current {@link game.main.GameEngine GameManager} object.
*
* @param e1 the first Entity object involved in the collision
* @param e2 the second Entity object involved in the collision
*/
private void fireCollisionEvent(Entity e1, Entity e2) {
gm.collisionOccurred(new CollisionEvent(this, e1, e2));
}
} | apache-2.0 |
wildfly-clustering/wildfly-clustering-tomcat | 10.0/catalina/src/main/java/org/wildfly/clustering/tomcat/catalina/authenticator/AuthenticationType.java | 1653 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.tomcat.catalina.authenticator;
import org.apache.catalina.authenticator.Constants;
import jakarta.servlet.http.HttpServletRequest;
/**
* @author Paul Ferraro
*/
public enum AuthenticationType {
BASIC(HttpServletRequest.BASIC_AUTH),
CLIENT_CERT(HttpServletRequest.CLIENT_CERT_AUTH),
DIGEST(HttpServletRequest.DIGEST_AUTH),
FORM(HttpServletRequest.FORM_AUTH),
SPNEGO(Constants.SPNEGO_METHOD),
;
private String name;
AuthenticationType(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
| apache-2.0 |
googlesamples/android-testdpc | app/src/main/java/com/afwsamples/testdpc/profilepolicy/ProfilePolicyManagementFragment.java | 18830 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afwsamples.testdpc.profilepolicy;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import androidx.preference.SwitchPreference;
import androidx.preference.Preference;
import android.widget.Toast;
import com.afwsamples.testdpc.DeviceAdminReceiver;
import com.afwsamples.testdpc.R;
import com.afwsamples.testdpc.common.AppInfoArrayAdapter;
import com.afwsamples.testdpc.common.BaseSearchablePolicyPreferenceFragment;
import com.afwsamples.testdpc.common.ColorPicker;
import com.afwsamples.testdpc.common.Util;
import com.afwsamples.testdpc.profilepolicy.crossprofileintentfilter.AddCrossProfileIntentFilterFragment;
import com.afwsamples.testdpc.profilepolicy.crossprofilewidgetprovider.ManageCrossProfileWidgetProviderUtil;
import java.util.List;
/**
* This fragment provides several functions that are available in a managed profile.
* These includes
* 1) {@link DevicePolicyManager#addCrossProfileIntentFilter(android.content.ComponentName,
* android.content.IntentFilter, int)}
* 2) {@link DevicePolicyManager#clearCrossProfileIntentFilters(android.content.ComponentName)}
* 3) {@link DevicePolicyManager#setCrossProfileCallerIdDisabled(android.content.ComponentName,
* boolean)}
* 4) {@link DevicePolicyManager#getCrossProfileCallerIdDisabled(android.content.ComponentName)}
* 5) {@link DevicePolicyManager#wipeData(int)}
* 6) {@link DevicePolicyManager#addCrossProfileWidgetProvider(android.content.ComponentName,
* String)}
* 7) {@link DevicePolicyManager#removeCrossProfileWidgetProvider(android.content.ComponentName,
* String)}
* 8) {@link DevicePolicyManager#setBluetoothContactSharingDisabled(ComponentName, boolean)}
*/
public class ProfilePolicyManagementFragment extends BaseSearchablePolicyPreferenceFragment implements
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener,
ColorPicker.OnColorSelectListener {
// Tag for creating this fragment. This tag can be used to retrieve this fragment.
public static final String FRAGMENT_TAG = "ProfilePolicyManagementFragment";
private static final String ADD_CROSS_PROFILE_APP_WIDGETS_KEY = "add_cross_profile_app_widgets";
private static final String ADD_CROSS_PROFILE_INTENT_FILTER_PREFERENCE_KEY
= "add_cross_profile_intent_filter";
private static final String CLEAR_CROSS_PROFILE_INTENT_FILTERS_PREFERENCE_KEY
= "clear_cross_profile_intent_filters";
private static final String DISABLE_BLUETOOTH_CONTACT_SHARING_KEY
= "disable_bluetooth_contact_sharing";
private static final String DISABLE_CROSS_PROFILE_CALLER_ID_KEY
= "disable_cross_profile_caller_id";
private static final String DISABLE_CROSS_PROFILE_CONTACTS_SEARCH_KEY
= "disable_cross_profile_contacts_search";
private static final String REMOVE_CROSS_PROFILE_APP_WIDGETS_KEY =
"remove_cross_profile_app_widgets";
private static final String REMOVE_PROFILE_KEY = "remove_profile";
private static final String SET_ORGANIZATION_COLOR_KEY = "set_organization_color";
private static final String SET_PROFILE_ORGANIZATION_NAME_KEY = "set_profile_organization_name";
private static final String ORGANIZATION_COLOR_ID = "organizationColor";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mAdminComponentName;
private Preference mAddCrossProfileIntentFilterPreference;
private Preference mClearCrossProfileIntentFiltersPreference;
private Preference mRemoveManagedProfilePreference;
private Preference mAddCrossProfileAppWidgetsPreference;
private Preference mRemoveCrossProfileAppWidgetsPreference;
private SwitchPreference mDisableBluetoothContactSharingSwitchPreference;
private SwitchPreference mDisableCrossProfileCallerIdSwitchPreference;
private SwitchPreference mDisableCrossProfileContactsSearchSwitchPreference;
private Preference mSetOrganizationNamePreference;
private Preference mSetOrganizationColorPreference;
@Override
public void onCreate(Bundle savedInstanceState) {
mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.profile_policy_header);
mAddCrossProfileIntentFilterPreference = findPreference(
ADD_CROSS_PROFILE_INTENT_FILTER_PREFERENCE_KEY);
mAddCrossProfileIntentFilterPreference.setOnPreferenceClickListener(this);
mClearCrossProfileIntentFiltersPreference = findPreference(
CLEAR_CROSS_PROFILE_INTENT_FILTERS_PREFERENCE_KEY);
mClearCrossProfileIntentFiltersPreference.setOnPreferenceClickListener(this);
mRemoveManagedProfilePreference = findPreference(REMOVE_PROFILE_KEY);
mRemoveManagedProfilePreference.setOnPreferenceClickListener(this);
mAddCrossProfileAppWidgetsPreference = findPreference(ADD_CROSS_PROFILE_APP_WIDGETS_KEY);
mAddCrossProfileAppWidgetsPreference.setOnPreferenceClickListener(this);
mRemoveCrossProfileAppWidgetsPreference = findPreference(
REMOVE_CROSS_PROFILE_APP_WIDGETS_KEY);
mRemoveCrossProfileAppWidgetsPreference.setOnPreferenceClickListener(this);
initSwitchPreferences();
initializeOrganizationInfoPreferences();
}
@Override
public boolean isAvailable(Context context) {
return Util.isManagedProfileOwner(context);
}
@Override
public void onResume() {
super.onResume();
getActivity().getActionBar().setTitle(R.string.profile_management_title);
if (!isAvailable(getActivity())) {
// Safe net: should never happen.
showToast(R.string.setup_management_message);
getActivity().finish();
}
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
switch (key) {
case ADD_CROSS_PROFILE_INTENT_FILTER_PREFERENCE_KEY:
showAddCrossProfileIntentFilterFragment();
return true;
case CLEAR_CROSS_PROFILE_INTENT_FILTERS_PREFERENCE_KEY:
mDevicePolicyManager.clearCrossProfileIntentFilters(mAdminComponentName);
showToast(R.string.cross_profile_intent_filters_cleared);
return true;
case REMOVE_PROFILE_KEY:
mRemoveManagedProfilePreference.setEnabled(false);
mDevicePolicyManager.wipeData(0);
showToast(R.string.removing_managed_profile);
// Finish the activity because all other functions will not work after the managed
// profile is removed.
getActivity().finish();
case ADD_CROSS_PROFILE_APP_WIDGETS_KEY:
showDisabledAppWidgetList();
return true;
case REMOVE_CROSS_PROFILE_APP_WIDGETS_KEY:
showEnabledAppWidgetList();
return true;
case SET_ORGANIZATION_COLOR_KEY:
int colorValue = getActivity().getResources().getColor(R.color.teal);
final CharSequence summary = mSetOrganizationColorPreference.getSummary();
if (summary != null) {
try {
colorValue = Color.parseColor(summary.toString());
} catch (IllegalArgumentException e) {
// Ignore
}
}
ColorPicker.newInstance(colorValue, FRAGMENT_TAG, ORGANIZATION_COLOR_ID)
.show(getFragmentManager(), "colorPicker");
}
return false;
}
@Override
@SuppressLint("NewApi")
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
switch (key) {
case DISABLE_BLUETOOTH_CONTACT_SHARING_KEY:
boolean disableBluetoothContactSharing = (Boolean) newValue;
mDevicePolicyManager.setBluetoothContactSharingDisabled(mAdminComponentName,
disableBluetoothContactSharing);
// Reload UI to verify the state of bluetooth contact sharing is set correctly.
reloadBluetoothContactSharing();
return true;
case DISABLE_CROSS_PROFILE_CALLER_ID_KEY:
boolean disableCrossProfileCallerId = (Boolean) newValue;
mDevicePolicyManager.setCrossProfileCallerIdDisabled(mAdminComponentName,
disableCrossProfileCallerId);
// Reload UI to verify the state of cross-profile caller Id is set correctly.
reloadCrossProfileCallerIdDisableUi();
return true;
case DISABLE_CROSS_PROFILE_CONTACTS_SEARCH_KEY:
boolean disableCrossProfileContactsSearch = (Boolean) newValue;
mDevicePolicyManager.setCrossProfileContactsSearchDisabled(mAdminComponentName,
disableCrossProfileContactsSearch);
// Reload UI to verify the state of cross-profile contacts search is set correctly.
reloadCrossProfileContactsSearchDisableUi();
return true;
case SET_PROFILE_ORGANIZATION_NAME_KEY:
mDevicePolicyManager.setOrganizationName(mAdminComponentName, (String) newValue);
mSetOrganizationNamePreference.setSummary((String) newValue);
return true;
}
return false;
}
@Override
@TargetApi(VERSION_CODES.N)
public void onColorSelected(int colorValue, String id) {
if (ORGANIZATION_COLOR_ID.equals(id)) {
mDevicePolicyManager.setOrganizationColor(mAdminComponentName, colorValue);
mSetOrganizationColorPreference.setSummary(
String.format(ColorPicker.COLOR_STRING_FORMATTER, colorValue));
}
}
@TargetApi(VERSION_CODES.N)
private void initializeOrganizationInfoPreferences() {
mSetOrganizationColorPreference = findPreference(SET_ORGANIZATION_COLOR_KEY);
mSetOrganizationNamePreference = findPreference(SET_PROFILE_ORGANIZATION_NAME_KEY);
if (mSetOrganizationColorPreference.isEnabled()) {
mSetOrganizationColorPreference.setOnPreferenceClickListener(this);
final int colorValue = mDevicePolicyManager.getOrganizationColor(mAdminComponentName);
mSetOrganizationColorPreference.setSummary(
String.format(ColorPicker.COLOR_STRING_FORMATTER, colorValue));
}
if (mSetOrganizationNamePreference.isEnabled()) {
mSetOrganizationNamePreference.setOnPreferenceChangeListener(this);
CharSequence organizationName = mDevicePolicyManager.getOrganizationName(
mAdminComponentName);
final String name = organizationName != null ? organizationName.toString() : null;
mSetOrganizationNamePreference.setSummary(name);
}
}
private void showAddCrossProfileIntentFilterFragment() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(
ProfilePolicyManagementFragment.class.getName()).replace(R.id.container,
new AddCrossProfileIntentFilterFragment()).commit();
}
private void initSwitchPreferences() {
mDisableBluetoothContactSharingSwitchPreference = (SwitchPreference) findPreference(
DISABLE_BLUETOOTH_CONTACT_SHARING_KEY);
mDisableCrossProfileCallerIdSwitchPreference = (SwitchPreference) findPreference(
DISABLE_CROSS_PROFILE_CALLER_ID_KEY);
mDisableCrossProfileContactsSearchSwitchPreference = (SwitchPreference) findPreference(
DISABLE_CROSS_PROFILE_CONTACTS_SEARCH_KEY);
mDisableBluetoothContactSharingSwitchPreference.setOnPreferenceChangeListener(this);
mDisableCrossProfileCallerIdSwitchPreference.setOnPreferenceChangeListener(this);
mDisableCrossProfileContactsSearchSwitchPreference.setOnPreferenceChangeListener(this);
reloadBluetoothContactSharing();
reloadCrossProfileCallerIdDisableUi();
}
@TargetApi(VERSION_CODES.M)
private void reloadBluetoothContactSharing() {
if (!mDisableBluetoothContactSharingSwitchPreference.isEnabled()) {
return;
}
boolean isBluetoothContactSharingDisabled = mDevicePolicyManager
.getBluetoothContactSharingDisabled(mAdminComponentName);
mDisableBluetoothContactSharingSwitchPreference
.setChecked(isBluetoothContactSharingDisabled);
}
private void reloadCrossProfileCallerIdDisableUi() {
if (!mDisableCrossProfileCallerIdSwitchPreference.isEnabled()) {
return;
}
boolean isCrossProfileCallerIdDisabled = mDevicePolicyManager
.getCrossProfileCallerIdDisabled(mAdminComponentName);
mDisableCrossProfileCallerIdSwitchPreference.setChecked(isCrossProfileCallerIdDisabled);
}
@TargetApi(VERSION_CODES.N)
private void reloadCrossProfileContactsSearchDisableUi() {
if (!mDisableCrossProfileContactsSearchSwitchPreference.isEnabled()) {
return;
}
boolean isCrossProfileContactsSearchDisabled = mDevicePolicyManager
.getCrossProfileContactsSearchDisabled(mAdminComponentName);
mDisableCrossProfileContactsSearchSwitchPreference.setChecked(
isCrossProfileContactsSearchDisabled);
}
/**
* Shows a list of work profile apps which have non-enabled widget providers.
* Clicking any item on the list will enable ALL the widgets from that app.
*
* Shows toast if there is no work profile app that has non-enabled widget providers.
*/
private void showDisabledAppWidgetList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
final List<String> disabledCrossProfileWidgetProvidersList
= ManageCrossProfileWidgetProviderUtil.getInstance(getActivity())
.getDisabledCrossProfileWidgetProvidersList();
if (disabledCrossProfileWidgetProvidersList.isEmpty()) {
showToast(R.string.all_cross_profile_widget_providers_are_enabled);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.layout.app_row, disabledCrossProfileWidgetProvidersList);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.add_cross_profile_app_widget_providers_title));
builder.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String pkgName = disabledCrossProfileWidgetProvidersList.get(which);
mDevicePolicyManager.addCrossProfileWidgetProvider(mAdminComponentName,
pkgName);
showToast(getString(R.string.cross_profile_widget_enable, pkgName));
dialog.dismiss();
}
});
builder.show();
}
}
/**
* Shows a list of work profile apps which have widget providers enabled.
* Clicking any item on the list will disable ALL the widgets from that app.
*
* Shows toast if there is no app that have non-enabled widget providers.
*/
private void showEnabledAppWidgetList() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
final List<String> enabledCrossProfileWidgetProvidersList = mDevicePolicyManager
.getCrossProfileWidgetProviders(mAdminComponentName);
if (enabledCrossProfileWidgetProvidersList.isEmpty()) {
showToast(R.string.all_cross_profile_widget_providers_are_disabled);
} else {
AppInfoArrayAdapter appInfoArrayAdapter = new AppInfoArrayAdapter(getActivity(),
R.layout.app_row, enabledCrossProfileWidgetProvidersList);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.remove_cross_profile_app_widget_providers_title));
builder.setAdapter(appInfoArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String pkgName = enabledCrossProfileWidgetProvidersList.get(which);
mDevicePolicyManager.removeCrossProfileWidgetProvider(mAdminComponentName,
pkgName);
showToast(getString(R.string.cross_profile_widget_disable, pkgName));
dialog.dismiss();
}
});
builder.show();
}
}
private void showToast(int msgId) {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, msgId, Toast.LENGTH_SHORT).show();
}
private void showToast(String msg) {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
}
}
| apache-2.0 |
manuelmagix/android_packages_apps_Settings | src/com/android/settings/ChooseLockPassword.java | 25249 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.PasswordEntryKeyboardHelper;
import com.android.internal.widget.PasswordEntryKeyboardView;
import com.android.settings.notification.RedactionInterstitial;
import android.app.Activity;
import android.app.Fragment;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class ChooseLockPassword extends SettingsActivity {
public static final String PASSWORD_MIN_KEY = "lockscreen.password_min";
public static final String PASSWORD_MAX_KEY = "lockscreen.password_max";
public static final String PASSWORD_MIN_LETTERS_KEY = "lockscreen.password_min_letters";
public static final String PASSWORD_MIN_LOWERCASE_KEY = "lockscreen.password_min_lowercase";
public static final String PASSWORD_MIN_UPPERCASE_KEY = "lockscreen.password_min_uppercase";
public static final String PASSWORD_MIN_NUMERIC_KEY = "lockscreen.password_min_numeric";
public static final String PASSWORD_MIN_SYMBOLS_KEY = "lockscreen.password_min_symbols";
public static final String PASSWORD_MIN_NONLETTER_KEY = "lockscreen.password_min_nonletter";
@Override
public Intent getIntent() {
Intent modIntent = new Intent(super.getIntent());
modIntent.putExtra(EXTRA_SHOW_FRAGMENT, getFragmentClass().getName());
return modIntent;
}
public static Intent createIntent(Context context, int quality, final boolean isFallback,
final boolean isFingerprintFallback,
int minLength, final int maxLength, boolean requirePasswordToDecrypt,
boolean confirmCredentials) {
Intent intent = new Intent().setClass(context, ChooseLockPassword.class);
intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality);
intent.putExtra(PASSWORD_MIN_KEY, minLength);
intent.putExtra(PASSWORD_MAX_KEY, maxLength);
intent.putExtra(ChooseLockGeneric.CONFIRM_CREDENTIALS, confirmCredentials);
intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback);
intent.putExtra(LockPatternUtils.LOCKSCREEN_FINGERPRINT_FALLBACK, isFingerprintFallback);
intent.putExtra(EncryptionInterstitial.EXTRA_REQUIRE_PASSWORD, requirePasswordToDecrypt);
return intent;
}
@Override
protected boolean isValidFragment(String fragmentName) {
if (ChooseLockPasswordFragment.class.getName().equals(fragmentName)) return true;
return false;
}
/* package */ Class<? extends Fragment> getFragmentClass() {
return ChooseLockPasswordFragment.class;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO: Fix on phones
// Disable IME on our window since we provide our own keyboard
//getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
//WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
super.onCreate(savedInstanceState);
CharSequence msg = getText(R.string.lockpassword_choose_your_password_header);
setTitle(msg);
}
public static class ChooseLockPasswordFragment extends Fragment
implements OnClickListener, OnEditorActionListener, TextWatcher {
private static final String KEY_FIRST_PIN = "first_pin";
private static final String KEY_UI_STAGE = "ui_stage";
private TextView mPasswordEntry;
private int mPasswordMinLength = 4;
private int mPasswordMaxLength = 16;
private int mPasswordMinLetters = 0;
private int mPasswordMinUpperCase = 0;
private int mPasswordMinLowerCase = 0;
private int mPasswordMinSymbols = 0;
private int mPasswordMinNumeric = 0;
private int mPasswordMinNonLetter = 0;
private LockPatternUtils mLockPatternUtils;
private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
private ChooseLockSettingsHelper mChooseLockSettingsHelper;
private Stage mUiStage = Stage.Introduction;
private boolean mDone = false;
private TextView mHeaderText;
private String mFirstPin;
private KeyboardView mKeyboardView;
private PasswordEntryKeyboardHelper mKeyboardHelper;
private boolean mIsAlphaMode;
private Button mCancelButton;
private Button mNextButton;
protected static final int CONFIRM_EXISTING_REQUEST = 58;
static final int RESULT_FINISHED = RESULT_FIRST_USER;
private static final long ERROR_MESSAGE_TIMEOUT = 3000;
private static final int MSG_SHOW_ERROR = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_SHOW_ERROR) {
updateStage((Stage) msg.obj);
}
}
};
/**
* Keep track internally of where the user is in choosing a pattern.
*/
protected enum Stage {
Introduction(R.string.lockpassword_choose_your_password_header,
R.string.lockpassword_choose_your_pin_header,
R.string.lockpassword_continue_label),
NeedToConfirm(R.string.lockpassword_confirm_your_password_header,
R.string.lockpassword_confirm_your_pin_header,
R.string.lockpassword_ok_label),
ConfirmWrong(R.string.lockpassword_confirm_passwords_dont_match,
R.string.lockpassword_confirm_pins_dont_match,
R.string.lockpassword_continue_label);
Stage(int hintInAlpha, int hintInNumeric, int nextButtonText) {
this.alphaHint = hintInAlpha;
this.numericHint = hintInNumeric;
this.buttonText = nextButtonText;
}
public final int alphaHint;
public final int numericHint;
public final int buttonText;
}
// required constructor for fragments
public ChooseLockPasswordFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLockPatternUtils = new LockPatternUtils(getActivity());
Intent intent = getActivity().getIntent();
if (!(getActivity() instanceof ChooseLockPassword)) {
throw new SecurityException("Fragment contained in wrong activity");
}
mRequestedQuality = Math.max(intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY,
mRequestedQuality), mLockPatternUtils.getRequestedPasswordQuality());
mPasswordMinLength = Math.max(
intent.getIntExtra(PASSWORD_MIN_KEY, mPasswordMinLength), mLockPatternUtils
.getRequestedMinimumPasswordLength());
mPasswordMaxLength = intent.getIntExtra(PASSWORD_MAX_KEY, mPasswordMaxLength);
mPasswordMinLetters = Math.max(intent.getIntExtra(PASSWORD_MIN_LETTERS_KEY,
mPasswordMinLetters), mLockPatternUtils.getRequestedPasswordMinimumLetters());
mPasswordMinUpperCase = Math.max(intent.getIntExtra(PASSWORD_MIN_UPPERCASE_KEY,
mPasswordMinUpperCase), mLockPatternUtils.getRequestedPasswordMinimumUpperCase());
mPasswordMinLowerCase = Math.max(intent.getIntExtra(PASSWORD_MIN_LOWERCASE_KEY,
mPasswordMinLowerCase), mLockPatternUtils.getRequestedPasswordMinimumLowerCase());
mPasswordMinNumeric = Math.max(intent.getIntExtra(PASSWORD_MIN_NUMERIC_KEY,
mPasswordMinNumeric), mLockPatternUtils.getRequestedPasswordMinimumNumeric());
mPasswordMinSymbols = Math.max(intent.getIntExtra(PASSWORD_MIN_SYMBOLS_KEY,
mPasswordMinSymbols), mLockPatternUtils.getRequestedPasswordMinimumSymbols());
mPasswordMinNonLetter = Math.max(intent.getIntExtra(PASSWORD_MIN_NONLETTER_KEY,
mPasswordMinNonLetter), mLockPatternUtils.getRequestedPasswordMinimumNonLetter());
mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.choose_lock_password, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mCancelButton = (Button) view.findViewById(R.id.cancel_button);
mCancelButton.setOnClickListener(this);
mNextButton = (Button) view.findViewById(R.id.next_button);
mNextButton.setOnClickListener(this);
mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality
|| DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality
|| DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality;
mKeyboardView = (PasswordEntryKeyboardView) view.findViewById(R.id.keyboard);
mPasswordEntry = (TextView) view.findViewById(R.id.password_entry);
mPasswordEntry.setOnEditorActionListener(this);
mPasswordEntry.addTextChangedListener(this);
final Activity activity = getActivity();
mKeyboardHelper = new PasswordEntryKeyboardHelper(activity,
mKeyboardView, mPasswordEntry);
mKeyboardHelper.setKeyboardMode(mIsAlphaMode ?
PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA
: PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
mHeaderText = (TextView) view.findViewById(R.id.headerText);
mKeyboardView.requestFocus();
int currentType = mPasswordEntry.getInputType();
mPasswordEntry.setInputType(mIsAlphaMode ? currentType
: (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
Intent intent = getActivity().getIntent();
final boolean confirmCredentials = intent.getBooleanExtra("confirm_credentials", true);
if (savedInstanceState == null) {
updateStage(Stage.Introduction);
if (confirmCredentials) {
mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST,
null, null);
}
} else {
mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN);
final String state = savedInstanceState.getString(KEY_UI_STAGE);
if (state != null) {
mUiStage = Stage.valueOf(state);
updateStage(mUiStage);
}
}
mDone = false;
if (activity instanceof SettingsActivity) {
final SettingsActivity sa = (SettingsActivity) activity;
int id = mIsAlphaMode ? R.string.lockpassword_choose_your_password_header
: R.string.lockpassword_choose_your_pin_header;
CharSequence title = getText(id);
sa.setTitle(title);
}
}
@Override
public void onResume() {
super.onResume();
updateStage(mUiStage);
mKeyboardView.requestFocus();
}
@Override
public void onPause() {
mHandler.removeMessages(MSG_SHOW_ERROR);
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_UI_STAGE, mUiStage.name());
outState.putString(KEY_FIRST_PIN, mFirstPin);
}
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CONFIRM_EXISTING_REQUEST:
if (resultCode != Activity.RESULT_OK) {
getActivity().setResult(RESULT_FINISHED);
getActivity().finish();
}
break;
}
}
protected Intent getRedactionInterstitialIntent(Context context) {
return RedactionInterstitial.createStartIntent(context);
}
protected void updateStage(Stage stage) {
final Stage previousStage = mUiStage;
mUiStage = stage;
updateUi();
// If the stage changed, announce the header for accessibility. This
// is a no-op when accessibility is disabled.
if (previousStage != stage) {
mHeaderText.announceForAccessibility(mHeaderText.getText());
}
}
/**
* Validates PIN and returns a message to display if PIN fails test.
* @param password the raw password the user typed in
* @return error message to show to user or null if password is OK
*/
private String validatePassword(String password) {
if (password.length() < mPasswordMinLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
}
if (password.length() > mPasswordMaxLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_long
: R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1);
}
int letters = 0;
int numbers = 0;
int lowercase = 0;
int symbols = 0;
int uppercase = 0;
int nonletter = 0;
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
// allow non control Latin-1 characters only
if (c < 32 || c > 127) {
return getString(R.string.lockpassword_illegal_character);
}
if (c >= '0' && c <= '9') {
numbers++;
nonletter++;
} else if (c >= 'A' && c <= 'Z') {
letters++;
uppercase++;
} else if (c >= 'a' && c <= 'z') {
letters++;
lowercase++;
} else {
symbols++;
nonletter++;
}
}
if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality
|| DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX == mRequestedQuality) {
if (letters > 0 || symbols > 0) {
// This shouldn't be possible unless user finds some way to bring up
// soft keyboard
return getString(R.string.lockpassword_pin_contains_non_digits);
}
// Check for repeated characters or sequences (e.g. '1234', '0000', '2468')
final int sequence = LockPatternUtils.maxLengthSequence(password);
if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX == mRequestedQuality
&& sequence > LockPatternUtils.MAX_ALLOWED_SEQUENCE) {
return getString(R.string.lockpassword_pin_no_sequential_digits);
}
} else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) {
if (letters < mPasswordMinLetters) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters),
mPasswordMinLetters);
} else if (numbers < mPasswordMinNumeric) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric),
mPasswordMinNumeric);
} else if (lowercase < mPasswordMinLowerCase) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase),
mPasswordMinLowerCase);
} else if (uppercase < mPasswordMinUpperCase) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase),
mPasswordMinUpperCase);
} else if (symbols < mPasswordMinSymbols) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols),
mPasswordMinSymbols);
} else if (nonletter < mPasswordMinNonLetter) {
return String.format(getResources().getQuantityString(
R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter),
mPasswordMinNonLetter);
}
} else {
final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
== mRequestedQuality;
final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
== mRequestedQuality;
if ((alphabetic || alphanumeric) && letters == 0) {
return getString(R.string.lockpassword_password_requires_alpha);
}
if (alphanumeric && numbers == 0) {
return getString(R.string.lockpassword_password_requires_digit);
}
}
if(mLockPatternUtils.checkPasswordHistory(password)) {
return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used
: R.string.lockpassword_pin_recently_used);
}
return null;
}
public void handleNext() {
if (mDone) return;
final String pin = mPasswordEntry.getText().toString();
if (TextUtils.isEmpty(pin)) {
return;
}
String errorMsg = null;
if (mUiStage == Stage.Introduction) {
errorMsg = validatePassword(pin);
if (errorMsg == null) {
mFirstPin = pin;
mPasswordEntry.setText("");
updateStage(Stage.NeedToConfirm);
}
} else if (mUiStage == Stage.NeedToConfirm) {
if (mFirstPin.equals(pin)) {
final boolean isFallback = getActivity().getIntent().getBooleanExtra(
LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
final boolean isFingerprintFallback = getActivity().getIntent().getBooleanExtra(
LockPatternUtils.LOCKSCREEN_FINGERPRINT_FALLBACK, false);
boolean wasSecureBefore = mLockPatternUtils.isSecure();
mLockPatternUtils.clearLock(isFallback);
final boolean required = getActivity().getIntent().getBooleanExtra(
EncryptionInterstitial.EXTRA_REQUIRE_PASSWORD, true);
mLockPatternUtils.setCredentialRequiredToDecrypt(required);
mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback,
isFingerprintFallback);
getActivity().setResult(RESULT_FINISHED);
getActivity().finish();
mDone = true;
if (!wasSecureBefore) {
startActivity(getRedactionInterstitialIntent(getActivity()));
}
} else {
CharSequence tmp = mPasswordEntry.getText();
if (tmp != null) {
Selection.setSelection((Spannable) tmp, 0, tmp.length());
}
updateStage(Stage.ConfirmWrong);
}
}
if (errorMsg != null) {
showError(errorMsg, mUiStage);
}
}
protected void setNextEnabled(boolean enabled) {
mNextButton.setEnabled(enabled);
}
protected void setNextText(int text) {
mNextButton.setText(text);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.next_button:
handleNext();
break;
case R.id.cancel_button:
getActivity().finish();
break;
}
}
private void showError(String msg, final Stage next) {
mHeaderText.setText(msg);
mHeaderText.announceForAccessibility(mHeaderText.getText());
Message mesg = mHandler.obtainMessage(MSG_SHOW_ERROR, next);
mHandler.removeMessages(MSG_SHOW_ERROR);
mHandler.sendMessageDelayed(mesg, ERROR_MESSAGE_TIMEOUT);
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Check if this was the result of hitting the enter or "done" key
if (actionId == EditorInfo.IME_NULL
|| actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT) {
handleNext();
return true;
}
return false;
}
/**
* Update the hint based on current Stage and length of password entry
*/
private void updateUi() {
String password = mPasswordEntry.getText().toString();
final int length = password.length();
if (mUiStage == Stage.Introduction && length > 0) {
if (length < mPasswordMinLength) {
String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
mHeaderText.setText(msg);
setNextEnabled(false);
} else {
String error = validatePassword(password);
if (error != null) {
mHeaderText.setText(error);
setNextEnabled(false);
} else {
mHeaderText.setText(R.string.lockpassword_press_continue);
setNextEnabled(true);
}
}
} else {
mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
setNextEnabled(length > 0);
}
setNextText(mUiStage.buttonText);
}
public void afterTextChanged(Editable s) {
// Changing the text while error displayed resets to NeedToConfirm state
if (mUiStage == Stage.ConfirmWrong) {
mUiStage = Stage.NeedToConfirm;
}
updateUi();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
}
| apache-2.0 |
phax/ph-commons | ph-commons/src/test/java/com/helger/commons/id/factory/FileIntIDFactoryTest.java | 2452 | /*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.commons.id.factory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import org.junit.Test;
import com.helger.commons.io.file.FileOperations;
import com.helger.commons.mock.CommonsTestHelper;
/**
* Test class for class {@link FileIntIDFactory}.
*
* @author Philip Helger
*/
public final class FileIntIDFactoryTest
{
@Test
public void testAll ()
{
final File f = new File ("my-file-with.ids");
final File f2 = new File ("my-other-file-with.ids");
try
{
final FileIntIDFactory x = new FileIntIDFactory (f);
// Compare before retrieving an ID!
CommonsTestHelper.testDefaultImplementationWithEqualContentObject (x, new FileIntIDFactory (f));
CommonsTestHelper.testDefaultImplementationWithDifferentContentObject (x, new FileIntIDFactory (f2));
CommonsTestHelper.testDefaultImplementationWithDifferentContentObject (x,
new FileIntIDFactory (f,
FileIntIDFactory.DEFAULT_RESERVE_COUNT *
2));
for (int i = 0; i < x.getReserveCount () * 10; ++i)
assertEquals (i, x.getNewID ());
}
finally
{
FileOperations.deleteFile (f);
FileOperations.deleteFile (f2);
}
try
{
new FileIntIDFactory (null);
fail ();
}
catch (final NullPointerException ex)
{}
try
{
// Invalid reserve count
new FileIntIDFactory (new File ("any"), 0);
fail ();
}
catch (final IllegalArgumentException ex)
{}
}
}
| apache-2.0 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusternodegroup_clusternode_binding.java | 8317 | /*
* Copyright (c) 2008-2015 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.citrix.netscaler.nitro.resource.config.cluster;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class clusternodegroup_clusternode_binding_response extends base_response
{
public clusternodegroup_clusternode_binding[] clusternodegroup_clusternode_binding;
}
/**
* Binding class showing the clusternode that can be bound to clusternodegroup.
*/
public class clusternodegroup_clusternode_binding extends base_resource
{
private Long node;
private String name;
private Long __count;
/**
* <pre>
* Name of the nodegroup. The name uniquely identifies the nodegroup on the cluster.<br> Minimum length = 1
* </pre>
*/
public void set_name(String name) throws Exception{
this.name = name;
}
/**
* <pre>
* Name of the nodegroup. The name uniquely identifies the nodegroup on the cluster.<br> Minimum length = 1
* </pre>
*/
public String get_name() throws Exception {
return this.name;
}
/**
* <pre>
* Nodes in the nodegroup.<br> Minimum value = 0<br> Maximum value = 31
* </pre>
*/
public void set_node(long node) throws Exception {
this.node = new Long(node);
}
/**
* <pre>
* Nodes in the nodegroup.<br> Minimum value = 0<br> Maximum value = 31
* </pre>
*/
public void set_node(Long node) throws Exception{
this.node = node;
}
/**
* <pre>
* Nodes in the nodegroup.<br> Minimum value = 0<br> Maximum value = 31
* </pre>
*/
public Long get_node() throws Exception {
return this.node;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
clusternodegroup_clusternode_binding_response result = (clusternodegroup_clusternode_binding_response) service.get_payload_formatter().string_to_resource(clusternodegroup_clusternode_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.clusternodegroup_clusternode_binding;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return null;
}
public static base_response add(nitro_service client, clusternodegroup_clusternode_binding resource) throws Exception {
clusternodegroup_clusternode_binding updateresource = new clusternodegroup_clusternode_binding();
updateresource.name = resource.name;
updateresource.node = resource.node;
return updateresource.update_resource(client);
}
public static base_responses add(nitro_service client, clusternodegroup_clusternode_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
clusternodegroup_clusternode_binding updateresources[] = new clusternodegroup_clusternode_binding[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new clusternodegroup_clusternode_binding();
updateresources[i].name = resources[i].name;
updateresources[i].node = resources[i].node;
}
result = update_bulk_request(client, updateresources);
}
return result;
}
public static base_response delete(nitro_service client, clusternodegroup_clusternode_binding resource) throws Exception {
clusternodegroup_clusternode_binding deleteresource = new clusternodegroup_clusternode_binding();
deleteresource.name = resource.name;
deleteresource.node = resource.node;
return deleteresource.delete_resource(client);
}
public static base_responses delete(nitro_service client, clusternodegroup_clusternode_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
clusternodegroup_clusternode_binding deleteresources[] = new clusternodegroup_clusternode_binding[resources.length];
for (int i=0;i<resources.length;i++){
deleteresources[i] = new clusternodegroup_clusternode_binding();
deleteresources[i].name = resources[i].name;
deleteresources[i].node = resources[i].node;
}
result = delete_bulk_request(client, deleteresources);
}
return result;
}
/**
* Use this API to fetch filtered set of clusternodegroup_clusternode_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static clusternodegroup_clusternode_binding[] get_filtered(nitro_service service, clusternodegroup_clusternode_binding obj, String filter) throws Exception{
options option = new options();
option.set_filter(filter);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_clusternode_binding[] response = (clusternodegroup_clusternode_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of clusternodegroup_clusternode_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static clusternodegroup_clusternode_binding[] get_filtered(nitro_service service, clusternodegroup_clusternode_binding obj, filtervalue[] filter) throws Exception{
options option = new options();
option.set_filter(filter);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_clusternode_binding[] response = (clusternodegroup_clusternode_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count clusternodegroup_clusternode_binding resources configued on NetScaler.
*/
public static long count(nitro_service service, clusternodegroup_clusternode_binding obj) throws Exception{
options option = new options();
option.set_count(true);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_clusternode_binding response[] = (clusternodegroup_clusternode_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of clusternodegroup_clusternode_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static long count_filtered(nitro_service service, clusternodegroup_clusternode_binding obj, String filter) throws Exception{
options option = new options();
option.set_count(true);
option.set_filter(filter);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_clusternode_binding[] response = (clusternodegroup_clusternode_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of clusternodegroup_clusternode_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, clusternodegroup_clusternode_binding obj, filtervalue[] filter) throws Exception{
options option = new options();
option.set_count(true);
option.set_filter(filter);
option.set_args(nitro_util.object_to_string_withoutquotes(obj));
clusternodegroup_clusternode_binding[] response = (clusternodegroup_clusternode_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
} | apache-2.0 |
jl1955/uPortal5 | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/DirectoryScanner.java | 1991 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.utils;
import com.google.common.base.Function;
import java.io.File;
import java.io.FileFilter;
import java.util.Map;
import org.springframework.core.io.Resource;
/**
* Scans a directory structure for files.
*
*/
public interface DirectoryScanner {
/**
* Scan the specified directory. Returning a {@link Map} of the processed results.
*
* @param directory The directory to scan
* @param fileFilter Used to filter the files during processing
* @param fileProcessor Callback, called for each matched {@link File}
* @return The Map of the processed results from the source file the result
*/
public abstract <T> Map<File, T> scanDirectoryWithResults(
File directory, FileFilter fileFilter, Function<Resource, T> fileProcessor);
/**
* Scan the specified directory.
*
* @param directory The directory to scan
* @param fileFilter Used to filter the files during processing
* @param fileProcessor Callback, called for each matched {@link File}
*/
public abstract void scanDirectoryNoResults(
File directory, FileFilter fileFilter, Function<Resource, ?> fileProcessor);
}
| apache-2.0 |
telefonicaid/fiware-cosmos-ambari | ambari-server/src/main/java/org/apache/ambari/server/orm/entities/HostComponentConfigMappingEntityPK.java | 3590 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.orm.entities;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class HostComponentConfigMappingEntityPK implements Serializable {
private Long clusterId;
private String serviceName;
private String componentName;
private String hostName;
private String configType;
@Id
@Column(name = "cluster_id", insertable = true, updatable = true, nullable = false, length = 10)
public Long getClusterId() {
return clusterId;
}
public void setClusterId(Long clusterId) {
this.clusterId = clusterId;
}
@Id
@Column(name = "service_name", insertable = true, updatable = true, nullable = false)
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
@Column(name = "component_name", insertable = true, updatable = true, nullable = false)
@Id
public String getComponentName() {
return componentName;
}
public void setComponentName(String name) {
componentName = name;
}
@Column(name = "host_name", insertable = true, updatable = true, nullable = false)
@Id
public String getHostName() {
return hostName;
}
public void setHostName(String name) {
hostName = name;
}
@Column(name = "config_type", insertable = true, updatable = false, nullable = false)
@Id
public String getConfigType() {
return configType;
}
public void setConfigType(String configType) {
this.configType = configType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HostComponentConfigMappingEntityPK that = (HostComponentConfigMappingEntityPK) o;
if (clusterId != null ? !clusterId.equals(that.clusterId) : that.clusterId != null) return false;
if (componentName != null ? !componentName.equals(that.componentName) : that.componentName != null) return false;
if (serviceName != null ? !serviceName.equals(that.serviceName) : that.serviceName != null) return false;
if (hostName != null ? !hostName.equals(that.hostName) : that.hostName != null) return false;
if (configType != null ? !configType.equals(that.configType) : that.configType != null) return false;
return true;
}
@Override
public int hashCode() {
int result = clusterId != null ? clusterId.intValue() : 0;
result = 31 * result + (serviceName != null ? serviceName.hashCode() : 0);
result = 31 * result + (componentName != null ? componentName.hashCode() : 0);
result = 31 * result + (hostName != null ? hostName.hashCode() : 0);
result = 31 * result + (configType != null ? configType.hashCode() : 0);
return result;
}
}
| apache-2.0 |
StathVaille/Imports | src/main/java/com/github/stathvaille/marketimports/MarketImportsApplication.java | 455 | package com.github.stathvaille.marketimports;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties
public class MarketImportsApplication {
public static void main(String[] args) {
SpringApplication.run(MarketImportsApplication.class, args);
}
}
| apache-2.0 |
google-code/android-scripting | jruby/src/src/org/jruby/management/ParserStatsMBean.java | 265 | package org.jruby.management;
public interface ParserStatsMBean {
public double getTotalParseTime();
public double getParseTimePerKB();
public int getTotalParsedBytes();
public int getNumberOfEvalParses();
public int getNumberOfLoadParses();
}
| apache-2.0 |
boldtrn/graphhopper-geocoder-converter | src/test/java/com/graphhopper/converter/resource/ConverterResourceNominatimTest.java | 7426 | package com.graphhopper.converter.resource;
import com.graphhopper.converter.ConverterApplication;
import com.graphhopper.converter.ConverterConfiguration;
import com.graphhopper.converter.api.GHResponse;
import io.dropwizard.client.JerseyClientBuilder;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.glassfish.jersey.client.ClientProperties;
import org.junit.ClassRule;
import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* @author Robin Boldt
*/
public class ConverterResourceNominatimTest {
@ClassRule
public static final DropwizardAppRule<ConverterConfiguration> RULE =
new DropwizardAppRule<>(ConverterApplication.class, ResourceHelpers.resourceFilePath("converter.yml"));
@Test
public void testHandleForward() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("test forward client");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
assertTrue(entry.getLocale().equals("en"));
// This might change in OSM and we might need to update this test then
List<Double> extent = entry.getHits().get(0).getExtent().getExtent();
assertEquals(extent.get(0), 13.2, .1);
assertEquals(extent.get(1), 52.3, .1);
assertEquals(extent.get(2), 13.5, .1);
assertEquals(extent.get(3), 52.6, .1);
}
@Test
public void testIssue38() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testIssue38");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin", RULE.getLocalPort()))
.request()
.get();
// Get the raw json String to check the structure of the json
String responseString = response.readEntity(String.class);
assertTrue(responseString.contains("\"extent\":["));
assertFalse(responseString.contains("\"extent\":{\"extent\""));
}
@Test
public void testHandleReverse() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("test reverse client");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?point=52.5487429714954,-1.81602098644987&reverse=true", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
public void testCorrectLocale() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testCorrectLocale");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin&locale=de", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
assertTrue(entry.getLocale().equals("de"));
}
@Test
public void testCorrectLocaleCountry() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testCorrectLocaleCountry");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin&locale=de-ch", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
assertTrue(entry.getLocale().equals("de-CH"));
}
@Test
public void testIncorrectLocale() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testIncorrectLocale");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin&locale=IAmNotValid", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
assertTrue(entry.getLocale().equals("en"));
}
@Test
public void testIncorrectLocaleCountry() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testIncorrectLocaleCountry");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?q=berlin&locale=de-zz", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
assertTrue(entry.getLocale().equals("en"));
}
@Test
public void testIncorrectFormattedPoint() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("testIncorrectFormattedPoint");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?reverse=true&point=NaN,NaN", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(400);
}
@Test
public void testIssue50() {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("test issue 50");
client.property(ClientProperties.CONNECT_TIMEOUT, 100000);
client.property(ClientProperties.READ_TIMEOUT, 100000);
Response response = client.target(
String.format("http://localhost:%d/nominatim?point=48.4882,2.6996&reverse=true", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
GHResponse entry = response.readEntity(GHResponse.class);
// OCD responds with "Seine-et-Marne", both seem to be interlinked: https://en.wikipedia.org/wiki/Fontainebleau
assertEquals("Fontainebleau", entry.getHits().get(0).getCounty());
}
}
| apache-2.0 |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/PutTask.java | 2012 | package com.magicmicky.habitrpglibrary.onlineapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import com.magicmicky.habitrpglibrary.habits.HabitItem;
import com.magicmicky.habitrpglibrary.onlineapi.WebServiceInteraction.Answer;
import com.magicmicky.habitrpglibrary.onlineapi.helper.ParseErrorException;
import com.magicmicky.habitrpglibrary.onlineapi.helper.ParserHelper;
/**
* Edit a task.
* @see PostTask#findAnswer(JSONObject)
* @author Mickael
*
*/
public class PutTask extends PostTask {
private static final String CMD = "user/tasks/";
public PutTask(OnHabitsAPIResult callback, HostConfig config, HabitItem habit) {
super(CMD + habit.getId(), callback, config, habit);
}
@Override
protected HttpRequestBase getRequest() {
HttpPut method = new HttpPut();
try {
StringEntity ent = new StringEntity(habit.getJSONString(), "utf-8");
ent.setContentType("application/json; charset=UTF-8");
method.setEntity(ent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return method;
}
@Override
protected Answer findAnswer(JSONObject answer) {
return new PutTaskData(answer, this.getCallback());
}
private class PutTaskData extends Answer {
public PutTaskData(JSONObject obj, OnHabitsAPIResult callback) {
super(obj, callback);
}
public void parse() {
HabitItem it;
try {
it = ParserHelper.parseHabitItem(getObject());
if(this.callback != null)
this.callback.onEditTaskAnswer(it);
} catch (ParseErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(this.callback != null)
this.callback.onError(e);
}
}
}
}
| apache-2.0 |
intuit/wasabi | modules/experiment-objects/src/test/java/com/intuit/wasabi/experimentobjects/NewExperimentTest.java | 4627 | /*******************************************************************************
* Copyright 2016 Intuit
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.intuit.wasabi.experimentobjects;
import org.junit.Test;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Test for the {@link NewExperiment} class.
*/
public class NewExperimentTest {
@Test
public void testBuilderCreation() {
Experiment.ID id = Experiment.ID.newInstance();
Date date = new Date();
String[] tagsArray = {"ui", "mobile", "12&"};
Set<String> tags = new HashSet<>(Arrays.asList(tagsArray));
NewExperiment.Builder builder = NewExperiment.withID(id);
NewExperiment newExperiment = builder.withDescription("desc")
.withIsPersonalizationEnabled(true)
.withModelName("m1")
.withModelVersion("v1")
.withRule("r1==1")
.withSamplingPercent(0.5)
.withStartTime(date)
.withEndTime(date)
.withLabel(Experiment.Label.valueOf("label"))
.withAppName(Application.Name.valueOf("app"))
.withIsRapidExperiment(true)
.withUserCap(1000)
.withCreatorID("c1")
.withTags(tags)
.build();
assertThat(newExperiment.getApplicationName(), is(Application.Name.valueOf("app")));
assertThat(newExperiment.getIsRapidExperiment(), is(true));
assertThat(newExperiment.getUserCap(), is(1000));
assertThat(newExperiment.getModelVersion(), is("v1"));
assertThat(newExperiment.getState(), is(Experiment.State.DRAFT));
assertThat(newExperiment.getCreatorID(), is("c1"));
assertThat(newExperiment.getID(), is(id));
assertThat(newExperiment.getDescription(), is("desc"));
assertThat(newExperiment.getLabel(), is(Experiment.Label.valueOf("label")));
assertThat(newExperiment.getTags().size(), is(3));
Arrays.sort(tagsArray); // the tags should be sorted
assertThat(newExperiment.getTags().toArray(), is(tagsArray));
newExperiment.setApplicationName(Application.Name.valueOf("NewApp"));
newExperiment.setCreatorID("c2");
assertThat(newExperiment.getApplicationName(), is(Application.Name.valueOf("NewApp")));
assertThat(newExperiment.getCreatorID(), is("c2"));
}
@Test(expected = IllegalArgumentException.class)
public void testBuildBadSamplePercentage() {
NewExperiment newExperiment = NewExperiment.withID(Experiment.ID.newInstance())
.withDescription("desc")
.withIsPersonalizationEnabled(true)
.withModelName("m1")
.withModelVersion("v1")
.withRule("r1")
.withSamplingPercent(null) //<-- this is what causes the exception
.withLabel(Experiment.Label.valueOf("label"))
.withAppName(Application.Name.valueOf("app"))
.withIsRapidExperiment(true)
.withUserCap(1000)
.withCreatorID("c1")
.build();
fail();
}
// New Experiment build should throw IllegalArgumentException when
// personalization is enabled and model name is not specified
@Test(expected = IllegalArgumentException.class)
public void testExperimentPartialPersonalizationInfo() {
NewExperiment.withID(Experiment.ID.newInstance())
.withAppName(Application.Name.valueOf("app"))
.withLabel(Experiment.Label.valueOf("label"))
.withIsPersonalizationEnabled(true)
.withSamplingPercent(0.5)
.withStartTime(new Date())
.withEndTime(new Date())
.withDescription("test").build();
}
}
| apache-2.0 |
gavanx/pdflearn | pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/function/type4/InstructionSequenceBuilder.java | 3703 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.common.function.type4;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Basic parser for Type 4 functions which is used to build up instruction sequences.
*/
public final class InstructionSequenceBuilder extends Parser.AbstractSyntaxHandler {
private final InstructionSequence mainSequence = new InstructionSequence();
private final Stack<InstructionSequence> seqStack = new Stack<InstructionSequence>();
private InstructionSequenceBuilder() {
this.seqStack.push(this.mainSequence);
}
/**
* Returns the instruction sequence that has been build from the syntactic elements.
*
* @return the instruction sequence
*/
public InstructionSequence getInstructionSequence() {
return this.mainSequence;
}
/**
* Parses the given text into an instruction sequence representing a Type 4 function
* that can be executed.
*
* @param text the Type 4 function text
* @return the instruction sequence
*/
public static InstructionSequence parse(CharSequence text) {
InstructionSequenceBuilder builder = new InstructionSequenceBuilder();
Parser.parse(text, builder);
return builder.getInstructionSequence();
}
private InstructionSequence getCurrentSequence() {
return this.seqStack.peek();
}
private static final Pattern INTEGER_PATTERN = Pattern.compile("[\\+\\-]?\\d+");
private static final Pattern REAL_PATTERN = Pattern.compile("[\\-]?\\d*\\.\\d*([Ee]\\-?\\d+)?");
/** {@inheritDoc} */
@Override
public void token(CharSequence text) {
String token = text.toString();
token(token);
}
private void token(String token) {
if ("{".equals(token)) {
InstructionSequence child = new InstructionSequence();
getCurrentSequence().addProc(child);
this.seqStack.push(child);
} else if ("}".equals(token)) {
this.seqStack.pop();
} else {
Matcher m = INTEGER_PATTERN.matcher(token);
if (m.matches()) {
getCurrentSequence().addInteger(parseInt(token));
return;
}
m = REAL_PATTERN.matcher(token);
if (m.matches()) {
getCurrentSequence().addReal(parseReal(token));
return;
}
//TODO Maybe implement radix numbers, such as 8#1777 or 16#FFFE
getCurrentSequence().addName(token);
}
}
/**
* Parses a value of type "int".
*
* @param token the token to be parsed
* @return the parsed value
*/
public static int parseInt(String token) {
//TODO Beginning with JDK7 Integer.parseInt accepts leading +'s
return Integer.parseInt(token.startsWith("+") ? token.substring(1) : token);
}
/**
* Parses a value of type "real".
*
* @param token the token to be parsed
* @return the parsed value
*/
public static float parseReal(String token) {
return Float.parseFloat(token);
}
}
| apache-2.0 |
Treydone/mandrel | mandrel-core/src/main/java/io/mandrel/requests/proxy/NoProxyProxyServersSource.java | 1779 | /*
* Licensed to Mandrel under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Mandrel licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.mandrel.requests.proxy;
import io.mandrel.common.data.Job;
import io.mandrel.common.service.TaskContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true, fluent = true)
@EqualsAndHashCode(callSuper = false)
public class NoProxyProxyServersSource extends ProxyServersSource {
@Data
@Accessors(chain = false, fluent = false)
@EqualsAndHashCode(callSuper = false)
public static class NoProxyProxyServersSourceDefinition extends ProxyServersSourceDefinition<NoProxyProxyServersSource> {
private static final long serialVersionUID = 4179034020754804054L;
@Override
public NoProxyProxyServersSource build(TaskContext context) {
return new NoProxyProxyServersSource(context);
}
@Override
public String name() {
return "no";
}
}
public NoProxyProxyServersSource(TaskContext context) {
super(context);
}
public ProxyServer findProxy(Job job) {
return null;
}
public void init() {
}
}
| apache-2.0 |
sonu283304/onos | protocols/ospf/protocol/src/main/java/org/onosproject/ospf/protocol/lsa/linksubtype/MaximumReservableBandwidth.java | 3351 | /*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.ospf.protocol.lsa.linksubtype;
import com.google.common.base.MoreObjects;
import com.google.common.primitives.Bytes;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.ospf.protocol.lsa.TlvHeader;
import org.onosproject.ospf.protocol.util.OspfUtil;
/**
* Representation of maximum reservable bandwidth TE value.
*/
public class MaximumReservableBandwidth extends TlvHeader implements LinkSubType {
private float maximumReservableBandwidth;
/**
* Creates an instance of maximum reservable bandwidth.
*
* @param header tlv header
*/
public MaximumReservableBandwidth(TlvHeader header) {
this.setTlvType(header.tlvType());
this.setTlvLength(header.tlvLength());
}
/**
* Sets value of maximum reversible bandwidth.
*
* @param maximumBandwidth maximum reversible bandwidth
*/
public void setMaximumBandwidth(float maximumBandwidth) {
this.maximumReservableBandwidth = maximumBandwidth;
}
/**
* Gets value of maximum reversible bandwidth.
*
* @return maximumBandwidth maximum reversible bandwidth
*/
public float getMaximumBandwidthValue() {
return this.maximumReservableBandwidth;
}
/**
* Reads bytes from channel buffer.
*
* @param channelBuffer channel buffer instance
*/
public void readFrom(ChannelBuffer channelBuffer) {
byte[] tempByteArray = new byte[tlvLength()];
channelBuffer.readBytes(tempByteArray, 0, tlvLength());
int maxBandwidth = (OspfUtil.byteToInteger(tempByteArray));
this.setMaximumBandwidth(Float.intBitsToFloat(maxBandwidth));
}
/**
* Returns byte array of maximum reservable bandwidth.
*
* @return byte array of maximum reservable bandwidth
*/
public byte[] asBytes() {
byte[] linkSubType = null;
byte[] linkSubTlvHeader = getTlvHeaderAsByteArray();
byte[] linkSubTlvBody = getLinksubTypeTlvBodyAsByteArray();
linkSubType = Bytes.concat(linkSubTlvHeader, linkSubTlvBody);
return linkSubType;
}
/**
* Gets maximum reservable bandwidth sub tlv body as byte array.
*
* @return byte of maximum reservable bandwidth sub tlv body
*/
public byte[] getLinksubTypeTlvBodyAsByteArray() {
byte[] linkSubTypeBody;
linkSubTypeBody = OspfUtil.convertToFourBytes(Float.floatToIntBits(this.maximumReservableBandwidth));
return linkSubTypeBody;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("maximumReservableBandwidth", maximumReservableBandwidth)
.toString();
}
} | apache-2.0 |
OSERAF/MASTERImpl | webapp/src/main/java/Runner.java | 1801 | import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import java.net.URL;
import java.security.ProtectionDomain;
public class Runner {
public static final int DEFAULT_PORT = 8081;
private final Config conf = ConfigFactory.load().getConfig("bullseye");
private Integer port;
public Runner(final Integer port) {
this.port = port;
}
public void start() {
try {
final Server server = new Server();
if (port != null) {
final SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
connector.setMaxIdleTime(60000);
server.addConnector(connector);
}
final ProtectionDomain domain = Runner.class.getProtectionDomain();
final URL location = domain.getCodeSource().getLocation();
final WebAppContext webapp = new WebAppContext();
webapp.setContextPath(conf.getString("app.contextPath"));
webapp.setWar(location.toExternalForm());
server.setHandler(webapp);
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private static Integer getPort(final String[] args) {
if (args.length >= 1) {
try {
return Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Error parsing port number as an integer: " + args[0]);
}
}
return null;
}
public static void main(final String[] args) {
Integer port = getPort(args);
if (port == null) port = DEFAULT_PORT;
System.out.println("Starting embedded server on port [" + port + "]");
final Runner runner = new Runner(port);
runner.start();
}
}
| apache-2.0 |
solaris0403/AndroidDemo | aidl/src/main/java/com/tony/aidl/BookManagerActivity.java | 3811 | package com.tony.aidl;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import butterknife.Bind;
import butterknife.ButterKnife;
public class BookManagerActivity extends AppCompatActivity {
private static final String TAG = BookManagerActivity.class.getSimpleName();
@Bind(R.id.btn_add_book)
Button btnAddBook;
private IBookManager bookManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_manager);
ButterKnife.bind(this);
btnAddBook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
bookManager.addBook(new Book(25, "name"));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
Intent intent = new Intent("com.tony.service.book");
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
Log.d(TAG, "binder died. tname:" + Thread.currentThread().getName());
if (bookManager == null)
return;
bookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
bookManager = null;
Intent intent = new Intent("com.tony.service.book");
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
};
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
bookManager = IBookManager.Stub.asInterface(service);
try {
bookManager.asBinder().linkToDeath(mDeathRecipient, 0);
bookManager.registerListener(listener);
// List<Book> list = bookManager.getBookList();
// Log.i(TAG, "query book list, list type:" + list.getClass().getCanonicalName());
// Log.i(TAG, "book list, list size:" + list.size());
// bookManager.addBook(new Book(25, "NewBook"));
// Log.i(TAG, "book list, list size:" + bookManager.getBookList().size());
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
bookManager = null;
Log.d(TAG, "onServiceDisconnected. tname:" + Thread.currentThread().getName());
}
};
private IOnNewBookArrivedListener listener = new IOnNewBookArrivedListener.Stub() {
@Override
public void onNewBookArrivedListener(Book book) throws RemoteException {
Log.e(TAG, "onNewBookArrivedListener:" + book);
Log.e(TAG, "bookList:" + bookManager.getBookList().size());
}
};
@Override
protected void onDestroy() {
if (bookManager != null && bookManager.asBinder().isBinderAlive()) {
try {
Log.e(TAG, "unregister listener:" + listener);
bookManager.unregisterListener(listener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
Log.e(TAG, "unbindService:" + connection);
unbindService(connection);
super.onDestroy();
}
}
| apache-2.0 |
itsmeneelu/MyEclipse | SampleTrailer/src/com/example/sampletrailer/MainActivity.java | 1604 | package com.example.sampletrailer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView tap;
WebView webView;
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
this.tap = ((TextView)findViewById(R.id.textView1));
this.webView = ((WebView)findViewById(R.id.webView2));
this.webView.getSettings().setJavaScriptEnabled(true);
//this one calls the url that is placed in our server.
this.webView.loadUrl("http://test-ads.peel.com/foryou?country=us&userid=200014788&counter=25");
//you can comment any of these above or below to check the compatibility of our need
// this one calls the videos3.jsp file that is placed in our projects assets.
//this.webView.loadUrl("file:///android_asset/videos3.jsp");
this.tap.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Intent localIntent = new Intent(MainActivity.this, MyVideoView.class);
MainActivity.this.startActivity(localIntent);
}
});
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(R.menu.activity_main, paramMenu);
return true;
}
} | apache-2.0 |
motorina0/flowable-engine | modules/flowable-rest/src/main/java/org/flowable/rest/service/api/history/HistoricDetailQueryResource.java | 2509 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.rest.service.api.history;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.flowable.rest.api.DataResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author Tijs Rademakers
*/
@RestController
@Api(tags = { "History" }, description = "Manage History")
public class HistoricDetailQueryResource extends HistoricDetailBaseResource {
@ApiOperation(value = "Query for historic details", tags = { "History" }, notes = "All supported JSON parameter fields allowed are exactly the same as the parameters found for getting a collection of historic process instances, but passed in as JSON-body arguments rather than URL-parameters to allow for more advanced querying and preventing errors with request-uri’s that are too long.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates request was successful and the historic details are returned"),
@ApiResponse(code = 400, message = "Indicates an parameter was passed in the wrong format. The status-message contains additional information.") })
@RequestMapping(value = "/query/historic-detail", method = RequestMethod.POST, produces = "application/json")
public DataResponse queryHistoricDetail(@RequestBody HistoricDetailQueryRequest queryRequest, @ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams, HttpServletRequest request) {
return getQueryResponse(queryRequest, allRequestParams);
}
}
| apache-2.0 |
gchq/stroom | stroom-pipeline/src/main/java/stroom/pipeline/xsltfunctions/ExtensionFunctionCallProxy.java | 1399 | /*
* Copyright 2016 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stroom.pipeline.xsltfunctions;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.trans.XPathException;
class ExtensionFunctionCallProxy extends ExtensionFunctionCall {
private final String functionName;
private transient StroomExtensionFunctionCall functionCall;
ExtensionFunctionCallProxy(final String functionName) {
this.functionName = functionName;
}
@Override
public Sequence call(final XPathContext context, final Sequence[] arguments) throws XPathException {
return functionCall.call(functionName, context, arguments);
}
void setFunctionCall(final StroomExtensionFunctionCall functionCall) {
this.functionCall = functionCall;
}
}
| apache-2.0 |
ecallac/sistemas | applications/security-webapp/src/main/java/com/security/web/bean/ModuleView.java | 1195 | /**
*
*/
package com.security.web.bean;
import org.hibernate.validator.constraints.NotEmpty;
/**
* @author efrain.calla
*
*/
public class ModuleView {
private Long id;
@NotEmpty
private String name;
@NotEmpty
private String description;
private String enabled;
private String author;
private String moduleVersion;
public String getIdString() {
return String.valueOf(id);
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getModuleVersion() {
return moduleVersion;
}
public void setModuleVersion(String moduleVersion) {
this.moduleVersion = moduleVersion;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
}
| apache-2.0 |
yyitsz/myjavastudio | studyjbpm/src/main/java/org/yy/studyjbpm/model/JobPositionRequest.java | 727 | package org.yy.studyjbpm.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class JobPositionRequest implements Serializable{
private Set<TechnicalSkills> techicalSkillsRequested = new HashSet<TechnicalSkills>();
private int yearsOfExperience = 0;
public Set<TechnicalSkills> getTechicalSkillsRequested() {
return techicalSkillsRequested;
}
public void setTechicalSkillsRequested(
Set<TechnicalSkills> techicalSkillsRequested) {
this.techicalSkillsRequested = techicalSkillsRequested;
}
public int getYearsOfExperience() {
return yearsOfExperience;
}
public void setYearsOfExperience(int yearsOfExperience) {
this.yearsOfExperience = yearsOfExperience;
}
}
| apache-2.0 |
MiniPlayer/log-island | logisland-api/src/main/java/com/hurence/logisland/component/ComponentType.java | 836 | /**
* Copyright (C) 2016 Hurence (bailet.thomas@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hurence.logisland.component;
public enum ComponentType {
PROCESSOR,
ENGINE,
PARSER,
SINK,
STREAM;
public String toString() {
return name().toLowerCase();
}
}
| apache-2.0 |
hurricup/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemExecuteTaskTask.java | 6083 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.service.internal;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.execution.ExternalTaskPojo;
import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager;
import com.intellij.openapi.externalSystem.service.RemoteExternalSystemFacade;
import com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemTaskManager;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.project.Project;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.execution.ParametersListUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author Denis Zhdanov
* @since 3/15/13 10:02 PM
*/
public class ExternalSystemExecuteTaskTask extends AbstractExternalSystemTask {
@NotNull private static final Function<ExternalTaskPojo, String> MAPPER = task -> task.getName();
@NotNull private final List<ExternalTaskPojo> myTasksToExecute;
@Nullable private final String myVmOptions;
@Nullable private String myScriptParameters;
@Nullable private final String myDebuggerSetup;
public ExternalSystemExecuteTaskTask(@NotNull ProjectSystemId externalSystemId,
@NotNull Project project,
@NotNull List<ExternalTaskPojo> tasksToExecute,
@Nullable String vmOptions,
@Nullable String scriptParameters,
@Nullable String debuggerSetup) throws IllegalArgumentException {
super(externalSystemId, ExternalSystemTaskType.EXECUTE_TASK, project, getLinkedExternalProjectPath(tasksToExecute));
myTasksToExecute = tasksToExecute;
myVmOptions = vmOptions;
myScriptParameters = scriptParameters;
myDebuggerSetup = debuggerSetup;
}
@NotNull
public List<ExternalTaskPojo> getTasksToExecute() {
return myTasksToExecute;
}
@Nullable
public String getVmOptions() {
return myVmOptions;
}
@Nullable
public String getScriptParameters() {
return myScriptParameters;
}
public void appendScriptParameters(@NotNull String scriptParameters) {
myScriptParameters = myScriptParameters == null ? scriptParameters : myScriptParameters + ' ' + scriptParameters;
}
@NotNull
private static String getLinkedExternalProjectPath(@NotNull Collection<ExternalTaskPojo> tasks) throws IllegalArgumentException {
if (tasks.isEmpty()) {
throw new IllegalArgumentException("Can't execute external tasks. Reason: given tasks list is empty");
}
String result = null;
for (ExternalTaskPojo task : tasks) {
String path = task.getLinkedExternalProjectPath();
if (result == null) {
result = path;
}
else if (!result.equals(path)) {
throw new IllegalArgumentException(String.format(
"Can't execute given external system tasks. Reason: expected that all of them belong to the same external project " +
"but they are not (at least two different projects detected - '%s' and '%s'). Tasks: %s",
result,
task.getLinkedExternalProjectPath(),
tasks
));
}
}
assert result != null;
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void doExecute() throws Exception {
final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
ExternalSystemExecutionSettings settings = ExternalSystemApiUtil.getExecutionSettings(getIdeProject(),
getExternalProjectPath(),
getExternalSystemId());
RemoteExternalSystemFacade facade = manager.getFacade(getIdeProject(), getExternalProjectPath(), getExternalSystemId());
RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
List<String> taskNames = ContainerUtilRt.map2List(myTasksToExecute, MAPPER);
final List<String> vmOptions = parseCmdParameters(myVmOptions);
final List<String> scriptParametersList = parseCmdParameters(myScriptParameters);
taskManager.executeTasks(getId(), taskNames, getExternalProjectPath(), settings, vmOptions, scriptParametersList, myDebuggerSetup);
}
@Override
protected boolean doCancel() throws Exception {
final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
RemoteExternalSystemFacade facade = manager.getFacade(getIdeProject(), getExternalProjectPath(), getExternalSystemId());
RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
return taskManager.cancelTask(getId());
}
private static List<String> parseCmdParameters(@Nullable String cmdArgsLine) {
return cmdArgsLine != null ? ParametersListUtil.parse(cmdArgsLine) : ContainerUtil.<String>newArrayList();
}
}
| apache-2.0 |
tomsnail/snail-dev-console | src/main/java/com/thinkgem/jeesite/modules/gen/entity/GenTemplate.java | 2134 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.gen.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.validator.constraints.Length;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.DataEntity;
import com.thinkgem.jeesite.common.utils.StringUtils;
/**
* 生成方案Entity
* @author ThinkGem
* @version 2013-10-15
*/
@XmlRootElement(name="template")
public class GenTemplate extends DataEntity<GenTemplate> {
private static final long serialVersionUID = 1L;
private String name; // 名称
private String category; // 分类
private String filePath; // 生成文件路径
private String fileName; // 文件名
private String content; // 内容
public GenTemplate() {
super();
}
public GenTemplate(String id){
super(id);
}
@Length(min=1, max=200)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@XmlTransient
public List<String> getCategoryList() {
if (category == null){
return Lists.newArrayList();
}else{
return Lists.newArrayList(StringUtils.split(category, ","));
}
}
public void setCategoryList(List<String> categoryList) {
if (categoryList == null){
this.category = "";
}else{
this.category = ","+StringUtils.join(categoryList, ",") + ",";
}
}
}
| apache-2.0 |
TroyHisted/relib | src/test/java/org/relib/util/StringsTest.java | 7086 | /**
* Copyright 2015 Troy Histed
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.relib.util;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests the {@link Strings} class.
*
* @author Troy Histed
*/
public class StringsTest {
/**
* Verify a trim works with a null string.
*/
@Test
public void testTrimNull() {
Assert.assertNull(Strings.trim(null));
}
/**
* Verify a trim works with an empty string.
*/
@Test
public void testTrimEmpty() {
Assert.assertEquals("", Strings.trim(""));
}
/**
* Verify a trim works with a nothing to trim string.
*/
@Test
public void testTrimNothing() {
Assert.assertEquals("abc", Strings.trim("abc"));
}
/**
* Verify a equals works with both null.
*/
@Test
public void testEqualsFalseWhenBothNull() {
Assert.assertFalse(Strings.equals((String) null, (String) null));
}
/**
* Verify a equals works when the first argument is null.
*/
@Test
public void testEqualsFalseWhenFirstNull() {
Assert.assertFalse(Strings.equals((String) null, "test"));
}
/**
* Verify a equals works when the second argument is null.
*/
@Test
public void testEqualsFalseWhenSecondNull() {
Assert.assertFalse(Strings.equals("test", (String) null));
}
/**
* Verify a equals works when the strings don't match.
*/
@Test
public void testEqualsFalseWhenNotMatching() {
Assert.assertFalse(Strings.equals("foo", "bar"));
}
/**
* Verify a equals works when the strings do match.
*/
@Test
public void testEqualsTrueWhenMatching() {
Assert.assertTrue(Strings.equals("foo", "foo"));
}
/**
* Verify a trim works with a leading trims.
*/
@Test
public void testTrimLeading() {
Assert.assertEquals("abc", Strings.trim(" abc"));
}
/**
* Verify a trim works with a trailing trims.
*/
@Test
public void testTrimTrailing() {
Assert.assertEquals("abc", Strings.trim("abc "));
}
/**
* Verify a trim works on both ends.
*/
@Test
public void testTrimBothSides() {
Assert.assertEquals("abc", Strings.trim(" abc "));
}
/**
* Verify a trim works with a null string.
*/
@Test
public void testTrimNullSlash() {
Assert.assertNull(Strings.trim(null, '/'));
}
/**
* Verify a trim works with an empty string.
*/
@Test
public void testTrimEmptySlash() {
Assert.assertEquals("", Strings.trim("", '/'));
}
/**
* Verify a trim works with a nothing to trim string.
*/
@Test
public void testTrimNothingSlash() {
Assert.assertEquals("abc", Strings.trim("abc", '/'));
}
/**
* Verify a trim works with a leading trims.
*/
@Test
public void testTrimLeadingSlash() {
Assert.assertEquals("abc", Strings.trim("//abc", '/'));
}
/**
* Verify a trim works with a trailing trims.
*/
@Test
public void testTrimTrailingSlash() {
Assert.assertEquals("abc", Strings.trim("abc//", '/'));
}
/**
* Verify a trim works with only the specified character being trimmed.
*/
@Test
public void testTrimOnlySlash() {
Assert.assertEquals("", Strings.trim("////", '/'));
}
/**
* Verify a trim works with for multiple characters.
*/
@Test
public void testTrimMultipleCharacters() {
Assert.assertEquals("abc", Strings.trim("/\\abc/\\", '/', '\\'));
}
/**
* Verify isBlank works with null.
*/
@Test
public void testIsBlankNull() {
Assert.assertTrue(Strings.isBlank(null));
}
/**
* Verify isBlank works with an empty string.
*/
@Test
public void testIsBlankEmpty() {
Assert.assertTrue(Strings.isBlank(""));
}
/**
* Verify isBlank works with a whitespace string.
*/
@Test
public void testIsBlankWhitespace() {
Assert.assertTrue(Strings.isBlank(" "));
}
/**
* Verify isBlank works with a character in the string.
*/
@Test
public void testIsBlankCharacter() {
Assert.assertFalse(Strings.isBlank(" - "));
}
/**
* Verify isNumeric is false with null.
*/
@Test
public void testIsNumericNull() {
Assert.assertFalse(Strings.isNumeric(null));
}
/**
* Verify isNumeric is true with an empty string.
*/
@Test
public void testIsNumericEmpty() {
Assert.assertTrue(Strings.isNumeric(""));
}
/**
* Verify isNumeric is false with whitespace.
*/
@Test
public void testIsNumericWhitespace() {
Assert.assertFalse(Strings.isNumeric(" "));
}
/**
* Verify isNumeric works with a numeric string.
*/
@Test
public void testIsNumericWithNumeric() {
Assert.assertTrue(Strings.isNumeric("0987654321"));
}
/**
* Verify isNumeric fails with an alphanumeric string.
*/
@Test
public void testIsNumericAlphanumeric() {
Assert.assertFalse(Strings.isNumeric("09876a54321"));
}
/**
* Verify substring handles null.
*/
@Test
public void testSubstringNull() {
Assert.assertNull(Strings.subString(null, 0, 9));
}
/**
* Verify substring handles a string.
*/
@Test
public void testSubstringString() {
Assert.assertEquals("b", Strings.subString("abc", 1, 2));
}
/**
* Verify capitalize handles null.
*/
@Test
public void testCapitalizeNull() {
Assert.assertEquals(null, Strings.capitalize(null));
}
/**
* Verify capitalize handles a string.
*/
@Test
public void testCapitalizeString() {
Assert.assertEquals("Test string", Strings.capitalize("test string"));
}
/**
* Verify capitalize handles a ignores non alpha characters.
*/
@Test
public void testCapitalizeNumber() {
Assert.assertEquals("5 string", Strings.capitalize("5 string"));
}
/**
* Verify unCapitalize handles null.
*/
@Test
public void testUnCapitalizeNull() {
Assert.assertEquals(null, Strings.unCapitalize(null));
}
/**
* Verify capitalize handles a string.
*/
@Test
public void testUnCapitalizeString() {
Assert.assertEquals("test string", Strings.unCapitalize("Test string"));
}
/**
* Verify unCapitalize handles a ignores non alpha characters.
*/
@Test
public void testUnCapitalizeNumber() {
Assert.assertEquals("5 string", Strings.unCapitalize("5 string"));
}
/**
* Verify default string handles null.
*/
@Test
public void testDefaultStringNull() {
Assert.assertEquals("", Strings.defaultString(null));
}
/**
* Verify default string handles a string.
*/
@Test
public void testDefaultString() {
Assert.assertEquals("test", Strings.defaultString("test"));
}
}
| apache-2.0 |
mbezjak/vhdllab | vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/schema2/gui/canvas/WirePreLocator.java | 13003 | /*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package hr.fer.zemris.vhdllab.applets.schema2.gui.canvas;
import hr.fer.zemris.vhdllab.applets.editor.schema2.constants.Constants;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommand;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommandResponse;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaController;
import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.Caseless;
import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.AddWireCommand;
import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.BindWireCommand;
import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.ExpandWireCommand;
import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.PlugWireCommand;
import java.awt.Graphics2D;
public class WirePreLocator implements IWirePreLocator {
public static int HORIZ_FIRST = 0;
public static int VERT_FIRST = 1;
private int x1;
private int y1;
private int x2;
private int y2;
private int orientation;
private int devition1;
private int deviation2;
private boolean wireInstantiable = true;
public WirePreLocator(int x1, int y1, int x2, int y2, int orientation, int odm1, int odm2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.devition1 = odm1;
this.deviation2 = odm2;
this.orientation = orientation;
}
public WirePreLocator() {
this(0,0,0,0,0,0,0);
}
public WirePreLocator(int x1, int y1, int x2, int y2){
this(x1,y1,x2,y2,0,0,0);
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getOdmak1()
*/
public int getOdmak1() {
return devition1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setOdmak1(int)
*/
public void setOdmak1(int odmak1) {
this.devition1 = odmak1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getOdmak2()
*/
public int getOdmak2() {
return deviation2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setOdmak2(int)
*/
public void setOdmak2(int odmak2) {
this.deviation2 = odmak2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getOrientation()
*/
public int getOrientation() {
return orientation;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setOrientation(int)
*/
public void setOrientation(int orientation) {
this.orientation = orientation;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getX1()
*/
public int getX1() {
return x1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setX1(int)
*/
public void setX1(int x1) {
this.x1 = x1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getX2()
*/
public int getX2() {
return x2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setX2(int)
*/
public void setX2(int x2) {
this.x2 = x2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getY1()
*/
public int getY1() {
return y1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setY1(int)
*/
public void setY1(int y1) {
this.y1 = y1;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#getY2()
*/
public int getY2() {
return y2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setY2(int)
*/
public void setY2(int y2) {
this.y2 = y2;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#instantiateWire(hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaController, hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.CriticalPoint, hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.CriticalPoint)
*/
public void instantiateWire(ISchemaController controller, CriticalPoint wireBeginning, CriticalPoint wireEnding) {
//TODO srediti za razlicit orientation i odmak ako ce to uopce postojati
if((wireBeginning == null || wireBeginning.getType()==CriticalPoint.ON_COMPONENT_PLUG) &&
(wireEnding == null || wireEnding.getType() == CriticalPoint.ON_COMPONENT_PLUG)){
addWire(controller, wireBeginning, wireEnding);
}else{
if(wireBeginning == null || wireBeginning.getType() == CriticalPoint.ON_COMPONENT_PLUG)
expandWire(controller, wireEnding, wireBeginning);
else
expandWire(controller, wireBeginning, wireEnding);
}
}
private void expandWire(ISchemaController controller, CriticalPoint wireBeginning, CriticalPoint wireEnding) {
Caseless wireName = wireBeginning.getName();
if(orientation == VERT_FIRST){
if (x1 != x2 && y1 != y2) {
ICommand instantiate = new ExpandWireCommand(wireName,x1,y1,x1,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
instantiate = new ExpandWireCommand(wireName,x1,y2,x2,y2);
response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
else{
ICommand instantiate = new ExpandWireCommand(wireName,x1,y1,x2,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
}else{
if (x1 != x2 && y1 != y2) {
ICommand instantiate = new ExpandWireCommand(wireName,x1,y1,x2,y1);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
instantiate = new ExpandWireCommand(wireName,x2,y1,x2,y2);
response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
else{
ICommand instantiate = new ExpandWireCommand(wireName,x1,y1,x2,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
}
plugToPoint(wireBeginning,controller,wireName);
plugToPoint(wireEnding,controller,wireName);
}
private void addWire(ISchemaController controller, CriticalPoint wireBeginning, CriticalPoint wireEnding) {
Caseless wireName = null;
if(orientation == VERT_FIRST){
if (x1 != x2 && y1 != y2) {
wireName = createName(x1,y1,x1,y2);
ICommand instantiate = new AddWireCommand(wireName,x1,y1,x1,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
instantiate = new ExpandWireCommand(wireName,x1,y2,x2,y2);
response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
else{
wireName = createName(x1,y1,x1,y2);
ICommand instantiate = new AddWireCommand(createName(x1, y1, x2, y2),x1,y1,x2,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
}else{
if (x1 != x2 && y1 != y2) {
wireName = createName(x1,y1,x1,y2);
ICommand instantiate = new AddWireCommand(wireName,x1,y1,x2,y1);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
instantiate = new ExpandWireCommand(wireName,x2,y1,x2,y2);
response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
else{
wireName = createName(x1, y1, x2, y2);
ICommand instantiate = new AddWireCommand(wireName,x1,y1,x2,y2);
ICommandResponse response = controller.send(instantiate);
System.out.println ("canvas report| wire instantiate succesful: "+response.isSuccessful());
}
}
plugToPoint(wireBeginning,controller,wireName);
plugToPoint(wireEnding,controller,wireName);
}
private void plugToPoint(CriticalPoint point, ISchemaController controller, Caseless wireName) {
//TODO napraviti plug wire!!!
if (point!=null){
if(point.getType()==CriticalPoint.ON_COMPONENT_PLUG){
Caseless componentName = point.getName();
ICommand plug = new PlugWireCommand(componentName, wireName, point.getPortName());
ICommandResponse response = controller.send(plug);
String message = "";
try{
message = response.getError().getMessage();
}catch (NullPointerException e) {}
System.out.println ("canvas report| wire instantiate & plug succesful: "+response.isSuccessful()+" "+message);
}else{
if(point.getType() == CriticalPoint.ON_WIRE_PLUG && !point.getName().equals(wireName)){
Caseless wireToBindName = point.getName();
ICommand plug = new BindWireCommand(wireToBindName, wireName);
ICommandResponse response = controller.send(plug);
String message = "";
try{
message = response.getError().getMessage();
}catch (NullPointerException e) {}
System.out.println ("canvas report| wire instantiate & plug succesful: "+response.isSuccessful()+" "+message);
}else{
System.out.println("canvas report| wire instantiate & plug expand wire");
}
}
}
}
private Caseless createName(int x1, int y1, int x2, int y2) {
StringBuilder build = new StringBuilder("WIRE_");
build.append(normalize(x1)).append("_").append(normalize(y1)).append("_")
.append(normalize(x2)).append("_").append(normalize(y2));
return new Caseless(build.toString());
}
private String normalize(int x) {
return x<0?"M"+String.valueOf(Math.abs(x)):String.valueOf(x);
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#draw(java.awt.Graphics2D)
*/
public void draw(Graphics2D g) {
if(orientation == VERT_FIRST){
g.drawLine(x1, y1, x1, y2);
g.drawLine(x1, y2, x2, y2);
}else{
g.drawLine(x1, y1, x2, y1);
g.drawLine(x2, y1, x2, y2);
}
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#isWireInstance()
*/
public boolean isWireInstance() {
return (Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>10) && wireInstantiable;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#isWireInstantiable()
*/
public boolean isWireInstantiable() {
return wireInstantiable;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setWireInstantiable(boolean)
*/
public void setWireInstantiable(boolean wireInstantiable) {
this.wireInstantiable = wireInstantiable;
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setWireInstantiable(hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.CriticalPoint, hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.CriticalPoint)
*/
public void setWireInstantiable(CriticalPoint wireBeginning, CriticalPoint wireEnding) {
if(wireBeginning != null && wireEnding != null){
if(wireBeginning.getType()==CriticalPoint.ON_WIRE_PLUG && wireEnding.getType()==CriticalPoint.ON_WIRE_PLUG){
if(wireBeginning.getName().equals(wireEnding.getName())){
wireInstantiable = false;
}else{
wireInstantiable = true;
}
}else{
wireInstantiable = true;
}
}else{
wireInstantiable = true;
}
}
/* (non-Javadoc)
* @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.IWirePreLocator#setWireOrientation()
*/
public void revalidateWire() {
double d = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
if(d>Constants.GRID_SIZE-1&&d<Constants.GRID_SIZE+1){
if(Math.abs(x1-x2)>Math.abs(y1-y2))
orientation = WirePreLocator.HORIZ_FIRST;
else
orientation = WirePreLocator.VERT_FIRST;
}
}
}
| apache-2.0 |
BruceHurrican/studydemo | libs_src/v4src/java/android/support/v4/view/KeyEventCompat.java | 7625 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.view;
import android.view.KeyEvent;
import android.view.View;
/**
* Helper for accessing features in {@link KeyEvent} introduced after
* API level 4 in a backwards compatible fashion.
*/
public class KeyEventCompat {
/**
* Select the correct implementation to use for the current platform.
*/
static final KeyEventVersionImpl IMPL;
static {
if (android.os.Build.VERSION.SDK_INT >= 11) {
IMPL = new HoneycombKeyEventVersionImpl();
} else {
IMPL = new BaseKeyEventVersionImpl();
}
}
public static int normalizeMetaState(int metaState) {
return IMPL.normalizeMetaState(metaState);
}
public static boolean metaStateHasModifiers(int metaState, int modifiers) {
return IMPL.metaStateHasModifiers(metaState, modifiers);
}
public static boolean metaStateHasNoModifiers(int metaState) {
return IMPL.metaStateHasNoModifiers(metaState);
}
public static boolean hasModifiers(KeyEvent event, int modifiers) {
return IMPL.metaStateHasModifiers(event.getMetaState(), modifiers);
}
// -------------------------------------------------------------------
public static boolean hasNoModifiers(KeyEvent event) {
return IMPL.metaStateHasNoModifiers(event.getMetaState());
}
public static void startTracking(KeyEvent event) {
IMPL.startTracking(event);
}
public static boolean isTracking(KeyEvent event) {
return IMPL.isTracking(event);
}
public static Object getKeyDispatcherState(View view) {
return IMPL.getKeyDispatcherState(view);
}
public static boolean dispatch(KeyEvent event, KeyEvent.Callback receiver, Object state,
Object target) {
return IMPL.dispatch(event, receiver, state, target);
}
/**
* Interface for the full API.
*/
interface KeyEventVersionImpl {
public int normalizeMetaState(int metaState);
public boolean metaStateHasModifiers(int metaState, int modifiers);
public boolean metaStateHasNoModifiers(int metaState);
public void startTracking(KeyEvent event);
public boolean isTracking(KeyEvent event);
public Object getKeyDispatcherState(View view);
public boolean dispatch(KeyEvent event, KeyEvent.Callback receiver, Object state,
Object target);
}
/**
* Interface implementation that doesn't use anything about v4 APIs.
*/
static class BaseKeyEventVersionImpl implements KeyEventVersionImpl {
private static final int META_MODIFIER_MASK =
KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON
| KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_ALT_RIGHT_ON
| KeyEvent.META_SYM_ON;
// Mask of all lock key meta states.
private static final int META_ALL_MASK = META_MODIFIER_MASK;
private static int metaStateFilterDirectionalModifiers(int metaState,
int modifiers, int basic, int left, int right) {
final boolean wantBasic = (modifiers & basic) != 0;
final int directional = left | right;
final boolean wantLeftOrRight = (modifiers & directional) != 0;
if (wantBasic) {
if (wantLeftOrRight) {
throw new IllegalArgumentException("bad arguments");
}
return metaState & ~directional;
} else if (wantLeftOrRight) {
return metaState & ~basic;
} else {
return metaState;
}
}
@Override
public int normalizeMetaState(int metaState) {
if ((metaState & (KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON)) != 0) {
metaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & (KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_ALT_RIGHT_ON)) != 0) {
metaState |= KeyEvent.META_ALT_ON;
}
return metaState & META_ALL_MASK;
}
@Override
public boolean metaStateHasModifiers(int metaState, int modifiers) {
metaState = normalizeMetaState(metaState) & META_MODIFIER_MASK;
metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
KeyEvent.META_SHIFT_ON, KeyEvent.META_SHIFT_LEFT_ON, KeyEvent.META_SHIFT_RIGHT_ON);
metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
KeyEvent.META_ALT_ON, KeyEvent.META_ALT_LEFT_ON, KeyEvent.META_ALT_RIGHT_ON);
return metaState == modifiers;
}
@Override
public boolean metaStateHasNoModifiers(int metaState) {
return (normalizeMetaState(metaState) & META_MODIFIER_MASK) == 0;
}
@Override
public void startTracking(KeyEvent event) {
}
@Override
public boolean isTracking(KeyEvent event) {
return false;
}
@Override
public Object getKeyDispatcherState(View view) {
return null;
}
@Override
public boolean dispatch(KeyEvent event, KeyEvent.Callback receiver, Object state,
Object target) {
return event.dispatch(receiver);
}
}
static class EclairKeyEventVersionImpl extends BaseKeyEventVersionImpl {
@Override
public void startTracking(KeyEvent event) {
KeyEventCompatEclair.startTracking(event);
}
@Override
public boolean isTracking(KeyEvent event) {
return KeyEventCompatEclair.isTracking(event);
}
@Override
public Object getKeyDispatcherState(View view) {
return KeyEventCompatEclair.getKeyDispatcherState(view);
}
@Override
public boolean dispatch(KeyEvent event, KeyEvent.Callback receiver, Object state,
Object target) {
return KeyEventCompatEclair.dispatch(event, receiver, state, target);
}
}
/**
* Interface implementation for devices with at least v11 APIs.
*/
static class HoneycombKeyEventVersionImpl extends EclairKeyEventVersionImpl {
@Override
public int normalizeMetaState(int metaState) {
return KeyEventCompatHoneycomb.normalizeMetaState(metaState);
}
@Override
public boolean metaStateHasModifiers(int metaState, int modifiers) {
return KeyEventCompatHoneycomb.metaStateHasModifiers(metaState, modifiers);
}
@Override
public boolean metaStateHasNoModifiers(int metaState) {
return KeyEventCompatHoneycomb.metaStateHasNoModifiers(metaState);
}
}
}
| apache-2.0 |
beni55/sqoop | src/java/com/cloudera/sqoop/metastore/JobStorage.java | 2959 | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.sqoop.metastore;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configured;
/**
* API that defines how jobs are saved, restored, and manipulated.
*
* <p>
* JobStorage instances may be created and then not used; the
* JobStorage factory may create additional JobStorage instances
* that return false from accept() and then discard them. The close()
* method will only be triggered for a JobStorage if the connect()
* method is called. Connection should not be triggered by a call to
* accept().</p>
*/
public abstract class JobStorage extends Configured implements Closeable {
/**
* Returns true if the JobStorage system can use the metadata in
* the descriptor to connect to an underlying storage resource.
*/
public abstract boolean canAccept(Map<String, String> descriptor);
/**
* Opens / connects to the underlying storage resource specified by the
* descriptor.
*/
public abstract void open(Map<String, String> descriptor)
throws IOException;
/**
* Given a job name, reconstitute a JobData that contains all
* configuration information required for the job. Returns null if the
* job name does not match an available job.
*/
public abstract JobData read(String jobName)
throws IOException;
/**
* Forget about a saved job.
*/
public abstract void delete(String jobName) throws IOException;
/**
* Given a job name and the data describing a configured job, record the job
* information to the storage medium.
*/
public abstract void create(String jobName, JobData data)
throws IOException;
/**
* Given a job name and configured job data, update the underlying resource
* to match the current job configuration.
*/
public abstract void update(String jobName, JobData data)
throws IOException;
/**
* Close any resources opened by the JobStorage system.
*/
public void close() throws IOException {
}
/**
* Enumerate all jobs held in the connected resource.
*/
public abstract List<String> list() throws IOException;
}
| apache-2.0 |
McLeodMoores/starling | projects/web/src/main/java/com/opengamma/web/WebHomeUris.java | 1321 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web;
import java.net.URI;
import javax.ws.rs.core.UriInfo;
import com.opengamma.util.ClassUtils;
/**
* URIs for web-based securities.
*/
public class WebHomeUris {
/**
* The data.
*/
private final UriInfo _uriInfo;
/**
* Creates an instance.
*
* @param uriInfo the request URI information, not null
*/
public WebHomeUris(final UriInfo uriInfo) {
_uriInfo = uriInfo;
}
//-------------------------------------------------------------------------
/**
* Gets the URI of the home page.
* @return the URI, not null
*/
public URI home() {
return WebHomeResource.uri(_uriInfo);
}
/**
* Gets the URI of the about page.
* @return the URI, not null
*/
public URI about() {
return WebAboutResource.uri(_uriInfo);
}
/**
* Gets the URI of the components page.
* @return the URI, null if not available
*/
public URI components() {
try {
ClassUtils.loadClass("com.opengamma.component.rest.DataComponentServerResource");
return _uriInfo.getBaseUriBuilder().path("components").build();
} catch (final ClassNotFoundException ex) {
return null;
}
}
}
| apache-2.0 |
Garbriel/AndroidExamples | src/io/android_tech/myexample/SNS/SNS_06_Activity.java | 1592 | package io.android_tech.myexample.SNS;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
public class SNS_06_Activity extends Activity {
TwitterLoginButton loginButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(io.android_tech.myexample.R.layout.activity_sns_06);
loginButton = (TwitterLoginButton) findViewById(io.android_tech.myexample.R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Toast.makeText(SNS_06_Activity.this, "twitter login suceess!!", Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(SNS_06_Activity.this, "twitter login failed!!", Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to the login button.
loginButton.onActivityResult(requestCode, resultCode, data);
}
}
| apache-2.0 |
neykov/incubator-brooklyn | usage/launcher/src/main/java/brooklyn/launcher/camp/BrooklynCampPlatformLauncher.java | 2467 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package brooklyn.launcher.camp;
import io.brooklyn.camp.CampServer;
import io.brooklyn.camp.brooklyn.BrooklynCampPlatform;
import io.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherAbstract;
import io.brooklyn.camp.spi.PlatformRootSummary;
import brooklyn.entity.basic.BrooklynShutdownHooks;
import brooklyn.launcher.BrooklynLauncher;
import brooklyn.management.internal.LocalManagementContext;
import com.google.common.annotations.Beta;
/** variant of super who also starts a CampServer for convenience */
@Beta
public class BrooklynCampPlatformLauncher extends BrooklynCampPlatformLauncherAbstract {
protected BrooklynLauncher brooklynLauncher;
protected CampServer campServer;
@Override
public BrooklynCampPlatformLauncher launch() {
assert platform == null;
mgmt = new LocalManagementContext();
// We created the management context, so we are responsible for terminating it
BrooklynShutdownHooks.invokeTerminateOnShutdown(mgmt);
brooklynLauncher = BrooklynLauncher.newInstance().managementContext(mgmt).start();
platform = new BrooklynCampPlatform(
PlatformRootSummary.builder().name("Brooklyn CAMP Platform").build(),
mgmt).setConfigKeyAtManagmentContext();
campServer = new CampServer(getCampPlatform(), "").start();
return this;
}
public static void main(String[] args) {
new BrooklynCampPlatformLauncher().launch();
}
public void stopServers() throws Exception {
brooklynLauncher.getServerDetails().getWebServer().stop();
campServer.stop();
}
}
| apache-2.0 |
googleapis/java-dataproc | proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/IdentityConfigOrBuilder.java | 2647 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/clusters.proto
package com.google.cloud.dataproc.v1;
public interface IdentityConfigOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.dataproc.v1.IdentityConfig)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. Map of user to service account.
* </pre>
*
* <code>
* map<string, string> user_service_account_mapping = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
int getUserServiceAccountMappingCount();
/**
*
*
* <pre>
* Required. Map of user to service account.
* </pre>
*
* <code>
* map<string, string> user_service_account_mapping = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
boolean containsUserServiceAccountMapping(java.lang.String key);
/** Use {@link #getUserServiceAccountMappingMap()} instead. */
@java.lang.Deprecated
java.util.Map<java.lang.String, java.lang.String> getUserServiceAccountMapping();
/**
*
*
* <pre>
* Required. Map of user to service account.
* </pre>
*
* <code>
* map<string, string> user_service_account_mapping = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
java.util.Map<java.lang.String, java.lang.String> getUserServiceAccountMappingMap();
/**
*
*
* <pre>
* Required. Map of user to service account.
* </pre>
*
* <code>
* map<string, string> user_service_account_mapping = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
java.lang.String getUserServiceAccountMappingOrDefault(
java.lang.String key, java.lang.String defaultValue);
/**
*
*
* <pre>
* Required. Map of user to service account.
* </pre>
*
* <code>
* map<string, string> user_service_account_mapping = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
java.lang.String getUserServiceAccountMappingOrThrow(java.lang.String key);
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/service/Customer574Service.java | 221 | package example.service;
import example.repo.Customer574Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer574Service {
public Customer574Service(Customer574Repository repo) {}
}
| apache-2.0 |
BeamFoundry/spring-osgi | spring-dm/annotation/src/main/java/org/springframework/osgi/extensions/annotation/ServiceReferenceClassLoader.java | 1359 | /*
* Copyright 2006-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.osgi.extensions.annotation;
import org.springframework.osgi.service.importer.support.ImportContextClassLoader;
/**
* Spring-DM managed OSGi service <code>ClassLoader</code> property.
*
* @author Andy Piper
*/
public enum ServiceReferenceClassLoader {
CLIENT(ImportContextClassLoader.CLIENT), SERVICE_PROVIDER(ImportContextClassLoader.SERVICE_PROVIDER), UNMANAGED(
ImportContextClassLoader.UNMANAGED);
private ImportContextClassLoader icclValue;
private ServiceReferenceClassLoader(ImportContextClassLoader iccl) {
icclValue = iccl;
}
public String toString() {
return icclValue.getLabel();
}
public ImportContextClassLoader toImportContextClassLoader() {
return icclValue;
}
}
| apache-2.0 |
ksgwr/ParallelPipeline | src/main/java/jp/ksgwr/pipeline/InTap.java | 835 | package jp.ksgwr.pipeline;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Input Pipe
* @author ksgwr
*
*/
public class InTap extends Pipe {
/**
* constructor
* @param in input stream
*/
public InTap(InputStream in) {
super.in = in;
}
/**
* constructor
* @param file file
* @throws FileNotFoundException exception
*/
public InTap(File file) throws FileNotFoundException {
InputStream in = new FileInputStream(file);
super.in = in;
}
/**
* constructor
* @param file file
* @param charset charset
* @throws FileNotFoundException exception
*/
public InTap(File file, String charset) throws FileNotFoundException {
InputStream in = new FileInputStream(file);
super.in = in;
super.inputCharset = charset;
}
}
| apache-2.0 |
agorava/agorava-linkedin | agorava-linkedin-cdi/src/main/java/org/agorava/linkedin/jackson/UpdateContentFollowMixin.java | 1627 | /*
* Copyright 2014 Agorava
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.agorava.linkedin.jackson;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.agorava.linkedin.model.UrlResource;
/**
* @author Antoine Sabot-Durand
*/
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class UpdateContentFollowMixin extends LinkedInObjectMixin {
@JsonProperty("summary")
String summary;
@JsonCreator
UpdateContentFollowMixin(@JsonProperty("id") String id, @JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName, @JsonProperty("email-address") String email,
@JsonProperty("headline") String headline,
@JsonProperty("industry") String industry, @JsonProperty("publicProfileUrl") String
publicProfileUrl,
@JsonProperty("siteStandardProfileRequest") UrlResource siteStandardProfileRequest,
@JsonProperty("pictureUrl") String profilePictureUrl) {
}
}
| apache-2.0 |
sibay/vertx-web | vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java | 1823 | package io.vertx.ext.web;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.VertxGen;
/**
* A container with the request's headers that are meaningful enough to be parsed
* Contains:
* <ul>
* <li>Accept -> MIME header, parameters and sortable</li>
* <li>Accept-Charset -> Parameters and sortable</li>
* <li>Accept-Encoding -> Parameters and sortable</li>
* <li>Accept-Language -> Parameters and sortable</li>
* <li>Content-Type -> MIME header and parameters</li>
* </ul>
*
*/
@VertxGen
public interface ParsedHeaderValues {
/**
* @return List of MIME values in the {@code Accept} header
*/
List<MIMEHeader> accept();
/**
* @return List of charset values in the {@code Accept-Charset} header
*/
List<ParsedHeaderValue> acceptCharset();
/**
* @return List of encofing values in the {@code Accept-Encoding} header
*/
List<ParsedHeaderValue> acceptEncoding();
/**
* @return List of languages in the {@code Accept-Language} header
*/
List<LanguageHeader> acceptLanguage();
/**
* @return MIME value in the {@code Content-Type} header
*/
MIMEHeader contentType();
/**
* Given the sorted list of parsed header values the user has sent and an Iterable of acceptable values:
* It finds the first accepted header that matches any inside the Iterable.
* <p>
* <b>Note:</b> This method is intended for internal usage.
* </p>
*
* @param accepted The sorted list of headers to find the best one.
* @param in The headers to match against.
* @return The first header that matched, otherwise empty if none matched
*/
@GenIgnore
<T extends ParsedHeaderValue> T findBestUserAcceptedIn(List<T> accepted, Collection<T> in);
}
| apache-2.0 |
hainguyen1989/oauthsample | src/main/java/com/haint/oauth/net/SocialNetworkAPIWrapper.java | 271 | /**
*
*/
package com.haint.oauth.net;
import com.haint.oauth.model.User;
/**
* @author HAINT
*
*/
public interface SocialNetworkAPIWrapper {
String getDialogLink();
String getAccessToken(String code);
User getUser();
void setAccessToken(String token);
}
| apache-2.0 |
ultradns/ultra-java-api | src/main/java/com/neustar/ultraservice/schema/v01/ReportType.java | 2755 |
package com.neustar.ultraservice.schema.v01;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for reportType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="reportType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Domains"/>
* <enumeration value="Records"/>
* <enumeration value="Queries"/>
* <enumeration value="Region"/>
* <enumeration value="PoolRecord"/>
* <enumeration value="FailoverProbe"/>
* <enumeration value="Failover"/>
* <enumeration value="Overall Activity - Domains"/>
* <enumeration value="Overall Activity - Records"/>
* <enumeration value="Overall Activity - Queries"/>
* <enumeration value="Activity by Region"/>
* <enumeration value="Failover - Pool Record"/>
* <enumeration value="Failover - Probe Statistics"/>
* <enumeration value="Failover - Failover"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "reportType")
@XmlEnum
public enum ReportType {
@XmlEnumValue("Domains")
DOMAINS("Domains"),
@XmlEnumValue("Records")
RECORDS("Records"),
@XmlEnumValue("Queries")
QUERIES("Queries"),
@XmlEnumValue("Region")
REGION("Region"),
@XmlEnumValue("PoolRecord")
POOL_RECORD("PoolRecord"),
@XmlEnumValue("FailoverProbe")
FAILOVER_PROBE("FailoverProbe"),
@XmlEnumValue("Failover")
FAILOVER("Failover"),
@XmlEnumValue("Overall Activity - Domains")
OVERALL_ACTIVITY_DOMAINS("Overall Activity - Domains"),
@XmlEnumValue("Overall Activity - Records")
OVERALL_ACTIVITY_RECORDS("Overall Activity - Records"),
@XmlEnumValue("Overall Activity - Queries")
OVERALL_ACTIVITY_QUERIES("Overall Activity - Queries"),
@XmlEnumValue("Activity by Region")
ACTIVITY_BY_REGION("Activity by Region"),
@XmlEnumValue("Failover - Pool Record")
FAILOVER_POOL_RECORD("Failover - Pool Record"),
@XmlEnumValue("Failover - Probe Statistics")
FAILOVER_PROBE_STATISTICS("Failover - Probe Statistics"),
@XmlEnumValue("Failover - Failover")
FAILOVER_FAILOVER("Failover - Failover");
private final String value;
ReportType(String v) {
value = v;
}
public String value() {
return value;
}
public static ReportType fromValue(String v) {
for (ReportType c: ReportType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| apache-2.0 |
donNewtonAlpha/onos | protocols/lisp/msg/src/test/java/org/onosproject/lisp/msg/types/lcaf/LispMulticastLcafAddressTest.java | 4517 | /*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.lisp.msg.types.lcaf;
import com.google.common.testing.EqualsTester;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.lisp.msg.exceptions.LispParseError;
import org.onosproject.lisp.msg.exceptions.LispReaderException;
import org.onosproject.lisp.msg.exceptions.LispWriterException;
import org.onosproject.lisp.msg.types.LispIpv4Address;
import org.onosproject.lisp.msg.types.lcaf.LispMulticastLcafAddress.MulticastAddressBuilder;
import org.onosproject.lisp.msg.types.lcaf.LispMulticastLcafAddress.MulticastLcafAddressReader;
import org.onosproject.lisp.msg.types.lcaf.LispMulticastLcafAddress.MulticastLcafAddressWriter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* Unit tests for LispMulticastLcafAddress class.
*/
public class LispMulticastLcafAddressTest {
private static final String IP_ADDRESS_1 = "192.168.1.1";
private static final String IP_ADDRESS_2 = "192.168.1.2";
private LispMulticastLcafAddress address1;
private LispMulticastLcafAddress sameAsAddress1;
private LispMulticastLcafAddress address2;
@Before
public void setup() {
MulticastAddressBuilder builder1 = new MulticastAddressBuilder();
LispIpv4Address ipv4Address1 =
new LispIpv4Address(IpAddress.valueOf(IP_ADDRESS_1));
address1 = builder1
.withInstanceId(1)
.withSrcMaskLength((byte) 0x24)
.withGrpMaskLength((byte) 0x24)
.withSrcAddress(ipv4Address1)
.withGrpAddress(ipv4Address1)
.build();
MulticastAddressBuilder builder2 = new MulticastAddressBuilder();
sameAsAddress1 = builder2
.withInstanceId(1)
.withSrcMaskLength((byte) 0x24)
.withGrpMaskLength((byte) 0x24)
.withSrcAddress(ipv4Address1)
.withGrpAddress(ipv4Address1)
.build();
MulticastAddressBuilder builder3 = new MulticastAddressBuilder();
LispIpv4Address ipv4Address2 =
new LispIpv4Address(IpAddress.valueOf(IP_ADDRESS_2));
address2 = builder3
.withInstanceId(2)
.withSrcMaskLength((byte) 0x24)
.withGrpMaskLength((byte) 0x24)
.withSrcAddress(ipv4Address2)
.withGrpAddress(ipv4Address2)
.build();
}
@Test
public void testEquality() {
new EqualsTester()
.addEqualityGroup(address1, sameAsAddress1)
.addEqualityGroup(address2).testEquals();
}
@Test
public void testConstruction() {
LispMulticastLcafAddress multicastLcafAddress = address1;
LispIpv4Address ipv4Address =
new LispIpv4Address(IpAddress.valueOf(IP_ADDRESS_1));
assertThat(multicastLcafAddress.getInstanceId(), is(1));
assertThat(multicastLcafAddress.getSrcMaskLenth(), is((byte) 0x24));
assertThat(multicastLcafAddress.getGrpMaskLength(), is((byte) 0x24));
assertThat(multicastLcafAddress.getSrcAddress(), is(ipv4Address));
assertThat(multicastLcafAddress.getGrpAddress(), is(ipv4Address));
}
@Test
public void testSerialization() throws LispWriterException, LispParseError,
LispReaderException {
ByteBuf byteBuf = Unpooled.buffer();
MulticastLcafAddressWriter writer = new MulticastLcafAddressWriter();
writer.writeTo(byteBuf, address1);
MulticastLcafAddressReader reader = new MulticastLcafAddressReader();
LispMulticastLcafAddress deserialized = reader.readFrom(byteBuf);
new EqualsTester().addEqualityGroup(address1, deserialized).testEquals();
}
}
| apache-2.0 |
dernasherbrezon/jradio | src/main/java/ru/r2cloud/jradio/eseo/CpuError.java | 6107 | package ru.r2cloud.jradio.eseo;
import java.io.IOException;
import ru.r2cloud.jradio.util.LittleEndianDataInputStream;
public class CpuError {
private boolean hardFaultVECTTBL;// forced hard fault generated by escalation
private boolean hardFaultFORCED;// hard fault during exception processing
private boolean memManageIACCVIOL;// Instruction access violating flag
private boolean memManageDACCVIOL;// data access violating flag
private boolean memManageMSTKERR;// memory manager fault on unstacking for a return from exception
private boolean memManageMUNKSERR;// memory manage fault on stacking for exception entry
private boolean memManageMLSPERR;// fault occurred during floating point state preservation
private boolean busErrorSTKERR;// bus fault on stacking for exception entry
private boolean busErrorUNSTKERR;// bus fault on unstacking for a return on exception
private boolean busErrorIBUSERR;// instruction bus error
private boolean busErrorLSPERR;// nus fault on floating point lazy state preservation
private boolean busErrorPRECISERR;// precise data bus error
private boolean busErrorIMPRECISERR;// imprecise data bus error
private boolean usageFaultNOCP;// no coprocessor usage fault
private boolean usageFaultUNDEFINSTR;// undefined instruction usage fault
private boolean usageFaultINVSTATE;// Invalid state usage fault
private boolean usageFaultINVCP;// Invalid PC load usage fault
private boolean usageFaultUNALIGNED;// unaligned access usage fault
private boolean usageFaultDIVBYZERO;// division by zero fault
public CpuError() {
// do nothing
}
public CpuError(LittleEndianDataInputStream dis) throws IOException {
int raw = dis.readUnsignedByte();
hardFaultVECTTBL = ((raw >> 7) & 0x1) > 0;
hardFaultFORCED = ((raw >> 6) & 0x1) > 0;
memManageIACCVIOL = ((raw >> 5) & 0x1) > 0;
memManageDACCVIOL = ((raw >> 4) & 0x1) > 0;
memManageMSTKERR = ((raw >> 3) & 0x1) > 0;
memManageMUNKSERR = ((raw >> 2) & 0x1) > 0;
memManageMLSPERR = ((raw >> 1) & 0x1) > 0;
busErrorSTKERR = (raw & 0x1) > 0;
raw = dis.readUnsignedByte();
busErrorUNSTKERR = ((raw >> 7) & 0x1) > 0;
busErrorIBUSERR = ((raw >> 6) & 0x1) > 0;
busErrorLSPERR = ((raw >> 5) & 0x1) > 0;
busErrorPRECISERR = ((raw >> 4) & 0x1) > 0;
busErrorIMPRECISERR = ((raw >> 3) & 0x1) > 0;
usageFaultNOCP = ((raw >> 2) & 0x1) > 0;
usageFaultUNDEFINSTR = ((raw >> 1) & 0x1) > 0;
usageFaultINVSTATE = (raw & 0x1) > 0;
raw = dis.readUnsignedByte();
usageFaultINVCP = ((raw >> 7) & 0x1) > 0;
usageFaultUNALIGNED = ((raw >> 6) & 0x1) > 0;
usageFaultDIVBYZERO = ((raw >> 5) & 0x1) > 0;
dis.skipBytes(1);
}
public boolean isHardFaultVECTTBL() {
return hardFaultVECTTBL;
}
public void setHardFaultVECTTBL(boolean hardFaultVECTTBL) {
this.hardFaultVECTTBL = hardFaultVECTTBL;
}
public boolean isHardFaultFORCED() {
return hardFaultFORCED;
}
public void setHardFaultFORCED(boolean hardFaultFORCED) {
this.hardFaultFORCED = hardFaultFORCED;
}
public boolean isMemManageIACCVIOL() {
return memManageIACCVIOL;
}
public void setMemManageIACCVIOL(boolean memManageIACCVIOL) {
this.memManageIACCVIOL = memManageIACCVIOL;
}
public boolean isMemManageDACCVIOL() {
return memManageDACCVIOL;
}
public void setMemManageDACCVIOL(boolean memManageDACCVIOL) {
this.memManageDACCVIOL = memManageDACCVIOL;
}
public boolean isMemManageMSTKERR() {
return memManageMSTKERR;
}
public void setMemManageMSTKERR(boolean memManageMSTKERR) {
this.memManageMSTKERR = memManageMSTKERR;
}
public boolean isMemManageMUNKSERR() {
return memManageMUNKSERR;
}
public void setMemManageMUNKSERR(boolean memManageMUNKSERR) {
this.memManageMUNKSERR = memManageMUNKSERR;
}
public boolean isMemManageMLSPERR() {
return memManageMLSPERR;
}
public void setMemManageMLSPERR(boolean memManageMLSPERR) {
this.memManageMLSPERR = memManageMLSPERR;
}
public boolean isBusErrorSTKERR() {
return busErrorSTKERR;
}
public void setBusErrorSTKERR(boolean busErrorSTKERR) {
this.busErrorSTKERR = busErrorSTKERR;
}
public boolean isBusErrorUNSTKERR() {
return busErrorUNSTKERR;
}
public void setBusErrorUNSTKERR(boolean busErrorUNSTKERR) {
this.busErrorUNSTKERR = busErrorUNSTKERR;
}
public boolean isBusErrorIBUSERR() {
return busErrorIBUSERR;
}
public void setBusErrorIBUSERR(boolean busErrorIBUSERR) {
this.busErrorIBUSERR = busErrorIBUSERR;
}
public boolean isBusErrorLSPERR() {
return busErrorLSPERR;
}
public void setBusErrorLSPERR(boolean busErrorLSPERR) {
this.busErrorLSPERR = busErrorLSPERR;
}
public boolean isBusErrorPRECISERR() {
return busErrorPRECISERR;
}
public void setBusErrorPRECISERR(boolean busErrorPRECISERR) {
this.busErrorPRECISERR = busErrorPRECISERR;
}
public boolean isBusErrorIMPRECISERR() {
return busErrorIMPRECISERR;
}
public void setBusErrorIMPRECISERR(boolean busErrorIMPRECISERR) {
this.busErrorIMPRECISERR = busErrorIMPRECISERR;
}
public boolean isUsageFaultNOCP() {
return usageFaultNOCP;
}
public void setUsageFaultNOCP(boolean usageFaultNOCP) {
this.usageFaultNOCP = usageFaultNOCP;
}
public boolean isUsageFaultUNDEFINSTR() {
return usageFaultUNDEFINSTR;
}
public void setUsageFaultUNDEFINSTR(boolean usageFaultUNDEFINSTR) {
this.usageFaultUNDEFINSTR = usageFaultUNDEFINSTR;
}
public boolean isUsageFaultINVSTATE() {
return usageFaultINVSTATE;
}
public void setUsageFaultINVSTATE(boolean usageFaultINVSTATE) {
this.usageFaultINVSTATE = usageFaultINVSTATE;
}
public boolean isUsageFaultINVCP() {
return usageFaultINVCP;
}
public void setUsageFaultINVCP(boolean usageFaultINVCP) {
this.usageFaultINVCP = usageFaultINVCP;
}
public boolean isUsageFaultUNALIGNED() {
return usageFaultUNALIGNED;
}
public void setUsageFaultUNALIGNED(boolean usageFaultUNALIGNED) {
this.usageFaultUNALIGNED = usageFaultUNALIGNED;
}
public boolean isUsageFaultDIVBYZERO() {
return usageFaultDIVBYZERO;
}
public void setUsageFaultDIVBYZERO(boolean usageFaultDIVBYZERO) {
this.usageFaultDIVBYZERO = usageFaultDIVBYZERO;
}
}
| apache-2.0 |
ymizusawa/Tatami | tatami/src/main/java/jp/yoshi_misa_kae/tatami/annotations/extra/ExtraSerializable.java | 566 | package jp.yoshi_misa_kae.tatami.annotations.extra;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jp.yoshi_misa_kae.tatami.TatamiType;
/**
* Created by Yoshitaka Mizusawa on 2015/12/24.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExtraSerializable {
public static final int annotationType = TatamiType.TYPE_EXTRA;
public static final int annotationProcess = TatamiType.EXTRA_SERIALIZABLE;
}
| apache-2.0 |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/HirschbergLinearSpaceLcsTest.java | 389 | package com.fillumina.lcs;
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest;
/**
*
* @author Francesco Illuminati
*/
public class HirschbergLinearSpaceLcsTest extends AbstractLcsLengthTest {
@Override
public LcsLength getLcsLengthAlgorithm() {
return new LcsLengthAdaptor(HirschbergLinearSpaceLcs.INSTANCE);
}
}
| apache-2.0 |
MACEPA/EpiSample | progressWheel/build/generated/source/buildConfig/debug/com/todddavies/components/progressbar/BuildConfig.java | 481 | /**
* Automatically generated file. DO NOT MODIFY
*/
package com.todddavies.components.progressbar;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.todddavies.components.progressbar";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| apache-2.0 |
ebi-uniprot/QuickGOBE | sources/src/main/java/uk/ac/ebi/quickgo/ff/loader/ontology/GOLoader.java | 4118 | package uk.ac.ebi.quickgo.ff.loader.ontology;
import uk.ac.ebi.quickgo.ff.files.ontology.GOSourceFiles;
import uk.ac.ebi.quickgo.model.ontology.go.GOTerm;
import uk.ac.ebi.quickgo.model.ontology.go.GeneOntology;
/**
* Loads a complete GO ontology from a suite of source files.
*
* Created by Edd on 11/12/2015.
*/
public class GOLoader extends AbstractGenericOLoader<GOSourceFiles, GeneOntology> {
public GOLoader(GOSourceFiles sourceFiles) {
super(sourceFiles);
}
@Override
public GeneOntology load() throws Exception {
GeneOntology go = getInstance();
// first add all GO terms to the ontology (additional information will be added to each term later)
for (String[] row : sourceFiles.goTerms.reader(GOSourceFiles.EGOTerm.GO_ID,
GOSourceFiles.EGOTerm.NAME,
GOSourceFiles.EGOTerm.CATEGORY,
GOSourceFiles.EGOTerm.IS_OBSOLETE)) {
go.addTerm(new GOTerm(row[0], row[1], row[2], row[3]));
}
// add generic ontology info
createWithGenericOInfo(GeneOntology.NAME_SPACE, GeneOntology.root);
for (String[] row : sourceFiles.taxonUnions.reader(GOSourceFiles.ETaxonUnion.UNION_ID,
GOSourceFiles.ETaxonUnion.NAME,
GOSourceFiles.ETaxonUnion.TAXA)) {
go.taxonConstraints.addTaxonUnion(row[0], row[1], row[2]);
}
for (String[] row : sourceFiles.taxonConstraints.reader(GOSourceFiles.ETaxonConstraint.RULE_ID,
GOSourceFiles.ETaxonConstraint.GO_ID,
GOSourceFiles.ETaxonConstraint.NAME,
GOSourceFiles.ETaxonConstraint.RELATIONSHIP,
GOSourceFiles.ETaxonConstraint.TAX_ID_TYPE,
GOSourceFiles.ETaxonConstraint.TAX_ID,
GOSourceFiles.ETaxonConstraint.TAXON_NAME,
GOSourceFiles.ETaxonConstraint.SOURCES)) {
go.taxonConstraints.addConstraint(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]);
}
for (String[] row : sourceFiles.termTaxonConstraints.reader(GOSourceFiles.ETermTaxonConstraint.GO_ID,
GOSourceFiles.ETermTaxonConstraint.RULE_ID)) {
GOTerm term = (GOTerm) go.getTerm(row[0]);
if (term != null) {
term.addTaxonConstraint(go.taxonConstraints.get(row[1]));
}
}
for (String[] row : sourceFiles.annotationGuidelines.reader(GOSourceFiles.EAnnotationGuidelineInfo.GO_ID,
GOSourceFiles.EAnnotationGuidelineInfo.TITLE,
GOSourceFiles.EAnnotationGuidelineInfo.URL)) {
GOTerm term = (GOTerm) go.getTerm(row[0]);
if (term != null) {
term.addGuideline(row[1], row[2]);
}
}
for (String[] row : sourceFiles.plannedGOChanges.reader(GOSourceFiles.EPlannedGOChangeInfo.GO_ID,
GOSourceFiles.EPlannedGOChangeInfo.TITLE,
GOSourceFiles.EPlannedGOChangeInfo.URL)) {
GOTerm term = (GOTerm) go.getTerm(row[0]);
if (term != null) {
term.addPlannedChange(row[1], row[2]);
}
}
for (String[] row : sourceFiles.blacklistForGoTerm.reader(GOSourceFiles.EAnnBlacklistEntry.GO_ID,
GOSourceFiles.EAnnBlacklistEntry.CATEGORY,
GOSourceFiles.EAnnBlacklistEntry.ENTITY_TYPE,
GOSourceFiles.EAnnBlacklistEntry.ENTITY_ID,
GOSourceFiles.EAnnBlacklistEntry.TAXON_ID,
GOSourceFiles.EAnnBlacklistEntry.ENTITY_NAME,
GOSourceFiles.EAnnBlacklistEntry.ANCESTOR_GO_ID,
GOSourceFiles.EAnnBlacklistEntry.REASON,
GOSourceFiles.EAnnBlacklistEntry.METHOD_ID)) {
GOTerm term = (GOTerm) go.getTerm(row[0]);
if (term != null) {
term.addBlacklist(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]);
}
}
return go;
}
@Override
protected GeneOntology newInstance() {
return new GeneOntology();
}
}
| apache-2.0 |
tommyettinger/sarong | sarong-benchmarks/src/test/java/sarong/ShufflerTest.java | 3659 | package sarong;
import org.junit.Test;
/**
* Created by Tommy Ettinger on 5/21/2016.
*/
public class ShufflerTest {
@Test
public void testLSSBounds()
{
for (int i = 2; i <= 42; i++) {
LowStorageShuffler lss = new LowStorageShuffler(i, 31337);
System.out.printf("Bound %02d: %d", i, lss.next());
for (int j = 1; j < i; j++) {
System.out.print(", " + lss.next());
}
System.out.println();
}
}
@Test
public void testLSSReseed()
{
LowStorageShuffler lss = new LowStorageShuffler(7, 0);
for (int i = 0; i < 30; i++) {
lss.restart(i);
System.out.printf("Seed %08X: %d", i, lss.next());
for (int j = 1; j < 7; j++) {
System.out.print(", " + lss.next());
}
System.out.println();
}
}
@Test
public void testLSSReverse()
{
LowStorageShuffler lss = new LowStorageShuffler(7, 0);
for (int i = 0; i < 10; i++) {
lss.restart(i);
System.out.printf("Seed %08X forward: %d", i, lss.next());
for (int j = 1; j < 7; j++) {
System.out.print(", " + lss.next());
}
System.out.println();
System.out.printf("Seed %08X reverse: %d", i, lss.previous());
for (int j = 1; j < 7; j++) {
System.out.print(", " + lss.previous());
}
System.out.println();
}
}
@Test
public void testSIS()
{
ShuffledIntSequence sis = new ShuffledIntSequence(10, 31337);
for (int j = 0; j < 10; j++) {
System.out.print(sis.next());
for (int i = 1; i < 20; i++) {
System.out.print(", " + sis.next());
}
System.out.println();
}
}
@Test
public void testSNBounds()
{
for (int i = 3; i <= 42; i++) {
SwapOrNotShuffler sn = new SwapOrNotShuffler(i, 0x1337CAFE);
System.out.printf("Bound %02d: %d", i, sn.next());
for (int j = 1; j < i; j++) {
System.out.print(", " + sn.next());
}
System.out.println();
}
}
@Test
public void testSNReseed()
{
SwapOrNotShuffler sn = new SwapOrNotShuffler(30, 0);
for (int i = 0; i < 30; i++) {
sn.restart(i);
System.out.printf("Seed %08X: %02d", i, sn.next());
for (int j = 1; j < 30; j++) {
System.out.printf(", %02d", sn.next());
}
System.out.println();
}
}
@Test
public void testSNReverse()
{
SwapOrNotShuffler sn = new SwapOrNotShuffler(7, 0);
for (int i = 0; i < 10; i++) {
sn.restart(i);
System.out.printf("Seed %08X forward: %d", i, sn.next());
for (int j = 1; j < 7; j++) {
System.out.print(", " + sn.next());
}
System.out.println();
System.out.printf("Seed %08X reverse: %d", i, sn.previous());
for (int j = 1; j < 7; j++) {
System.out.print(", " + sn.previous());
}
System.out.println();
}
}
@Test
public void testSNSIS()
{
SNShuffledIntSequence sis = new SNShuffledIntSequence(10, 0xBEEF1E57);
for (int j = 0; j < 10; j++) {
System.out.print(sis.next());
for (int i = 1; i < 20; i++) {
System.out.print(", " + sis.next());
}
System.out.println();
}
}
}
| apache-2.0 |
kulinski/myfaces | impl/src/test/java/org/apache/myfaces/el/unified/NoOpPropertyResolver.java | 2564 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.myfaces.el.unified;
import javax.faces.el.EvaluationException;
import javax.faces.el.PropertyNotFoundException;
import javax.faces.el.PropertyResolver;
/**
* @author Mathias Broekelmann (latest modification by $Author: slessard $)
* @version $Revision: 699848 $ $Date: 2008-09-28 11:12:21 -0500 (Sun, 28 Sep 2008) $
*/
@SuppressWarnings("deprecation")
public class NoOpPropertyResolver extends PropertyResolver
{
@SuppressWarnings("unchecked")
@Override
public Class getType(Object base, int index) throws EvaluationException, PropertyNotFoundException
{
return null;
}
@SuppressWarnings("unchecked")
@Override
public Class getType(Object base, Object property) throws EvaluationException, PropertyNotFoundException
{
return null;
}
@Override
public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException
{
return null;
}
@Override
public Object getValue(Object base, Object property) throws EvaluationException, PropertyNotFoundException
{
return null;
}
@Override
public boolean isReadOnly(Object base, int index) throws EvaluationException, PropertyNotFoundException
{
return false;
}
@Override
public boolean isReadOnly(Object base, Object property) throws EvaluationException, PropertyNotFoundException
{
return false;
}
@Override
public void setValue(Object base, int index, Object value) throws EvaluationException, PropertyNotFoundException
{
}
@Override
public void setValue(Object base, Object property, Object value) throws EvaluationException,
PropertyNotFoundException
{
}
}
| apache-2.0 |
zhangbz/androidannotation | src/com/example/androidannotation/ThirdActivity.java | 119 | package com.example.androidannotation;
import android.app.Activity;
public class ThirdActivity extends Activity {
}
| apache-2.0 |
ontopia/ontopia | ontopia-engine/src/main/java/net/ontopia/topicmaps/utils/deciders/TMDecider.java | 2444 | /*
* #!
* Ontopia Engine
* #-
* Copyright (C) 2001 - 2013 The Ontopia Project
* #-
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* !#
*/
package net.ontopia.topicmaps.utils.deciders;
import net.ontopia.utils.DeciderIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.core.VariantNameIF;
import net.ontopia.topicmaps.core.TopicNameIF;
import net.ontopia.topicmaps.core.TypedIF;
import java.util.Iterator;
/**
* INTERNAL: Decider that allows the user to filter out chosen objects
* used for testing the filtering of exporters.
*/
public class TMDecider implements DeciderIF<Object> {
@Override
public boolean ok(Object object) {
// a topic can be disallowed by being named "Disallowed Topic"
// a typed object can be disallowed by being typed with a topic named
// "Disallowed Type", but the typing topic itself will be accepted
if (object instanceof TopicIF)
return !isTopicName((TopicIF) object, "Disallowed Topic");
if (object instanceof TypedIF) {
TypedIF typed = (TypedIF) object;
boolean filtered = typed == null ||
!isTopicName(typed.getType(), "Disallowed Type");
if (!filtered)
return false;
}
if (object instanceof VariantNameIF)
return !((VariantNameIF) object).getValue().equals("Disallowed Variant");
if (object instanceof TopicNameIF)
return !((TopicNameIF) object).getValue().equals("Disallowed Name");
return true;
}
private static boolean isTopicName(TopicIF topic, String value) {
String v = getTopicName(topic);
return v != null && v.equals(value);
}
private static String getTopicName(TopicIF topic) {
if (topic == null)
return null;
Iterator<TopicNameIF> it = topic.getTopicNames().iterator();
if (it.hasNext()) {
TopicNameIF name = it.next();
return name.getValue();
}
return null;
}
}
| apache-2.0 |
b2ihealthcare/snow-owl | core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/commit/CommitInfos.java | 1459 | /*
* Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.core.commit;
import java.util.Collections;
import java.util.List;
import com.b2international.snowowl.core.domain.PageableCollectionResource;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @since 5.2
*/
public final class CommitInfos extends PageableCollectionResource<CommitInfo> {
private static final long serialVersionUID = 1L;
public CommitInfos(int limit, int total) {
this(Collections.emptyList(), null, limit, total);
}
@JsonCreator
public CommitInfos(
@JsonProperty("items") final List<CommitInfo> items,
@JsonProperty("searchAfter") final String searchAfter,
@JsonProperty("limit") final int limit,
@JsonProperty("total") final int total) {
super(items, searchAfter, limit, total);
}
}
| apache-2.0 |
elena20ruiz/ApiNRP | src/main/java/io/swagger/api/ReplanApi.java | 1600 | package io.swagger.api;
import io.swagger.model.*;
import io.swagger.annotations.*;
import io.swagger.model.Error;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-01T15:48:29.618Z")
@Api(value = "replan", description = "the replan API")
public interface ReplanApi {
@ApiOperation(value = "Generates a Planning Solution for a given Next Release Problem", notes = "", response = PlanningSolution.class, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = PlanningSolution.class),
@ApiResponse(code = 400, message = "Bad Request", response = PlanningSolution.class),
@ApiResponse(code = 422, message = "Unprocessable Entity", response = PlanningSolution.class) })
@RequestMapping(value = "/replan",
produces = { "application/json" },
method = RequestMethod.POST)
ResponseEntity<PlanningSolution> replan(
@ApiParam(value = "" ,required=true ) @RequestBody NextReleaseProblem body
);
}
| apache-2.0 |
BeanSugar/bs-oauth-java | oauth-client/src/main/java/org/scriptonbasestar/oauth/client/http/HttpRequest.java | 4105 | package org.scriptonbasestar.oauth.client.http;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.scriptonbasestar.oauth.client.exception.OAuthNetworkException;
import org.scriptonbasestar.oauth.client.exception.OAuthNetworkRemoteException;
import org.scriptonbasestar.oauth.client.type.OAuthHttpVerb;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
/**
* @author archmagece
* @since 2016-10-25 16
*/
@Slf4j
public final class HttpRequest {
private final CloseableHttpClient httpclient;
private final String url;
private final ParamList paramList;
private HttpRequest(String url, ParamList paramList) {
this.httpclient = HttpClients.createDefault();
this.url = url;
this.paramList = paramList;
}
private HttpRequest(String url, ParamList paramList, Collection<Header> headers) {
this.httpclient = HttpClients.custom().setDefaultHeaders(headers).build();
this.url = url;
this.paramList = paramList;
}
public static HttpRequest create(String url) {
return new HttpRequest(url, new ParamList());
}
public static HttpRequest create(String url, ParamList paramList) {
return new HttpRequest(url, paramList);
}
public static HttpRequest create(String url, ParamList paramList, Collection<Header> headers) {
return new HttpRequest(url, paramList, headers);
}
public static HttpRequest create(String url, Collection<Header> headers) {
return new HttpRequest(url, new ParamList(), headers);
}
public String run(OAuthHttpVerb httpVerb) {
try {
switch (httpVerb) {
case POST:
return postContent();
case GET:
default:
return getContent();
}
} catch (IOException e) {
// e.printStackTrace();
throw new OAuthNetworkException("extends IOException - 네트워크 오류");
}
}
private String postContent() throws IOException {
log.debug("postContent()");
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(ParamUtil.generateNameValueList(paramList),
Consts.UTF_8);
log.debug("post to :" + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(urlEncodedFormEntity);
log.debug("Executing request " + httpPost.getRequestLine());
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
return httpResponseToString(response);
} finally {
httpclient.close();
}
}
private String getContent() throws IOException {
log.debug("getContent()");
HttpGet httpget = new HttpGet(ParamUtil.generateOAuthQuery(url, paramList));
log.trace("get to :" + httpget.getURI().toURL());
log.debug("Executing request " + httpget.getRequestLine());
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
return httpResponseToString(response);
} finally {
httpclient.close();
}
}
private String httpResponseToString(CloseableHttpResponse response) throws IOException {
log.debug(response.getStatusLine().toString());
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new OAuthNetworkRemoteException("network connection exception. Remote 서버에서 응답이 없습니다.");
}
try (InputStream inStream = entity.getContent()) {
BufferedInputStream bufInStream = new BufferedInputStream(inStream);
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = bufInStream.read(b)) != -1; ) {
sb.append(new String(b, 0, n));
}
return sb.toString();
} catch (IOException e) {
throw new OAuthNetworkRemoteException("network stream exception. 데이터를 받아오는 중 문제 발생", e);
}
} finally {
response.close();
}
}
}
| apache-2.0 |
johnpfield/mytime | mytime-ejb/src/main/java/org/apache/geronimo/samples/mytimepak/MyTimeBean.java | 1584 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.samples.mytimepak;
import javax.ejb.Stateless;
import javax.ejb.EnterpriseBean;
import javax.ejb.SessionContext;
import javax.annotation.Resource;
@Stateless
public class MyTimeBean implements EnterpriseBean, MyTimeLocal {
@Resource
private SessionContext ctx;
public SessionContext getSessionContext() {
return this.ctx;
}
public void setSessionContext(SessionContext aCtx) {
this.ctx = aCtx;
}
public String getTime(String dummy) {
String s = new java.util.Date().toString();
String s2 = s.concat(dummy);
return s2;
}
public String getTimePrivate(String dummy) {
String s = new java.util.Date().toString();
String s2 = s.concat(dummy);
return s2;
}
}
| apache-2.0 |
bootique/bootique | bootique/src/test/java/io/bootique/Bootique_CliOptionsIT.java | 19107 | /*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC licenses
* this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.bootique;
import io.bootique.cli.Cli;
import io.bootique.command.CommandOutcome;
import io.bootique.command.CommandWithMetadata;
import io.bootique.config.ConfigurationFactory;
import io.bootique.config.jackson.CliConfigurationLoader;
import io.bootique.di.DIRuntimeException;
import io.bootique.meta.application.CommandMetadata;
import io.bootique.meta.application.OptionMetadata;
import io.bootique.run.Runner;
import io.bootique.unit.BQInternalTestFactory;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Collection;
import static org.junit.jupiter.api.Assertions.*;
public class Bootique_CliOptionsIT {
@RegisterExtension
public BQInternalTestFactory runtimeFactory = new BQInternalTestFactory();
@Test
public void testConfigOption() {
BQRuntime runtime = runtimeFactory.app("--config=abc.yml").createRuntime();
assertCollectionsEquals(runtime.getInstance(Cli.class).optionStrings(CliConfigurationLoader.CONFIG_OPTION), "abc.yml");
}
@Test
public void testConfigOptions() {
BQRuntime runtime = runtimeFactory.app("--config=abc.yml", "--config=xyz.yml").createRuntime();
assertCollectionsEquals(runtime.getInstance(Cli.class).optionStrings(CliConfigurationLoader.CONFIG_OPTION), "abc.yml",
"xyz.yml");
}
@Test
public void testHelpOption() {
BQRuntime runtime = runtimeFactory.app("--help").createRuntime();
assertTrue(runtime.getInstance(Cli.class).hasOption("help"));
}
@Test
public void testHelpOption_Short() {
BQRuntime runtime = runtimeFactory.app("-h").createRuntime();
assertTrue(runtime.getInstance(Cli.class).hasOption("help"));
}
@Test
public void testNoHelpOption() {
BQRuntime runtime = runtimeFactory.app("a", "b").createRuntime();
assertFalse(runtime.getInstance(Cli.class).hasOption("help"));
}
@Test
public void testOverlappingOptions() {
BQRuntime runtime = runtimeFactory.app("--o1")
.module(b -> BQCoreModule.extend(b).addOptions(
OptionMetadata.builder("o1").build(),
OptionMetadata.builder("o2").build()
))
.createRuntime();
assertTrue(runtime.getInstance(Cli.class).hasOption("o1"));
assertFalse(runtime.getInstance(Cli.class).hasOption("o2"));
}
@Test
public void testNameConflict_TwoOptions() {
assertThrows(DIRuntimeException.class, () -> runtimeFactory.app()
.module(b -> BQCoreModule.extend(b)
.addOptions(
OptionMetadata.builder("opt1").build(),
OptionMetadata.builder("opt1").build()))
.createRuntime()
.run());
}
@Test
public void testNameConflict_TwoCommands() {
assertThrows(DIRuntimeException.class, () -> runtimeFactory.app()
.module(b -> BQCoreModule.extend(b)
.addCommand(Xd1Command.class)
.addCommand(Xd2Command.class))
.createRuntime()
.run());
}
// TODO: ignoring this test for now. There is a bug in JOpt 5.0.3...
// JOpt should detect conflicting options and throw an exception. Instead JOpts triggers second option.
@Test
@Disabled
public void testOverlappingOptions_Short() {
BQRuntime runtime = runtimeFactory.app("-o")
.module(b -> BQCoreModule.extend(b).addOptions(
OptionMetadata.builder("o1").build(),
OptionMetadata.builder("o2").build()
))
.createRuntime();
assertThrows(DIRuntimeException.class, () -> runtime.getInstance(Cli.class));
}
// TODO: Same name of option and command should be disallowed.
// This test is broken, it is here just to document current behaviour.
@Test
public void testCommandWithOptionNameOverlap() {
BQRuntime runtime = runtimeFactory.app("-x")
.module(b -> BQCoreModule.extend(b)
.addCommand(Xd1Command.class)
.addOption(OptionMetadata.builder("xd").build())
).createRuntime();
runtime.run();
assertTrue(runtime.getInstance(Cli.class).hasOption("xd"));
}
@Test
public void testCommand_IllegalShort() {
BQRuntime runtime = runtimeFactory.app("-x")
.module(b -> BQCoreModule.extend(b).addCommand(XaCommand.class))
.createRuntime();
assertThrows(DIRuntimeException.class, () -> runtime.getInstance(Cli.class));
}
@Test
public void testCommand_ExplicitShort() {
BQRuntime runtime = runtimeFactory.app("-A")
.module(b -> BQCoreModule.extend(b).addCommand(XaCommand.class))
.createRuntime();
assertTrue(runtime.getInstance(Cli.class).hasOption("xa"));
}
@Test
public void testOverlappingCommands_IllegalShort() {
BQRuntime runtime = runtimeFactory.app("-x")
.module(b -> BQCoreModule.extend(b).addCommand(XaCommand.class).addCommand(XbCommand.class))
.createRuntime();
assertThrows(DIRuntimeException.class, () -> runtime.getInstance(Cli.class));
}
@Test
public void testIllegalAbbreviation() {
BQRuntime runtime = runtimeFactory.app("--xc")
.module(b -> BQCoreModule.extend(b).addCommand(XccCommand.class))
.createRuntime();
assertThrows(DIRuntimeException.class, () -> runtime.getInstance(Cli.class));
}
@Test
public void testOverlappingCommands_Short() {
BQRuntime runtime = runtimeFactory.app("-A")
.module(b -> BQCoreModule.extend(b).addCommand(XaCommand.class).addCommand(XbCommand.class))
.createRuntime();
assertTrue(runtime.getInstance(Cli.class).hasOption("xa"));
assertFalse(runtime.getInstance(Cli.class).hasOption("xb"));
}
@Test
public void testDefaultCommandOptions() {
BQRuntime runtime = runtimeFactory.app("-l", "x", "--long=y", "-s")
.module(binder -> BQCoreModule.extend(binder).setDefaultCommand(TestCommand.class))
.createRuntime();
Cli cli = runtime.getInstance(Cli.class);
assertTrue(cli.hasOption("s"));
assertEquals("x_y", String.join("_", cli.optionStrings("long")));
}
@Test
public void testOption_OverrideConfig() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--opt-1=x")
.module(binder -> BQCoreModule
.extend(binder)
.addOptions(OptionMetadata.builder("opt-1").valueOptional().build(),
OptionMetadata.builder("opt-2").valueOptionalWithDefault("2").build())
.mapConfigPath("opt-1", "c.m.l")
.mapConfigPath("opt-2", "c.m.k"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals("e", bean1.a);
assertEquals("x", bean1.c.m.l);
assertEquals(1, bean1.c.m.k);
}
@Test
public void testOptionPathAbsentInYAML() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--opt-1=x")
.module(binder -> BQCoreModule
.extend(binder)
.addOption(OptionMetadata.builder("opt-1").valueOptional().build())
.mapConfigPath("opt-1", "c.m.f"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals("x", bean1.c.m.f);
}
@Test
public void testOptionsCommandAndModuleOverlapping() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--cmd-1", "--opt-1")
.module(binder -> BQCoreModule.extend(binder)
.addOption(OptionMetadata.builder("opt-1").valueOptionalWithDefault("2").build())
.mapConfigPath("opt-1", "c.m.k")
.addCommand(new TestOptionCommand1()))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
Runner runner = runtime.getInstance(Runner.class);
runner.run();
assertEquals(2, bean1.c.m.k);
}
@Test
public void testOptionsOrder_OnCLI() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--file-opt-1",
"--opt-2=y", "--opt-1=x")
.module(binder -> BQCoreModule.extend(binder)
.addConfig("classpath:io/bootique/config/test4Copy.yml")
.addOptions(OptionMetadata.builder("opt-1").valueOptional().build(),
OptionMetadata.builder("opt-2").valueOptional().build(),
OptionMetadata.builder("file-opt-1").build())
.mapConfigPath("opt-1", "c.m.f")
.mapConfigPath("opt-2", "c.m.f")
.mapConfigResource("file-opt-1", "classpath:io/bootique/config/configTest4Opt1.yml")
.mapConfigResource("file-opt-1", "classpath:io/bootique/config/configTest4Decorate.yml"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals(4, bean1.c.m.k);
assertEquals("x", bean1.c.m.f);
assertEquals("copy", bean1.c.m.l);
assertEquals("e", bean1.a);
}
@Test
public void testOptionsWithOverlappingPath_OverrideConfig() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--opt-2", "--opt-3")
.module(binder -> BQCoreModule.extend(binder)
.addOptions(OptionMetadata.builder("opt-1").valueOptional().build(),
OptionMetadata.builder("opt-2").valueOptionalWithDefault("2").build(),
OptionMetadata.builder("opt-3").valueOptionalWithDefault("3").build())
.mapConfigPath("opt-1", "c.m.k")
.mapConfigPath("opt-2", "c.m.k")
.mapConfigPath("opt-3", "c.m.k"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals(3, bean1.c.m.k);
}
@Test
public void testOptionWithNotMappedConfigPath() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--opt-1=x")
.module(binder -> BQCoreModule.extend(binder)
.mapConfigPath("opt-1", "c.m.k.x"))
.createRuntime();
assertThrows(DIRuntimeException.class, () -> runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, ""));
}
@Test
public void testOptionConfigFile_OverrideConfig() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--file-opt")
.module(binder -> BQCoreModule.extend(binder)
.addOption(OptionMetadata.builder("file-opt").build())
.mapConfigResource("file-opt", "classpath:io/bootique/config/configTest4.yml"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals("x", bean1.c.m.l);
}
@Test
public void testMultipleOptionsConfigFiles_OverrideInCLIOrder() {
BQRuntime runtime = runtimeFactory.app("--config=classpath:io/bootique/config/test4.yml", "--file-opt-2", "--file-opt-1")
.module(binder -> BQCoreModule.extend(binder)
.addOptions(OptionMetadata.builder("file-opt-1").build(),
OptionMetadata.builder("file-opt-2").build())
.mapConfigPath("opt-1", "c.m.f")
.mapConfigResource("file-opt-1", "classpath:io/bootique/config/configTest4Opt1.yml")
.mapConfigResource("file-opt-2", "classpath:io/bootique/config/configTest4Opt2.yml"))
.createRuntime();
Bean1 bean1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");
assertEquals(2, bean1.c.m.k);
assertEquals("f", bean1.c.m.f);
}
@Test
public void testOptionDefaultValue() {
BQRuntime runtime = runtimeFactory.app("--option")
.module(b -> BQCoreModule.extend(b).addOptions(
OptionMetadata.builder("option").valueOptionalWithDefault("val").build()
))
.createRuntime();
Cli cli = runtime.getInstance(Cli.class);
assertTrue(cli.hasOption("option"));
assertEquals("val", cli.optionString("option"));
}
@Test
public void testMissingOptionDefaultValue() {
BQRuntime runtime = runtimeFactory.app()
.module(b -> BQCoreModule.extend(b).addOptions(
OptionMetadata.builder("option").valueOptionalWithDefault("val").build()
))
.createRuntime();
Cli cli = runtime.getInstance(Cli.class);
// Check that no value is set if option is missing in args
assertFalse(cli.hasOption("option"));
assertNull(cli.optionString("option"));
}
@Test
public void testCommandWithOptionWithDefaultValue() {
BQRuntime runtime = runtimeFactory.app("-cmd", "--option")
.module(b -> BQCoreModule.extend(b).addCommand(CommandWithDefaultOptionValue.class))
.createRuntime();
Cli cli = runtime.getInstance(Cli.class);
assertTrue(cli.hasOption("o"));
assertEquals("val", cli.optionString("o"));
}
private void assertCollectionsEquals(Collection<String> result, String... expected) {
assertArrayEquals(expected, result.toArray());
}
static final class TestCommand extends CommandWithMetadata {
public TestCommand() {
super(CommandMetadata.builder(TestCommand.class)
.addOption(OptionMetadata.builder("long").valueRequired())
.addOption(OptionMetadata.builder("s")));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class XaCommand extends CommandWithMetadata {
public XaCommand() {
super(CommandMetadata.builder(XaCommand.class).shortName('A'));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class XbCommand extends CommandWithMetadata {
public XbCommand() {
super(CommandMetadata.builder(XbCommand.class).shortName('B'));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class XccCommand extends CommandWithMetadata {
public XccCommand() {
super(CommandMetadata.builder(XccCommand.class).shortName('B'));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class Xd1Command extends CommandWithMetadata {
public Xd1Command() {
super(CommandMetadata.builder("xd"));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class Xd2Command extends CommandWithMetadata {
public Xd2Command() {
super(CommandMetadata.builder("xd"));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class XeCommand extends CommandWithMetadata {
public XeCommand() {
super(CommandMetadata.builder("xe")
.addOption(OptionMetadata.builder("opt1").build()));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class TestOptionCommand1 extends CommandWithMetadata {
public TestOptionCommand1() {
super(CommandMetadata.builder(TestOptionCommand1.class)
.name("cmd-1")
.addOption(OptionMetadata.builder("opt-1").build()));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static final class CommandWithDefaultOptionValue extends CommandWithMetadata {
public CommandWithDefaultOptionValue() {
super(CommandMetadata.builder("cmd")
.addOption(OptionMetadata.builder("option").valueOptionalWithDefault("val").build()));
}
@Override
public CommandOutcome run(Cli cli) {
return CommandOutcome.succeeded();
}
}
static class Bean1 {
private String a;
private Bean2 c;
public void setA(String a) {
this.a = a;
}
public void setC(Bean2 c) {
this.c = c;
}
}
static class Bean2 {
private Bean3 m;
public void setM(Bean3 m) {
this.m = m;
}
}
static class Bean3 {
private int k;
private String f;
private String l;
public void setK(int k) {
this.k = k;
}
public void setF(String f) {
this.f = f;
}
public void setL(String l) {
this.l = l;
}
}
}
| apache-2.0 |
FrankHossfeld/Training | GWT-Grundlagen-Maven/module1002/src/main/java/de/gishmo/gwt/example/module1002/client/ui/navigation/NavigationPresenter.java | 2110 | package de.gishmo.gwt.example.module1002.client.ui.navigation;
import de.gishmo.gwt.example.module0503.shared.dto.PersonSearch;
import de.gishmo.gwt.example.module1002.client.ClientContext;
import de.gishmo.gwt.example.module1002.client.events.SearchPersons;
import de.gishmo.gwt.example.module1002.client.events.SetNavigation;
import de.gishmo.gwt.example.module1002.client.ui.list.ListPlace;
import de.gishmo.gwt.example.module1002.client.ui.search.SearchPlace;
public class NavigationPresenter
implements INavigationView.Presenter {
private INavigationView view;
private ClientContext clientContext;
private PersonSearch search;
//------------------------------------------------------------------------------
public NavigationPresenter(ClientContext clientContext) {
this.clientContext = clientContext;
view = new NavigationView(clientContext.getStyle());
view.setPresenter(this);
bind();
}
//------------------------------------------------------------------------------
@Override
public void doShowList() {
clientContext.getPlaceController().goTo(createListPlace());
}
@Override
public void doShowSearch() {
clientContext.getPlaceController().goTo(createSearchPlace());
}
//------------------------------------------------------------------------------
private void bind() {
clientContext.getEventBus().addHandler(SearchPersons.TYPE,
new SearchPersons.SearchPersonsHandler() {
@Override
public void onSearchPersons(SearchPersons event) {
search = event.getSearch();
}
});
clientContext.getEventBus().fireEvent(new SetNavigation(view.asWidget()));
}
private ListPlace createListPlace() {
if (search == null) {
return new ListPlace("", "");
} else {
return new ListPlace(search.getName(), search.getCity());
}
}
private SearchPlace createSearchPlace() {
if (search == null) {
return new SearchPlace("", "");
} else {
return new SearchPlace(search.getName(), search.getCity());
}
}
}
| apache-2.0 |
firebase/firebase-android-sdk | firebase-components/src/main/java/com/google/firebase/events/Subscriber.java | 1719 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.events;
import java.util.concurrent.Executor;
/** Defines the API for event subscription. */
public interface Subscriber {
/**
* Subscribe to events of a given {@code type}.
*
* <p>Upon receipt of events, the specified {@link EventHandler} will be executed on the specified
* executor.
*
* <p>Note: subscribing the same (type, handler) pair on different executors will not register
* multiple times. Instead only the last subscription will be respected.
*/
<T> void subscribe(Class<T> type, Executor executor, EventHandler<? super T> handler);
/**
* Subscribe to events of a given {@code type}.
*
* <p>Upon receipt of events, the specified {@link EventHandler} will be executed on the
* publisher's thread.
*
* <p>By subscribing the {@link EventHandler}'s lifetime and its captured scope's is extended
* until an unsubscribe is called.
*/
<T> void subscribe(Class<T> type, EventHandler<? super T> handler);
/** Unsubscribe a handler from events of a given type. */
<T> void unsubscribe(Class<T> type, EventHandler<? super T> handler);
}
| apache-2.0 |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/UnexpectedResponseException.java | 988 | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.internal.core.adminrequest;
import com.datastax.oss.protocol.internal.Message;
public class UnexpectedResponseException extends Exception {
public final Message message;
public UnexpectedResponseException(String requestName, Message message) {
super(String.format("%s got unexpected response %s", requestName, message));
this.message = message;
}
}
| apache-2.0 |
azusa/hatunatu | hatunatu/src/main/java/jp/fieldnotes/hatunatu/dao/handler/BasicSelectHandler.java | 6824 | /*
* Copyright 2004-2015 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package jp.fieldnotes.hatunatu.dao.handler;
import jp.fieldnotes.hatunatu.dao.ResultSetFactory;
import jp.fieldnotes.hatunatu.dao.ResultSetHandler;
import jp.fieldnotes.hatunatu.dao.SelectHandler;
import jp.fieldnotes.hatunatu.dao.StatementFactory;
import jp.fieldnotes.hatunatu.dao.exception.EmptyRuntimeException;
import jp.fieldnotes.hatunatu.dao.impl.BasicResultSetFactory;
import jp.fieldnotes.hatunatu.dao.jdbc.QueryObject;
import jp.fieldnotes.hatunatu.util.sql.StatementUtil;
import javax.sql.DataSource;
import java.sql.*;
public class BasicSelectHandler extends BasicHandler implements SelectHandler {
private ResultSetFactory resultSetFactory = BasicResultSetFactory.INSTANCE;
private ResultSetHandler resultSetHandler;
private int fetchSize = 100;
private int maxRows = -1;
/**
* {@link BasicSelectHandler}を作成します。
*/
public BasicSelectHandler() {
}
/**
* {@link BasicSelectHandler}を作成します。
*
* @param dataSource
* データソース
* @param resultSetHandler
* 結果セットハンドラ
*/
public BasicSelectHandler(DataSource dataSource,
ResultSetHandler resultSetHandler) {
this(dataSource, resultSetHandler, StatementFactory.INSTANCE,
BasicResultSetFactory.INSTANCE);
}
/**
* {@link BasicSelectHandler}を作成します。
*
* @param dataSource
* データソース
* @param resultSetHandler
* 結果セットハンドラ
* @param statementFactory
* ステートメントファクトリ
* @param resultSetFactory
* 結果セットファクトリ
*/
public BasicSelectHandler(DataSource dataSource,
ResultSetHandler resultSetHandler,
StatementFactory statementFactory, ResultSetFactory resultSetFactory) {
setDataSource(dataSource);
setResultSetHandler(resultSetHandler);
setStatementFactory(statementFactory);
setResultSetFactory(resultSetFactory);
}
/**
* 結果セットファクトリを返します。
*
* @return 結果セットファクトリ
*/
public ResultSetFactory getResultSetFactory() {
return resultSetFactory;
}
/**
* 結果セットファクトリを設定します。
*
* @param resultSetFactory
* 結果セットファクトリ
*/
public void setResultSetFactory(ResultSetFactory resultSetFactory) {
this.resultSetFactory = resultSetFactory;
}
/**
* 結果セットハンドラを返します。
*
* @return 結果セットハンドラ
*/
public ResultSetHandler getResultSetHandler() {
return resultSetHandler;
}
/**
* 結果セットハンドラを設定します。
*
* @param resultSetHandler
* 結果セットハンドラ
*/
public void setResultSetHandler(ResultSetHandler resultSetHandler) {
this.resultSetHandler = resultSetHandler;
}
/**
* フェッチ数を返します。
*
* @return フェッチ数
*/
public int getFetchSize() {
return fetchSize;
}
/**
* フェッチ数を設定します。
*
* @param fetchSize
* フェッチ数
*/
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
/**
* 最大行数を返します。
*
* @return 最大行数
*/
public int getMaxRows() {
return maxRows;
}
/**
* 最大行数を設定します。
*
* @param maxRows
* 最大行数
*/
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
@Override
public Object execute(QueryObject queryObject)
throws Exception {
try (Connection con = getConnection()) {
return execute(con, queryObject);
}
}
protected Object execute(Connection connection, QueryObject queryObject)
throws Exception {
logSql(queryObject);
try (PreparedStatement ps = prepareStatement(connection, queryObject)) {
bindArgs(ps, queryObject.getBindArguments(), queryObject.getBindTypes());
return execute(ps, queryObject);
}
}
/**
* 引数のセットアップを行ないます。
*
* @param con
* コネクション
* @param args
* 引数
* @return セットアップ後の引数
*/
protected Object[] setup(Connection con, Object[] args) {
return args;
}
@Override
protected PreparedStatement prepareStatement(Connection connection, QueryObject queryObject) {
PreparedStatement ps = super.prepareStatement(connection, queryObject);
if (fetchSize > -1) {
StatementUtil.setFetchSize(ps, fetchSize);
}
if (maxRows > -1) {
StatementUtil.setMaxRows(ps, maxRows);
}
return ps;
}
protected Object execute(PreparedStatement ps, QueryObject queryObject) throws SQLException {
if (resultSetHandler == null) {
throw new EmptyRuntimeException("resultSetHandler");
}
try (ResultSet resultSet = createResultSet(ps, queryObject.getMethodArguments())) {
return resultSetHandler.handle(resultSet, queryObject);
}
}
/**
* データベースメタデータによるセットアップを行ないます。
*
* @param dbMetaData
* データベースメタデータ
*/
protected void setupDatabaseMetaData(DatabaseMetaData dbMetaData) {
}
/**
* 結果セットを作成します。
*
* @param ps
* 準備されたステートメント
* @return 結果セット
*/
protected ResultSet createResultSet(PreparedStatement ps, Object[] methodArgument) {
return resultSetFactory.createResultSet(ps, methodArgument);
}
} | apache-2.0 |
Nithanim/longbuffer | src/main/java/me/nithanim/longbuffer/Disposer.java | 445 | package me.nithanim.longbuffer;
import java.util.List;
public class Disposer {
public static void dispose(Disposable o) {
o.dispose();
}
public static void dispose(List l) {
for(Object o : l) {
dispose(o);
}
}
public static void dispose(Object o) {
if(o instanceof Disposable) {
dispose((Disposable)o);
}
}
private Disposer() {
}
}
| apache-2.0 |
seeburger-ag/commons-vfs | commons-vfs2-jackrabbit1/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavVersioningTests.java | 7010 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav.test;
import java.io.OutputStream;
import java.util.Map;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.provider.webdav.WebdavFileSystemConfigBuilder;
import org.apache.commons.vfs2.test.AbstractProviderTestCase;
import org.apache.jackrabbit.webdav.version.DeltaVConstants;
import org.apache.jackrabbit.webdav.version.VersionControlledResource;
/**
* Test to verify Webdav Versioning support
*/
public class WebdavVersioningTests extends AbstractProviderTestCase {
/**
*/
public void testVersioning() throws Exception {
final FileObject scratchFolder = createScratchFolder();
final FileSystemOptions opts = scratchFolder.getFileSystem().getFileSystemOptions();
final WebdavFileSystemConfigBuilder builder = (WebdavFileSystemConfigBuilder) getManager()
.getFileSystemConfigBuilder("webdav");
builder.setVersioning(opts, true);
final FileObject file = getManager().resolveFile(scratchFolder, "file1.txt", opts);
final FileSystemOptions newOpts = file.getFileSystem().getFileSystemOptions();
assertTrue(opts == newOpts);
assertTrue(builder.isVersioning(newOpts));
assertTrue(!file.exists());
file.createFile();
assertTrue(file.exists());
assertSame(FileType.FILE, file.getType());
assertTrue(file.isFile());
assertEquals(0, file.getContent().getSize());
assertTrue(file.getContent().isEmpty());
assertFalse(file.isExecutable());
assertFalse(file.isHidden());
assertTrue(file.isReadable());
assertTrue(file.isWriteable());
Map<?, ?> map = file.getContent().getAttributes();
final String name = ((URLFileName) file.getName()).getUserName();
assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
if (name != null) {
assertEquals(name, map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
}
assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
// Create the source file
final String content = "Here is some sample content for the file. Blah Blah Blah.";
final OutputStream os = file.getContent().getOutputStream();
try {
os.write(content.getBytes("utf-8"));
} finally {
os.close();
}
assertSameContent(content, file);
map = file.getContent().getAttributes();
assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
if (name != null) {
assertEquals(name, map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
}
assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
builder.setVersioning(opts, false);
}
/**
*/
public void testVersioningWithCreator() throws Exception {
final FileObject scratchFolder = createScratchFolder();
final FileSystemOptions opts = scratchFolder.getFileSystem().getFileSystemOptions();
final WebdavFileSystemConfigBuilder builder = (WebdavFileSystemConfigBuilder) getManager()
.getFileSystemConfigBuilder("webdav");
builder.setVersioning(opts, true);
builder.setCreatorName(opts, "testUser");
final FileObject file = getManager().resolveFile(scratchFolder, "file1.txt", opts);
final FileSystemOptions newOpts = file.getFileSystem().getFileSystemOptions();
assertTrue(opts == newOpts);
assertTrue(builder.isVersioning(newOpts));
assertTrue(!file.exists());
file.createFile();
assertTrue(file.exists());
assertSame(FileType.FILE, file.getType());
assertTrue(file.isFile());
assertEquals(0, file.getContent().getSize());
assertTrue(file.getContent().isEmpty());
assertFalse(file.isExecutable());
assertFalse(file.isHidden());
assertTrue(file.isReadable());
assertTrue(file.isWriteable());
Map<?, ?> map = file.getContent().getAttributes();
final String name = ((URLFileName) file.getName()).getUserName();
assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
assertEquals(map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()), "testUser");
if (name != null) {
assertTrue(map.containsKey(DeltaVConstants.COMMENT.toString()));
assertEquals("Modified by user " + name, map.get(DeltaVConstants.COMMENT.toString()));
}
assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
// Create the source file
final String content = "Here is some sample content for the file. Blah Blah Blah.";
final OutputStream os = file.getContent().getOutputStream();
try {
os.write(content.getBytes("utf-8"));
} finally {
os.close();
}
assertSameContent(content, file);
map = file.getContent().getAttributes();
assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
assertEquals(map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()), "testUser");
if (name != null) {
assertTrue(map.containsKey(DeltaVConstants.COMMENT.toString()));
assertEquals("Modified by user " + name, map.get(DeltaVConstants.COMMENT.toString()));
}
assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
builder.setVersioning(opts, false);
builder.setCreatorName(opts, null);
}
/**
* Sets up a scratch folder for the test to use.
*/
protected FileObject createScratchFolder() throws Exception {
final FileObject scratchFolder = getWriteFolder();
// Make sure the test folder is empty
scratchFolder.delete(Selectors.EXCLUDE_SELF);
scratchFolder.createFolder();
return scratchFolder;
}
}
| apache-2.0 |
reactor/reactor-incubator | reactor-amqp/src/main/java/reactor/rx/amqp/spec/Exchange.java | 2519 | package reactor.rx.amqp.spec;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import java.util.function.Function;
import java.io.IOException;
import java.util.Map;
/**
* @author Stephane Maldini
*/
public final class Exchange implements Function<Channel, AMQP.Exchange.DeclareOk> {
public static final String TYPE_FANOUT = "fanout";
public static final String TYPE_HEADERS = "headers";
public static final String TYPE_DIRECT = "direct";
public static final String TYPE_TOPIC = "topic";
public static final Exchange DEFAULT = Exchange.lookup("");
private final String exchange;
private final boolean passive;
private String type;
private boolean durable;
private boolean autoDelete;
private Map<String, Object> arguments;
//boolean internal,
public static Exchange empty() {
return DEFAULT;
}
public static Exchange lookup(String exchange) {
return new Exchange(exchange, true);
}
public static Exchange create(String exchange) {
return new Exchange(exchange, false);
}
Exchange(String exchange, boolean passive) {
this.exchange = exchange;
this.passive = passive;
if (!passive) {
fanOut();
}
}
public String exchange() {
return exchange;
}
public String type() {
return type;
}
public Exchange type(String type) {
this.type = type;
return this;
}
public boolean durable() {
return durable;
}
public Exchange durable(boolean durable) {
this.durable = durable;
return this;
}
public boolean autoDelete() {
return autoDelete;
}
public Exchange autoDelete(boolean autoDelete) {
this.autoDelete = autoDelete;
return this;
}
public Exchange topic() {
return type(TYPE_TOPIC);
}
public Exchange fanOut() {
return type(TYPE_FANOUT);
}
public Exchange direct() {
return type(TYPE_DIRECT);
}
public Exchange headers() {
return type(TYPE_HEADERS);
}
public Map<String, Object> arguments() {
return arguments;
}
public Exchange arguments(Map<String, Object> arguments) {
this.arguments = arguments;
return this;
}
@Override
public AMQP.Exchange.DeclareOk apply(Channel channel) {
try {
if(this == DEFAULT){
return null;
} else if (passive) {
return channel.exchangeDeclarePassive(exchange);
} else {
return channel.exchangeDeclare(exchange, type, autoDelete, durable, arguments);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/CreativeServiceInterface.java | 5692 |
package com.google.api.ads.dfp.jaxws.v201511;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
*
* Provides methods for adding, updating and retrieving {@link Creative}
* objects.
*
* <p>For a creative to run, it must be associated with a {@link LineItem}
* managed by the {@link LineItemCreativeAssociationService}.
*
*
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.1
*
*/
@WebService(name = "CreativeServiceInterface", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
@XmlSeeAlso({
ObjectFactory.class
})
public interface CreativeServiceInterface {
/**
*
* Creates new {@link Creative} objects.
*
* @param creatives the creatives to create
* @return the created creatives with their IDs filled in
*
*
* @param creatives
* @return
* returns java.util.List<com.google.api.ads.dfp.jaxws.v201511.Creative>
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
@RequestWrapper(localName = "createCreatives", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfacecreateCreatives")
@ResponseWrapper(localName = "createCreativesResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfacecreateCreativesResponse")
public List<Creative> createCreatives(
@WebParam(name = "creatives", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
List<Creative> creatives)
throws ApiException_Exception
;
/**
*
* Gets a {@link CreativePage} of {@link Creative} objects that satisfy the
* given {@link Statement#query}. The following fields are supported for
* filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link Creative#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link Creative#name}</td>
* </tr>
* <tr>
* <td>{@code advertiserId}</td>
* <td>{@link Creative#advertiserId}</td>
* </tr>
* <tr>
* <td>{@code width}</td>
* <td>{@link Creative#size}</td>
* </tr>
* <tr>
* <td>{@code height}</td>
* <td>{@link Creative#size}</td>
* </tr>
* <tr>
* <td>{@code lastModifiedDateTime}</td>
* <td>{@link Creative#lastModifiedDateTime}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of creatives
* @return the creatives that match the given filter
*
*
* @param filterStatement
* @return
* returns com.google.api.ads.dfp.jaxws.v201511.CreativePage
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
@RequestWrapper(localName = "getCreativesByStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfacegetCreativesByStatement")
@ResponseWrapper(localName = "getCreativesByStatementResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfacegetCreativesByStatementResponse")
public CreativePage getCreativesByStatement(
@WebParam(name = "filterStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
Statement filterStatement)
throws ApiException_Exception
;
/**
*
* Updates the specified {@link Creative} objects.
*
* @param creatives the creatives to update
* @return the updated creatives
*
*
* @param creatives
* @return
* returns java.util.List<com.google.api.ads.dfp.jaxws.v201511.Creative>
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
@RequestWrapper(localName = "updateCreatives", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfaceupdateCreatives")
@ResponseWrapper(localName = "updateCreativesResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511", className = "com.google.api.ads.dfp.jaxws.v201511.CreativeServiceInterfaceupdateCreativesResponse")
public List<Creative> updateCreatives(
@WebParam(name = "creatives", targetNamespace = "https://www.google.com/apis/ads/publisher/v201511")
List<Creative> creatives)
throws ApiException_Exception
;
}
| apache-2.0 |
cisoft8341/starapp | starapp-webapp/src/main/java/org/starapp/rbac/exception/ServiceException.java | 497 | package org.starapp.rbac.exception;
/**
* Service Exception
* @author wangqiang888888@gmail.com
*
*/
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 3583566093089790852L;
public ServiceException() {
super();
}
public ServiceException(String message) {
super(message);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
}
| apache-2.0 |
spepping/fop-cs | src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/IRtfParagraphKeepTogetherContainer.java | 1544 | /*
* 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.
*/
/* $Id$ */
package org.apache.fop.render.rtf.rtflib.rtfdoc;
/*
* This file is part of the RTF library of the FOP project, which was originally
* created by Bertrand Delacretaz <bdelacretaz@codeconsult.ch> and by other
* contributors to the jfor project (www.jfor.org), who agreed to donate jfor to
* the FOP project.
*/
import java.io.IOException;
/**
* Interface for classes containing Paragraphs with Keep Together
*/
public interface IRtfParagraphKeepTogetherContainer {
/**
* Close current paragraph, if any, and start a new one
* @return new paragraph object (with keep together)
* @throws IOException for I/O problems
*/
RtfParagraphKeepTogether newParagraphKeepTogether() throws IOException;
} | apache-2.0 |
k4kentchow/qqmusic | src/com/bdqn/qqmusic/pojo/ArtistDAO.java | 5668 | package com.bdqn.qqmusic.pojo;
import com.bdqn.qqmusic.dao.BaseDAO;
import java.util.List;
import java.util.Set;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A data access object (DAO) providing persistence and search support for
* Artist entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.bdqn.qqmusic.pojo.Artist
* @author MyEclipse Persistence Tools
*/
public class ArtistDAO extends BaseDAO {
private static final Logger log = LoggerFactory.getLogger(ArtistDAO.class);
// property constants
public static final String ANAME = "aname";
public static final String AGRADUATION = "agraduation";
public static final String ANATIONALITY = "anationality";
public static final String ABIRTHPLACE = "abirthplace";
public static final String APROFESSION = "aprofession";
public static final String AHEIGHT = "aheight";
public static final String AWEIGHT = "aweight";
public static final String ABLOODTYPE = "abloodtype";
public static final String AACHIEVEMENT = "aachievement";
public static final String AINTERESTS = "ainterests";
public static final String APICPATH = "apicpath";
public static final String ATYPE = "atype";
public void save(Artist transientInstance) {
log.debug("saving Artist instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Artist persistentInstance) {
log.debug("deleting Artist instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Artist findById(java.lang.Integer id) {
log.debug("getting Artist instance with id: " + id);
try {
Artist instance = (Artist) getSession().get(
"com.bdqn.qqmusic.pojo.Artist", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Artist instance) {
log.debug("finding Artist instance by example");
try {
List results = getSession()
.createCriteria("com.bdqn.qqmusic.pojo.Artist")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Artist instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Artist as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByAname(Object aname) {
return findByProperty(ANAME, aname);
}
public List findByAgraduation(Object agraduation) {
return findByProperty(AGRADUATION, agraduation);
}
public List findByAnationality(Object anationality) {
return findByProperty(ANATIONALITY, anationality);
}
public List findByAbirthplace(Object abirthplace) {
return findByProperty(ABIRTHPLACE, abirthplace);
}
public List findByAprofession(Object aprofession) {
return findByProperty(APROFESSION, aprofession);
}
public List findByAheight(Object aheight) {
return findByProperty(AHEIGHT, aheight);
}
public List findByAweight(Object aweight) {
return findByProperty(AWEIGHT, aweight);
}
public List findByAbloodtype(Object abloodtype) {
return findByProperty(ABLOODTYPE, abloodtype);
}
public List findByAachievement(Object aachievement) {
return findByProperty(AACHIEVEMENT, aachievement);
}
public List findByAinterests(Object ainterests) {
return findByProperty(AINTERESTS, ainterests);
}
public List findByApicpath(Object apicpath) {
return findByProperty(APICPATH, apicpath);
}
public List findByAtype(Object atype) {
return findByProperty(ATYPE, atype);
}
public List findAll() {
log.debug("finding all Artist instances");
try {
String queryString = "from Artist";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Artist merge(Artist detachedInstance) {
log.debug("merging Artist instance");
try {
Artist result = (Artist) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Artist instance) {
log.debug("attaching dirty Artist instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Artist instance) {
log.debug("attaching clean Artist instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
} | apache-2.0 |
koitoer/Web-Services | jax-ws/src/main/java/com/koitoer/jax/ws/soap/addressing/service/CalculatorService.java | 207 | package com.koitoer.jax.ws.soap.addressing.service;
import javax.jws.WebService;
@WebService
public interface CalculatorService {
public abstract int addition(int i, int o) throws AddNumbersException;
}
| apache-2.0 |
DPain/DiscordBot | src/main/java/com/dpain/DiscordBot/enums/AudioType.java | 286 | package com.dpain.DiscordBot.enums;
public enum AudioType {
/* @formatter:off */
// Enums of audio types
FILE("file"),
URL("url");
/* @formatter:on */
private String key;
AudioType(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
| apache-2.0 |
zackcheng520/perfect-work | TreasureHouse/app/src/main/java/com/perfect/treasurehouse/utils/TLog.java | 2207 | package com.perfect.treasurehouse.utils;
import android.util.Log;
/**
* Created by Zack on 2016/12/22.
*/
public class TLog {
private final static boolean DEBUG = true;
private final static String TAG = "TREASURE_HOUSE";
private final static String ERROR_INFO = "EEROR_UNKNOW_CLASS";
public static void v(String msg) {
if (DEBUG) {
String info = getThreadInfo();
Log.v(TAG, info + msg);
}
}
public static void d(String msg) {
String info = getThreadInfo();
if (DEBUG) {
Log.d(TAG, info + msg);
} else {
Log.v(TAG, info + msg);
}
}
public static void i(String msg) {
String info = getThreadInfo();
if (DEBUG) {
Log.i(TAG, info + msg);
} else {
Log.d(TAG, info + msg);
}
}
public static void w(String msg) {
String info = getThreadInfo();
if (DEBUG) {
Log.w(TAG, info + msg);
} else {
Log.i(TAG, info + msg);
}
}
public static void e(String msg) {
String info = getThreadInfo();
if (DEBUG) {
Log.e(TAG, info + msg);
throw new TLogException("msg");
} else {
Log.w(TAG, info + msg);
}
}
private static String getThreadInfo() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (trace.length > 4) {
return getFileName(trace[4]) + ":" + trace[4].getMethodName() + "() ";
} else {
return ERROR_INFO;
}
}
private static String getFileName(StackTraceElement element) {
String fileName = element.getFileName();
return fileName.substring(0, fileName.lastIndexOf("."));
}
private static String getFileName() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
return getFileName(trace[3]);
}
private static class TLogException extends RuntimeException{
private TLogException(String info){
super(info);
}
}
}
| apache-2.0 |